@ours.network/mcp 0.15.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
3
- var P_=Object.create;var Hs=Object.defineProperty;var T_=Object.getOwnPropertyDescriptor;var R_=Object.getOwnPropertyNames;var E_=Object.getPrototypeOf,I_=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Bs=(e,t)=>{for(var r in t)Hs(e,r,{get:t[r],enumerable:!0})},O_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of R_(t))!I_.call(e,o)&&o!==r&&Hs(e,o,{get:()=>t[o],enumerable:!(n=T_(t,o))||n.enumerable});return e};var ju=(e,t,r)=>(r=e!=null?P_(E_(e)):{},O_(t||!e||!e.__esModule?Hs(r,"default",{value:e,enumerable:!0}):r,e));var Sn=T(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.regexpCode=J.getEsmExportName=J.getProperty=J.safeStringify=J.stringify=J.strConcat=J.addCodeArg=J.str=J._=J.nil=J._Code=J.Name=J.IDENTIFIER=J._CodeOrName=void 0;var bn=class{};J._CodeOrName=bn;J.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Yt=class extends bn{constructor(t){if(super(),!J.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}}};J.Name=Yt;var Ge=class extends bn{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 Yt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};J._Code=Ge;J.nil=new Ge("");function Sf(e,...t){let r=[e[0]],n=0;for(;n<t.length;)ha(r,t[n]),r.push(e[++n]);return new Ge(r)}J._=Sf;var ma=new Ge("+");function xf(e,...t){let r=[$n(e[0])],n=0;for(;n<t.length;)r.push(ma),ha(r,t[n]),r.push(ma,$n(e[++n]));return Uw(r),new Ge(r)}J.str=xf;function ha(e,t){t instanceof Ge?e.push(...t._items):t instanceof Yt?e.push(t):e.push(qw(t))}J.addCodeArg=ha;function Uw(e){let t=1;for(;t<e.length-1;){if(e[t]===ma){let r=Dw(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Dw(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Yt||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 Yt))return`"${e}${t.slice(1)}`}function Zw(e,t){return t.emptyStr()?e:e.emptyStr()?t:xf`${e}${t}`}J.strConcat=Zw;function qw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:$n(Array.isArray(e)?e.join(","):e)}function Lw(e){return new Ge($n(e))}J.stringify=Lw;function $n(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}J.safeStringify=$n;function Fw(e){return typeof e=="string"&&J.IDENTIFIER.test(e)?new Ge(`.${e}`):Sf`[${e}]`}J.getProperty=Fw;function Vw(e){if(typeof e=="string"&&J.IDENTIFIER.test(e))return new Ge(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}J.getEsmExportName=Vw;function Hw(e){return new Ge(e.toString())}J.regexpCode=Hw});var ya=T(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.ValueScope=Ue.ValueScopeName=Ue.Scope=Ue.varKinds=Ue.UsedValueState=void 0;var Me=Sn(),ga=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Ho;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Ho||(Ue.UsedValueState=Ho={}));Ue.varKinds={const:new Me.Name("const"),let:new Me.Name("let"),var:new Me.Name("var")};var Bo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Me.Name?t:this.name(t)}name(t){return new Me.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}}};Ue.Scope=Bo;var Ko=class extends Me.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Me._)`.${new Me.Name(r)}[${n}]`}};Ue.ValueScopeName=Ko;var Bw=(0,Me._)`\n`,_a=class extends Bo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Bw:Me.nil}}get(){return this._scope}name(t){return new Ko(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 u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),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,Me._)`${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=Me.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Ho.Started);let u=r(l);if(u){let d=this.opts.es5?Ue.varKinds.var:Ue.varKinds.const;s=(0,Me._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Me._)`${s}${u}${this.opts._n}`;else throw new ga(l);c.set(l,Ho.Completed)})}return s}};Ue.ValueScope=_a});var U=T(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var F=Sn(),ot=ya(),Ot=Sn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return Ot._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return Ot.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return Ot.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return Ot.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return Ot.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return Ot.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return Ot.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return Ot.Name}});var Yo=ya();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Yo.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Yo.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Yo.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Yo.varKinds}});D.operators={GT:new F._Code(">"),GTE:new F._Code(">="),LT:new F._Code("<"),LTE:new F._Code("<="),EQ:new F._Code("==="),NEQ:new F._Code("!=="),NOT:new F._Code("!"),OR:new F._Code("||"),AND:new F._Code("&&"),ADD:new F._Code("+")};var wt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},va=class extends wt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ot.varKinds.var:this.varKind,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=Or(this.rhs,t,r)),this}get names(){return this.rhs instanceof F._CodeOrName?this.rhs.names:{}}},Jo=class extends wt{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 F.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Or(this.rhs,t,r),this}get names(){let t=this.lhs instanceof F.Name?{}:{...this.lhs.names};return Wo(t,this.rhs)}},wa=class extends Jo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ba=class extends wt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},$a=class extends wt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Sa=class extends wt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},xa=class extends wt{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=Or(this.code,t,r),this}get names(){return this.code instanceof F._CodeOrName?this.code.names:{}}},xn=class extends wt{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)||(Kw(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>er(t,r.names),{})}},bt=class extends xn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},za=class extends xn{},Ir=class extends bt{};Ir.kind="else";var Qt=class e extends bt{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 Ir(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(zf(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=Or(this.condition,t,r),this}get names(){let t=super.names;return Wo(t,this.condition),this.else&&er(t,this.else.names),t}};Qt.kind="if";var Xt=class extends bt{};Xt.kind="for";var ka=class extends Xt{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=Or(this.iteration,t,r),this}get names(){return er(super.names,this.iteration.names)}},Pa=class extends Xt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?ot.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=Wo(super.names,this.from);return Wo(t,this.to)}},Go=class extends Xt{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=Or(this.iterable,t,r),this}get names(){return er(super.names,this.iterable.names)}},zn=class extends bt{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)}};zn.kind="func";var kn=class extends xn{render(t){return"return "+super.render(t)}};kn.kind="return";var Ta=class extends bt{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&&er(t,this.catch.names),this.finally&&er(t,this.finally.names),t}},Pn=class extends bt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Pn.kind="catch";var Tn=class extends bt{render(t){return"finally"+super.render(t)}};Tn.kind="finally";var Ra=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new ot.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 va(t,s,n)),s}const(t,r,n){return this._def(ot.varKinds.const,t,r,n)}let(t,r,n){return this._def(ot.varKinds.let,t,r,n)}var(t,r,n){return this._def(ot.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Jo(t,r,n))}add(t,r){return this._leafNode(new wa(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==F.nil&&this._leafNode(new xa(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,F.addCodeArg)(r,o));return r.push("}"),new F._Code(r)}if(t,r,n){if(this._blockNode(new Qt(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 Qt(t))}else(){return this._elseNode(new Ir)}endIf(){return this._endBlockNode(Qt,Ir)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new ka(t),r)}forRange(t,r,n,o,s=this.opts.es5?ot.varKinds.var:ot.varKinds.let){let i=this._scope.toName(t);return this._for(new Pa(s,i,r,n),()=>o(i))}forOf(t,r,n,o=ot.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof F.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,F._)`${i}.length`,a=>{this.var(s,(0,F._)`${i}[${a}]`),n(s)})}return this._for(new Go("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?ot.varKinds.var:ot.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,F._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new Go("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Xt)}label(t){return this._leafNode(new ba(t))}break(t){return this._leafNode(new $a(t))}return(t){let r=new kn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(kn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ta;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new Pn(s),r(s)}return n&&(this._currNode=o.finally=new Tn,this.code(n)),this._endBlockNode(Pn,Tn)}throw(t){return this._leafNode(new Sa(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=F.nil,n,o){return this._blockNode(new zn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(zn)}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 Qt))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}};D.CodeGen=Ra;function er(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Wo(e,t){return t instanceof F._CodeOrName?er(e,t.names):e}function Or(e,t,r){if(e instanceof F.Name)return n(e);if(!o(e))return e;return new F._Code(e._items.reduce((s,i)=>(i instanceof F.Name&&(i=n(i)),i instanceof F._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 F._Code&&s._items.some(i=>i instanceof F.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function Kw(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function zf(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,F._)`!${Ea(e)}`}D.not=zf;var Jw=kf(D.operators.AND);function Gw(...e){return e.reduce(Jw)}D.and=Gw;var Ww=kf(D.operators.OR);function Yw(...e){return e.reduce(Ww)}D.or=Yw;function kf(e){return(t,r)=>t===F.nil?r:r===F.nil?t:(0,F._)`${Ea(t)} ${e} ${Ea(r)}`}function Ea(e){return e instanceof F.Name?e:(0,F._)`(${e})`}});var H=T(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;var ne=U(),Qw=Sn();function Xw(e){let t={};for(let r of e)t[r]=!0;return t}Z.toHash=Xw;function eb(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Rf(e,t),!Ef(t,e.self.RULES.all))}Z.alwaysValidSchema=eb;function Rf(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]||Af(e,`unknown keyword: "${s}"`)}Z.checkUnknownRules=Rf;function Ef(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}Z.schemaHasRules=Ef;function tb(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Z.schemaHasRulesButRef=tb;function rb({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ne._)`${r}`}return(0,ne._)`${e}${t}${(0,ne.getProperty)(n)}`}Z.schemaRefOrVal=rb;function nb(e){return If(decodeURIComponent(e))}Z.unescapeFragment=nb;function ob(e){return encodeURIComponent(Oa(e))}Z.escapeFragment=ob;function Oa(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=Oa;function If(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=If;function sb(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}Z.eachItem=sb;function Pf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ne.Name?(s instanceof ne.Name?e(o,s,i):t(o,s,i),i):s instanceof ne.Name?(t(o,i,s),s):r(s,i);return a===ne.Name&&!(c instanceof ne.Name)?n(o,c):c}}Z.mergeEvaluated={props:Pf({mergeNames:(e,t,r)=>e.if((0,ne._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ne._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ne._)`${r} || {}`).code((0,ne._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,ne._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ne._)`${r} || {}`),Aa(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Of}),items:Pf({mergeNames:(e,t,r)=>e.if((0,ne._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ne._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,ne._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ne._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Of(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ne._)`{}`);return t!==void 0&&Aa(e,r,t),r}Z.evaluatedPropsToName=Of;function Aa(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ne._)`${t}${(0,ne.getProperty)(n)}`,!0))}Z.setEvaluated=Aa;var Tf={};function ib(e,t){return e.scopeValue("func",{ref:t,code:Tf[t.code]||(Tf[t.code]=new Qw._Code(t.code))})}Z.useFunc=ib;var Ia;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ia||(Z.Type=Ia={}));function ab(e,t,r){if(e instanceof ne.Name){let n=t===Ia.Num;return r?n?(0,ne._)`"[" + ${e} + "]"`:(0,ne._)`"['" + ${e} + "']"`:n?(0,ne._)`"/" + ${e}`:(0,ne._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ne.getProperty)(e).toString():"/"+Oa(e)}Z.getErrorPath=ab;function Af(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Z.checkStrictMode=Af});var $t=T(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var Re=U(),cb={data:new Re.Name("data"),valCxt:new Re.Name("valCxt"),instancePath:new Re.Name("instancePath"),parentData:new Re.Name("parentData"),parentDataProperty:new Re.Name("parentDataProperty"),rootData:new Re.Name("rootData"),dynamicAnchors:new Re.Name("dynamicAnchors"),vErrors:new Re.Name("vErrors"),errors:new Re.Name("errors"),this:new Re.Name("this"),self:new Re.Name("self"),scope:new Re.Name("scope"),json:new Re.Name("json"),jsonPos:new Re.Name("jsonPos"),jsonLen:new Re.Name("jsonLen"),jsonPart:new Re.Name("jsonPart")};Ca.default=cb});var Rn=T(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.extendErrors=Ee.resetErrorsCount=Ee.reportExtraError=Ee.reportError=Ee.keyword$DataError=Ee.keywordError=void 0;var B=U(),Qo=H(),Ae=$t();Ee.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};Ee.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function ub(e,t=Ee.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=jf(e,t,r);n??(i||a)?Cf(s,c):Nf(o,(0,B._)`[${c}]`)}Ee.reportError=ub;function lb(e,t=Ee.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=jf(e,t,r);Cf(o,a),s||i||Nf(n,Ae.default.vErrors)}Ee.reportExtraError=lb;function db(e,t){e.assign(Ae.default.errors,t),e.if((0,B._)`${Ae.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Ae.default.vErrors}.length`,t),()=>e.assign(Ae.default.vErrors,null)))}Ee.resetErrorsCount=db;function pb({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,Ae.default.errors,a=>{e.const(i,(0,B._)`${Ae.default.vErrors}[${a}]`),e.if((0,B._)`${i}.instancePath === undefined`,()=>e.assign((0,B._)`${i}.instancePath`,(0,B.strConcat)(Ae.default.instancePath,s.errorPath))),e.assign((0,B._)`${i}.schemaPath`,(0,B.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,B._)`${i}.schema`,r),e.assign((0,B._)`${i}.data`,n))})}Ee.extendErrors=pb;function Cf(e,t){let r=e.const("err",t);e.if((0,B._)`${Ae.default.vErrors} === null`,()=>e.assign(Ae.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Ae.default.vErrors}.push(${r})`),e.code((0,B._)`${Ae.default.errors}++`)}function Nf(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var tr={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function jf(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:fb(e,t,r)}function fb(e,t,r={}){let{gen:n,it:o}=e,s=[mb(o,r),hb(e,r)];return gb(e,t,s),n.object(...s)}function mb({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,Qo.getErrorPath)(t,Qo.Type.Str)}`:e;return[Ae.default.instancePath,(0,B.strConcat)(Ae.default.instancePath,r)]}function hb({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,B.str)`${t}/${e}`;return r&&(o=(0,B.str)`${o}${(0,Qo.getErrorPath)(r,Qo.Type.Str)}`),[tr.schemaPath,o]}function gb(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([tr.keyword,o],[tr.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([tr.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([tr.schema,i],[tr.parentSchema,(0,B._)`${u}${d}`],[Ae.default.data,s]),l&&n.push([tr.propertyName,l])}});var Uf=T(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.boolOrEmptySchema=Ar.topBoolOrEmptySchema=void 0;var _b=Rn(),yb=U(),vb=$t(),wb={message:"boolean schema is false"};function bb(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Mf(e,!1):typeof r=="object"&&r.$async===!0?t.return(vb.default.data):(t.assign((0,yb._)`${n}.errors`,null),t.return(!0))}Ar.topBoolOrEmptySchema=bb;function $b(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Mf(e)):r.var(t,!0)}Ar.boolOrEmptySchema=$b;function Mf(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,_b.reportError)(o,wb,void 0,t)}});var Na=T(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getRules=Cr.isJSONType=void 0;var Sb=["string","number","integer","boolean","null","object","array"],xb=new Set(Sb);function zb(e){return typeof e=="string"&&xb.has(e)}Cr.isJSONType=zb;function kb(){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:{}}}Cr.getRules=kb});var ja=T(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.shouldUseRule=At.shouldUseGroup=At.schemaHasRulesForType=void 0;function Pb({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Df(e,n)}At.schemaHasRulesForType=Pb;function Df(e,t){return t.rules.some(r=>Zf(e,r))}At.shouldUseGroup=Df;function Zf(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))}At.shouldUseRule=Zf});var En=T(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;var Tb=Na(),Rb=ja(),Eb=Rn(),M=U(),qf=H(),Nr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Nr||(Ie.DataType=Nr={}));function Ib(e){let t=Lf(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}Ie.getSchemaTypes=Ib;function Lf(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Tb.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ie.getJSONTypes=Lf;function Ob(e,t){let{gen:r,data:n,opts:o}=e,s=Ab(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Rb.schemaHasRulesForType)(e,t[0]));if(i){let a=Ua(t,n,o.strictNumbers,Nr.Wrong);r.if(a,()=>{s.length?Cb(e,t,s):Da(e)})}return i}Ie.coerceAndCheckDataType=Ob;var Ff=new Set(["string","number","integer","boolean","null"]);function Ab(e,t){return t?e.filter(r=>Ff.has(r)||t==="array"&&r==="array"):[]}function Cb(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,M._)`typeof ${o}`),a=n.let("coerced",(0,M._)`undefined`);s.coerceTypes==="array"&&n.if((0,M._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,M._)`${o}[0]`).assign(i,(0,M._)`typeof ${o}`).if(Ua(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,M._)`${a} !== undefined`);for(let l of r)(Ff.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Da(e),n.endIf(),n.if((0,M._)`${a} !== undefined`,()=>{n.assign(o,a),Nb(e,a)});function c(l){switch(l){case"string":n.elseIf((0,M._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,M._)`"" + ${o}`).elseIf((0,M._)`${o} === null`).assign(a,(0,M._)`""`);return;case"number":n.elseIf((0,M._)`${i} == "boolean" || ${o} === null
3
+ var j_=Object.create;var Ks=Object.defineProperty;var M_=Object.getOwnPropertyDescriptor;var U_=Object.getOwnPropertyNames;var D_=Object.getPrototypeOf,Z_=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Js=(e,t)=>{for(var r in t)Ks(e,r,{get:t[r],enumerable:!0})},q_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of U_(t))!Z_.call(e,o)&&o!==r&&Ks(e,o,{get:()=>t[o],enumerable:!(n=M_(t,o))||n.enumerable});return e};var Du=(e,t,r)=>(r=e!=null?j_(D_(e)):{},q_(t||!e||!e.__esModule?Ks(r,"default",{value:e,enumerable:!0}):r,e));var xn=T(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.regexpCode=J.getEsmExportName=J.getProperty=J.safeStringify=J.stringify=J.strConcat=J.addCodeArg=J.str=J._=J.nil=J._Code=J.Name=J.IDENTIFIER=J._CodeOrName=void 0;var $n=class{};J._CodeOrName=$n;J.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Yt=class extends $n{constructor(t){if(super(),!J.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}}};J.Name=Yt;var Ge=class extends $n{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 Yt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};J._Code=Ge;J.nil=new Ge("");function zf(e,...t){let r=[e[0]],n=0;for(;n<t.length;)_a(r,t[n]),r.push(e[++n]);return new Ge(r)}J._=zf;var ga=new Ge("+");function Pf(e,...t){let r=[Sn(e[0])],n=0;for(;n<t.length;)r.push(ga),_a(r,t[n]),r.push(ga,Sn(e[++n]));return Kb(r),new Ge(r)}J.str=Pf;function _a(e,t){t instanceof Ge?e.push(...t._items):t instanceof Yt?e.push(t):e.push(Wb(t))}J.addCodeArg=_a;function Kb(e){let t=1;for(;t<e.length-1;){if(e[t]===ga){let r=Jb(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Jb(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Yt||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 Yt))return`"${e}${t.slice(1)}`}function Gb(e,t){return t.emptyStr()?e:e.emptyStr()?t:Pf`${e}${t}`}J.strConcat=Gb;function Wb(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Sn(Array.isArray(e)?e.join(","):e)}function Yb(e){return new Ge(Sn(e))}J.stringify=Yb;function Sn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}J.safeStringify=Sn;function Qb(e){return typeof e=="string"&&J.IDENTIFIER.test(e)?new Ge(`.${e}`):zf`[${e}]`}J.getProperty=Qb;function Xb(e){if(typeof e=="string"&&J.IDENTIFIER.test(e))return new Ge(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}J.getEsmExportName=Xb;function ew(e){return new Ge(e.toString())}J.regexpCode=ew});var ba=T(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.ValueScope=De.ValueScopeName=De.Scope=De.varKinds=De.UsedValueState=void 0;var Ue=xn(),ya=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Ko;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Ko||(De.UsedValueState=Ko={}));De.varKinds={const:new Ue.Name("const"),let:new Ue.Name("let"),var:new Ue.Name("var")};var Jo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ue.Name?t:this.name(t)}name(t){return new Ue.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}}};De.Scope=Jo;var Go=class extends Ue.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ue._)`.${new Ue.Name(r)}[${n}]`}};De.ValueScopeName=Go;var tw=(0,Ue._)`\n`,va=class extends Jo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?tw:Ue.nil}}get(){return this._scope}name(t){return new Go(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 u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),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,Ue._)`${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=Ue.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Ko.Started);let u=r(l);if(u){let d=this.opts.es5?De.varKinds.var:De.varKinds.const;s=(0,Ue._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Ue._)`${s}${u}${this.opts._n}`;else throw new ya(l);c.set(l,Ko.Completed)})}return s}};De.ValueScope=va});var U=T(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var F=xn(),ot=ba(),Ot=xn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return Ot._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return Ot.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return Ot.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return Ot.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return Ot.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return Ot.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return Ot.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return Ot.Name}});var Xo=ba();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Xo.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Xo.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Xo.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Xo.varKinds}});D.operators={GT:new F._Code(">"),GTE:new F._Code(">="),LT:new F._Code("<"),LTE:new F._Code("<="),EQ:new F._Code("==="),NEQ:new F._Code("!=="),NOT:new F._Code("!"),OR:new F._Code("||"),AND:new F._Code("&&"),ADD:new F._Code("+")};var wt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},wa=class extends wt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ot.varKinds.var:this.varKind,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=Ar(this.rhs,t,r)),this}get names(){return this.rhs instanceof F._CodeOrName?this.rhs.names:{}}},Wo=class extends wt{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 F.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Ar(this.rhs,t,r),this}get names(){let t=this.lhs instanceof F.Name?{}:{...this.lhs.names};return Qo(t,this.rhs)}},$a=class extends Wo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Sa=class extends wt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},xa=class extends wt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},ka=class extends wt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},za=class extends wt{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=Ar(this.code,t,r),this}get names(){return this.code instanceof F._CodeOrName?this.code.names:{}}},kn=class extends wt{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)||(rw(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>er(t,r.names),{})}},$t=class extends kn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Pa=class extends kn{},Or=class extends $t{};Or.kind="else";var Qt=class e extends $t{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 Or(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Tf(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=Ar(this.condition,t,r),this}get names(){let t=super.names;return Qo(t,this.condition),this.else&&er(t,this.else.names),t}};Qt.kind="if";var Xt=class extends $t{};Xt.kind="for";var Ta=class extends Xt{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=Ar(this.iteration,t,r),this}get names(){return er(super.names,this.iteration.names)}},Ra=class extends Xt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?ot.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=Qo(super.names,this.from);return Qo(t,this.to)}},Yo=class extends Xt{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=Ar(this.iterable,t,r),this}get names(){return er(super.names,this.iterable.names)}},zn=class extends $t{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)}};zn.kind="func";var Pn=class extends kn{render(t){return"return "+super.render(t)}};Pn.kind="return";var Ea=class extends $t{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&&er(t,this.catch.names),this.finally&&er(t,this.finally.names),t}},Tn=class extends $t{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Tn.kind="catch";var Rn=class extends $t{render(t){return"finally"+super.render(t)}};Rn.kind="finally";var Ia=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new ot.Scope({parent:t}),this._nodes=[new Pa]}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 wa(t,s,n)),s}const(t,r,n){return this._def(ot.varKinds.const,t,r,n)}let(t,r,n){return this._def(ot.varKinds.let,t,r,n)}var(t,r,n){return this._def(ot.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Wo(t,r,n))}add(t,r){return this._leafNode(new $a(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==F.nil&&this._leafNode(new za(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,F.addCodeArg)(r,o));return r.push("}"),new F._Code(r)}if(t,r,n){if(this._blockNode(new Qt(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 Qt(t))}else(){return this._elseNode(new Or)}endIf(){return this._endBlockNode(Qt,Or)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Ta(t),r)}forRange(t,r,n,o,s=this.opts.es5?ot.varKinds.var:ot.varKinds.let){let i=this._scope.toName(t);return this._for(new Ra(s,i,r,n),()=>o(i))}forOf(t,r,n,o=ot.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof F.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,F._)`${i}.length`,a=>{this.var(s,(0,F._)`${i}[${a}]`),n(s)})}return this._for(new Yo("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?ot.varKinds.var:ot.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,F._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new Yo("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Xt)}label(t){return this._leafNode(new Sa(t))}break(t){return this._leafNode(new xa(t))}return(t){let r=new Pn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Pn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ea;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new Tn(s),r(s)}return n&&(this._currNode=o.finally=new Rn,this.code(n)),this._endBlockNode(Tn,Rn)}throw(t){return this._leafNode(new ka(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=F.nil,n,o){return this._blockNode(new zn(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(zn)}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 Qt))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}};D.CodeGen=Ia;function er(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Qo(e,t){return t instanceof F._CodeOrName?er(e,t.names):e}function Ar(e,t,r){if(e instanceof F.Name)return n(e);if(!o(e))return e;return new F._Code(e._items.reduce((s,i)=>(i instanceof F.Name&&(i=n(i)),i instanceof F._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 F._Code&&s._items.some(i=>i instanceof F.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function rw(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Tf(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,F._)`!${Oa(e)}`}D.not=Tf;var nw=Rf(D.operators.AND);function ow(...e){return e.reduce(nw)}D.and=ow;var sw=Rf(D.operators.OR);function iw(...e){return e.reduce(sw)}D.or=iw;function Rf(e){return(t,r)=>t===F.nil?r:r===F.nil?t:(0,F._)`${Oa(t)} ${e} ${Oa(r)}`}function Oa(e){return e instanceof F.Name?e:(0,F._)`(${e})`}});var H=T(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;var re=U(),aw=xn();function cw(e){let t={};for(let r of e)t[r]=!0;return t}Z.toHash=cw;function uw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Of(e,t),!Af(t,e.self.RULES.all))}Z.alwaysValidSchema=uw;function Of(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]||jf(e,`unknown keyword: "${s}"`)}Z.checkUnknownRules=Of;function Af(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}Z.schemaHasRules=Af;function lw(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Z.schemaHasRulesButRef=lw;function dw({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,re._)`${r}`}return(0,re._)`${e}${t}${(0,re.getProperty)(n)}`}Z.schemaRefOrVal=dw;function pw(e){return Cf(decodeURIComponent(e))}Z.unescapeFragment=pw;function fw(e){return encodeURIComponent(Ca(e))}Z.escapeFragment=fw;function Ca(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=Ca;function Cf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=Cf;function mw(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}Z.eachItem=mw;function Ef({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof re.Name?(s instanceof re.Name?e(o,s,i):t(o,s,i),i):s instanceof re.Name?(t(o,i,s),s):r(s,i);return a===re.Name&&!(c instanceof re.Name)?n(o,c):c}}Z.mergeEvaluated={props:Ef({mergeNames:(e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,re._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,re._)`${r} || {}`).code((0,re._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,re._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,re._)`${r} || {}`),Na(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Nf}),items:Ef({mergeNames:(e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,re._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,re._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,re._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Nf(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,re._)`{}`);return t!==void 0&&Na(e,r,t),r}Z.evaluatedPropsToName=Nf;function Na(e,t,r){Object.keys(r).forEach(n=>e.assign((0,re._)`${t}${(0,re.getProperty)(n)}`,!0))}Z.setEvaluated=Na;var If={};function hw(e,t){return e.scopeValue("func",{ref:t,code:If[t.code]||(If[t.code]=new aw._Code(t.code))})}Z.useFunc=hw;var Aa;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Aa||(Z.Type=Aa={}));function gw(e,t,r){if(e instanceof re.Name){let n=t===Aa.Num;return r?n?(0,re._)`"[" + ${e} + "]"`:(0,re._)`"['" + ${e} + "']"`:n?(0,re._)`"/" + ${e}`:(0,re._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,re.getProperty)(e).toString():"/"+Ca(e)}Z.getErrorPath=gw;function jf(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Z.checkStrictMode=jf});var St=T(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var Re=U(),_w={data:new Re.Name("data"),valCxt:new Re.Name("valCxt"),instancePath:new Re.Name("instancePath"),parentData:new Re.Name("parentData"),parentDataProperty:new Re.Name("parentDataProperty"),rootData:new Re.Name("rootData"),dynamicAnchors:new Re.Name("dynamicAnchors"),vErrors:new Re.Name("vErrors"),errors:new Re.Name("errors"),this:new Re.Name("this"),self:new Re.Name("self"),scope:new Re.Name("scope"),json:new Re.Name("json"),jsonPos:new Re.Name("jsonPos"),jsonLen:new Re.Name("jsonLen"),jsonPart:new Re.Name("jsonPart")};ja.default=_w});var En=T(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.extendErrors=Ee.resetErrorsCount=Ee.reportExtraError=Ee.reportError=Ee.keyword$DataError=Ee.keywordError=void 0;var B=U(),es=H(),Ae=St();Ee.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};Ee.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function yw(e,t=Ee.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=Df(e,t,r);n??(i||a)?Mf(s,c):Uf(o,(0,B._)`[${c}]`)}Ee.reportError=yw;function vw(e,t=Ee.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=Df(e,t,r);Mf(o,a),s||i||Uf(n,Ae.default.vErrors)}Ee.reportExtraError=vw;function bw(e,t){e.assign(Ae.default.errors,t),e.if((0,B._)`${Ae.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Ae.default.vErrors}.length`,t),()=>e.assign(Ae.default.vErrors,null)))}Ee.resetErrorsCount=bw;function ww({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,Ae.default.errors,a=>{e.const(i,(0,B._)`${Ae.default.vErrors}[${a}]`),e.if((0,B._)`${i}.instancePath === undefined`,()=>e.assign((0,B._)`${i}.instancePath`,(0,B.strConcat)(Ae.default.instancePath,s.errorPath))),e.assign((0,B._)`${i}.schemaPath`,(0,B.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,B._)`${i}.schema`,r),e.assign((0,B._)`${i}.data`,n))})}Ee.extendErrors=ww;function Mf(e,t){let r=e.const("err",t);e.if((0,B._)`${Ae.default.vErrors} === null`,()=>e.assign(Ae.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Ae.default.vErrors}.push(${r})`),e.code((0,B._)`${Ae.default.errors}++`)}function Uf(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var tr={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function Df(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:$w(e,t,r)}function $w(e,t,r={}){let{gen:n,it:o}=e,s=[Sw(o,r),xw(e,r)];return kw(e,t,s),n.object(...s)}function Sw({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,es.getErrorPath)(t,es.Type.Str)}`:e;return[Ae.default.instancePath,(0,B.strConcat)(Ae.default.instancePath,r)]}function xw({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,B.str)`${t}/${e}`;return r&&(o=(0,B.str)`${o}${(0,es.getErrorPath)(r,es.Type.Str)}`),[tr.schemaPath,o]}function kw(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([tr.keyword,o],[tr.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([tr.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([tr.schema,i],[tr.parentSchema,(0,B._)`${u}${d}`],[Ae.default.data,s]),l&&n.push([tr.propertyName,l])}});var qf=T(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.boolOrEmptySchema=Cr.topBoolOrEmptySchema=void 0;var zw=En(),Pw=U(),Tw=St(),Rw={message:"boolean schema is false"};function Ew(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Zf(e,!1):typeof r=="object"&&r.$async===!0?t.return(Tw.default.data):(t.assign((0,Pw._)`${n}.errors`,null),t.return(!0))}Cr.topBoolOrEmptySchema=Ew;function Iw(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Zf(e)):r.var(t,!0)}Cr.boolOrEmptySchema=Iw;function Zf(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,zw.reportError)(o,Rw,void 0,t)}});var Ma=T(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.getRules=Nr.isJSONType=void 0;var Ow=["string","number","integer","boolean","null","object","array"],Aw=new Set(Ow);function Cw(e){return typeof e=="string"&&Aw.has(e)}Nr.isJSONType=Cw;function Nw(){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:{}}}Nr.getRules=Nw});var Ua=T(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.shouldUseRule=At.shouldUseGroup=At.schemaHasRulesForType=void 0;function jw({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Lf(e,n)}At.schemaHasRulesForType=jw;function Lf(e,t){return t.rules.some(r=>Ff(e,r))}At.shouldUseGroup=Lf;function Ff(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))}At.shouldUseRule=Ff});var In=T(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;var Mw=Ma(),Uw=Ua(),Dw=En(),M=U(),Vf=H(),jr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(jr||(Ie.DataType=jr={}));function Zw(e){let t=Hf(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}Ie.getSchemaTypes=Zw;function Hf(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Mw.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ie.getJSONTypes=Hf;function qw(e,t){let{gen:r,data:n,opts:o}=e,s=Lw(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Uw.schemaHasRulesForType)(e,t[0]));if(i){let a=Za(t,n,o.strictNumbers,jr.Wrong);r.if(a,()=>{s.length?Fw(e,t,s):qa(e)})}return i}Ie.coerceAndCheckDataType=qw;var Bf=new Set(["string","number","integer","boolean","null"]);function Lw(e,t){return t?e.filter(r=>Bf.has(r)||t==="array"&&r==="array"):[]}function Fw(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,M._)`typeof ${o}`),a=n.let("coerced",(0,M._)`undefined`);s.coerceTypes==="array"&&n.if((0,M._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,M._)`${o}[0]`).assign(i,(0,M._)`typeof ${o}`).if(Za(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,M._)`${a} !== undefined`);for(let l of r)(Bf.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),qa(e),n.endIf(),n.if((0,M._)`${a} !== undefined`,()=>{n.assign(o,a),Vw(e,a)});function c(l){switch(l){case"string":n.elseIf((0,M._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,M._)`"" + ${o}`).elseIf((0,M._)`${o} === null`).assign(a,(0,M._)`""`);return;case"number":n.elseIf((0,M._)`${i} == "boolean" || ${o} === null
5
5
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,M._)`+${o}`);return;case"integer":n.elseIf((0,M._)`${i} === "boolean" || ${o} === null
6
6
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,M._)`+${o}`);return;case"boolean":n.elseIf((0,M._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,M._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,M._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,M._)`${i} === "string" || ${i} === "number"
7
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,M._)`[${o}]`)}}}function Nb({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,M._)`${t} !== undefined`,()=>e.assign((0,M._)`${t}[${r}]`,n))}function Ma(e,t,r,n=Nr.Correct){let o=n===Nr.Correct?M.operators.EQ:M.operators.NEQ,s;switch(e){case"null":return(0,M._)`${t} ${o} null`;case"array":s=(0,M._)`Array.isArray(${t})`;break;case"object":s=(0,M._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,M._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,M._)`typeof ${t} ${o} ${e}`}return n===Nr.Correct?s:(0,M.not)(s);function i(a=M.nil){return(0,M.and)((0,M._)`typeof ${t} == "number"`,a,r?(0,M._)`isFinite(${t})`:M.nil)}}Ie.checkDataType=Ma;function Ua(e,t,r,n){if(e.length===1)return Ma(e[0],t,r,n);let o,s=(0,qf.toHash)(e);if(s.array&&s.object){let i=(0,M._)`typeof ${t} != "object"`;o=s.null?i:(0,M._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=M.nil;s.number&&delete s.integer;for(let i in s)o=(0,M.and)(o,Ma(i,t,r,n));return o}Ie.checkDataTypes=Ua;var jb={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,M._)`{type: ${e}}`:(0,M._)`{type: ${t}}`};function Da(e){let t=Mb(e);(0,Eb.reportError)(t,jb)}Ie.reportTypeError=Da;function Mb(e){let{gen:t,data:r,schema:n}=e,o=(0,qf.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Hf=T(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.assignDefaults=void 0;var jr=U(),Ub=H();function Db(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Vf(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Vf(e,s,o.default))}Xo.assignDefaults=Db;function Vf(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,jr._)`${s}${(0,jr.getProperty)(t)}`;if(o){(0,Ub.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,jr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,jr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,jr._)`${a} = ${(0,jr.stringify)(r)}`)}});var We=T(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.validateUnion=ee.validateArray=ee.usePattern=ee.callValidateCode=ee.schemaProperties=ee.allSchemaProperties=ee.noPropertyInData=ee.propertyInData=ee.isOwnProperty=ee.hasPropFunc=ee.reportMissingProp=ee.checkMissingProp=ee.checkReportMissingProp=void 0;var ue=U(),Za=H(),Ct=$t(),Zb=H();function qb(e,t){let{gen:r,data:n,it:o}=e;r.if(La(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ue._)`${t}`},!0),e.error()})}ee.checkReportMissingProp=qb;function Lb({gen:e,data:t,it:{opts:r}},n,o){return(0,ue.or)(...n.map(s=>(0,ue.and)(La(e,t,s,r.ownProperties),(0,ue._)`${o} = ${s}`)))}ee.checkMissingProp=Lb;function Fb(e,t){e.setParams({missingProperty:t},!0),e.error()}ee.reportMissingProp=Fb;function Bf(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}ee.hasPropFunc=Bf;function qa(e,t,r){return(0,ue._)`${Bf(e)}.call(${t}, ${r})`}ee.isOwnProperty=qa;function Vb(e,t,r,n){let o=(0,ue._)`${t}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${qa(e,t,r)}`:o}ee.propertyInData=Vb;function La(e,t,r,n){let o=(0,ue._)`${t}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(qa(e,t,r))):o}ee.noPropertyInData=La;function Kf(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ee.allSchemaProperties=Kf;function Hb(e,t){return Kf(t).filter(r=>!(0,Za.alwaysValidSchema)(e,t[r]))}ee.schemaProperties=Hb;function Bb({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,ue._)`${e}, ${t}, ${n}${o}`:t,d=[[Ct.default.instancePath,(0,ue.strConcat)(Ct.default.instancePath,s)],[Ct.default.parentData,i.parentData],[Ct.default.parentDataProperty,i.parentDataProperty],[Ct.default.rootData,Ct.default.rootData]];i.opts.dynamicRef&&d.push([Ct.default.dynamicAnchors,Ct.default.dynamicAnchors]);let f=(0,ue._)`${u}, ${r.object(...d)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${f})`:(0,ue._)`${a}(${f})`}ee.callValidateCode=Bb;var Kb=(0,ue._)`new RegExp`;function Jb({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,ue._)`${o.code==="new RegExp"?Kb:(0,Zb.useFunc)(e,o)}(${r}, ${n})`})}ee.usePattern=Jb;function Gb(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,ue._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Za.Type.Num},s),t.if((0,ue.not)(s),a)})}}ee.validateArray=Gb;function Wb(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,Za.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(i,(0,ue._)`${i} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,ue.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}ee.validateUnion=Wb});var Wf=T(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.validateKeywordUsage=lt.validSchemaType=lt.funcKeywordCode=lt.macroKeywordCode=void 0;var Ce=U(),rr=$t(),Yb=We(),Qb=Rn();function Xb(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=Gf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Ce.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}lt.macroKeywordCode=Xb;function e$(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;r$(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,u=Gf(n,o,l),d=n.let("valid");e.block$data(d,f),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function f(){if(t.errors===!1)g(),t.modifying&&Jf(e),y(()=>e.error());else{let b=t.async?m():h();t.modifying&&Jf(e),y(()=>t$(e,b))}}function m(){let b=n.let("ruleErrs",null);return n.try(()=>g((0,Ce._)`await `),S=>n.assign(d,!1).if((0,Ce._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,Ce._)`${S}.errors`),()=>n.throw(S))),b}function h(){let b=(0,Ce._)`${u}.errors`;return n.assign(b,null),g(Ce.nil),b}function g(b=t.async?(0,Ce._)`await `:Ce.nil){let S=c.opts.passContext?rr.default.this:rr.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Ce._)`${b}${(0,Yb.callValidateCode)(e,u,S,$)}`,t.modifying)}function y(b){var S;n.if((0,Ce.not)((S=t.valid)!==null&&S!==void 0?S:d),b)}}lt.funcKeywordCode=e$;function Jf(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ce._)`${n.parentData}[${n.parentDataProperty}]`))}function t$(e,t){let{gen:r}=e;r.if((0,Ce._)`Array.isArray(${t})`,()=>{r.assign(rr.default.vErrors,(0,Ce._)`${rr.default.vErrors} === null ? ${t} : ${rr.default.vErrors}.concat(${t})`).assign(rr.default.errors,(0,Ce._)`${rr.default.vErrors}.length`),(0,Qb.extendErrors)(e)},()=>e.error())}function r$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Gf(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,Ce.stringify)(r)})}function n$(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")}lt.validSchemaType=n$;function o$({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)}}lt.validateKeywordUsage=o$});var Qf=T(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.extendSubschemaMode=Nt.extendSubschemaData=Nt.getSubschema=void 0;var dt=U(),Yf=H();function s$(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,dt._)`${e.schemaPath}${(0,dt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,dt._)`${e.schemaPath}${(0,dt.getProperty)(t)}${(0,dt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Yf.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')}Nt.getSubschema=s$;function i$(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:l,dataPathArr:u,opts:d}=t,f=a.let("data",(0,dt._)`${t.data}${(0,dt.getProperty)(r)}`,!0);c(f),e.errorPath=(0,dt.str)`${l}${(0,Yf.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,dt._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof dt.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Nt.extendSubschemaData=i$;function a$(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}Nt.extendSubschemaMode=a$});var Fa=T((pA,Xf)=>{"use strict";Xf.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 tm=T((fA,em)=>{"use strict";var jt=em.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(){};es(t,n,o,e,"",e)};jt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};jt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};jt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};jt.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 es(e,t,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in jt.arrayKeywords)for(var f=0;f<d.length;f++)es(e,t,r,d[f],o+"/"+u+"/"+f,s,o,u,n,f)}else if(u in jt.propsKeywords){if(d&&typeof d=="object")for(var m in d)es(e,t,r,d[m],o+"/"+u+"/"+c$(m),s,o,u,n,m)}else(u in jt.keywords||e.allKeys&&!(u in jt.skipKeywords))&&es(e,t,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function c$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var In=T(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.getSchemaRefs=De.resolveUrl=De.normalizeId=De._getFullPath=De.getFullPath=De.inlineRef=void 0;var u$=H(),l$=Fa(),d$=tm(),p$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function f$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Va(e):t?rm(e)<=t:!1}De.inlineRef=f$;var m$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Va(e){for(let t in e){if(m$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Va)||typeof r=="object"&&Va(r))return!0}return!1}function rm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!p$.has(r)&&(typeof e[r]=="object"&&(0,u$.eachItem)(e[r],n=>t+=rm(n)),t===1/0))return 1/0}return t}function nm(e,t="",r){r!==!1&&(t=Mr(t));let n=e.parse(t);return om(e,n)}De.getFullPath=nm;function om(e,t){return e.serialize(t).split("#")[0]+"#"}De._getFullPath=om;var h$=/#\/?$/;function Mr(e){return e?e.replace(h$,""):""}De.normalizeId=Mr;function g$(e,t,r){return r=Mr(r),e.resolve(t,r)}De.resolveUrl=g$;var _$=/^[a-z_][-a-z0-9._]*$/i;function y$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Mr(e[r]||t),s={"":o},i=nm(n,o,!1),a={},c=new Set;return d$(e,{allKeys:!0},(d,f,m,h)=>{if(h===void 0)return;let g=i+f,y=s[h];typeof d[r]=="string"&&(y=b.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[f]=y;function b($){let P=this.opts.uriResolver.resolve;if($=Mr(y?P(y,$):$),c.has($))throw u($);c.add($);let v=this.refs[$];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(d,v.schema,$):$!==Mr(g)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=g),$}function S($){if(typeof $=="string"){if(!_$.test($))throw new Error(`invalid anchor "${$}"`);b.call(this,`#${$}`)}}}),a;function l(d,f,m){if(f!==void 0&&!l$(d,f))throw u(m)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}De.getSchemaRefs=y$});var Cn=T(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getData=Mt.KeywordCxt=Mt.validateFunctionCode=void 0;var um=Uf(),sm=En(),Ba=ja(),ts=En(),v$=Hf(),An=Wf(),Ha=Qf(),O=U(),j=$t(),w$=In(),St=H(),On=Rn();function b$(e){if(pm(e)&&(fm(e),dm(e))){x$(e);return}lm(e,()=>(0,um.topBoolOrEmptySchema)(e))}Mt.validateFunctionCode=b$;function lm({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,O._)`${j.default.data}, ${j.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${im(r,o)}`),S$(e,o),e.code(s)}):e.func(t,(0,O._)`${j.default.data}, ${$$(o)}`,n.$async,()=>e.code(im(r,o)).code(s))}function $$(e){return(0,O._)`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?(0,O._)`, ${j.default.dynamicAnchors}={}`:O.nil}}={}`}function S$(e,t){e.if(j.default.valCxt,()=>{e.var(j.default.instancePath,(0,O._)`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,(0,O._)`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,(0,O._)`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,(0,O._)`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef&&e.var(j.default.dynamicAnchors,(0,O._)`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{e.var(j.default.instancePath,(0,O._)`""`),e.var(j.default.parentData,(0,O._)`undefined`),e.var(j.default.parentDataProperty,(0,O._)`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef&&e.var(j.default.dynamicAnchors,(0,O._)`{}`)})}function x$(e){let{schema:t,opts:r,gen:n}=e;lm(e,()=>{r.$comment&&t.$comment&&hm(e),R$(e),n.let(j.default.vErrors,null),n.let(j.default.errors,0),r.unevaluated&&z$(e),mm(e),O$(e)})}function z$(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 im(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 k$(e,t){if(pm(e)&&(fm(e),dm(e))){P$(e,t);return}(0,um.boolOrEmptySchema)(e,t)}function dm({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 pm(e){return typeof e.schema!="boolean"}function P$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&hm(e),E$(e),I$(e);let s=n.const("_errs",j.default.errors);mm(e,s),n.var(t,(0,O._)`${s} === ${j.default.errors}`)}function fm(e){(0,St.checkUnknownRules)(e),T$(e)}function mm(e,t){if(e.opts.jtd)return am(e,[],!1,t);let r=(0,sm.getSchemaTypes)(e.schema),n=(0,sm.coerceAndCheckDataType)(e,r);am(e,r,!n,t)}function T$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,St.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function R$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,St.checkStrictMode)(e,"default is ignored in the schema root")}function E$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,w$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function I$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function hm({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,O._)`${j.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._)`${j.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function O$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,O._)`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw((0,O._)`new ${o}(${j.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,j.default.vErrors),s.unevaluated&&A$(e),t.return((0,O._)`${j.default.errors} === 0`))}function A$({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 am(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,St.schemaHasRulesButRef)(s,u))){o.block(()=>_m(e,"$ref",u.all.$ref.definition));return}c.jtd||C$(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ba.shouldUseGroup)(s,f)&&(f.type?(o.if((0,ts.checkDataType)(f.type,i,c.strictNumbers)),cm(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,ts.reportTypeError)(e)),o.endIf()):cm(e,f),a||o.if((0,O._)`${j.default.errors} === ${n||0}`))}}function cm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,v$.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,Ba.shouldUseRule)(n,s)&&_m(e,s.keyword,s.definition,t.type)})}function C$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(N$(e,t),e.opts.allowUnionTypes||j$(e,t),M$(e,e.dataTypes))}function N$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{gm(e.dataTypes,r)||Ka(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),D$(e,t)}}function j$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ka(e,"use allowUnionTypes to allow union type keyword")}function M$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ba.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>U$(t,i))&&Ka(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function U$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function gm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function D$(e,t){let r=[];for(let n of e.dataTypes)gm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ka(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,St.checkStrictMode)(e,t,e.opts.strictTypes)}var rs=class{constructor(t,r,n){if((0,An.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,St.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",ym(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,An.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",j.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?On.reportExtraError:On.reportError)(this,this.def.error,r)}$dataError(){(0,On.reportError)(this,this.def.$dataError||On.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,On.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,ts.checkDataTypes)(c,r,s.opts.strictNumbers,ts.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,Ha.getSubschema)(this.it,t);(0,Ha.extendSubschemaData)(n,this.it,t),(0,Ha.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return k$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=St.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=St.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}};Mt.KeywordCxt=rs;function _m(e,t,r,n){let o=new rs(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,An.funcKeywordCode)(o,r):"macro"in r?(0,An.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,An.funcKeywordCode)(o,r)}var Z$=/^\/(?:[^~]|~0|~1)*$/,q$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ym(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!Z$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=j.default.rootData}else{let l=q$.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(s=r[t-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,O._)`${s}${(0,O.getProperty)((0,St.unescapeJsonPointer)(l))}`,i=(0,O._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Mt.getData=ym});var ns=T(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Ja=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ga.default=Ja});var Nn=T(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var Wa=In(),Ya=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Wa.resolveUrl)(t,r,n),this.missingSchema=(0,Wa.normalizeId)((0,Wa.getFullPath)(t,this.missingRef))}};Qa.default=Ya});var ss=T(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.resolveSchema=Ye.getCompilingSchema=Ye.resolveRef=Ye.compileSchema=Ye.SchemaEnv=void 0;var st=U(),L$=ns(),nr=$t(),it=In(),vm=H(),F$=Cn(),Ur=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,it.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ye.SchemaEnv=Ur;function ec(e){let t=wm.call(this,e);if(t)return t;let r=(0,it.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new st.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:L$.default,code:(0,st._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:nr.default.data,parentData:nr.default.parentData,parentDataProperty:nr.default.parentDataProperty,dataNames:[nr.default.data],dataPathArr:[st.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,st.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:st.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,st._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,F$.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(nr.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let m=new Function(`${nr.default.self}`,`${nr.default.scope}`,u)(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}=l;m.evaluated={props:h instanceof st.Name?void 0:h,items:g instanceof st.Name?void 0:g,dynamicProps:h instanceof st.Name,dynamicItems:g instanceof st.Name},m.source&&(m.source.evaluated=(0,st.stringify)(m.evaluated))}return e.validate=m,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}Ye.compileSchema=ec;function V$(e,t,r){var n;r=(0,it.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=K$.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 Ur({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=H$.call(this,s)}Ye.resolveRef=V$;function H$(e){return(0,it.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ec.call(this,e)}function wm(e){for(let t of this._compilations)if(B$(t,e))return t}Ye.getCompilingSchema=wm;function B$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function K$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||os.call(this,e,t)}function os(e,t){let r=this.opts.uriResolver.parse(t),n=(0,it._getFullPath)(this.opts.uriResolver,r),o=(0,it.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Xa.call(this,r,e);let s=(0,it.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=os.call(this,e,i);return typeof a?.schema!="object"?void 0:Xa.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ec.call(this,i),s===(0,it.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,it.resolveUrl)(this.opts.uriResolver,o,l)),new Ur({schema:a,schemaId:c,root:e,baseId:o})}return Xa.call(this,r,i)}}Ye.resolveSchema=os;var J$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Xa(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,vm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!J$.has(a)&&l&&(t=(0,it.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,vm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,it.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=os.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ur({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var bm=T((vA,G$)=>{G$.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 nc=T((wA,Pm)=>{"use strict";var W$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Sm=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),tc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),xm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Y$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function rc(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 Q$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $m(e){return e.length=0,!0}function X$(e,t,r){if(e.length){let n=rc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function e0(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=X$;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){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(l==="%"){if(!a(o,n,r))break;a=$m}else{o.push(l);continue}}return o.length&&(a===$m?r.zone=o.join(""):i?n.push(o.join("")):n.push(rc(o))),r.address=n.join(""),r}function zm(e){if(t0(e,":")<2)return{host:e,isIPV6:!1};let t=e0(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 t0(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function r0(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 n0={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},o0=/[@/?#:]/g,s0=/[@/?#]/g;function km(e,t){let r=t?s0:o0;return r.lastIndex=0,e.replace(r,n=>n0[n])}function i0(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(tc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&xm(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function a0(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(tc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&xm(s)?t+=s:t+="%"+o,r+=2;continue}}Y$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function c0(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(tc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function u0(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Sm(r)){let n=zm(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}Pm.exports={nonSimpleDomain:Q$,recomposeAuthority:u0,reescapeHostDelimiters:km,normalizePercentEncoding:i0,normalizePathEncoding:a0,escapePreservingEscapes:c0,removeDotSegments:r0,isIPv4:Sm,isUUID:W$,normalizeIPv6:zm,stringArrayToHexStripped:rc}});var Om=T((bA,Im)=>{"use strict";var{isUUID:l0}=nc(),d0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,p0=["http","https","ws","wss","urn","urn:uuid"];function f0(e){return p0.indexOf(e)!==-1}function oc(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 Tm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Rm(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 m0(e){return e.secure=oc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function h0(e){if((e.port===(oc(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 g0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(d0);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=sc(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function _0(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=sc(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 y0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!l0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function v0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Em={scheme:"http",domainHost:!0,parse:Tm,serialize:Rm},w0={scheme:"https",domainHost:Em.domainHost,parse:Tm,serialize:Rm},is={scheme:"ws",domainHost:!0,parse:m0,serialize:h0},b0={scheme:"wss",domainHost:is.domainHost,parse:is.parse,serialize:is.serialize},$0={scheme:"urn",parse:g0,serialize:_0,skipNormalize:!0},S0={scheme:"urn:uuid",parse:y0,serialize:v0,skipNormalize:!0},as={http:Em,https:w0,ws:is,wss:b0,urn:$0,"urn:uuid":S0};Object.setPrototypeOf(as,null);function sc(e){return e&&(as[e]||as[e.toLowerCase()])||void 0}Im.exports={wsIsSecure:oc,SCHEMES:as,isValidSchemeName:f0,getSchemeHandler:sc}});var Um=T(($A,cs)=>{"use strict";var{normalizeIPv6:x0,removeDotSegments:jn,recomposeAuthority:z0,normalizePercentEncoding:k0,normalizePathEncoding:P0,escapePreservingEscapes:T0,reescapeHostDelimiters:R0,isIPv4:E0,nonSimpleDomain:I0}=nc(),{SCHEMES:O0,getSchemeHandler:Cm}=Om();function A0(e,t){return typeof e=="string"?e=D0(e,t):typeof e=="object"&&(e=Dr(or(e,t),t)),e}function C0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Nm(Dr(e,n),Dr(t,n),n,!0);return n.skipEscape=!0,or(o,n)}function Nm(e,t,r,n){let o={};return n||(e=Dr(or(e,r),r),t=Dr(or(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=jn(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=jn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=jn(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=jn(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 N0(e,t,r){let n=Am(e,r),o=Am(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function or(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=Cm(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=k0(r.path):(r.path=T0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=z0(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=jn(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 j0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,M0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function U0(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 jm(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(M0);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=e.match(j0);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=U0(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(E0(n.host)===!1){let d=x0(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 l=Cm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&s===!1&&I0(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!l||l&&!l.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=R0(unescape(n.host),s))),n.path&&(n.path=P0(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Dr(e,t){return jm(e,t).parsed}function D0(e,t){return Mm(e,t).normalized}function Mm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=jm(e,t);return{normalized:n?e:or(r,t),malformedAuthorityOrPort:n}}function Am(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Mm(e,t);return n?void 0:r}if(typeof e=="object")return or(e,t)}var ic={SCHEMES:O0,normalize:A0,resolve:C0,resolveComponent:Nm,equal:N0,serialize:or,parse:Dr};cs.exports=ic;cs.exports.default=ic;cs.exports.fastUri=ic});var Zm=T(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Dm=Um();Dm.code='require("ajv/dist/runtime/uri").default';ac.default=Dm});var Jm=T(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.CodeGen=xe.Name=xe.nil=xe.stringify=xe.str=xe._=xe.KeywordCxt=void 0;var Z0=Cn();Object.defineProperty(xe,"KeywordCxt",{enumerable:!0,get:function(){return Z0.KeywordCxt}});var Zr=U();Object.defineProperty(xe,"_",{enumerable:!0,get:function(){return Zr._}});Object.defineProperty(xe,"str",{enumerable:!0,get:function(){return Zr.str}});Object.defineProperty(xe,"stringify",{enumerable:!0,get:function(){return Zr.stringify}});Object.defineProperty(xe,"nil",{enumerable:!0,get:function(){return Zr.nil}});Object.defineProperty(xe,"Name",{enumerable:!0,get:function(){return Zr.Name}});Object.defineProperty(xe,"CodeGen",{enumerable:!0,get:function(){return Zr.CodeGen}});var q0=ns(),Hm=Nn(),L0=Na(),Mn=ss(),F0=U(),Un=In(),us=En(),uc=H(),qm=bm(),V0=Zm(),Bm=(e,t)=>new RegExp(e,t);Bm.code="new RegExp";var H0=["removeAdditional","useDefaults","coerceTypes"],B0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),K0={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."},J0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Lm=200;function G0(e){var t,r,n,o,s,i,a,c,l,u,d,f,m,h,g,y,b,S,$,P,v,x,R,L,Y;let me=e.strict,Le=(t=e.code)===null||t===void 0?void 0:t.optimize,gr=Le===!0||Le===void 0?1:Le||0,Tt=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Bm,Ne=(o=e.uriResolver)!==null&&o!==void 0?o:V0.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:me)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:me)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:me)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:me)!==null&&f!==void 0?f:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:me)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:gr,regExp:Tt}:{optimize:gr,regExp:Tt},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Lm,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:Lm,meta:(b=e.meta)!==null&&b!==void 0?b:!0,messages:(S=e.messages)!==null&&S!==void 0?S:!0,inlineRefs:($=e.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(v=e.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(x=e.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(R=e.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(L=e.unicodeRegExp)!==null&&L!==void 0?L:!0,int32range:(Y=e.int32range)!==null&&Y!==void 0?Y:!0,uriResolver:Ne}}var Dn=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,...G0(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new F0.ValueScope({scope:{},prefixes:B0,es5:r,lines:n}),this.logger=tS(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,L0.getRules)(),Fm.call(this,K0,t,"NOT SUPPORTED"),Fm.call(this,J0,t,"DEPRECATED","warn"),this._metaOpts=X0.call(this),t.formats&&Y0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Q0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),W0.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=qm;n==="id"&&(o={...qm},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(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||i.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Hm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}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,Un.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=Vm.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Mn.SchemaEnv({schema:{},schemaId:n});if(r=Mn.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=Vm.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,Un.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(nS.call(this,n,r),!r)return(0,uc.eachItem)(n,s=>cc.call(this,s)),this;sS.call(this,r);let o={...r,type:(0,us.getJSONTypes)(r.type),schemaType:(0,us.getJSONTypes)(r.schemaType)};return(0,uc.eachItem)(n,o.type.length===0?s=>cc.call(this,s,o):s=>o.type.forEach(i=>cc.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:l}=c.definition,u=i[a];l&&u&&(i[a]=Km(u))}}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,Un.normalizeId)(i||n);let l=Un.getSchemaRefs.call(this,t,n);return c=new Mn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),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):Mn.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{Mn.compileSchema.call(this,t)}finally{this.opts=r}}};Dn.ValidationError=q0.default;Dn.MissingRefError=Hm.default;xe.default=Dn;function Fm(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 Vm(e){return e=(0,Un.normalizeId)(e),this.schemas[e]||this.refs[e]}function W0(){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 Y0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Q0(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 X0(){let e={...this.opts};for(let t of H0)delete e[t];return e}var eS={log(){},warn(){},error(){}};function tS(e){if(e===!1)return eS;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 rS=/^[a-z_$][a-z0-9_$:-]*$/i;function nS(e,t){let{RULES:r}=this;if((0,uc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!rS.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 cc(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,us.getJSONTypes)(t.type),schemaType:(0,us.getJSONTypes)(t.schemaType)}};t.before?oS.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 oS(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 sS(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Km(t)),e.validateSchema=this.compile(t,!0))}var iS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Km(e){return{anyOf:[e,iS]}}});var Gm=T(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var aS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lc.default=aS});var Xm=T(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.callRef=sr.getValidate=void 0;var cS=Nn(),Wm=We(),Ze=U(),qr=$t(),Ym=ss(),ls=H(),uS={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:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=Ym.resolveRef.call(c,l,o,r);if(u===void 0)throw new cS.default(n.opts.uriResolver,o,r);if(u instanceof Ym.SchemaEnv)return f(u);return m(u);function d(){if(s===l)return ds(e,i,s,s.$async);let h=t.scopeValue("root",{ref:l});return ds(e,(0,Ze._)`${h}.validate`,l,l.$async)}function f(h){let g=Qm(e,h);ds(e,g,h,h.$async)}function m(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Ze.stringify)(h)}:{ref:h}),y=t.name("valid"),b=e.subschema({schema:h,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(b),e.ok(y)}}};function Qm(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ze._)`${r.scopeValue("wrapper",{ref:t})}.validate`}sr.getValidate=Qm;function ds(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?qr.default.this:Ze.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Ze._)`await ${(0,Wm.callValidateCode)(e,t,l)}`),m(t),i||o.assign(h,!0)},g=>{o.if((0,Ze._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),f(g),i||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,Wm.callValidateCode)(e,t,l),()=>m(t),()=>f(t))}function f(h){let g=(0,Ze._)`${h}.errors`;o.assign(qr.default.vErrors,(0,Ze._)`${qr.default.vErrors} === null ? ${g} : ${qr.default.vErrors}.concat(${g})`),o.assign(qr.default.errors,(0,Ze._)`${qr.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=ls.mergeEvaluated.props(o,y.props,s.props));else{let b=o.var("props",(0,Ze._)`${h}.evaluated.props`);s.props=ls.mergeEvaluated.props(o,b,s.props,Ze.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ls.mergeEvaluated.items(o,y.items,s.items));else{let b=o.var("items",(0,Ze._)`${h}.evaluated.items`);s.items=ls.mergeEvaluated.items(o,b,s.items,Ze.Name)}}}sr.callRef=ds;sr.default=uS});var eh=T(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var lS=Gm(),dS=Xm(),pS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",lS.default,dS.default];dc.default=pS});var th=T(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var ps=U(),Ut=ps.operators,fs={maximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},minimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},exclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},exclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},fS={message:({keyword:e,schemaCode:t})=>(0,ps.str)`must be ${fs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ps._)`{comparison: ${fs[e].okStr}, limit: ${t}}`},mS={keyword:Object.keys(fs),type:"number",schemaType:"number",$data:!0,error:fS,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ps._)`${r} ${fs[t].fail} ${n} || isNaN(${r})`)}};pc.default=mS});var rh=T(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Zn=U(),hS={message:({schemaCode:e})=>(0,Zn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Zn._)`{multipleOf: ${e}}`},gS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:hS,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,Zn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Zn._)`${i} !== parseInt(${i})`;e.fail$data((0,Zn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};fc.default=gS});var oh=T(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});function nh(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}mc.default=nh;nh.code='require("ajv/dist/runtime/ucs2length").default'});var sh=T(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var ir=U(),_S=H(),yS=oh(),vS={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,ir.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,ir._)`{limit: ${e}}`},wS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:vS,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?ir.operators.GT:ir.operators.LT,i=o.opts.unicode===!1?(0,ir._)`${r}.length`:(0,ir._)`${(0,_S.useFunc)(e.gen,yS.default)}(${r})`;e.fail$data((0,ir._)`${i} ${s} ${n}`)}};hc.default=wS});var ih=T(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var bS=We(),$S=H(),Lr=U(),SS={message:({schemaCode:e})=>(0,Lr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Lr._)`{pattern: ${e}}`},xS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:SS,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,l=c.code==="new RegExp"?(0,Lr._)`new RegExp`:(0,$S.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,Lr._)`${l}(${s}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,Lr._)`!${u}`)}else{let c=(0,bS.usePattern)(e,o);e.fail$data((0,Lr._)`!${c}.test(${r})`)}}};gc.default=xS});var ah=T(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var qn=U(),zS={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,qn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,qn._)`{limit: ${e}}`},kS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:zS,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?qn.operators.GT:qn.operators.LT;e.fail$data((0,qn._)`Object.keys(${r}).length ${o} ${n}`)}};_c.default=kS});var ch=T(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Ln=We(),Fn=U(),PS=H(),TS={message:({params:{missingProperty:e}})=>(0,Fn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Fn._)`{missingProperty: ${e}}`},RS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:TS,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?l():u(),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,b=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,PS.checkStrictMode)(i,b,i.opts.strictRequired)}}function l(){if(c||s)e.block$data(Fn.nil,d);else for(let m of r)(0,Ln.checkReportMissingProp)(e,m)}function u(){let m=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>f(m,h)),e.ok(h)}else t.if((0,Ln.checkMissingProp)(e,r,m)),(0,Ln.reportMissingProp)(e,m),t.else()}function d(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,Ln.noPropertyInData)(t,o,m,a.ownProperties),()=>e.error())})}function f(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,Ln.propertyInData)(t,o,m,a.ownProperties)),t.if((0,Fn.not)(h),()=>{e.error(),t.break()})},Fn.nil)}}};yc.default=RS});var uh=T(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var Vn=U(),ES={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Vn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Vn._)`{limit: ${e}}`},IS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ES,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Vn.operators.GT:Vn.operators.LT;e.fail$data((0,Vn._)`${r}.length ${o} ${n}`)}};vc.default=IS});var ms=T(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var lh=Fa();lh.code='require("ajv/dist/runtime/equal").default';wc.default=lh});var dh=T($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var bc=En(),ze=U(),OS=H(),AS=ms(),CS={message:({params:{i:e,j:t}})=>(0,ze.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ze._)`{i: ${e}, j: ${t}}`},NS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:CS,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"),l=s.items?(0,bc.getSchemaTypes)(s.items):[];e.block$data(c,u,(0,ze._)`${i} === false`),e.ok(c);function u(){let h=t.let("i",(0,ze._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,ze._)`${h} > 1`,()=>(d()?f:m)(h,g))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,g){let y=t.name("item"),b=(0,bc.checkDataTypes)(l,y,a.opts.strictNumbers,bc.DataType.Wrong),S=t.const("indices",(0,ze._)`{}`);t.for((0,ze._)`;${h}--;`,()=>{t.let(y,(0,ze._)`${r}[${h}]`),t.if(b,(0,ze._)`continue`),l.length>1&&t.if((0,ze._)`typeof ${y} == "string"`,(0,ze._)`${y} += "_"`),t.if((0,ze._)`typeof ${S}[${y}] == "number"`,()=>{t.assign(g,(0,ze._)`${S}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ze._)`${S}[${y}] = ${h}`)})}function m(h,g){let y=(0,OS.useFunc)(t,AS.default),b=t.name("outer");t.label(b).for((0,ze._)`;${h}--;`,()=>t.for((0,ze._)`${g} = ${h}; ${g}--;`,()=>t.if((0,ze._)`${y}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(b)})))}}};$c.default=NS});var ph=T(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Sc=U(),jS=H(),MS=ms(),US={message:"must be equal to constant",params:({schemaCode:e})=>(0,Sc._)`{allowedValue: ${e}}`},DS={keyword:"const",$data:!0,error:US,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Sc._)`!${(0,jS.useFunc)(t,MS.default)}(${r}, ${o})`):e.fail((0,Sc._)`${s} !== ${r}`)}};xc.default=DS});var fh=T(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var Hn=U(),ZS=H(),qS=ms(),LS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Hn._)`{allowedValues: ${e}}`},FS={keyword:"enum",schemaType:"array",$data:!0,error:LS,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,l=()=>c??(c=(0,ZS.useFunc)(t,qS.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=t.const("vSchema",s);u=(0,Hn.or)(...o.map((h,g)=>f(m,g)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",s,m=>t.if((0,Hn._)`${l()}(${r}, ${m})`,()=>t.assign(u,!0).break()))}function f(m,h){let g=o[h];return typeof g=="object"&&g!==null?(0,Hn._)`${l()}(${r}, ${m}[${h}])`:(0,Hn._)`${r} === ${g}`}}};zc.default=FS});var mh=T(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var VS=th(),HS=rh(),BS=sh(),KS=ih(),JS=ah(),GS=ch(),WS=uh(),YS=dh(),QS=ph(),XS=fh(),ex=[VS.default,HS.default,BS.default,KS.default,JS.default,GS.default,WS.default,YS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},QS.default,XS.default];kc.default=ex});var Tc=T(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.validateAdditionalItems=void 0;var ar=U(),Pc=H(),tx={message:({params:{len:e}})=>(0,ar.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ar._)`{limit: ${e}}`},rx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:tx,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Pc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}hh(e,n)}};function hh(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,ar._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,ar._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Pc.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,ar._)`${a} <= ${t.length}`);r.if((0,ar.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:s,dataProp:u,dataPropType:Pc.Type.Num},l),i.allErrors||r.if((0,ar.not)(l),()=>r.break())})}}Bn.validateAdditionalItems=hh;Bn.default=rx});var Rc=T(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.validateTuple=void 0;var gh=U(),hs=H(),nx=We(),ox={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return _h(e,"additionalItems",t);r.items=!0,!(0,hs.alwaysValidSchema)(r,t)&&e.ok((0,nx.validateArray)(e))}};function _h(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=hs.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,gh._)`${s}.length`);r.forEach((d,f)=>{(0,hs.alwaysValidSchema)(a,d)||(n.if((0,gh._)`${l} > ${f}`,()=>e.subschema({keyword:i,schemaProp:f,dataProp:f},c)),e.ok(c))});function u(d){let{opts:f,errSchemaPath:m}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(f.strictTuples&&!g){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,hs.checkStrictMode)(a,y,f.strictTuples)}}}Kn.validateTuple=_h;Kn.default=ox});var yh=T(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var sx=Rc(),ix={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,sx.validateTuple)(e,"items")};Ec.default=ix});var wh=T(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var vh=U(),ax=H(),cx=We(),ux=Tc(),lx={message:({params:{len:e}})=>(0,vh.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,vh._)`{limit: ${e}}`},dx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:lx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,ax.alwaysValidSchema)(n,t)&&(o?(0,ux.validateAdditionalItems)(e,o):e.ok((0,cx.validateArray)(e)))}};Ic.default=dx});var bh=T(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Qe=U(),gs=H(),px={message:({params:{min:e,max:t}})=>t===void 0?(0,Qe.str)`must contain at least ${e} valid item(s)`:(0,Qe.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Qe._)`{minContains: ${e}}`:(0,Qe._)`{minContains: ${e}, maxContains: ${t}}`},fx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:px,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=t.const("len",(0,Qe._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,gs.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gs.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,gs.alwaysValidSchema)(s,r)){let g=(0,Qe._)`${u} >= ${i}`;a!==void 0&&(g=(0,Qe._)`${g} && ${u} <= ${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,Qe._)`${o}.length > 0`,f)):(t.let(d,!1),f()),e.result(d,()=>e.reset());function f(){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,u,b=>{e.subschema({keyword:"contains",dataProp:b,dataPropType:gs.Type.Num,compositeRule:!0},g),y()})}function h(g){t.code((0,Qe._)`${g}++`),a===void 0?t.if((0,Qe._)`${g} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,Qe._)`${g} > ${a}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,Qe._)`${g} >= ${i}`,()=>t.assign(d,!0)))}}};Oc.default=fx});var xh=T(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.validateSchemaDeps=pt.validatePropertyDeps=pt.error=void 0;var Ac=U(),mx=H(),Jn=We();pt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Ac.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Ac._)`{property: ${e},
7
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,M._)`[${o}]`)}}}function Vw({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,M._)`${t} !== undefined`,()=>e.assign((0,M._)`${t}[${r}]`,n))}function Da(e,t,r,n=jr.Correct){let o=n===jr.Correct?M.operators.EQ:M.operators.NEQ,s;switch(e){case"null":return(0,M._)`${t} ${o} null`;case"array":s=(0,M._)`Array.isArray(${t})`;break;case"object":s=(0,M._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,M._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,M._)`typeof ${t} ${o} ${e}`}return n===jr.Correct?s:(0,M.not)(s);function i(a=M.nil){return(0,M.and)((0,M._)`typeof ${t} == "number"`,a,r?(0,M._)`isFinite(${t})`:M.nil)}}Ie.checkDataType=Da;function Za(e,t,r,n){if(e.length===1)return Da(e[0],t,r,n);let o,s=(0,Vf.toHash)(e);if(s.array&&s.object){let i=(0,M._)`typeof ${t} != "object"`;o=s.null?i:(0,M._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=M.nil;s.number&&delete s.integer;for(let i in s)o=(0,M.and)(o,Da(i,t,r,n));return o}Ie.checkDataTypes=Za;var Hw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,M._)`{type: ${e}}`:(0,M._)`{type: ${t}}`};function qa(e){let t=Bw(e);(0,Dw.reportError)(t,Hw)}Ie.reportTypeError=qa;function Bw(e){let{gen:t,data:r,schema:n}=e,o=(0,Vf.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Jf=T(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.assignDefaults=void 0;var Mr=U(),Kw=H();function Jw(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Kf(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Kf(e,s,o.default))}ts.assignDefaults=Jw;function Kf(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,Mr._)`${s}${(0,Mr.getProperty)(t)}`;if(o){(0,Kw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Mr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Mr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Mr._)`${a} = ${(0,Mr.stringify)(r)}`)}});var We=T(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.validateUnion=ee.validateArray=ee.usePattern=ee.callValidateCode=ee.schemaProperties=ee.allSchemaProperties=ee.noPropertyInData=ee.propertyInData=ee.isOwnProperty=ee.hasPropFunc=ee.reportMissingProp=ee.checkMissingProp=ee.checkReportMissingProp=void 0;var ue=U(),La=H(),Ct=St(),Gw=H();function Ww(e,t){let{gen:r,data:n,it:o}=e;r.if(Va(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ue._)`${t}`},!0),e.error()})}ee.checkReportMissingProp=Ww;function Yw({gen:e,data:t,it:{opts:r}},n,o){return(0,ue.or)(...n.map(s=>(0,ue.and)(Va(e,t,s,r.ownProperties),(0,ue._)`${o} = ${s}`)))}ee.checkMissingProp=Yw;function Qw(e,t){e.setParams({missingProperty:t},!0),e.error()}ee.reportMissingProp=Qw;function Gf(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}ee.hasPropFunc=Gf;function Fa(e,t,r){return(0,ue._)`${Gf(e)}.call(${t}, ${r})`}ee.isOwnProperty=Fa;function Xw(e,t,r,n){let o=(0,ue._)`${t}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${Fa(e,t,r)}`:o}ee.propertyInData=Xw;function Va(e,t,r,n){let o=(0,ue._)`${t}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(Fa(e,t,r))):o}ee.noPropertyInData=Va;function Wf(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ee.allSchemaProperties=Wf;function e$(e,t){return Wf(t).filter(r=>!(0,La.alwaysValidSchema)(e,t[r]))}ee.schemaProperties=e$;function t$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,ue._)`${e}, ${t}, ${n}${o}`:t,d=[[Ct.default.instancePath,(0,ue.strConcat)(Ct.default.instancePath,s)],[Ct.default.parentData,i.parentData],[Ct.default.parentDataProperty,i.parentDataProperty],[Ct.default.rootData,Ct.default.rootData]];i.opts.dynamicRef&&d.push([Ct.default.dynamicAnchors,Ct.default.dynamicAnchors]);let f=(0,ue._)`${u}, ${r.object(...d)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${f})`:(0,ue._)`${a}(${f})`}ee.callValidateCode=t$;var r$=(0,ue._)`new RegExp`;function n$({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,ue._)`${o.code==="new RegExp"?r$:(0,Gw.useFunc)(e,o)}(${r}, ${n})`})}ee.usePattern=n$;function o$(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,ue._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:La.Type.Num},s),t.if((0,ue.not)(s),a)})}}ee.validateArray=o$;function s$(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,La.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(i,(0,ue._)`${i} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,ue.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}ee.validateUnion=s$});var Xf=T(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.validateKeywordUsage=lt.validSchemaType=lt.funcKeywordCode=lt.macroKeywordCode=void 0;var Ce=U(),rr=St(),i$=We(),a$=En();function c$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=Qf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Ce.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}lt.macroKeywordCode=c$;function u$(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;d$(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,u=Qf(n,o,l),d=n.let("valid");e.block$data(d,f),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function f(){if(t.errors===!1)g(),t.modifying&&Yf(e),y(()=>e.error());else{let w=t.async?m():h();t.modifying&&Yf(e),y(()=>l$(e,w))}}function m(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,Ce._)`await `),S=>n.assign(d,!1).if((0,Ce._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Ce._)`${S}.errors`),()=>n.throw(S))),w}function h(){let w=(0,Ce._)`${u}.errors`;return n.assign(w,null),g(Ce.nil),w}function g(w=t.async?(0,Ce._)`await `:Ce.nil){let S=c.opts.passContext?rr.default.this:rr.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,Ce._)`${w}${(0,i$.callValidateCode)(e,u,S,$)}`,t.modifying)}function y(w){var S;n.if((0,Ce.not)((S=t.valid)!==null&&S!==void 0?S:d),w)}}lt.funcKeywordCode=u$;function Yf(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ce._)`${n.parentData}[${n.parentDataProperty}]`))}function l$(e,t){let{gen:r}=e;r.if((0,Ce._)`Array.isArray(${t})`,()=>{r.assign(rr.default.vErrors,(0,Ce._)`${rr.default.vErrors} === null ? ${t} : ${rr.default.vErrors}.concat(${t})`).assign(rr.default.errors,(0,Ce._)`${rr.default.vErrors}.length`),(0,a$.extendErrors)(e)},()=>e.error())}function d$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Qf(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,Ce.stringify)(r)})}function p$(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")}lt.validSchemaType=p$;function f$({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)}}lt.validateKeywordUsage=f$});var tm=T(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.extendSubschemaMode=Nt.extendSubschemaData=Nt.getSubschema=void 0;var dt=U(),em=H();function m$(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,dt._)`${e.schemaPath}${(0,dt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,dt._)`${e.schemaPath}${(0,dt.getProperty)(t)}${(0,dt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,em.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')}Nt.getSubschema=m$;function h$(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:l,dataPathArr:u,opts:d}=t,f=a.let("data",(0,dt._)`${t.data}${(0,dt.getProperty)(r)}`,!0);c(f),e.errorPath=(0,dt.str)`${l}${(0,em.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,dt._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof dt.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Nt.extendSubschemaData=h$;function g$(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}Nt.extendSubschemaMode=g$});var Ha=T((RA,rm)=>{"use strict";rm.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 om=T((EA,nm)=>{"use strict";var jt=nm.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(){};rs(t,n,o,e,"",e)};jt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};jt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};jt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};jt.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 rs(e,t,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in jt.arrayKeywords)for(var f=0;f<d.length;f++)rs(e,t,r,d[f],o+"/"+u+"/"+f,s,o,u,n,f)}else if(u in jt.propsKeywords){if(d&&typeof d=="object")for(var m in d)rs(e,t,r,d[m],o+"/"+u+"/"+_$(m),s,o,u,n,m)}else(u in jt.keywords||e.allKeys&&!(u in jt.skipKeywords))&&rs(e,t,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function _$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var On=T(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var y$=H(),v$=Ha(),b$=om(),w$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Ba(e):t?sm(e)<=t:!1}Ze.inlineRef=$$;var S$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ba(e){for(let t in e){if(S$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Ba)||typeof r=="object"&&Ba(r))return!0}return!1}function sm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!w$.has(r)&&(typeof e[r]=="object"&&(0,y$.eachItem)(e[r],n=>t+=sm(n)),t===1/0))return 1/0}return t}function im(e,t="",r){r!==!1&&(t=Ur(t));let n=e.parse(t);return am(e,n)}Ze.getFullPath=im;function am(e,t){return e.serialize(t).split("#")[0]+"#"}Ze._getFullPath=am;var x$=/#\/?$/;function Ur(e){return e?e.replace(x$,""):""}Ze.normalizeId=Ur;function k$(e,t,r){return r=Ur(r),e.resolve(t,r)}Ze.resolveUrl=k$;var z$=/^[a-z_][-a-z0-9._]*$/i;function P$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Ur(e[r]||t),s={"":o},i=im(n,o,!1),a={},c=new Set;return b$(e,{allKeys:!0},(d,f,m,h)=>{if(h===void 0)return;let g=i+f,y=s[h];typeof d[r]=="string"&&(y=w.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[f]=y;function w($){let P=this.opts.uriResolver.resolve;if($=Ur(y?P(y,$):$),c.has($))throw u($);c.add($);let v=this.refs[$];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(d,v.schema,$):$!==Ur(g)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=g),$}function S($){if(typeof $=="string"){if(!z$.test($))throw new Error(`invalid anchor "${$}"`);w.call(this,`#${$}`)}}}),a;function l(d,f,m){if(f!==void 0&&!v$(d,f))throw u(m)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ze.getSchemaRefs=P$});var Nn=T(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getData=Mt.KeywordCxt=Mt.validateFunctionCode=void 0;var pm=qf(),cm=In(),Ja=Ua(),ns=In(),T$=Jf(),Cn=Xf(),Ka=tm(),O=U(),j=St(),R$=On(),xt=H(),An=En();function E$(e){if(hm(e)&&(gm(e),mm(e))){A$(e);return}fm(e,()=>(0,pm.topBoolOrEmptySchema)(e))}Mt.validateFunctionCode=E$;function fm({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,O._)`${j.default.data}, ${j.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${um(r,o)}`),O$(e,o),e.code(s)}):e.func(t,(0,O._)`${j.default.data}, ${I$(o)}`,n.$async,()=>e.code(um(r,o)).code(s))}function I$(e){return(0,O._)`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?(0,O._)`, ${j.default.dynamicAnchors}={}`:O.nil}}={}`}function O$(e,t){e.if(j.default.valCxt,()=>{e.var(j.default.instancePath,(0,O._)`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,(0,O._)`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,(0,O._)`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,(0,O._)`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef&&e.var(j.default.dynamicAnchors,(0,O._)`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{e.var(j.default.instancePath,(0,O._)`""`),e.var(j.default.parentData,(0,O._)`undefined`),e.var(j.default.parentDataProperty,(0,O._)`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef&&e.var(j.default.dynamicAnchors,(0,O._)`{}`)})}function A$(e){let{schema:t,opts:r,gen:n}=e;fm(e,()=>{r.$comment&&t.$comment&&ym(e),U$(e),n.let(j.default.vErrors,null),n.let(j.default.errors,0),r.unevaluated&&C$(e),_m(e),q$(e)})}function C$(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 um(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 N$(e,t){if(hm(e)&&(gm(e),mm(e))){j$(e,t);return}(0,pm.boolOrEmptySchema)(e,t)}function mm({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 hm(e){return typeof e.schema!="boolean"}function j$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&ym(e),D$(e),Z$(e);let s=n.const("_errs",j.default.errors);_m(e,s),n.var(t,(0,O._)`${s} === ${j.default.errors}`)}function gm(e){(0,xt.checkUnknownRules)(e),M$(e)}function _m(e,t){if(e.opts.jtd)return lm(e,[],!1,t);let r=(0,cm.getSchemaTypes)(e.schema),n=(0,cm.coerceAndCheckDataType)(e,r);lm(e,r,!n,t)}function M$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,xt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function U$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,xt.checkStrictMode)(e,"default is ignored in the schema root")}function D$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,R$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Z$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function ym({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,O._)`${j.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._)`${j.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function q$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,O._)`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw((0,O._)`new ${o}(${j.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,j.default.vErrors),s.unevaluated&&L$(e),t.return((0,O._)`${j.default.errors} === 0`))}function L$({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 lm(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,xt.schemaHasRulesButRef)(s,u))){o.block(()=>bm(e,"$ref",u.all.$ref.definition));return}c.jtd||F$(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ja.shouldUseGroup)(s,f)&&(f.type?(o.if((0,ns.checkDataType)(f.type,i,c.strictNumbers)),dm(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,ns.reportTypeError)(e)),o.endIf()):dm(e,f),a||o.if((0,O._)`${j.default.errors} === ${n||0}`))}}function dm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,T$.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,Ja.shouldUseRule)(n,s)&&bm(e,s.keyword,s.definition,t.type)})}function F$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(V$(e,t),e.opts.allowUnionTypes||H$(e,t),B$(e,e.dataTypes))}function V$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{vm(e.dataTypes,r)||Ga(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),J$(e,t)}}function H$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ga(e,"use allowUnionTypes to allow union type keyword")}function B$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ja.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>K$(t,i))&&Ga(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function K$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function vm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function J$(e,t){let r=[];for(let n of e.dataTypes)vm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Ga(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,xt.checkStrictMode)(e,t,e.opts.strictTypes)}var os=class{constructor(t,r,n){if((0,Cn.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,xt.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",wm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Cn.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",j.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?An.reportExtraError:An.reportError)(this,this.def.error,r)}$dataError(){(0,An.reportError)(this,this.def.$dataError||An.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,An.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,ns.checkDataTypes)(c,r,s.opts.strictNumbers,ns.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,Ka.getSubschema)(this.it,t);(0,Ka.extendSubschemaData)(n,this.it,t),(0,Ka.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return N$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=xt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=xt.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}};Mt.KeywordCxt=os;function bm(e,t,r,n){let o=new os(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Cn.funcKeywordCode)(o,r):"macro"in r?(0,Cn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Cn.funcKeywordCode)(o,r)}var G$=/^\/(?:[^~]|~0|~1)*$/,W$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function wm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!G$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=j.default.rootData}else{let l=W$.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(s=r[t-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,O._)`${s}${(0,O.getProperty)((0,xt.unescapeJsonPointer)(l))}`,i=(0,O._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Mt.getData=wm});var ss=T(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Wa=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ya.default=Wa});var jn=T(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Qa=On(),Xa=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qa.resolveUrl)(t,r,n),this.missingSchema=(0,Qa.normalizeId)((0,Qa.getFullPath)(t,this.missingRef))}};ec.default=Xa});var as=T(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.resolveSchema=Ye.getCompilingSchema=Ye.resolveRef=Ye.compileSchema=Ye.SchemaEnv=void 0;var st=U(),Y$=ss(),nr=St(),it=On(),$m=H(),Q$=Nn(),Dr=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,it.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ye.SchemaEnv=Dr;function rc(e){let t=Sm.call(this,e);if(t)return t;let r=(0,it.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new st.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:Y$.default,code:(0,st._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:nr.default.data,parentData:nr.default.parentData,parentDataProperty:nr.default.parentDataProperty,dataNames:[nr.default.data],dataPathArr:[st.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,st.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:st.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,st._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,Q$.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(nr.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let m=new Function(`${nr.default.self}`,`${nr.default.scope}`,u)(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}=l;m.evaluated={props:h instanceof st.Name?void 0:h,items:g instanceof st.Name?void 0:g,dynamicProps:h instanceof st.Name,dynamicItems:g instanceof st.Name},m.source&&(m.source.evaluated=(0,st.stringify)(m.evaluated))}return e.validate=m,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}Ye.compileSchema=rc;function X$(e,t,r){var n;r=(0,it.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=r0.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 Dr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=e0.call(this,s)}Ye.resolveRef=X$;function e0(e){return(0,it.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:rc.call(this,e)}function Sm(e){for(let t of this._compilations)if(t0(t,e))return t}Ye.getCompilingSchema=Sm;function t0(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function r0(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||is.call(this,e,t)}function is(e,t){let r=this.opts.uriResolver.parse(t),n=(0,it._getFullPath)(this.opts.uriResolver,r),o=(0,it.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return tc.call(this,r,e);let s=(0,it.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=is.call(this,e,i);return typeof a?.schema!="object"?void 0:tc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||rc.call(this,i),s===(0,it.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,it.resolveUrl)(this.opts.uriResolver,o,l)),new Dr({schema:a,schemaId:c,root:e,baseId:o})}return tc.call(this,r,i)}}Ye.resolveSchema=is;var n0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tc(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,$m.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!n0.has(a)&&l&&(t=(0,it.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,$m.schemaHasRulesButRef)(r,this.RULES)){let a=(0,it.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=is.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Dr({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var xm=T((jA,o0)=>{o0.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 sc=T((MA,Em)=>{"use strict";var s0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zm=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),nc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Pm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),i0=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function oc(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 a0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function km(e){return e.length=0,!0}function c0(e,t,r){if(e.length){let n=oc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function u0(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=c0;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){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(l==="%"){if(!a(o,n,r))break;a=km}else{o.push(l);continue}}return o.length&&(a===km?r.zone=o.join(""):i?n.push(o.join("")):n.push(oc(o))),r.address=n.join(""),r}function Tm(e){if(l0(e,":")<2)return{host:e,isIPV6:!1};let t=u0(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 l0(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function d0(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 p0={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},f0=/[@/?#:]/g,m0=/[@/?#]/g;function Rm(e,t){let r=t?m0:f0;return r.lastIndex=0,e.replace(r,n=>p0[n])}function h0(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(nc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Pm(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function g0(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(nc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Pm(s)?t+=s:t+="%"+o,r+=2;continue}}i0(e[r])?t+=e[r]:t+=escape(e[r])}return t}function _0(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(nc(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function y0(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!zm(r)){let n=Tm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Rm(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}Em.exports={nonSimpleDomain:a0,recomposeAuthority:y0,reescapeHostDelimiters:Rm,normalizePercentEncoding:h0,normalizePathEncoding:g0,escapePreservingEscapes:_0,removeDotSegments:d0,isIPv4:zm,isUUID:s0,normalizeIPv6:Tm,stringArrayToHexStripped:oc}});var Nm=T((UA,Cm)=>{"use strict";var{isUUID:v0}=sc(),b0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,w0=["http","https","ws","wss","urn","urn:uuid"];function $0(e){return w0.indexOf(e)!==-1}function ic(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 Im(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Om(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 S0(e){return e.secure=ic(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function x0(e){if((e.port===(ic(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 k0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(b0);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=ac(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function z0(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=ac(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 P0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!v0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function T0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Am={scheme:"http",domainHost:!0,parse:Im,serialize:Om},R0={scheme:"https",domainHost:Am.domainHost,parse:Im,serialize:Om},cs={scheme:"ws",domainHost:!0,parse:S0,serialize:x0},E0={scheme:"wss",domainHost:cs.domainHost,parse:cs.parse,serialize:cs.serialize},I0={scheme:"urn",parse:k0,serialize:z0,skipNormalize:!0},O0={scheme:"urn:uuid",parse:P0,serialize:T0,skipNormalize:!0},us={http:Am,https:R0,ws:cs,wss:E0,urn:I0,"urn:uuid":O0};Object.setPrototypeOf(us,null);function ac(e){return e&&(us[e]||us[e.toLowerCase()])||void 0}Cm.exports={wsIsSecure:ic,SCHEMES:us,isValidSchemeName:$0,getSchemeHandler:ac}});var qm=T((DA,ls)=>{"use strict";var{normalizeIPv6:A0,removeDotSegments:Mn,recomposeAuthority:C0,normalizePercentEncoding:N0,normalizePathEncoding:j0,escapePreservingEscapes:M0,reescapeHostDelimiters:U0,isIPv4:D0,nonSimpleDomain:Z0}=sc(),{SCHEMES:q0,getSchemeHandler:Mm}=Nm();function L0(e,t){return typeof e=="string"?e=J0(e,t):typeof e=="object"&&(e=Zr(or(e,t),t)),e}function F0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Um(Zr(e,n),Zr(t,n),n,!0);return n.skipEscape=!0,or(o,n)}function Um(e,t,r,n){let o={};return n||(e=Zr(or(e,r),r),t=Zr(or(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=Mn(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=Mn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Mn(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=Mn(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 V0(e,t,r){let n=jm(e,r),o=jm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function or(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=Mm(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=N0(r.path):(r.path=M0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=C0(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=Mn(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 H0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,B0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function K0(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 Dm(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(B0);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=e.match(H0);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=K0(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(D0(n.host)===!1){let d=A0(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 l=Mm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&s===!1&&Z0(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!l||l&&!l.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=U0(unescape(n.host),s))),n.path&&(n.path=j0(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Zr(e,t){return Dm(e,t).parsed}function J0(e,t){return Zm(e,t).normalized}function Zm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Dm(e,t);return{normalized:n?e:or(r,t),malformedAuthorityOrPort:n}}function jm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Zm(e,t);return n?void 0:r}if(typeof e=="object")return or(e,t)}var cc={SCHEMES:q0,normalize:L0,resolve:F0,resolveComponent:Um,equal:V0,serialize:or,parse:Zr};ls.exports=cc;ls.exports.default=cc;ls.exports.fastUri=cc});var Fm=T(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Lm=qm();Lm.code='require("ajv/dist/runtime/uri").default';uc.default=Lm});var Ym=T(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.CodeGen=xe.Name=xe.nil=xe.stringify=xe.str=xe._=xe.KeywordCxt=void 0;var G0=Nn();Object.defineProperty(xe,"KeywordCxt",{enumerable:!0,get:function(){return G0.KeywordCxt}});var qr=U();Object.defineProperty(xe,"_",{enumerable:!0,get:function(){return qr._}});Object.defineProperty(xe,"str",{enumerable:!0,get:function(){return qr.str}});Object.defineProperty(xe,"stringify",{enumerable:!0,get:function(){return qr.stringify}});Object.defineProperty(xe,"nil",{enumerable:!0,get:function(){return qr.nil}});Object.defineProperty(xe,"Name",{enumerable:!0,get:function(){return qr.Name}});Object.defineProperty(xe,"CodeGen",{enumerable:!0,get:function(){return qr.CodeGen}});var W0=ss(),Jm=jn(),Y0=Ma(),Un=as(),Q0=U(),Dn=On(),ds=In(),dc=H(),Vm=xm(),X0=Fm(),Gm=(e,t)=>new RegExp(e,t);Gm.code="new RegExp";var eS=["removeAdditional","useDefaults","coerceTypes"],tS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),rS={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."},nS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Hm=200;function oS(e){var t,r,n,o,s,i,a,c,l,u,d,f,m,h,g,y,w,S,$,P,v,x,R,L,Y;let me=e.strict,Le=(t=e.code)===null||t===void 0?void 0:t.optimize,_r=Le===!0||Le===void 0?1:Le||0,Tt=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Gm,je=(o=e.uriResolver)!==null&&o!==void 0?o:X0.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:me)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:me)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:me)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:me)!==null&&f!==void 0?f:"log",strictRequired:(h=(m=e.strictRequired)!==null&&m!==void 0?m:me)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:_r,regExp:Tt}:{optimize:_r,regExp:Tt},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Hm,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:Hm,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(S=e.messages)!==null&&S!==void 0?S:!0,inlineRefs:($=e.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(v=e.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(x=e.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(R=e.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(L=e.unicodeRegExp)!==null&&L!==void 0?L:!0,int32range:(Y=e.int32range)!==null&&Y!==void 0?Y:!0,uriResolver:je}}var Zn=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,...oS(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Q0.ValueScope({scope:{},prefixes:tS,es5:r,lines:n}),this.logger=lS(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,Y0.getRules)(),Bm.call(this,rS,t,"NOT SUPPORTED"),Bm.call(this,nS,t,"DEPRECATED","warn"),this._metaOpts=cS.call(this),t.formats&&iS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&aS.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),sS.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Vm;n==="id"&&(o={...Vm},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(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||i.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Jm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}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,Dn.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=Km.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Un.SchemaEnv({schema:{},schemaId:n});if(r=Un.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=Km.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,Dn.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(pS.call(this,n,r),!r)return(0,dc.eachItem)(n,s=>lc.call(this,s)),this;mS.call(this,r);let o={...r,type:(0,ds.getJSONTypes)(r.type),schemaType:(0,ds.getJSONTypes)(r.schemaType)};return(0,dc.eachItem)(n,o.type.length===0?s=>lc.call(this,s,o):s=>o.type.forEach(i=>lc.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:l}=c.definition,u=i[a];l&&u&&(i[a]=Wm(u))}}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,Dn.normalizeId)(i||n);let l=Dn.getSchemaRefs.call(this,t,n);return c=new Un.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),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):Un.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{Un.compileSchema.call(this,t)}finally{this.opts=r}}};Zn.ValidationError=W0.default;Zn.MissingRefError=Jm.default;xe.default=Zn;function Bm(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 Km(e){return e=(0,Dn.normalizeId)(e),this.schemas[e]||this.refs[e]}function sS(){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 iS(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function aS(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 cS(){let e={...this.opts};for(let t of eS)delete e[t];return e}var uS={log(){},warn(){},error(){}};function lS(e){if(e===!1)return uS;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 dS=/^[a-z_$][a-z0-9_$:-]*$/i;function pS(e,t){let{RULES:r}=this;if((0,dc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!dS.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 lc(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,ds.getJSONTypes)(t.type),schemaType:(0,ds.getJSONTypes)(t.schemaType)}};t.before?fS.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 fS(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 mS(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Wm(t)),e.validateSchema=this.compile(t,!0))}var hS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Wm(e){return{anyOf:[e,hS]}}});var Qm=T(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var gS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};pc.default=gS});var rh=T(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.callRef=sr.getValidate=void 0;var _S=jn(),Xm=We(),qe=U(),Lr=St(),eh=as(),ps=H(),yS={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:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=eh.resolveRef.call(c,l,o,r);if(u===void 0)throw new _S.default(n.opts.uriResolver,o,r);if(u instanceof eh.SchemaEnv)return f(u);return m(u);function d(){if(s===l)return fs(e,i,s,s.$async);let h=t.scopeValue("root",{ref:l});return fs(e,(0,qe._)`${h}.validate`,l,l.$async)}function f(h){let g=th(e,h);fs(e,g,h,h.$async)}function m(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,qe.stringify)(h)}:{ref:h}),y=t.name("valid"),w=e.subschema({schema:h,dataTypes:[],schemaPath:qe.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(w),e.ok(y)}}};function th(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,qe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}sr.getValidate=th;function fs(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Lr.default.this:qe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,qe._)`await ${(0,Xm.callValidateCode)(e,t,l)}`),m(t),i||o.assign(h,!0)},g=>{o.if((0,qe._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),f(g),i||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,Xm.callValidateCode)(e,t,l),()=>m(t),()=>f(t))}function f(h){let g=(0,qe._)`${h}.errors`;o.assign(Lr.default.vErrors,(0,qe._)`${Lr.default.vErrors} === null ? ${g} : ${Lr.default.vErrors}.concat(${g})`),o.assign(Lr.default.errors,(0,qe._)`${Lr.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=ps.mergeEvaluated.props(o,y.props,s.props));else{let w=o.var("props",(0,qe._)`${h}.evaluated.props`);s.props=ps.mergeEvaluated.props(o,w,s.props,qe.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ps.mergeEvaluated.items(o,y.items,s.items));else{let w=o.var("items",(0,qe._)`${h}.evaluated.items`);s.items=ps.mergeEvaluated.items(o,w,s.items,qe.Name)}}}sr.callRef=fs;sr.default=yS});var nh=T(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var vS=Qm(),bS=rh(),wS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vS.default,bS.default];fc.default=wS});var oh=T(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ms=U(),Ut=ms.operators,hs={maximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},minimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},exclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},exclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},$S={message:({keyword:e,schemaCode:t})=>(0,ms.str)`must be ${hs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ms._)`{comparison: ${hs[e].okStr}, limit: ${t}}`},SS={keyword:Object.keys(hs),type:"number",schemaType:"number",$data:!0,error:$S,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ms._)`${r} ${hs[t].fail} ${n} || isNaN(${r})`)}};mc.default=SS});var sh=T(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var qn=U(),xS={message:({schemaCode:e})=>(0,qn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,qn._)`{multipleOf: ${e}}`},kS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:xS,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,qn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,qn._)`${i} !== parseInt(${i})`;e.fail$data((0,qn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};hc.default=kS});var ah=T(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});function ih(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}gc.default=ih;ih.code='require("ajv/dist/runtime/ucs2length").default'});var ch=T(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var ir=U(),zS=H(),PS=ah(),TS={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,ir.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,ir._)`{limit: ${e}}`},RS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TS,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?ir.operators.GT:ir.operators.LT,i=o.opts.unicode===!1?(0,ir._)`${r}.length`:(0,ir._)`${(0,zS.useFunc)(e.gen,PS.default)}(${r})`;e.fail$data((0,ir._)`${i} ${s} ${n}`)}};_c.default=RS});var uh=T(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var ES=We(),IS=H(),Fr=U(),OS={message:({schemaCode:e})=>(0,Fr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Fr._)`{pattern: ${e}}`},AS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:OS,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,l=c.code==="new RegExp"?(0,Fr._)`new RegExp`:(0,IS.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,Fr._)`${l}(${s}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,Fr._)`!${u}`)}else{let c=(0,ES.usePattern)(e,o);e.fail$data((0,Fr._)`!${c}.test(${r})`)}}};yc.default=AS});var lh=T(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var Ln=U(),CS={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Ln.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Ln._)`{limit: ${e}}`},NS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CS,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?Ln.operators.GT:Ln.operators.LT;e.fail$data((0,Ln._)`Object.keys(${r}).length ${o} ${n}`)}};vc.default=NS});var dh=T(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var Fn=We(),Vn=U(),jS=H(),MS={message:({params:{missingProperty:e}})=>(0,Vn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Vn._)`{missingProperty: ${e}}`},US={keyword:"required",type:"object",schemaType:"array",$data:!0,error:MS,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?l():u(),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,w=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,jS.checkStrictMode)(i,w,i.opts.strictRequired)}}function l(){if(c||s)e.block$data(Vn.nil,d);else for(let m of r)(0,Fn.checkReportMissingProp)(e,m)}function u(){let m=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>f(m,h)),e.ok(h)}else t.if((0,Fn.checkMissingProp)(e,r,m)),(0,Fn.reportMissingProp)(e,m),t.else()}function d(){t.forOf("prop",n,m=>{e.setParams({missingProperty:m}),t.if((0,Fn.noPropertyInData)(t,o,m,a.ownProperties),()=>e.error())})}function f(m,h){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(h,(0,Fn.propertyInData)(t,o,m,a.ownProperties)),t.if((0,Vn.not)(h),()=>{e.error(),t.break()})},Vn.nil)}}};bc.default=US});var ph=T(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var Hn=U(),DS={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Hn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Hn._)`{limit: ${e}}`},ZS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:DS,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Hn.operators.GT:Hn.operators.LT;e.fail$data((0,Hn._)`${r}.length ${o} ${n}`)}};wc.default=ZS});var gs=T($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var fh=Ha();fh.code='require("ajv/dist/runtime/equal").default';$c.default=fh});var mh=T(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Sc=In(),ke=U(),qS=H(),LS=gs(),FS={message:({params:{i:e,j:t}})=>(0,ke.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ke._)`{i: ${e}, j: ${t}}`},VS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:FS,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"),l=s.items?(0,Sc.getSchemaTypes)(s.items):[];e.block$data(c,u,(0,ke._)`${i} === false`),e.ok(c);function u(){let h=t.let("i",(0,ke._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,ke._)`${h} > 1`,()=>(d()?f:m)(h,g))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,g){let y=t.name("item"),w=(0,Sc.checkDataTypes)(l,y,a.opts.strictNumbers,Sc.DataType.Wrong),S=t.const("indices",(0,ke._)`{}`);t.for((0,ke._)`;${h}--;`,()=>{t.let(y,(0,ke._)`${r}[${h}]`),t.if(w,(0,ke._)`continue`),l.length>1&&t.if((0,ke._)`typeof ${y} == "string"`,(0,ke._)`${y} += "_"`),t.if((0,ke._)`typeof ${S}[${y}] == "number"`,()=>{t.assign(g,(0,ke._)`${S}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ke._)`${S}[${y}] = ${h}`)})}function m(h,g){let y=(0,qS.useFunc)(t,LS.default),w=t.name("outer");t.label(w).for((0,ke._)`;${h}--;`,()=>t.for((0,ke._)`${g} = ${h}; ${g}--;`,()=>t.if((0,ke._)`${y}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};xc.default=VS});var hh=T(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var kc=U(),HS=H(),BS=gs(),KS={message:"must be equal to constant",params:({schemaCode:e})=>(0,kc._)`{allowedValue: ${e}}`},JS={keyword:"const",$data:!0,error:KS,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,kc._)`!${(0,HS.useFunc)(t,BS.default)}(${r}, ${o})`):e.fail((0,kc._)`${s} !== ${r}`)}};zc.default=JS});var gh=T(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var Bn=U(),GS=H(),WS=gs(),YS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Bn._)`{allowedValues: ${e}}`},QS={keyword:"enum",schemaType:"array",$data:!0,error:YS,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,l=()=>c??(c=(0,GS.useFunc)(t,WS.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=t.const("vSchema",s);u=(0,Bn.or)(...o.map((h,g)=>f(m,g)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",s,m=>t.if((0,Bn._)`${l()}(${r}, ${m})`,()=>t.assign(u,!0).break()))}function f(m,h){let g=o[h];return typeof g=="object"&&g!==null?(0,Bn._)`${l()}(${r}, ${m}[${h}])`:(0,Bn._)`${r} === ${g}`}}};Pc.default=QS});var _h=T(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var XS=oh(),ex=sh(),tx=ch(),rx=uh(),nx=lh(),ox=dh(),sx=ph(),ix=mh(),ax=hh(),cx=gh(),ux=[XS.default,ex.default,tx.default,rx.default,nx.default,ox.default,sx.default,ix.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ax.default,cx.default];Tc.default=ux});var Ec=T(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.validateAdditionalItems=void 0;var ar=U(),Rc=H(),lx={message:({params:{len:e}})=>(0,ar.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ar._)`{limit: ${e}}`},dx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:lx,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Rc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}yh(e,n)}};function yh(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,ar._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,ar._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Rc.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,ar._)`${a} <= ${t.length}`);r.if((0,ar.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:s,dataProp:u,dataPropType:Rc.Type.Num},l),i.allErrors||r.if((0,ar.not)(l),()=>r.break())})}}Kn.validateAdditionalItems=yh;Kn.default=dx});var Ic=T(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.validateTuple=void 0;var vh=U(),_s=H(),px=We(),fx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return bh(e,"additionalItems",t);r.items=!0,!(0,_s.alwaysValidSchema)(r,t)&&e.ok((0,px.validateArray)(e))}};function bh(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=_s.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,vh._)`${s}.length`);r.forEach((d,f)=>{(0,_s.alwaysValidSchema)(a,d)||(n.if((0,vh._)`${l} > ${f}`,()=>e.subschema({keyword:i,schemaProp:f,dataProp:f},c)),e.ok(c))});function u(d){let{opts:f,errSchemaPath:m}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(f.strictTuples&&!g){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,_s.checkStrictMode)(a,y,f.strictTuples)}}}Jn.validateTuple=bh;Jn.default=fx});var wh=T(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var mx=Ic(),hx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,mx.validateTuple)(e,"items")};Oc.default=hx});var Sh=T(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var $h=U(),gx=H(),_x=We(),yx=Ec(),vx={message:({params:{len:e}})=>(0,$h.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,$h._)`{limit: ${e}}`},bx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:vx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,gx.alwaysValidSchema)(n,t)&&(o?(0,yx.validateAdditionalItems)(e,o):e.ok((0,_x.validateArray)(e)))}};Ac.default=bx});var xh=T(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var Qe=U(),ys=H(),wx={message:({params:{min:e,max:t}})=>t===void 0?(0,Qe.str)`must contain at least ${e} valid item(s)`:(0,Qe.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Qe._)`{minContains: ${e}}`:(0,Qe._)`{minContains: ${e}, maxContains: ${t}}`},$x={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=t.const("len",(0,Qe._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,ys.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ys.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,ys.alwaysValidSchema)(s,r)){let g=(0,Qe._)`${u} >= ${i}`;a!==void 0&&(g=(0,Qe._)`${g} && ${u} <= ${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,Qe._)`${o}.length > 0`,f)):(t.let(d,!1),f()),e.result(d,()=>e.reset());function f(){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,u,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:ys.Type.Num,compositeRule:!0},g),y()})}function h(g){t.code((0,Qe._)`${g}++`),a===void 0?t.if((0,Qe._)`${g} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,Qe._)`${g} > ${a}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,Qe._)`${g} >= ${i}`,()=>t.assign(d,!0)))}}};Cc.default=$x});var Ph=T(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.validateSchemaDeps=pt.validatePropertyDeps=pt.error=void 0;var Nc=U(),Sx=H(),Gn=We();pt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Nc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Nc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var hx={keyword:"dependencies",type:"object",schemaType:"object",error:pt.error,code(e){let[t,r]=gx(e);$h(e,t),Sh(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 $h(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,Jn.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,Jn.checkReportMissingProp)(e,l)}):(r.if((0,Ac._)`${c} && (${(0,Jn.checkMissingProp)(e,a,s)})`),(0,Jn.reportMissingProp)(e,s),r.else())}}pt.validatePropertyDeps=$h;function Sh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,mx.alwaysValidSchema)(s,t[a])||(r.if((0,Jn.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))}pt.validateSchemaDeps=Sh;pt.default=hx});var kh=T(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var zh=U(),_x=H(),yx={message:"property name must be valid",params:({params:e})=>(0,zh._)`{propertyName: ${e.propertyName}}`},vx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:yx,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,_x.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,zh.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Cc.default=vx});var jc=T(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var _s=We(),at=U(),wx=$t(),ys=H(),bx={message:"must NOT have additional properties",params:({params:e})=>(0,at._)`{additionalProperty: ${e.additionalProperty}}`},$x={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:bx,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,ys.alwaysValidSchema)(i,r))return;let l=(0,_s.allSchemaProperties)(n.properties),u=(0,_s.allSchemaProperties)(n.patternProperties);d(),e.ok((0,at._)`${s} === ${wx.default.errors}`);function d(){t.forIn("key",o,y=>{!l.length&&!u.length?h(y):t.if(f(y),()=>h(y))})}function f(y){let b;if(l.length>8){let S=(0,ys.schemaRefOrVal)(i,n.properties,"properties");b=(0,_s.isOwnProperty)(t,S,y)}else l.length?b=(0,at.or)(...l.map(S=>(0,at._)`${y} === ${S}`)):b=at.nil;return u.length&&(b=(0,at.or)(b,...u.map(S=>(0,at._)`${(0,_s.usePattern)(e,S)}.test(${y})`))),(0,at.not)(b)}function m(y){t.code((0,at._)`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,ys.alwaysValidSchema)(i,r)){let b=t.name("valid");c.removeAdditional==="failing"?(g(y,b,!1),t.if((0,at.not)(b),()=>{e.reset(),m(y)})):(g(y,b),a||t.if((0,at.not)(b),()=>t.break()))}}function g(y,b,S){let $={keyword:"additionalProperties",dataProp:y,dataPropType:ys.Type.Str};S===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,b)}}};Nc.default=$x});var Rh=T(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Sx=Cn(),Ph=We(),Mc=H(),Th=jc(),xx={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&&Th.default.code(new Sx.KeywordCxt(s,Th.default,"additionalProperties"));let i=(0,Ph.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Mc.mergeEvaluated.props(t,(0,Mc.toHash)(i),s.props));let a=i.filter(d=>!(0,Mc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Ph.propertyInData)(t,o,d,s.opts.ownProperties)),u(d),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Uc.default=xx});var Ah=T(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Eh=We(),vs=U(),Ih=H(),Oh=H(),zx={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,Eh.allSchemaProperties)(r),c=a.filter(g=>(0,Ih.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=t.name("valid");s.props!==!0&&!(s.props instanceof vs.Name)&&(s.props=(0,Oh.evaluatedPropsToName)(t,s.props));let{props:d}=s;f();function f(){for(let g of a)l&&m(g),s.allErrors?h(g):(t.var(u,!0),h(g),t.if(u))}function m(g){for(let y in l)new RegExp(g).test(y)&&(0,Ih.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,y=>{t.if((0,vs._)`${(0,Eh.usePattern)(e,g)}.test(${y})`,()=>{let b=c.includes(g);b||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Oh.Type.Str},u),s.opts.unevaluated&&d!==!0?t.assign((0,vs._)`${d}[${y}]`,!0):!b&&!s.allErrors&&t.if((0,vs.not)(u),()=>t.break())})})}}};Dc.default=zx});var Ch=T(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var kx=H(),Px={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,kx.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"}};Zc.default=Px});var Nh=T(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Tx=We(),Rx={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Tx.validateUnion,error:{message:"must match a schema in anyOf"}};qc.default=Rx});var jh=T(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var ws=U(),Ex=H(),Ix={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ws._)`{passingSchemas: ${e.passing}}`},Ox={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ix,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(l),e.result(i,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((u,d)=>{let f;(0,Ex.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,ws._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ws._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,d),f&&e.mergeEvaluated(f,ws.Name)})})}}};Lc.default=Ox});var Mh=T(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Ax=H(),Cx={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,Ax.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Fc.default=Cx});var Zh=T(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var bs=U(),Dh=H(),Nx={message:({params:e})=>(0,bs.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,bs._)`{failingKeyword: ${e.ifClause}}`},jx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Nx,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Dh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Uh(n,"then"),s=Uh(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else o?t.if(a,l("then")):t.if((0,bs.not)(a),l("else"));e.pass(i,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let f=e.subschema({keyword:u},a);t.assign(i,a),e.mergeValidEvaluated(f,i),d?t.assign(d,(0,bs._)`${u}`):e.setParams({ifClause:u})}}}};function Uh(e,t){let r=e.schema[t];return r!==void 0&&!(0,Dh.alwaysValidSchema)(e,r)}Vc.default=jx});var qh=T(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Mx=H(),Ux={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Mx.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hc.default=Ux});var Lh=T(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Dx=Tc(),Zx=yh(),qx=Rc(),Lx=wh(),Fx=bh(),Vx=xh(),Hx=kh(),Bx=jc(),Kx=Rh(),Jx=Ah(),Gx=Ch(),Wx=Nh(),Yx=jh(),Qx=Mh(),Xx=Zh(),ez=qh();function tz(e=!1){let t=[Gx.default,Wx.default,Yx.default,Qx.default,Xx.default,ez.default,Hx.default,Bx.default,Vx.default,Kx.default,Jx.default];return e?t.push(Zx.default,Lx.default):t.push(Dx.default,qx.default),t.push(Fx.default),t}Bc.default=tz});var Fh=T(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var he=U(),rz={message:({schemaCode:e})=>(0,he.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,he._)`{format: ${e}}`},nz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:rz,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():m();function f(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,he._)`${h}[${i}]`),y=r.let("fType"),b=r.let("format");r.if((0,he._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,he._)`${g}.type || "string"`).assign(b,(0,he._)`${g}.validate`),()=>r.assign(y,(0,he._)`"string"`).assign(b,g)),e.fail$data((0,he.or)(S(),$()));function S(){return c.strictSchema===!1?he.nil:(0,he._)`${i} && !${b}`}function $(){let P=u.$async?(0,he._)`(${g}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,he._)`${b}(${n})`,v=(0,he._)`(typeof ${b} == "function" ? ${P} : ${b}.test(${n}))`;return(0,he._)`${b} && ${b} !== true && ${y} === ${t} && !${v}`}}function m(){let h=d.formats[s];if(!h){S();return}if(h===!0)return;let[g,y,b]=$(h);g===t&&e.pass(P());function S(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function $(v){let x=v instanceof RegExp?(0,he.regexpCode)(v):c.code.formats?(0,he._)`${c.code.formats}${(0,he.getProperty)(s)}`:void 0,R=r.scopeValue("formats",{key:s,ref:v,code:x});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,he._)`${R}.validate`]:["string",v,R]}function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,he._)`await ${b}(${n})`}return typeof y=="function"?(0,he._)`${b}(${n})`:(0,he._)`${b}.test(${n})`}}}};Kc.default=nz});var Vh=T(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var oz=Fh(),sz=[oz.default];Jc.default=sz});var Hh=T(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.contentVocabulary=Fr.metadataVocabulary=void 0;Fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Kh=T(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var iz=eh(),az=mh(),cz=Lh(),uz=Vh(),Bh=Hh(),lz=[iz.default,az.default,(0,cz.default)(),uz.default,Bh.metadataVocabulary,Bh.contentVocabulary];Gc.default=lz});var Gh=T($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.DiscrError=void 0;var Jh;(function(e){e.Tag="tag",e.Mapping="mapping"})(Jh||($s.DiscrError=Jh={}))});var Yh=T(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Vr=U(),Wc=Gh(),Wh=ss(),dz=Nn(),pz=H(),fz={message:({params:{discrError:e,tagName:t}})=>e===Wc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Vr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},mz={keyword:"discriminator",type:"object",schemaType:"object",error:fz,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),l=t.const("tag",(0,Vr._)`${r}${(0,Vr.getProperty)(a)}`);t.if((0,Vr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Wc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let m=f();t.if(!1);for(let h in m)t.elseIf((0,Vr._)`${l} === ${h}`),t.assign(c,d(m[h]));t.else(),e.error(!1,{discrError:Wc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(m){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(g,Vr.Name),h}function f(){var m;let h={},g=b(o),y=!0;for(let P=0;P<i.length;P++){let v=i[P];if(v?.$ref&&!(0,pz.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=Wh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof Wh.SchemaEnv&&(v=v.schema),v===void 0)throw new dz.default(s.opts.uriResolver,s.baseId,R)}let x=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||b(v)),S(x,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function b({required:P}){return Array.isArray(P)&&P.includes(a)}function S(P,v){if(P.const)$(P.const,v);else if(P.enum)for(let x of P.enum)$(x,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(P,v){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[P]=v}}}};Yc.default=mz});var Qh=T((l1,hz)=>{hz.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 Xc=T((le,Qc)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var gz=Jm(),_z=Kh(),yz=Yh(),Xh=Qh(),vz=["/properties"],Ss="http://json-schema.org/draft-07/schema",Hr=class extends gz.default{_addVocabularies(){super._addVocabularies(),_z.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(yz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Xh,vz):Xh;this.addMetaSchema(t,Ss,!1),this.refs["http://json-schema.org/schema"]=Ss}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ss)?Ss:void 0)}};le.Ajv=Hr;Qc.exports=le=Hr;Qc.exports.Ajv=Hr;Object.defineProperty(le,"__esModule",{value:!0});le.default=Hr;var wz=Cn();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return wz.KeywordCxt}});var Br=U();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Br._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Br.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Br.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Br.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Br.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Br.CodeGen}});var bz=ns();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return bz.default}});var $z=Nn();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return $z.default}})});var ag=T(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.formatNames=mt.fastFormats=mt.fullFormats=void 0;function ft(e,t){return{validate:e,compare:t}}mt.fullFormats={date:ft(ng,nu),time:ft(tu(!0),ou),"date-time":ft(eg(!0),sg),"iso-time":ft(tu(),og),"iso-date-time":ft(eg(),ig),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Tz,"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:Nz,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:Rz,int32:{type:"number",validate:Oz},int64:{type:"number",validate:Az},float:{type:"number",validate:rg},double:{type:"number",validate:rg},password:!0,binary:!0};mt.fastFormats={...mt.fullFormats,date:ft(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,nu),time:ft(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ou),"date-time":ft(/^\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,sg),"iso-time":ft(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,og),"iso-date-time":ft(/^\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,ig),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};mt.formatNames=Object.keys(mt.fullFormats);function Sz(e){return e%4===0&&(e%100!==0||e%400===0)}var xz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,zz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ng(e){let t=xz.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&&Sz(r)?29:zz[n])}function nu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var eu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function tu(e){return function(r){let n=eu.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*c,f=o-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function ou(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 og(e,t){if(!(e&&t))return;let r=eu.exec(e),n=eu.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 ru=/t|\s/i;function eg(e){let t=tu(e);return function(n){let o=n.split(ru);return o.length===2&&ng(o[0])&&t(o[1])}}function sg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function ig(e,t){if(!(e&&t))return;let[r,n]=e.split(ru),[o,s]=t.split(ru),i=nu(r,o);if(i!==void 0)return i||ou(n,s)}var kz=/\/|:/,Pz=/^(?:[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 Tz(e){return kz.test(e)&&Pz.test(e)}var tg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Rz(e){return tg.lastIndex=0,tg.test(e)}var Ez=-(2**31),Iz=2**31-1;function Oz(e){return Number.isInteger(e)&&e<=Iz&&e>=Ez}function Az(e){return Number.isInteger(e)}function rg(){return!0}var Cz=/[^\\]\\Z/;function Nz(e){if(Cz.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var cg=T(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.formatLimitDefinition=void 0;var jz=Xc(),ct=U(),Dt=ct.operators,xs={formatMaximum:{okStr:"<=",ok:Dt.LTE,fail:Dt.GT},formatMinimum:{okStr:">=",ok:Dt.GTE,fail:Dt.LT},formatExclusiveMaximum:{okStr:"<",ok:Dt.LT,fail:Dt.GTE},formatExclusiveMinimum:{okStr:">",ok:Dt.GT,fail:Dt.LTE}},Mz={message:({keyword:e,schemaCode:t})=>(0,ct.str)`should be ${xs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ct._)`{comparison: ${xs[e].okStr}, limit: ${t}}`};Kr.formatLimitDefinition={keyword:Object.keys(xs),type:"string",schemaType:"string",$data:!0,error:Mz,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 jz.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=t.const("fmt",(0,ct._)`${f}[${c.schemaCode}]`);e.fail$data((0,ct.or)((0,ct._)`typeof ${m} != "object"`,(0,ct._)`${m} instanceof RegExp`,(0,ct._)`typeof ${m}.compare != "function"`,d(m)))}function u(){let f=c.schema,m=a.formats[f];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=t.scopeValue("formats",{key:f,ref:m,code:i.code.formats?(0,ct._)`${i.code.formats}${(0,ct.getProperty)(f)}`:void 0});e.fail$data(d(h))}function d(f){return(0,ct._)`${f}.compare(${r}, ${n}) ${xs[o].fail} 0`}},dependencies:["format"]};var Uz=e=>(e.addKeyword(Kr.formatLimitDefinition),e);Kr.default=Uz});var pg=T((Gn,dg)=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});var Jr=ag(),Dz=cg(),su=U(),ug=new su.Name("fullFormats"),Zz=new su.Name("fastFormats"),iu=(e,t={keywords:!0})=>{if(Array.isArray(t))return lg(e,t,Jr.fullFormats,ug),e;let[r,n]=t.mode==="fast"?[Jr.fastFormats,Zz]:[Jr.fullFormats,ug],o=t.formats||Jr.formatNames;return lg(e,o,r,n),t.keywords&&(0,Dz.default)(e),e};iu.get=(e,t="full")=>{let n=(t==="fast"?Jr.fastFormats:Jr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function lg(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,su._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}dg.exports=Gn=iu;Object.defineProperty(Gn,"__esModule",{value:!0});Gn.default=iu});import{spawn as h_,spawnSync as Qr}from"node:child_process";import{connect as eP}from"node:net";import{homedir as g_,userInfo as Su}from"node:os";import{resolve as __,join as kt,dirname as Eu}from"node:path";import{fileURLToPath as tP,pathToFileURL as rP}from"node:url";import{createInterface as Ds}from"node:readline/promises";import*as q from"node:fs";var Ks=Object.freeze({status:"aborted"});function _(e,t,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].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 l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}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 A_=Symbol("zod_brand"),_t=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ho={};function Fe(e){return e&&Object.assign(ho,e),ho}var G={};Bs(G,{BIGINT_FORMAT_RANGES:()=>Uu,Class:()=>Gs,NUMBER_FORMAT_RANGES:()=>ni,aborted:()=>Bt,allowsEval:()=>ei,assert:()=>U_,assertEqual:()=>C_,assertIs:()=>j_,assertNever:()=>M_,assertNotEqual:()=>N_,assignProp:()=>Xs,cached:()=>rn,captureStackTrace:()=>_o,cleanEnum:()=>Y_,cleanRegex:()=>on,clone:()=>et,createTransparentProxy:()=>V_,defineLazy:()=>oe,esc:()=>Ht,escapeRegex:()=>Rt,extend:()=>K_,finalizeIssue:()=>tt,floatSafeRemainder:()=>Qs,getElementAtPath:()=>D_,getEnumValues:()=>Ws,getLengthableOrigin:()=>sn,getParsedType:()=>F_,getSizableOrigin:()=>Du,isObject:()=>yr,isPlainObject:()=>vr,issue:()=>oi,joinValues:()=>go,jsonStringifyReplacer:()=>Ys,merge:()=>J_,normalizeParams:()=>A,nullish:()=>nn,numKeys:()=>L_,omit:()=>B_,optionalKeys:()=>ri,partial:()=>G_,pick:()=>H_,prefixIssues:()=>ut,primitiveTypes:()=>Mu,promiseAllObject:()=>Z_,propertyKeyTypes:()=>ti,randomString:()=>q_,required:()=>W_,stringifyPrimitive:()=>yo,unwrapMessage:()=>tn});function C_(e){return e}function N_(e){return e}function j_(e){}function M_(e){throw new Error}function U_(e){}function Ws(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 go(e,t="|"){return e.map(r=>yo(r)).join(t)}function Ys(e,t){return typeof t=="bigint"?t.toString():t}function rn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function nn(e){return e==null}function on(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Qs(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 oe(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 Xs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function D_(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Z_(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 q_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Ht(e){return JSON.stringify(e)}var _o=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ei=rn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function vr(e){if(yr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(yr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function L_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var F_=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}`)}},ti=new Set(["string","number","symbol"]),Mu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function et(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function A(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 V_(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 yo(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function ri(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ni={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]},Uu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function H_(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 et(e,{...e._zod.def,shape:r,checks:[]})}function B_(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 et(e,{...e._zod.def,shape:r,checks:[]})}function K_(e,t){if(!vr(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 Xs(this,"shape",n),n},checks:[]};return et(e,r)}function J_(e,t){return et(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Xs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function G_(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 et(t,{...t._zod.def,shape:o,checks:[]})}function W_(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 et(t,{...t._zod.def,shape:o,checks:[]})}function Bt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ut(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function tn(e){return typeof e=="string"?e:e?.message}function tt(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=tn(e.inst?._zod.def?.error?.(e))??tn(t?.error?.(e))??tn(r.customError?.(e))??tn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Du(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function sn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function oi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Y_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Gs=class{constructor(...t){}};var Zu=(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,Ys,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},vo=_("$ZodError",Zu),si=_("$ZodError",Zu,{Parent:Error});function ii(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 ai(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 l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var qu=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 _t;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>tt(c,s,Fe())));throw _o(a,o?.callee),a}return i.value};var Lu=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=>tt(c,s,Fe())));throw _o(a,o?.callee),a}return i.value};var ci=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 _t;return s.issues.length?{success:!1,error:new(e??vo)(s.issues.map(i=>tt(i,o,Fe())))}:{success:!0,data:s.value}},an=ci(si),ui=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=>tt(i,o,Fe())))}:{success:!0,data:s.value}},wo=ui(si);var Fu=/^[cC][^\s-]{8,}$/,Vu=/^[0-9a-z]+$/,Hu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Bu=/^[0-9a-vA-V]{20}$/,Ku=/^[A-Za-z0-9]{27}$/,Ju=/^[a-zA-Z0-9_-]{21}$/,Gu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Wu=/^([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})$/,li=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 Yu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var X_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Qu(){return new RegExp(X_,"u")}var Xu=/^(?:(?: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])$/,el=/^(([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})$/,tl=/^((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])$/,rl=/^(([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])$/,nl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,di=/^[A-Za-z0-9_-]*$/,ol=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var sl=/^\+(?:[0-9]){6,14}[0-9]$/,il="(?:(?:\\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])))",al=new RegExp(`^${il}$`);function cl(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 ul(e){return new RegExp(`^${cl(e)}$`)}function ll(e){let t=cl({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(`^${il}T(?:${n})$`)}var dl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},pl=/^\d+n?$/,fl=/^\d+$/,ml=/^-?\d+(?:\.\d+)?/i,hl=/true|false/i,gl=/null/i;var _l=/^[^A-Z]*$/,yl=/^[^a-z]*$/;var Te=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),vl={number:"number",bigint:"bigint",object:"date"},pi=_("$ZodCheckLessThan",(e,t)=>{Te.init(e,t);let r=vl[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})}}),fi=_("$ZodCheckGreaterThan",(e,t)=>{Te.init(e,t);let r=vl[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})}}),wl=_("$ZodCheckMultipleOf",(e,t)=>{Te.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):Qs(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})}}),bl=_("$ZodCheckNumberFormat",(e,t)=>{Te.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=ni[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=fl)}),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 $l=_("$ZodCheckMaxLength",(e,t)=>{var r;Te.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!nn(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=sn(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Sl=_("$ZodCheckMinLength",(e,t)=>{var r;Te.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!nn(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=sn(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xl=_("$ZodCheckLengthEquals",(e,t)=>{var r;Te.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!nn(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=sn(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})}}),cn=_("$ZodCheckStringFormat",(e,t)=>{var r,n;Te.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=()=>{})}),zl=_("$ZodCheckRegex",(e,t)=>{cn.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=_l),cn.init(e,t)}),Pl=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yl),cn.init(e,t)}),Tl=_("$ZodCheckIncludes",(e,t)=>{Te.init(e,t);let r=Rt(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})}}),Rl=_("$ZodCheckStartsWith",(e,t)=>{Te.init(e,t);let r=new RegExp(`^${Rt(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})}}),El=_("$ZodCheckEndsWith",(e,t)=>{Te.init(e,t);let r=new RegExp(`.*${Rt(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 Il=_("$ZodCheckOverwrite",(e,t)=>{Te.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var $o=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 xx={keyword:"dependencies",type:"object",schemaType:"object",error:pt.error,code(e){let[t,r]=kx(e);kh(e,t),zh(e,r)}};function kx({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 kh(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,Gn.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,Gn.checkReportMissingProp)(e,l)}):(r.if((0,Nc._)`${c} && (${(0,Gn.checkMissingProp)(e,a,s)})`),(0,Gn.reportMissingProp)(e,s),r.else())}}pt.validatePropertyDeps=kh;function zh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,Sx.alwaysValidSchema)(s,t[a])||(r.if((0,Gn.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))}pt.validateSchemaDeps=zh;pt.default=xx});var Rh=T(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Th=U(),zx=H(),Px={message:"property name must be valid",params:({params:e})=>(0,Th._)`{propertyName: ${e.propertyName}}`},Tx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Px,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,zx.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,Th.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};jc.default=Tx});var Uc=T(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var vs=We(),at=U(),Rx=St(),bs=H(),Ex={message:"must NOT have additional properties",params:({params:e})=>(0,at._)`{additionalProperty: ${e.additionalProperty}}`},Ix={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Ex,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,bs.alwaysValidSchema)(i,r))return;let l=(0,vs.allSchemaProperties)(n.properties),u=(0,vs.allSchemaProperties)(n.patternProperties);d(),e.ok((0,at._)`${s} === ${Rx.default.errors}`);function d(){t.forIn("key",o,y=>{!l.length&&!u.length?h(y):t.if(f(y),()=>h(y))})}function f(y){let w;if(l.length>8){let S=(0,bs.schemaRefOrVal)(i,n.properties,"properties");w=(0,vs.isOwnProperty)(t,S,y)}else l.length?w=(0,at.or)(...l.map(S=>(0,at._)`${y} === ${S}`)):w=at.nil;return u.length&&(w=(0,at.or)(w,...u.map(S=>(0,at._)`${(0,vs.usePattern)(e,S)}.test(${y})`))),(0,at.not)(w)}function m(y){t.code((0,at._)`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,bs.alwaysValidSchema)(i,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(y,w,!1),t.if((0,at.not)(w),()=>{e.reset(),m(y)})):(g(y,w),a||t.if((0,at.not)(w),()=>t.break()))}}function g(y,w,S){let $={keyword:"additionalProperties",dataProp:y,dataPropType:bs.Type.Str};S===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,w)}}};Mc.default=Ix});var Oh=T(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Ox=Nn(),Eh=We(),Dc=H(),Ih=Uc(),Ax={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&&Ih.default.code(new Ox.KeywordCxt(s,Ih.default,"additionalProperties"));let i=(0,Eh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Dc.mergeEvaluated.props(t,(0,Dc.toHash)(i),s.props));let a=i.filter(d=>!(0,Dc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Eh.propertyInData)(t,o,d,s.opts.ownProperties)),u(d),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Zc.default=Ax});var jh=T(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Ah=We(),ws=U(),Ch=H(),Nh=H(),Cx={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,Ah.allSchemaProperties)(r),c=a.filter(g=>(0,Ch.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=t.name("valid");s.props!==!0&&!(s.props instanceof ws.Name)&&(s.props=(0,Nh.evaluatedPropsToName)(t,s.props));let{props:d}=s;f();function f(){for(let g of a)l&&m(g),s.allErrors?h(g):(t.var(u,!0),h(g),t.if(u))}function m(g){for(let y in l)new RegExp(g).test(y)&&(0,Ch.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,y=>{t.if((0,ws._)`${(0,Ah.usePattern)(e,g)}.test(${y})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Nh.Type.Str},u),s.opts.unevaluated&&d!==!0?t.assign((0,ws._)`${d}[${y}]`,!0):!w&&!s.allErrors&&t.if((0,ws.not)(u),()=>t.break())})})}}};qc.default=Cx});var Mh=T(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var Nx=H(),jx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Nx.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"}};Lc.default=jx});var Uh=T(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Mx=We(),Ux={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Mx.validateUnion,error:{message:"must match a schema in anyOf"}};Fc.default=Ux});var Dh=T(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var $s=U(),Dx=H(),Zx={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,$s._)`{passingSchemas: ${e.passing}}`},qx={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Zx,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(l),e.result(i,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((u,d)=>{let f;(0,Dx.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,$s._)`${c} && ${i}`).assign(i,!1).assign(a,(0,$s._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,d),f&&e.mergeEvaluated(f,$s.Name)})})}}};Vc.default=qx});var Zh=T(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Lx=H(),Fx={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,Lx.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Hc.default=Fx});var Fh=T(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Ss=U(),Lh=H(),Vx={message:({params:e})=>(0,Ss.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ss._)`{failingKeyword: ${e.ifClause}}`},Hx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Vx,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Lh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=qh(n,"then"),s=qh(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else o?t.if(a,l("then")):t.if((0,Ss.not)(a),l("else"));e.pass(i,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let f=e.subschema({keyword:u},a);t.assign(i,a),e.mergeValidEvaluated(f,i),d?t.assign(d,(0,Ss._)`${u}`):e.setParams({ifClause:u})}}}};function qh(e,t){let r=e.schema[t];return r!==void 0&&!(0,Lh.alwaysValidSchema)(e,r)}Bc.default=Hx});var Vh=T(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var Bx=H(),Kx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Bx.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Kc.default=Kx});var Hh=T(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Jx=Ec(),Gx=wh(),Wx=Ic(),Yx=Sh(),Qx=xh(),Xx=Ph(),ek=Rh(),tk=Uc(),rk=Oh(),nk=jh(),ok=Mh(),sk=Uh(),ik=Dh(),ak=Zh(),ck=Fh(),uk=Vh();function lk(e=!1){let t=[ok.default,sk.default,ik.default,ak.default,ck.default,uk.default,ek.default,tk.default,Xx.default,rk.default,nk.default];return e?t.push(Gx.default,Yx.default):t.push(Jx.default,Wx.default),t.push(Qx.default),t}Jc.default=lk});var Bh=T(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var he=U(),dk={message:({schemaCode:e})=>(0,he.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,he._)`{format: ${e}}`},pk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:dk,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():m();function f(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,he._)`${h}[${i}]`),y=r.let("fType"),w=r.let("format");r.if((0,he._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,he._)`${g}.type || "string"`).assign(w,(0,he._)`${g}.validate`),()=>r.assign(y,(0,he._)`"string"`).assign(w,g)),e.fail$data((0,he.or)(S(),$()));function S(){return c.strictSchema===!1?he.nil:(0,he._)`${i} && !${w}`}function $(){let P=u.$async?(0,he._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,he._)`${w}(${n})`,v=(0,he._)`(typeof ${w} == "function" ? ${P} : ${w}.test(${n}))`;return(0,he._)`${w} && ${w} !== true && ${y} === ${t} && !${v}`}}function m(){let h=d.formats[s];if(!h){S();return}if(h===!0)return;let[g,y,w]=$(h);g===t&&e.pass(P());function S(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function $(v){let x=v instanceof RegExp?(0,he.regexpCode)(v):c.code.formats?(0,he._)`${c.code.formats}${(0,he.getProperty)(s)}`:void 0,R=r.scopeValue("formats",{key:s,ref:v,code:x});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,he._)`${R}.validate`]:["string",v,R]}function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,he._)`await ${w}(${n})`}return typeof y=="function"?(0,he._)`${w}(${n})`:(0,he._)`${w}.test(${n})`}}}};Gc.default=pk});var Kh=T(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var fk=Bh(),mk=[fk.default];Wc.default=mk});var Jh=T(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.contentVocabulary=Vr.metadataVocabulary=void 0;Vr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Vr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Wh=T(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var hk=nh(),gk=_h(),_k=Hh(),yk=Kh(),Gh=Jh(),vk=[hk.default,gk.default,(0,_k.default)(),yk.default,Gh.metadataVocabulary,Gh.contentVocabulary];Yc.default=vk});var Qh=T(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.DiscrError=void 0;var Yh;(function(e){e.Tag="tag",e.Mapping="mapping"})(Yh||(xs.DiscrError=Yh={}))});var eg=T(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var Hr=U(),Qc=Qh(),Xh=as(),bk=jn(),wk=H(),$k={message:({params:{discrError:e,tagName:t}})=>e===Qc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Hr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Sk={keyword:"discriminator",type:"object",schemaType:"object",error:$k,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),l=t.const("tag",(0,Hr._)`${r}${(0,Hr.getProperty)(a)}`);t.if((0,Hr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Qc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let m=f();t.if(!1);for(let h in m)t.elseIf((0,Hr._)`${l} === ${h}`),t.assign(c,d(m[h]));t.else(),e.error(!1,{discrError:Qc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(m){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:m},h);return e.mergeEvaluated(g,Hr.Name),h}function f(){var m;let h={},g=w(o),y=!0;for(let P=0;P<i.length;P++){let v=i[P];if(v?.$ref&&!(0,wk.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=Xh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof Xh.SchemaEnv&&(v=v.schema),v===void 0)throw new bk.default(s.opts.uriResolver,s.baseId,R)}let x=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||w(v)),S(x,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function w({required:P}){return Array.isArray(P)&&P.includes(a)}function S(P,v){if(P.const)$(P.const,v);else if(P.enum)for(let x of P.enum)$(x,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(P,v){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[P]=v}}}};Xc.default=Sk});var tg=T((P1,xk)=>{xk.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 tu=T((le,eu)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var kk=Ym(),zk=Wh(),Pk=eg(),rg=tg(),Tk=["/properties"],ks="http://json-schema.org/draft-07/schema",Br=class extends kk.default{_addVocabularies(){super._addVocabularies(),zk.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Pk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(rg,Tk):rg;this.addMetaSchema(t,ks,!1),this.refs["http://json-schema.org/schema"]=ks}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ks)?ks:void 0)}};le.Ajv=Br;eu.exports=le=Br;eu.exports.Ajv=Br;Object.defineProperty(le,"__esModule",{value:!0});le.default=Br;var Rk=Nn();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return Rk.KeywordCxt}});var Kr=U();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Kr._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Kr.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Kr.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Kr.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Kr.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Kr.CodeGen}});var Ek=ss();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return Ek.default}});var Ik=jn();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return Ik.default}})});var lg=T(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.formatNames=mt.fastFormats=mt.fullFormats=void 0;function ft(e,t){return{validate:e,compare:t}}mt.fullFormats={date:ft(ig,su),time:ft(nu(!0),iu),"date-time":ft(ng(!0),cg),"iso-time":ft(nu(),ag),"iso-date-time":ft(ng(),ug),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Mk,"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:Vk,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:Uk,int32:{type:"number",validate:qk},int64:{type:"number",validate:Lk},float:{type:"number",validate:sg},double:{type:"number",validate:sg},password:!0,binary:!0};mt.fastFormats={...mt.fullFormats,date:ft(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,su),time:ft(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,iu),"date-time":ft(/^\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,cg),"iso-time":ft(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ag),"iso-date-time":ft(/^\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,ug),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};mt.formatNames=Object.keys(mt.fullFormats);function Ok(e){return e%4===0&&(e%100!==0||e%400===0)}var Ak=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ck=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ig(e){let t=Ak.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&&Ok(r)?29:Ck[n])}function su(e,t){if(e&&t)return e>t?1:e<t?-1:0}var ru=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function nu(e){return function(r){let n=ru.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*c,f=o-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function iu(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 ag(e,t){if(!(e&&t))return;let r=ru.exec(e),n=ru.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 ou=/t|\s/i;function ng(e){let t=nu(e);return function(n){let o=n.split(ou);return o.length===2&&ig(o[0])&&t(o[1])}}function cg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function ug(e,t){if(!(e&&t))return;let[r,n]=e.split(ou),[o,s]=t.split(ou),i=su(r,o);if(i!==void 0)return i||iu(n,s)}var Nk=/\/|:/,jk=/^(?:[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 Mk(e){return Nk.test(e)&&jk.test(e)}var og=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Uk(e){return og.lastIndex=0,og.test(e)}var Dk=-(2**31),Zk=2**31-1;function qk(e){return Number.isInteger(e)&&e<=Zk&&e>=Dk}function Lk(e){return Number.isInteger(e)}function sg(){return!0}var Fk=/[^\\]\\Z/;function Vk(e){if(Fk.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var dg=T(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.formatLimitDefinition=void 0;var Hk=tu(),ct=U(),Dt=ct.operators,zs={formatMaximum:{okStr:"<=",ok:Dt.LTE,fail:Dt.GT},formatMinimum:{okStr:">=",ok:Dt.GTE,fail:Dt.LT},formatExclusiveMaximum:{okStr:"<",ok:Dt.LT,fail:Dt.GTE},formatExclusiveMinimum:{okStr:">",ok:Dt.GT,fail:Dt.LTE}},Bk={message:({keyword:e,schemaCode:t})=>(0,ct.str)`should be ${zs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ct._)`{comparison: ${zs[e].okStr}, limit: ${t}}`};Jr.formatLimitDefinition={keyword:Object.keys(zs),type:"string",schemaType:"string",$data:!0,error:Bk,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 Hk.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=t.const("fmt",(0,ct._)`${f}[${c.schemaCode}]`);e.fail$data((0,ct.or)((0,ct._)`typeof ${m} != "object"`,(0,ct._)`${m} instanceof RegExp`,(0,ct._)`typeof ${m}.compare != "function"`,d(m)))}function u(){let f=c.schema,m=a.formats[f];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=t.scopeValue("formats",{key:f,ref:m,code:i.code.formats?(0,ct._)`${i.code.formats}${(0,ct.getProperty)(f)}`:void 0});e.fail$data(d(h))}function d(f){return(0,ct._)`${f}.compare(${r}, ${n}) ${zs[o].fail} 0`}},dependencies:["format"]};var Kk=e=>(e.addKeyword(Jr.formatLimitDefinition),e);Jr.default=Kk});var hg=T((Wn,mg)=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});var Gr=lg(),Jk=dg(),au=U(),pg=new au.Name("fullFormats"),Gk=new au.Name("fastFormats"),cu=(e,t={keywords:!0})=>{if(Array.isArray(t))return fg(e,t,Gr.fullFormats,pg),e;let[r,n]=t.mode==="fast"?[Gr.fastFormats,Gk]:[Gr.fullFormats,pg],o=t.formats||Gr.formatNames;return fg(e,o,r,n),t.keywords&&(0,Jk.default)(e),e};cu.get=(e,t="full")=>{let n=(t==="fast"?Gr.fastFormats:Gr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function fg(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,au._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}mg.exports=Wn=cu;Object.defineProperty(Wn,"__esModule",{value:!0});Wn.default=cu});import{spawn as $_,spawnSync as Xr}from"node:child_process";import{connect as mP}from"node:net";import{homedir as S_,userInfo as Pu}from"node:os";import{resolve as x_,join as Pt,dirname as Ou}from"node:path";import{fileURLToPath as hP,pathToFileURL as gP}from"node:url";import{createInterface as qs}from"node:readline/promises";import*as q from"node:fs";var Gs=Object.freeze({status:"aborted"});function _(e,t,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].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 l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}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 L_=Symbol("zod_brand"),yt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_o={};function Fe(e){return e&&Object.assign(_o,e),_o}var G={};Js(G,{BIGINT_FORMAT_RANGES:()=>qu,Class:()=>Ys,NUMBER_FORMAT_RANGES:()=>si,aborted:()=>Bt,allowsEval:()=>ri,assert:()=>K_,assertEqual:()=>F_,assertIs:()=>H_,assertNever:()=>B_,assertNotEqual:()=>V_,assignProp:()=>ti,cached:()=>nn,captureStackTrace:()=>vo,cleanEnum:()=>iy,cleanRegex:()=>sn,clone:()=>et,createTransparentProxy:()=>X_,defineLazy:()=>oe,esc:()=>Ht,escapeRegex:()=>Rt,extend:()=>ry,finalizeIssue:()=>tt,floatSafeRemainder:()=>ei,getElementAtPath:()=>J_,getEnumValues:()=>Qs,getLengthableOrigin:()=>an,getParsedType:()=>Q_,getSizableOrigin:()=>Lu,isObject:()=>vr,isPlainObject:()=>br,issue:()=>ii,joinValues:()=>yo,jsonStringifyReplacer:()=>Xs,merge:()=>ny,normalizeParams:()=>A,nullish:()=>on,numKeys:()=>Y_,omit:()=>ty,optionalKeys:()=>oi,partial:()=>oy,pick:()=>ey,prefixIssues:()=>ut,primitiveTypes:()=>Zu,promiseAllObject:()=>G_,propertyKeyTypes:()=>ni,randomString:()=>W_,required:()=>sy,stringifyPrimitive:()=>bo,unwrapMessage:()=>rn});function F_(e){return e}function V_(e){return e}function H_(e){}function B_(e){throw new Error}function K_(e){}function Qs(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 yo(e,t="|"){return e.map(r=>bo(r)).join(t)}function Xs(e,t){return typeof t=="bigint"?t.toString():t}function nn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function on(e){return e==null}function sn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ei(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 oe(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 ti(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function J_(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function G_(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 W_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Ht(e){return JSON.stringify(e)}var vo=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ri=nn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function br(e){if(vr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(vr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Y_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Q_=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}`)}},ni=new Set(["string","number","symbol"]),Zu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function et(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function A(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 X_(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 bo(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function oi(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var si={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]},qu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ey(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 et(e,{...e._zod.def,shape:r,checks:[]})}function ty(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 et(e,{...e._zod.def,shape:r,checks:[]})}function ry(e,t){if(!br(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 ti(this,"shape",n),n},checks:[]};return et(e,r)}function ny(e,t){return et(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ti(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function oy(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 et(t,{...t._zod.def,shape:o,checks:[]})}function sy(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 et(t,{...t._zod.def,shape:o,checks:[]})}function Bt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ut(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function rn(e){return typeof e=="string"?e:e?.message}function tt(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=rn(e.inst?._zod.def?.error?.(e))??rn(t?.error?.(e))??rn(r.customError?.(e))??rn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Lu(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function an(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ii(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function iy(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ys=class{constructor(...t){}};var Fu=(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,Xs,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},wo=_("$ZodError",Fu),ai=_("$ZodError",Fu,{Parent:Error});function ci(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 ui(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 l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var Vu=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 yt;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>tt(c,s,Fe())));throw vo(a,o?.callee),a}return i.value};var Hu=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=>tt(c,s,Fe())));throw vo(a,o?.callee),a}return i.value};var li=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 yt;return s.issues.length?{success:!1,error:new(e??wo)(s.issues.map(i=>tt(i,o,Fe())))}:{success:!0,data:s.value}},cn=li(ai),di=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=>tt(i,o,Fe())))}:{success:!0,data:s.value}},$o=di(ai);var Bu=/^[cC][^\s-]{8,}$/,Ku=/^[0-9a-z]+$/,Ju=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gu=/^[0-9a-vA-V]{20}$/,Wu=/^[A-Za-z0-9]{27}$/,Yu=/^[a-zA-Z0-9_-]{21}$/,Qu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Xu=/^([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})$/,pi=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 el=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var cy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function tl(){return new RegExp(cy,"u")}var rl=/^(?:(?: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])$/,nl=/^(([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})$/,ol=/^((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])$/,il=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,fi=/^[A-Za-z0-9_-]*$/,al=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var cl=/^\+(?:[0-9]){6,14}[0-9]$/,ul="(?:(?:\\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])))",ll=new RegExp(`^${ul}$`);function dl(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 pl(e){return new RegExp(`^${dl(e)}$`)}function fl(e){let t=dl({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(`^${ul}T(?:${n})$`)}var ml=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},hl=/^\d+n?$/,gl=/^\d+$/,_l=/^-?\d+(?:\.\d+)?/i,yl=/true|false/i,vl=/null/i;var bl=/^[^A-Z]*$/,wl=/^[^a-z]*$/;var Te=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),$l={number:"number",bigint:"bigint",object:"date"},mi=_("$ZodCheckLessThan",(e,t)=>{Te.init(e,t);let r=$l[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})}}),hi=_("$ZodCheckGreaterThan",(e,t)=>{Te.init(e,t);let r=$l[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})}}),Sl=_("$ZodCheckMultipleOf",(e,t)=>{Te.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):ei(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})}}),xl=_("$ZodCheckNumberFormat",(e,t)=>{Te.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=si[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=gl)}),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 kl=_("$ZodCheckMaxLength",(e,t)=>{var r;Te.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!on(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=an(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),zl=_("$ZodCheckMinLength",(e,t)=>{var r;Te.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!on(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=an(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Pl=_("$ZodCheckLengthEquals",(e,t)=>{var r;Te.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!on(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=an(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})}}),un=_("$ZodCheckStringFormat",(e,t)=>{var r,n;Te.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=()=>{})}),Tl=_("$ZodCheckRegex",(e,t)=>{un.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})}}),Rl=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=bl),un.init(e,t)}),El=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wl),un.init(e,t)}),Il=_("$ZodCheckIncludes",(e,t)=>{Te.init(e,t);let r=Rt(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})}}),Ol=_("$ZodCheckStartsWith",(e,t)=>{Te.init(e,t);let r=new RegExp(`^${Rt(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})}}),Al=_("$ZodCheckEndsWith",(e,t)=>{Te.init(e,t);let r=new RegExp(`.*${Rt(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 Cl=_("$ZodCheckOverwrite",(e,t)=>{Te.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var xo=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 Al={major:4,minor:0,patch:0};var X=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Al;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=Bt(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,f=u._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new _t;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=Bt(s,d)))});else{if(s.issues.length===d)continue;c||(c=Bt(s,d))}}return l?l.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 _t;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=an(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return wo(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),xo=_("$ZodString",(e,t)=>{X.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??dl(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}}),ae=_("$ZodStringFormat",(e,t)=>{cn.init(e,t),xo.init(e,t)}),Fl=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Wu),ae.init(e,t)}),Vl=_("$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=li(n))}else t.pattern??(t.pattern=li());ae.init(e,t)}),Hl=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Yu),ae.init(e,t)}),Bl=_("$ZodURL",(e,t)=>{ae.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:ol.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})}}}),Kl=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Qu()),ae.init(e,t)}),Jl=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ju),ae.init(e,t)}),Gl=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Fu),ae.init(e,t)}),Wl=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Vu),ae.init(e,t)}),Yl=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Hu),ae.init(e,t)}),Ql=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Bu),ae.init(e,t)}),Xl=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ku),ae.init(e,t)}),ed=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ll(t)),ae.init(e,t)}),td=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=al),ae.init(e,t)}),rd=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ul(t)),ae.init(e,t)}),nd=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Gu),ae.init(e,t)}),od=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Xu),ae.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),sd=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=el),ae.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})}}}),id=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=tl),ae.init(e,t)}),ad=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=rl),ae.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 cd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var ud=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=nl),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{cd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ey(e){if(!di.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return cd(r)}var ld=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=di),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ey(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),dd=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=sl),ae.init(e,t)});function ty(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 pd=_("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=r=>{ty(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var hi=_("$ZodNumber",(e,t)=>{X.init(e,t),e._zod.pattern=e._zod.bag.pattern??ml,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}}),fd=_("$ZodNumber",(e,t)=>{bl.init(e,t),hi.init(e,t)}),md=_("$ZodBoolean",(e,t)=>{X.init(e,t),e._zod.pattern=hl,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}}),hd=_("$ZodBigInt",(e,t)=>{X.init(e,t),e._zod.pattern=pl,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 gd=_("$ZodNull",(e,t)=>{X.init(e,t),e._zod.pattern=gl,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}}),_d=_("$ZodAny",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),yd=_("$ZodUnknown",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),vd=_("$ZodNever",(e,t)=>{X.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var wd=_("$ZodDate",(e,t)=>{X.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 Cl(e,t,r){e.issues.length&&t.issues.push(...ut(r,e.issues)),t.value[r]=e.value}var bd=_("$ZodArray",(e,t)=>{X.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(l=>Cl(l,r,i))):Cl(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function So(e,t,r){e.issues.length&&t.issues.push(...ut(r,e.issues)),t.value[r]=e.value}function Nl(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(...ut(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var $d=_("$ZodObject",(e,t)=>{X.init(e,t);let r=rn(()=>{let d=Object.keys(t.shape);for(let m of d)if(!(t.shape[m]instanceof X))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=ri(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});oe(e._zod,"propValues",()=>{let d=t.shape,f={};for(let m in d){let h=d[m]._zod;if(h.values){f[m]??(f[m]=new Set);for(let g of h.values)f[m].add(g)}}return f});let n=d=>{let f=new $o(["shape","payload","ctx"]),m=r.value,h=S=>{let $=Ht(S);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let g=Object.create(null),y=0;for(let S of m.keys)g[S]=`key_${y++}`;f.write("const newResult = {}");for(let S of m.keys)if(m.optionalKeys.has(S)){let $=g[S];f.write(`const ${$} = ${h(S)};`);let P=Ht(S);f.write(`
12
+ `))}};var jl={major:4,minor:0,patch:0};var X=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=jl;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=Bt(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,f=u._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new yt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=Bt(s,d)))});else{if(s.issues.length===d)continue;c||(c=Bt(s,d))}}return l?l.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 yt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=cn(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return $o(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),zo=_("$ZodString",(e,t)=>{X.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ml(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}}),ae=_("$ZodStringFormat",(e,t)=>{un.init(e,t),zo.init(e,t)}),Bl=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xu),ae.init(e,t)}),Kl=_("$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=pi(n))}else t.pattern??(t.pattern=pi());ae.init(e,t)}),Jl=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=el),ae.init(e,t)}),Gl=_("$ZodURL",(e,t)=>{ae.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:al.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})}}}),Wl=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=tl()),ae.init(e,t)}),Yl=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Yu),ae.init(e,t)}),Ql=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Bu),ae.init(e,t)}),Xl=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ku),ae.init(e,t)}),ed=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ju),ae.init(e,t)}),td=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Gu),ae.init(e,t)}),rd=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Wu),ae.init(e,t)}),nd=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=fl(t)),ae.init(e,t)}),od=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ll),ae.init(e,t)}),sd=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=pl(t)),ae.init(e,t)}),id=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qu),ae.init(e,t)}),ad=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=rl),ae.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),cd=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=nl),ae.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})}}}),ud=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ol),ae.init(e,t)}),ld=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=sl),ae.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 dd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var pd=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=il),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{dd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function uy(e){if(!fi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return dd(r)}var fd=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=fi),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{uy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),md=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=cl),ae.init(e,t)});function ly(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 hd=_("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=r=>{ly(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var _i=_("$ZodNumber",(e,t)=>{X.init(e,t),e._zod.pattern=e._zod.bag.pattern??_l,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}}),gd=_("$ZodNumber",(e,t)=>{xl.init(e,t),_i.init(e,t)}),_d=_("$ZodBoolean",(e,t)=>{X.init(e,t),e._zod.pattern=yl,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}}),yd=_("$ZodBigInt",(e,t)=>{X.init(e,t),e._zod.pattern=hl,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 vd=_("$ZodNull",(e,t)=>{X.init(e,t),e._zod.pattern=vl,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}}),bd=_("$ZodAny",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),wd=_("$ZodUnknown",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),$d=_("$ZodNever",(e,t)=>{X.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var Sd=_("$ZodDate",(e,t)=>{X.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 Ml(e,t,r){e.issues.length&&t.issues.push(...ut(r,e.issues)),t.value[r]=e.value}var xd=_("$ZodArray",(e,t)=>{X.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(l=>Ml(l,r,i))):Ml(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ko(e,t,r){e.issues.length&&t.issues.push(...ut(r,e.issues)),t.value[r]=e.value}function Ul(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(...ut(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var kd=_("$ZodObject",(e,t)=>{X.init(e,t);let r=nn(()=>{let d=Object.keys(t.shape);for(let m of d)if(!(t.shape[m]instanceof X))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=oi(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});oe(e._zod,"propValues",()=>{let d=t.shape,f={};for(let m in d){let h=d[m]._zod;if(h.values){f[m]??(f[m]=new Set);for(let g of h.values)f[m].add(g)}}return f});let n=d=>{let f=new xo(["shape","payload","ctx"]),m=r.value,h=S=>{let $=Ht(S);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let g=Object.create(null),y=0;for(let S of m.keys)g[S]=`key_${y++}`;f.write("const newResult = {}");for(let S of m.keys)if(m.optionalKeys.has(S)){let $=g[S];f.write(`const ${$} = ${h(S)};`);let P=Ht(S);f.write(`
13
13
  if (${$}.issues.length) {
14
14
  if (input[${P}] === undefined) {
15
15
  if (${P} in input) {
@@ -32,35 +32,35 @@ var P_=Object.create;var Hs=Object.defineProperty;var T_=Object.getOwnPropertyDe
32
32
  if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
33
33
  ...iss,
34
34
  path: iss.path ? [${Ht(S)}, ...iss.path] : [${Ht(S)}]
35
- })));`),f.write(`newResult[${Ht(S)}] = ${$}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let b=f.compile();return(S,$)=>b(d,S,$)},o,s=yr,i=!ho.jitless,c=i&&ei.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??(u=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&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let $=u.shape;for(let P of u.keys){let v=$[P],x=v._zod.run({value:m[P],issues:[]},f),R=v._zod.optin==="optional"&&v._zod.optout==="optional";x instanceof Promise?h.push(x.then(L=>R?Nl(L,d,P,m):So(L,d,P))):R?Nl(x,d,P,m):So(x,d,P)}}if(!l)return h.length?Promise.all(h).then(()=>d):d;let g=[],y=u.keySet,b=l._zod,S=b.def.type;for(let $ of Object.keys(m)){if(y.has($))continue;if(S==="never"){g.push($);continue}let P=b.run({value:m[$],issues:[]},f);P instanceof Promise?h.push(P.then(v=>So(v,d,$))):So(P,d,$)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:m,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function jl(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=>tt(s,n,Fe())))}),t}var gi=_("$ZodUnion",(e,t)=>{X.init(e,t),oe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),oe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),oe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),oe(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=>on(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=>jl(i,r,e,n)):jl(s,r,e,n)}}),Sd=_("$ZodDiscriminatedUnion",(e,t)=>{gi.init(e,t);let r=e._zod.parse;oe(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 l of c)o[a].add(l)}}return o});let n=rn(()=>{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(!yr(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)}}),xd=_("$ZodIntersection",(e,t)=>{X.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,l])=>Ml(r,c,l)):Ml(r,s,i)}});function mi(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(vr(e)&&vr(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=mi(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=mi(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 Ml(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Bt(e))return e;let n=mi(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 zd=_("$ZodRecord",(e,t)=>{X.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!vr(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 l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...ut(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...ut(c,l.issues)),r.value[c]=l.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(l=>tt(l,n,Fe())),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(l=>{l.issues.length&&r.issues.push(...ut(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...ut(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var kd=_("$ZodEnum",(e,t)=>{X.init(e,t);let r=Ws(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>ti.has(typeof n)).map(n=>typeof n=="string"?Rt(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}}),Pd=_("$ZodLiteral",(e,t)=>{X.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Rt(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 Td=_("$ZodTransform",(e,t)=>{X.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 _t;return r.value=o,r}}),Rd=_("$ZodOptional",(e,t)=>{X.init(e,t),e._zod.optin="optional",e._zod.optout="optional",oe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),oe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${on(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)}),Ed=_("$ZodNullable",(e,t)=>{X.init(e,t),oe(e._zod,"optin",()=>t.innerType._zod.optin),oe(e._zod,"optout",()=>t.innerType._zod.optout),oe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${on(r.source)}|null)$`):void 0}),oe(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)}),Id=_("$ZodDefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",oe(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=>Ul(s,t)):Ul(o,t)}});function Ul(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Od=_("$ZodPrefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",oe(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))}),Ad=_("$ZodNonOptional",(e,t)=>{X.init(e,t),oe(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=>Dl(s,e)):Dl(o,e)}});function Dl(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 Cd=_("$ZodCatch",(e,t)=>{X.init(e,t),e._zod.optin="optional",oe(e._zod,"optout",()=>t.innerType._zod.optout),oe(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=>tt(i,n,Fe()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>tt(s,n,Fe()))},input:r.value}),r.issues=[]),r)}});var Nd=_("$ZodPipe",(e,t)=>{X.init(e,t),oe(e._zod,"values",()=>t.in._zod.values),oe(e._zod,"optin",()=>t.in._zod.optin),oe(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=>Zl(s,t,n)):Zl(o,t,n)}});function Zl(e,t,r){return Bt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var jd=_("$ZodReadonly",(e,t)=>{X.init(e,t),oe(e._zod,"propValues",()=>t.innerType._zod.propValues),oe(e._zod,"values",()=>t.innerType._zod.values),oe(e._zod,"optin",()=>t.innerType._zod.optin),oe(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(ql):ql(o)}});function ql(e){return e.value=Object.freeze(e.value),e}var Md=_("$ZodCustom",(e,t)=>{Te.init(e,t),X.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=>Ll(s,r,n,e));Ll(o,r,n,e)}});function Ll(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(oi(o))}}var ry=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},ny=()=>{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 ${ry(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${yo(n.values[0])}`:`Invalid option: expected one of ${go(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":""}: ${go(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 Ud(){return{localeError:ny()}}var oy=Symbol("ZodOutput"),sy=Symbol("ZodInput"),_i=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 Dd(){return new _i}var wr=Dd();function Zd(e,t){return new e({type:"string",...A(t)})}function qd(e,t){return new e({type:"string",coerce:!0,...A(t)})}function Ld(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...A(t)})}function yi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A(t)})}function Fd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...A(t)})}function Vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(t)})}function Hd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(t)})}function Bd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(t)})}function vi(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...A(t)})}function Kd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...A(t)})}function Jd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(t)})}function Gd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...A(t)})}function Wd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(t)})}function Yd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...A(t)})}function Qd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...A(t)})}function Xd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(t)})}function ep(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(t)})}function tp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(t)})}function rp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(t)})}function np(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(t)})}function op(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...A(t)})}function sp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...A(t)})}function ip(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...A(t)})}function ap(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...A(t)})}function cp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(t)})}function up(e,t){return new e({type:"string",format:"date",check:"string_format",...A(t)})}function lp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...A(t)})}function dp(e,t){return new e({type:"string",format:"duration",check:"string_format",...A(t)})}function pp(e,t){return new e({type:"number",checks:[],...A(t)})}function fp(e,t){return new e({type:"number",coerce:!0,checks:[],...A(t)})}function mp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...A(t)})}function hp(e,t){return new e({type:"boolean",...A(t)})}function gp(e,t){return new e({type:"boolean",coerce:!0,...A(t)})}function _p(e,t){return new e({type:"bigint",coerce:!0,...A(t)})}function yp(e,t){return new e({type:"null",...A(t)})}function vp(e){return new e({type:"any"})}function wp(e){return new e({type:"unknown"})}function bp(e,t){return new e({type:"never",...A(t)})}function $p(e,t){return new e({type:"date",coerce:!0,...A(t)})}function br(e,t){return new pi({check:"less_than",...A(t),value:e,inclusive:!1})}function yt(e,t){return new pi({check:"less_than",...A(t),value:e,inclusive:!0})}function $r(e,t){return new fi({check:"greater_than",...A(t),value:e,inclusive:!1})}function rt(e,t){return new fi({check:"greater_than",...A(t),value:e,inclusive:!0})}function un(e,t){return new wl({check:"multiple_of",...A(t),value:e})}function zo(e,t){return new $l({check:"max_length",...A(t),maximum:e})}function Sr(e,t){return new Sl({check:"min_length",...A(t),minimum:e})}function ko(e,t){return new xl({check:"length_equals",...A(t),length:e})}function wi(e,t){return new zl({check:"string_format",format:"regex",...A(t),pattern:e})}function bi(e){return new kl({check:"string_format",format:"lowercase",...A(e)})}function $i(e){return new Pl({check:"string_format",format:"uppercase",...A(e)})}function Si(e,t){return new Tl({check:"string_format",format:"includes",...A(t),includes:e})}function xi(e,t){return new Rl({check:"string_format",format:"starts_with",...A(t),prefix:e})}function zi(e,t){return new El({check:"string_format",format:"ends_with",...A(t),suffix:e})}function Kt(e){return new Il({check:"overwrite",tx:e})}function ki(e){return Kt(t=>t.normalize(e))}function Pi(){return Kt(e=>e.trim())}function Ti(){return Kt(e=>e.toLowerCase())}function Ri(){return Kt(e=>e.toUpperCase())}function Sp(e,t,r){return new e({type:"array",element:t,...A(r)})}function xp(e,t,r){let n=A(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function zp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...A(r)})}function zr(e){return!!e._zod}function nt(e,t){return zr(e)?an(e,t):e.safeParse(t)}function Po(e){if(!e)return;let t;if(zr(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(zr(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 ln={};Bs(ln,{ZodISODate:()=>Tp,ZodISODateTime:()=>Pp,ZodISODuration:()=>Ep,ZodISOTime:()=>Rp,date:()=>Ii,datetime:()=>Ei,duration:()=>Ai,time:()=>Oi});var Pp=_("ZodISODateTime",(e,t)=>{ed.init(e,t),de.init(e,t)});function Ei(e){return cp(Pp,e)}var Tp=_("ZodISODate",(e,t)=>{td.init(e,t),de.init(e,t)});function Ii(e){return up(Tp,e)}var Rp=_("ZodISOTime",(e,t)=>{rd.init(e,t),de.init(e,t)});function Oi(e){return lp(Rp,e)}var Ep=_("ZodISODuration",(e,t)=>{nd.init(e,t),de.init(e,t)});function Ai(e){return dp(Ep,e)}var Op=(e,t)=>{vo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ai(e,r)},flatten:{value:r=>ii(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},yT=_("ZodError",Op),dn=_("ZodError",Op,{Parent:Error});var Ap=qu(dn),Cp=Lu(dn),Np=ci(dn),jp=ui(dn);var se=_("ZodType",(e,t)=>(X.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)=>et(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Ap(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Np(e,r,n),e.parseAsync=async(r,n)=>Cp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>jp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Xy(r,n)),e.superRefine=r=>e.check(ev(r)),e.overwrite=r=>e.check(Kt(r)),e.optional=()=>fe(e),e.nullable=()=>Dp(e),e.nullish=()=>fe(Dp(e)),e.nonoptional=r=>By(e,r),e.array=()=>z(e),e.or=r=>ce([e,r]),e.and=r=>Eo(e,r),e.transform=r=>Ni(e,Gp(r)),e.default=r=>Fy(e,r),e.prefault=r=>Hy(e,r),e.catch=r=>Jy(e,r),e.pipe=r=>Ni(e,r),e.readonly=()=>Yy(e),e.describe=r=>{let n=e.clone();return wr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return wr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return wr.get(e);let n=e.clone();return wr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Zp=_("_ZodString",(e,t)=>{xo.init(e,t),se.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(wi(...n)),e.includes=(...n)=>e.check(Si(...n)),e.startsWith=(...n)=>e.check(xi(...n)),e.endsWith=(...n)=>e.check(zi(...n)),e.min=(...n)=>e.check(Sr(...n)),e.max=(...n)=>e.check(zo(...n)),e.length=(...n)=>e.check(ko(...n)),e.nonempty=(...n)=>e.check(Sr(1,...n)),e.lowercase=n=>e.check(bi(n)),e.uppercase=n=>e.check($i(n)),e.trim=()=>e.check(Pi()),e.normalize=(...n)=>e.check(ki(...n)),e.toLowerCase=()=>e.check(Ti()),e.toUpperCase=()=>e.check(Ri())}),ji=_("ZodString",(e,t)=>{xo.init(e,t),Zp.init(e,t),e.email=r=>e.check(Ld(fy,r)),e.url=r=>e.check(vi(qp,r)),e.jwt=r=>e.check(ap(Ty,r)),e.emoji=r=>e.check(Kd(my,r)),e.guid=r=>e.check(yi(Mp,r)),e.uuid=r=>e.check(Fd(To,r)),e.uuidv4=r=>e.check(Vd(To,r)),e.uuidv6=r=>e.check(Hd(To,r)),e.uuidv7=r=>e.check(Bd(To,r)),e.nanoid=r=>e.check(Jd(hy,r)),e.guid=r=>e.check(yi(Mp,r)),e.cuid=r=>e.check(Gd(gy,r)),e.cuid2=r=>e.check(Wd(_y,r)),e.ulid=r=>e.check(Yd(yy,r)),e.base64=r=>e.check(op(zy,r)),e.base64url=r=>e.check(sp(ky,r)),e.xid=r=>e.check(Qd(vy,r)),e.ksuid=r=>e.check(Xd(wy,r)),e.ipv4=r=>e.check(ep(by,r)),e.ipv6=r=>e.check(tp($y,r)),e.cidrv4=r=>e.check(rp(Sy,r)),e.cidrv6=r=>e.check(np(xy,r)),e.e164=r=>e.check(ip(Py,r)),e.datetime=r=>e.check(Ei(r)),e.date=r=>e.check(Ii(r)),e.time=r=>e.check(Oi(r)),e.duration=r=>e.check(Ai(r))});function p(e){return Zd(ji,e)}var de=_("ZodStringFormat",(e,t)=>{ae.init(e,t),Zp.init(e,t)}),fy=_("ZodEmail",(e,t)=>{Hl.init(e,t),de.init(e,t)});var Mp=_("ZodGUID",(e,t)=>{Fl.init(e,t),de.init(e,t)});var To=_("ZodUUID",(e,t)=>{Vl.init(e,t),de.init(e,t)});var qp=_("ZodURL",(e,t)=>{Bl.init(e,t),de.init(e,t)});function Lp(e){return vi(qp,e)}var my=_("ZodEmoji",(e,t)=>{Kl.init(e,t),de.init(e,t)});var hy=_("ZodNanoID",(e,t)=>{Jl.init(e,t),de.init(e,t)});var gy=_("ZodCUID",(e,t)=>{Gl.init(e,t),de.init(e,t)});var _y=_("ZodCUID2",(e,t)=>{Wl.init(e,t),de.init(e,t)});var yy=_("ZodULID",(e,t)=>{Yl.init(e,t),de.init(e,t)});var vy=_("ZodXID",(e,t)=>{Ql.init(e,t),de.init(e,t)});var wy=_("ZodKSUID",(e,t)=>{Xl.init(e,t),de.init(e,t)});var by=_("ZodIPv4",(e,t)=>{od.init(e,t),de.init(e,t)});var $y=_("ZodIPv6",(e,t)=>{sd.init(e,t),de.init(e,t)});var Sy=_("ZodCIDRv4",(e,t)=>{id.init(e,t),de.init(e,t)});var xy=_("ZodCIDRv6",(e,t)=>{ad.init(e,t),de.init(e,t)});var zy=_("ZodBase64",(e,t)=>{ud.init(e,t),de.init(e,t)});var ky=_("ZodBase64URL",(e,t)=>{ld.init(e,t),de.init(e,t)});var Py=_("ZodE164",(e,t)=>{dd.init(e,t),de.init(e,t)});var Ty=_("ZodJWT",(e,t)=>{pd.init(e,t),de.init(e,t)});var Ro=_("ZodNumber",(e,t)=>{hi.init(e,t),se.init(e,t),e.gt=(n,o)=>e.check($r(n,o)),e.gte=(n,o)=>e.check(rt(n,o)),e.min=(n,o)=>e.check(rt(n,o)),e.lt=(n,o)=>e.check(br(n,o)),e.lte=(n,o)=>e.check(yt(n,o)),e.max=(n,o)=>e.check(yt(n,o)),e.int=n=>e.check(Up(n)),e.safe=n=>e.check(Up(n)),e.positive=n=>e.check($r(0,n)),e.nonnegative=n=>e.check(rt(0,n)),e.negative=n=>e.check(br(0,n)),e.nonpositive=n=>e.check(yt(0,n)),e.multipleOf=(n,o)=>e.check(un(n,o)),e.step=(n,o)=>e.check(un(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 K(e){return pp(Ro,e)}var Ry=_("ZodNumberFormat",(e,t)=>{fd.init(e,t),Ro.init(e,t)});function Up(e){return mp(Ry,e)}var Mi=_("ZodBoolean",(e,t)=>{md.init(e,t),se.init(e,t)});function re(e){return hp(Mi,e)}var Fp=_("ZodBigInt",(e,t)=>{hd.init(e,t),se.init(e,t),e.gte=(n,o)=>e.check(rt(n,o)),e.min=(n,o)=>e.check(rt(n,o)),e.gt=(n,o)=>e.check($r(n,o)),e.gte=(n,o)=>e.check(rt(n,o)),e.min=(n,o)=>e.check(rt(n,o)),e.lt=(n,o)=>e.check(br(n,o)),e.lte=(n,o)=>e.check(yt(n,o)),e.max=(n,o)=>e.check(yt(n,o)),e.positive=n=>e.check($r(BigInt(0),n)),e.negative=n=>e.check(br(BigInt(0),n)),e.nonpositive=n=>e.check(yt(BigInt(0),n)),e.nonnegative=n=>e.check(rt(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(un(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Ey=_("ZodNull",(e,t)=>{gd.init(e,t),se.init(e,t)});function Vp(e){return yp(Ey,e)}var Iy=_("ZodAny",(e,t)=>{_d.init(e,t),se.init(e,t)});function Hp(){return vp(Iy)}var Oy=_("ZodUnknown",(e,t)=>{yd.init(e,t),se.init(e,t)});function pe(){return wp(Oy)}var Ay=_("ZodNever",(e,t)=>{vd.init(e,t),se.init(e,t)});function Cy(e){return bp(Ay,e)}var Bp=_("ZodDate",(e,t)=>{wd.init(e,t),se.init(e,t),e.min=(n,o)=>e.check(rt(n,o)),e.max=(n,o)=>e.check(yt(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 Ny=_("ZodArray",(e,t)=>{bd.init(e,t),se.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Sr(r,n)),e.nonempty=r=>e.check(Sr(1,r)),e.max=(r,n)=>e.check(zo(r,n)),e.length=(r,n)=>e.check(ko(r,n)),e.unwrap=()=>e.element});function z(e,t){return Sp(Ny,e,t)}var Kp=_("ZodObject",(e,t)=>{$d.init(e,t),se.init(e,t),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>je(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:pe()}),e.loose=()=>e.clone({...e._zod.def,catchall:pe()}),e.strict=()=>e.clone({...e._zod.def,catchall:Cy()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>G.extend(e,r),e.merge=r=>G.merge(e,r),e.pick=r=>G.pick(e,r),e.omit=r=>G.omit(e,r),e.partial=(...r)=>G.partial(Wp,e,r[0]),e.required=(...r)=>G.required(Yp,e,r[0])});function k(e,t){let r={type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},...G.normalizeParams(t)};return new Kp(r)}function ye(e,t){return new Kp({type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},catchall:pe(),...G.normalizeParams(t)})}var Jp=_("ZodUnion",(e,t)=>{gi.init(e,t),se.init(e,t),e.options=t.options});function ce(e,t){return new Jp({type:"union",options:e,...G.normalizeParams(t)})}var jy=_("ZodDiscriminatedUnion",(e,t)=>{Jp.init(e,t),Sd.init(e,t)});function Ui(e,t,r){return new jy({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}var My=_("ZodIntersection",(e,t)=>{xd.init(e,t),se.init(e,t)});function Eo(e,t){return new My({type:"intersection",left:e,right:t})}var Uy=_("ZodRecord",(e,t)=>{zd.init(e,t),se.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ie(e,t,r){return new Uy({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}var Ci=_("ZodEnum",(e,t)=>{kd.init(e,t),se.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 Ci({...t,checks:[],...G.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 Ci({...t,checks:[],...G.normalizeParams(o),entries:s})}});function je(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ci({type:"enum",entries:r,...G.normalizeParams(t)})}var Dy=_("ZodLiteral",(e,t)=>{Pd.init(e,t),se.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 Dy({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}var Zy=_("ZodTransform",(e,t)=>{Td.init(e,t),se.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.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(G.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 Gp(e){return new Zy({type:"transform",transform:e})}var Wp=_("ZodOptional",(e,t)=>{Rd.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fe(e){return new Wp({type:"optional",innerType:e})}var qy=_("ZodNullable",(e,t)=>{Ed.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Dp(e){return new qy({type:"nullable",innerType:e})}var Ly=_("ZodDefault",(e,t)=>{Id.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Fy(e,t){return new Ly({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Vy=_("ZodPrefault",(e,t)=>{Od.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Hy(e,t){return new Vy({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Yp=_("ZodNonOptional",(e,t)=>{Ad.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function By(e,t){return new Yp({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}var Ky=_("ZodCatch",(e,t)=>{Cd.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jy(e,t){return new Ky({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Gy=_("ZodPipe",(e,t)=>{Nd.init(e,t),se.init(e,t),e.in=t.in,e.out=t.out});function Ni(e,t){return new Gy({type:"pipe",in:e,out:t})}var Wy=_("ZodReadonly",(e,t)=>{jd.init(e,t),se.init(e,t)});function Yy(e){return new Wy({type:"readonly",innerType:e})}var Qp=_("ZodCustom",(e,t)=>{Md.init(e,t),se.init(e,t)});function Qy(e){let t=new Te({check:"custom"});return t._zod.check=e,t}function Xp(e,t){return xp(Qp,e??(()=>!0),t)}function Xy(e,t={}){return zp(Qp,e,t)}function ev(e){let t=Qy(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(G.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(G.issue(o))}},e(r.value,r)));return t}function Di(e,t){return Ni(Gp(e),t)}var ef={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 Io={};Bs(Io,{bigint:()=>ov,boolean:()=>nv,date:()=>sv,number:()=>rv,string:()=>tv});function tv(e){return qd(ji,e)}function rv(e){return fp(Ro,e)}function nv(e){return gp(Mi,e)}function ov(e){return _p(Fp,e)}function sv(e){return $p(Bp,e)}Fe(Ud());var Pr="2025-11-25";var tf=[Pr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Et="io.modelcontextprotocol/related-task",Ao="2.0",ve=Xp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),rf=ce([p(),K().int()]),nf=p(),pR=ye({ttl:K().optional(),pollInterval:K().optional()}),av=k({ttl:K().optional()}),cv=k({taskId:p()}),qi=ye({progressToken:rf.optional(),[Et]:cv.optional()}),Ve=k({_meta:qi.optional()}),pn=Ve.extend({task:av.optional()}),of=e=>pn.safeParse(e).success,be=k({method:p(),params:Ve.loose().optional()}),Ke=k({_meta:qi.optional()}),Je=k({method:p(),params:Ke.loose().optional()}),$e=ye({_meta:qi.optional()}),Co=ce([p(),K().int()]),sf=k({jsonrpc:E(Ao),id:Co,...be.shape}).strict(),fn=e=>sf.safeParse(e).success,af=k({jsonrpc:E(Ao),...Je.shape}).strict(),cf=e=>af.safeParse(e).success,Li=k({jsonrpc:E(Ao),id:Co,result:$e}).strict(),Jt=e=>Li.safeParse(e).success;var N;(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"})(N||(N={}));var Fi=k({jsonrpc:E(Ao),id:Co.optional(),error:k({code:K().int(),message:p(),data:pe().optional()})}).strict();var uf=e=>Fi.safeParse(e).success;var Tr=ce([sf,af,Li,Fi]),fR=ce([Li,Fi]),Gt=$e.strict(),uv=Ke.extend({requestId:Co.optional(),reason:p().optional()}),No=Je.extend({method:E("notifications/cancelled"),params:uv}),lv=k({src:p(),mimeType:p().optional(),sizes:z(p()).optional(),theme:je(["light","dark"]).optional()}),mn=k({icons:z(lv).optional()}),kr=k({name:p(),title:p().optional()}),lf=kr.extend({...kr.shape,...mn.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),dv=Eo(k({applyDefaults:re().optional()}),ie(p(),pe())),pv=Di(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Eo(k({form:dv.optional(),url:ve.optional()}),ie(p(),pe()).optional())),fv=ye({list:ve.optional(),cancel:ve.optional(),requests:ye({sampling:ye({createMessage:ve.optional()}).optional(),elicitation:ye({create:ve.optional()}).optional()}).optional()}),mv=ye({list:ve.optional(),cancel:ve.optional(),requests:ye({tools:ye({call:ve.optional()}).optional()}).optional()}),hv=k({experimental:ie(p(),ve).optional(),sampling:k({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:pv.optional(),roots:k({listChanged:re().optional()}).optional(),tasks:fv.optional(),extensions:ie(p(),ve).optional()}),gv=Ve.extend({protocolVersion:p(),capabilities:hv,clientInfo:lf}),_v=be.extend({method:E("initialize"),params:gv});var yv=k({experimental:ie(p(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:k({listChanged:re().optional()}).optional(),resources:k({subscribe:re().optional(),listChanged:re().optional()}).optional(),tools:k({listChanged:re().optional()}).optional(),tasks:mv.optional(),extensions:ie(p(),ve).optional()}),Vi=$e.extend({protocolVersion:p(),capabilities:yv,serverInfo:lf,instructions:p().optional()}),df=Je.extend({method:E("notifications/initialized"),params:Ke.optional()}),pf=e=>df.safeParse(e).success,jo=be.extend({method:E("ping"),params:Ve.optional()}),vv=k({progress:K(),total:fe(K()),message:fe(p())}),wv=k({...Ke.shape,...vv.shape,progressToken:rf}),Mo=Je.extend({method:E("notifications/progress"),params:wv}),bv=Ve.extend({cursor:nf.optional()}),hn=be.extend({params:bv.optional()}),gn=$e.extend({nextCursor:nf.optional()}),$v=je(["working","input_required","completed","failed","cancelled"]),_n=k({taskId:p(),status:$v,ttl:ce([K(),Vp()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:fe(K()),statusMessage:fe(p())}),Wt=$e.extend({task:_n}),Sv=Ke.merge(_n),yn=Je.extend({method:E("notifications/tasks/status"),params:Sv}),Uo=be.extend({method:E("tasks/get"),params:Ve.extend({taskId:p()})}),Do=$e.merge(_n),Zo=be.extend({method:E("tasks/result"),params:Ve.extend({taskId:p()})}),mR=$e.loose(),qo=hn.extend({method:E("tasks/list")}),Lo=gn.extend({tasks:z(_n)}),Fo=be.extend({method:E("tasks/cancel"),params:Ve.extend({taskId:p()})}),ff=$e.merge(_n),mf=k({uri:p(),mimeType:fe(p()),_meta:ie(p(),pe()).optional()}),hf=mf.extend({text:p()}),Hi=p().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),gf=mf.extend({blob:Hi}),vn=je(["user","assistant"]),Rr=k({audience:z(vn).optional(),priority:K().min(0).max(1).optional(),lastModified:ln.datetime({offset:!0}).optional()}),_f=k({...kr.shape,...mn.shape,uri:p(),description:fe(p()),mimeType:fe(p()),size:fe(K()),annotations:Rr.optional(),_meta:fe(ye({}))}),xv=k({...kr.shape,...mn.shape,uriTemplate:p(),description:fe(p()),mimeType:fe(p()),annotations:Rr.optional(),_meta:fe(ye({}))}),zv=hn.extend({method:E("resources/list")}),Bi=gn.extend({resources:z(_f)}),kv=hn.extend({method:E("resources/templates/list")}),Ki=gn.extend({resourceTemplates:z(xv)}),Ji=Ve.extend({uri:p()}),Pv=Ji,Tv=be.extend({method:E("resources/read"),params:Pv}),Gi=$e.extend({contents:z(ce([hf,gf]))}),Wi=Je.extend({method:E("notifications/resources/list_changed"),params:Ke.optional()}),Rv=Ji,Ev=be.extend({method:E("resources/subscribe"),params:Rv}),Iv=Ji,Ov=be.extend({method:E("resources/unsubscribe"),params:Iv}),Av=Ke.extend({uri:p()}),Cv=Je.extend({method:E("notifications/resources/updated"),params:Av}),Nv=k({name:p(),description:fe(p()),required:fe(re())}),jv=k({...kr.shape,...mn.shape,description:fe(p()),arguments:fe(z(Nv)),_meta:fe(ye({}))}),Mv=hn.extend({method:E("prompts/list")}),Yi=gn.extend({prompts:z(jv)}),Uv=Ve.extend({name:p(),arguments:ie(p(),p()).optional()}),Dv=be.extend({method:E("prompts/get"),params:Uv}),Qi=k({type:E("text"),text:p(),annotations:Rr.optional(),_meta:ie(p(),pe()).optional()}),Xi=k({type:E("image"),data:Hi,mimeType:p(),annotations:Rr.optional(),_meta:ie(p(),pe()).optional()}),ea=k({type:E("audio"),data:Hi,mimeType:p(),annotations:Rr.optional(),_meta:ie(p(),pe()).optional()}),Zv=k({type:E("tool_use"),name:p(),id:p(),input:ie(p(),pe()),_meta:ie(p(),pe()).optional()}),qv=k({type:E("resource"),resource:ce([hf,gf]),annotations:Rr.optional(),_meta:ie(p(),pe()).optional()}),Lv=_f.extend({type:E("resource_link")}),ta=ce([Qi,Xi,ea,Lv,qv]),Fv=k({role:vn,content:ta}),ra=$e.extend({description:p().optional(),messages:z(Fv)}),na=Je.extend({method:E("notifications/prompts/list_changed"),params:Ke.optional()}),Vv=k({title:p().optional(),readOnlyHint:re().optional(),destructiveHint:re().optional(),idempotentHint:re().optional(),openWorldHint:re().optional()}),Hv=k({taskSupport:je(["required","optional","forbidden"]).optional()}),yf=k({...kr.shape,...mn.shape,description:p().optional(),inputSchema:k({type:E("object"),properties:ie(p(),ve).optional(),required:z(p()).optional()}).catchall(pe()),outputSchema:k({type:E("object"),properties:ie(p(),ve).optional(),required:z(p()).optional()}).catchall(pe()).optional(),annotations:Vv.optional(),execution:Hv.optional(),_meta:ie(p(),pe()).optional()}),Bv=hn.extend({method:E("tools/list")}),oa=gn.extend({tools:z(yf)}),Er=$e.extend({content:z(ta).default([]),structuredContent:ie(p(),pe()).optional(),isError:re().optional()}),hR=Er.or($e.extend({toolResult:pe()})),Kv=pn.extend({name:p(),arguments:ie(p(),pe()).optional()}),Jv=be.extend({method:E("tools/call"),params:Kv}),sa=Je.extend({method:E("notifications/tools/list_changed"),params:Ke.optional()}),vf=k({autoRefresh:re().default(!0),debounceMs:K().int().nonnegative().default(300)}),wf=je(["debug","info","notice","warning","error","critical","alert","emergency"]),Gv=Ve.extend({level:wf}),Wv=be.extend({method:E("logging/setLevel"),params:Gv}),Yv=Ke.extend({level:wf,logger:p().optional(),data:pe()}),Qv=Je.extend({method:E("notifications/message"),params:Yv}),Xv=k({name:p().optional()}),ew=k({hints:z(Xv).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),tw=k({mode:je(["auto","required","none"]).optional()}),rw=k({type:E("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:z(ta).default([]),structuredContent:k({}).loose().optional(),isError:re().optional(),_meta:ie(p(),pe()).optional()}),nw=Ui("type",[Qi,Xi,ea]),Oo=Ui("type",[Qi,Xi,ea,Zv,rw]),ow=k({role:vn,content:ce([Oo,z(Oo)]),_meta:ie(p(),pe()).optional()}),sw=pn.extend({messages:z(ow),modelPreferences:ew.optional(),systemPrompt:p().optional(),includeContext:je(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:z(p()).optional(),metadata:ve.optional(),tools:z(yf).optional(),toolChoice:tw.optional()}),ia=be.extend({method:E("sampling/createMessage"),params:sw}),aa=$e.extend({model:p(),stopReason:fe(je(["endTurn","stopSequence","maxTokens"]).or(p())),role:vn,content:nw}),ca=$e.extend({model:p(),stopReason:fe(je(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:vn,content:ce([Oo,z(Oo)])}),iw=k({type:E("boolean"),title:p().optional(),description:p().optional(),default:re().optional()}),aw=k({type:E("string"),title:p().optional(),description:p().optional(),minLength:K().optional(),maxLength:K().optional(),format:je(["email","uri","date","date-time"]).optional(),default:p().optional()}),cw=k({type:je(["number","integer"]),title:p().optional(),description:p().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),uw=k({type:E("string"),title:p().optional(),description:p().optional(),enum:z(p()),default:p().optional()}),lw=k({type:E("string"),title:p().optional(),description:p().optional(),oneOf:z(k({const:p(),title:p()})),default:p().optional()}),dw=k({type:E("string"),title:p().optional(),description:p().optional(),enum:z(p()),enumNames:z(p()).optional(),default:p().optional()}),pw=ce([uw,lw]),fw=k({type:E("array"),title:p().optional(),description:p().optional(),minItems:K().optional(),maxItems:K().optional(),items:k({type:E("string"),enum:z(p())}),default:z(p()).optional()}),mw=k({type:E("array"),title:p().optional(),description:p().optional(),minItems:K().optional(),maxItems:K().optional(),items:k({anyOf:z(k({const:p(),title:p()}))}),default:z(p()).optional()}),hw=ce([fw,mw]),gw=ce([dw,pw,hw]),_w=ce([gw,iw,aw,cw]),yw=pn.extend({mode:E("form").optional(),message:p(),requestedSchema:k({type:E("object"),properties:ie(p(),_w),required:z(p()).optional()})}),vw=pn.extend({mode:E("url"),message:p(),elicitationId:p(),url:p().url()}),ww=ce([yw,vw]),ua=be.extend({method:E("elicitation/create"),params:ww}),bw=Ke.extend({elicitationId:p()}),$w=Je.extend({method:E("notifications/elicitation/complete"),params:bw}),la=$e.extend({action:je(["accept","decline","cancel"]),content:Di(e=>e===null?void 0:e,ie(p(),ce([p(),K(),re(),z(p())])).optional())}),Sw=k({type:E("ref/resource"),uri:p()});var xw=k({type:E("ref/prompt"),name:p()}),zw=Ve.extend({ref:ce([xw,Sw]),argument:k({name:p(),value:p()}),context:k({arguments:ie(p(),p()).optional()}).optional()}),kw=be.extend({method:E("completion/complete"),params:zw});var da=$e.extend({completion:ye({values:z(p()).max(100),total:fe(K().int()),hasMore:fe(re())})}),Pw=k({uri:p().startsWith("file://"),name:p().optional(),_meta:ie(p(),pe()).optional()}),Tw=be.extend({method:E("roots/list"),params:Ve.optional()}),Rw=$e.extend({roots:z(Pw)}),Ew=Je.extend({method:E("notifications/roots/list_changed"),params:Ke.optional()}),gR=ce([jo,_v,kw,Wv,Dv,Mv,zv,kv,Tv,Ev,Ov,Jv,Bv,Uo,Zo,qo,Fo]),_R=ce([No,Mo,df,Ew,yn]),yR=ce([Gt,aa,ca,la,Rw,Do,Lo,Wt]),vR=ce([jo,ia,ua,Tw,Uo,Zo,qo,Fo]),wR=ce([No,Mo,Qv,Cv,Wi,sa,na,yn,$w]),bR=ce([Gt,Vi,da,ra,Yi,Bi,Ki,Gi,Er,oa,Do,Lo,Wt]),C=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===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Zi(o.elicitations,r)}return new e(t,r,n)}},Zi=class extends C{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function It(e){return e==="completed"||e==="failed"||e==="cancelled"}var Iw=Symbol("Let zodToJsonSchema decide on which parser to use");var eE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pa(e){let r=Po(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 fa(e,t){let r=nt(e,t);if(!r.success)throw r.error;return r.data}var Mw=6e4,Vo=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(No,r=>{this._oncancel(r)}),this.setNotificationHandler(Mo,r=>{this._onprogress(r)}),this.setRequestHandler(jo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Uo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Zo,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,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,f=new C(d.error.code,d.error.message,d.error.data);u(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new C(N.InvalidParams,`Task not found: ${s}`);if(!It(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(It(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Et]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(qo,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 C(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Fo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(It(o.status))throw new C(N.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 C(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof C?o:new C(N.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),C.fromError(N.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),Jt(s)||uf(s)?this._onresponse(s):fn(s)?this._onrequest(s,i):cf(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=C.fromError(N.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?.[Et]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).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=of(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:t.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(i.signal.aborted)throw new C(N.ConnectionClosed,"Request was cancelled");let m={...f,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(u,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,l)).then(async u=>{if(i.signal.aborted)return;let d={result:u,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 u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:N.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).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),Jt(t))n(t);else{let i=new C(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(Jt(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),Jt(t))o(t);else{let i=C.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 C?i:new C(N.InternalError,String(i))}}return}let s;try{let i=await this.request(t,Wt,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new C(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},It(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new C(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(N.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(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof C?i:new C(N.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=S=>{u(S)};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(S){d(S);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Et]:c}});let h=S=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let $=S instanceof C?S:new C(N.RequestTimeout,String(S));u($)};this._responseHandlers.set(f,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return u(S);try{let $=nt(r,S.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??Mw,y=()=>h(C.fromError(N.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(f,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let S=$=>{let P=this._responseHandlers.get(f);P?P($):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,S),this._enqueueTaskMessage(b,{type:"request",message:m,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(f),u($)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(f),u(S)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Do,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},Lo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},ff,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||{},[Et]: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||{},[Et]: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||{},[Et]: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=fa(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=fa(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"&&fn(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new C(N.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 C(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new C(N.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 C(N.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=yn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),It(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 C(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(It(a.status))throw new C(N.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 l=yn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),It(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function bf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $f(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];bf(i)&&bf(s)?r[o]={...i,...s}:r[o]=s}return r}var fg=ju(Xc(),1),mg=ju(pg(),1);function qz(){let e=new fg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,mg.default)(e),e}var zs=class{constructor(t){this._ajv=t??qz()}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 ks=class{constructor(t){this._client=t}async*callToolStream(t,r=Er,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 l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new C(N.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new C(N.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof C){yield{type:"error",error:u};return}yield{type:"error",error:new C(N.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};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 hg(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 gg(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 Ps(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let 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&&Ps(s,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Ps(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Ps(r,t)}}function Lz(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 Ts=class extends Vo{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 zs,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",sa,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",na,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Wi,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ks(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=$f(this._capabilities,t)}setRequestHandler(t,r){let o=Po(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(zr(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,l)=>{let u=nt(ua,c);if(!u.success){let S=u.error instanceof Error?u.error.message:String(u.error);throw new C(N.InvalidParams,`Invalid elicitation request: ${S}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:m}=Lz(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new C(N.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!m)throw new C(N.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,l));if(d.task){let S=nt(Wt,h);if(!S.success){let $=S.error instanceof Error?S.error.message:String(S.error);throw new C(N.InvalidParams,`Invalid task creation result: ${$}`)}return S.data}let g=nt(la,h);if(!g.success){let S=g.error instanceof Error?g.error.message:String(g.error);throw new C(N.InvalidParams,`Invalid elicitation result: ${S}`)}let y=g.data,b=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&b&&this._capabilities.elicitation?.form?.applyDefaults)try{Ps(b,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){let a=async(c,l)=>{let u=nt(ia,c);if(!u.success){let y=u.error instanceof Error?u.error.message:String(u.error);throw new C(N.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let y=nt(Wt,f);if(!y.success){let b=y.error instanceof Error?y.error.message:String(y.error);throw new C(N.InvalidParams,`Invalid task creation result: ${b}`)}return y.data}let h=d.tools||d.toolChoice?ca:aa,g=nt(h,f);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new C(N.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:Pr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vi,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!tf.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){hg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&gg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Gt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},da,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Gt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},ra,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Yi,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Bi,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Ki,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Gi,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Gt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Gt,r)}async callTool(t,r=Er,n){if(this.isToolTaskRequired(t.name))throw new C(N.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 C(N.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 C(N.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof C?i:new C(N.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},oa,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let s=vf.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,l=async()=>{if(!i){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let f=setTimeout(l,a);this._listChangedDebounceTimers.set(t,f)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Rs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function _g(e=fetch,t){return t?async(r,n)=>{let o={...t,...n,headers:n?.headers?{...Rs(t.headers),...Rs(n.headers)}:t.headers};return e(r,o)}:e}var au;au=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function Fz(e){return(await au).getRandomValues(new Uint8Array(e))}async function Vz(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let o=await Fz(e-n.length);for(let s of o)s<r&&(n+=t[s%t.length])}return n}async function Hz(e){return await Vz(e)}async function Bz(e){let t=await(await au).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function cu(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Hz(e),r=await Bz(t);return{code_verifier:t,code_challenge:r}}var ke=Lp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ef.custom,message:"URL must be parseable",fatal:!0}),Ks}).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"}),vg=ye({resource:p().url(),authorization_servers:z(ke).optional(),jwks_uri:p().url().optional(),scopes_supported:z(p()).optional(),bearer_methods_supported:z(p()).optional(),resource_signing_alg_values_supported:z(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:re().optional(),authorization_details_types_supported:z(p()).optional(),dpop_signing_alg_values_supported:z(p()).optional(),dpop_bound_access_tokens_required:re().optional()}),uu=ye({issuer:p(),authorization_endpoint:ke,token_endpoint:ke,registration_endpoint:ke.optional(),scopes_supported:z(p()).optional(),response_types_supported:z(p()),response_modes_supported:z(p()).optional(),grant_types_supported:z(p()).optional(),token_endpoint_auth_methods_supported:z(p()).optional(),token_endpoint_auth_signing_alg_values_supported:z(p()).optional(),service_documentation:ke.optional(),revocation_endpoint:ke.optional(),revocation_endpoint_auth_methods_supported:z(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:z(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(p()).optional(),code_challenge_methods_supported:z(p()).optional(),client_id_metadata_document_supported:re().optional()}),Kz=ye({issuer:p(),authorization_endpoint:ke,token_endpoint:ke,userinfo_endpoint:ke.optional(),jwks_uri:ke,registration_endpoint:ke.optional(),scopes_supported:z(p()).optional(),response_types_supported:z(p()),response_modes_supported:z(p()).optional(),grant_types_supported:z(p()).optional(),acr_values_supported:z(p()).optional(),subject_types_supported:z(p()),id_token_signing_alg_values_supported:z(p()),id_token_encryption_alg_values_supported:z(p()).optional(),id_token_encryption_enc_values_supported:z(p()).optional(),userinfo_signing_alg_values_supported:z(p()).optional(),userinfo_encryption_alg_values_supported:z(p()).optional(),userinfo_encryption_enc_values_supported:z(p()).optional(),request_object_signing_alg_values_supported:z(p()).optional(),request_object_encryption_alg_values_supported:z(p()).optional(),request_object_encryption_enc_values_supported:z(p()).optional(),token_endpoint_auth_methods_supported:z(p()).optional(),token_endpoint_auth_signing_alg_values_supported:z(p()).optional(),display_values_supported:z(p()).optional(),claim_types_supported:z(p()).optional(),claims_supported:z(p()).optional(),service_documentation:p().optional(),claims_locales_supported:z(p()).optional(),ui_locales_supported:z(p()).optional(),claims_parameter_supported:re().optional(),request_parameter_supported:re().optional(),request_uri_parameter_supported:re().optional(),require_request_uri_registration:re().optional(),op_policy_uri:ke.optional(),op_tos_uri:ke.optional(),client_id_metadata_document_supported:re().optional()}),wg=k({...Kz.shape,...uu.pick({code_challenge_methods_supported:!0}).shape}),bg=k({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:Io.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),$g=k({error:p(),error_description:p().optional(),error_uri:p().optional()}),yg=ke.optional().or(E("").transform(()=>{})),Jz=k({redirect_uris:z(ke),token_endpoint_auth_method:p().optional(),grant_types:z(p()).optional(),response_types:z(p()).optional(),client_name:p().optional(),client_uri:ke.optional(),logo_uri:yg,scope:p().optional(),contacts:z(p()).optional(),tos_uri:yg,policy_uri:p().optional(),jwks_uri:ke.optional(),jwks:Hp().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),Gz=k({client_id:p(),client_secret:p().optional(),client_id_issued_at:K().optional(),client_secret_expires_at:K().optional()}).strip(),Sg=Jz.merge(Gz),k1=k({error:p(),error_description:p().optional()}).strip(),P1=k({token:p(),token_type_hint:p().optional()}).strip();function xg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function zg({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 ge=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}},Wn=class extends ge{};Wn.errorCode="invalid_request";var cr=class extends ge{};cr.errorCode="invalid_client";var ur=class extends ge{};ur.errorCode="invalid_grant";var lr=class extends ge{};lr.errorCode="unauthorized_client";var Yn=class extends ge{};Yn.errorCode="unsupported_grant_type";var Qn=class extends ge{};Qn.errorCode="invalid_scope";var Xn=class extends ge{};Xn.errorCode="access_denied";var xt=class extends ge{};xt.errorCode="server_error";var eo=class extends ge{};eo.errorCode="temporarily_unavailable";var to=class extends ge{};to.errorCode="unsupported_response_type";var ro=class extends ge{};ro.errorCode="unsupported_token_type";var no=class extends ge{};no.errorCode="invalid_token";var oo=class extends ge{};oo.errorCode="method_not_allowed";var so=class extends ge{};so.errorCode="too_many_requests";var dr=class extends ge{};dr.errorCode="invalid_client_metadata";var io=class extends ge{};io.errorCode="insufficient_scope";var ao=class extends ge{};ao.errorCode="invalid_target";var kg={[Wn.errorCode]:Wn,[cr.errorCode]:cr,[ur.errorCode]:ur,[lr.errorCode]:lr,[Yn.errorCode]:Yn,[Qn.errorCode]:Qn,[Xn.errorCode]:Xn,[xt.errorCode]:xt,[eo.errorCode]:eo,[to.errorCode]:to,[ro.errorCode]:ro,[no.errorCode]:no,[oo.errorCode]:oo,[so.errorCode]:so,[dr.errorCode]:dr,[io.errorCode]:io,[ao.errorCode]:ao};var zt=class extends Error{constructor(t){super(t??"Unauthorized")}};function Wz(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var lu="code",du="S256";function Yz(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Wz(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 Qz(e,t,r,n){let{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":Xz(o,s,r);return;case"client_secret_post":ek(o,s,n);return;case"none":tk(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Xz(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 ek(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function tk(e,t){t.set("client_id",e)}async function Tg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=$g.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=kg[o]||xt;return new a(s||"",i)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new xt(o)}}async function co(e,t){try{return await pu(e,t)}catch(r){if(r instanceof cr||r instanceof lr)return await e.invalidateCredentials?.("all"),await pu(e,t);if(r instanceof ur)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,l,u=o;if(!u&&i?.resourceMetadataUrl&&(u=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,l=i.authorizationServerMetadata??await Eg(c,{fetchFn:s}),!a)try{a=await Rg(t,{resourceMetadataUrl:u},s)}catch{}(l!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}else{let $=await ck(t,{resourceMetadataUrl:u,fetchFn:s});c=$.authorizationServerUrl,l=$.authorizationServerMetadata,a=$.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}let d=await nk(t,e,a),f=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 $=l?.client_id_metadata_document_supported===!0,P=e.clientMetadataUrl;if(P&&!rk(P))throw new dr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if($&&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 x=await fk(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:s});await e.saveClientInformation(x),m=x}}let h=!e.redirectUrl;if(r!==void 0||h){let $=await pk(e,c,{metadata:l,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens($),"AUTHORIZED"}let g=await e.tokens();if(g?.refresh_token)try{let $=await dk(c,{metadata:l,clientInformation:m,refreshToken:g.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens($),"AUTHORIZED"}catch($){if(!(!($ instanceof ge)||$ instanceof xt))throw $}let y=e.state?await e.state():void 0,{authorizationUrl:b,codeVerifier:S}=await uk(c,{metadata:l,clientInformation:m,state:y,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(S),await e.redirectToAuthorization(b),"REDIRECT"}function rk(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function nk(e,t,r){let n=xg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!zg({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 mu(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=fu(e,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=fu(e,"scope")||void 0,a=fu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function fu(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 Rg(e,t,r=fetch){let n=await ik(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 vg.parse(await n.json())}async function hu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?hu(e,void 0,r):void 0;throw n}}function ok(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Pg(e,t,r=fetch){return await hu(e,{"MCP-Protocol-Version":t},r)}function sk(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function ik(e,t,r,n){let o=new URL(e),s=n?.protocolVersion??Pr,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=ok(t,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Pg(i,s,r);if(!n?.metadataUrl&&sk(a,o.pathname)){let c=new URL(`/.well-known/${t}`,o);a=await Pg(c,s,r)}return a}function ak(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 Eg(e,{fetchFn:t=fetch,protocolVersion:r=Pr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=ak(e);for(let{url:s,type:i}of o){let a=await hu(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"?uu.parse(await a.json()):wg.parse(await a.json())}}}async function ck(e,t){let r,n;try{r=await Rg(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 Eg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function uk(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(lu))throw new Error(`Incompatible auth server: does not support response type ${lu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(du))throw new Error(`Incompatible auth server: does not support code challenge method ${du}`)}else a=new URL("/authorize",e);let c=await cu(),l=c.code_verifier,u=c.code_challenge;return a.searchParams.set("response_type",lu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",du),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:l}}function lk(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Ig(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 u=t?.token_endpoint_auth_methods_supported??[],d=Yz(n,u);Qz(d,n,c,r)}let l=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!l.ok)throw await Tg(l);return bg.parse(await l.json())}async function dk(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 Ig(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function pk(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 l=await e.codeVerifier();a=lk(o,l,e.redirectUrl)}let c=await e.clientInformation();return Ig(t,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function fk(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 Tg(i);return Sg.parse(await i.json())}var uo=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}},Og=10,mk=13,pr=32;function gu(e){}function Ng(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=gu,onError:r=gu,onRetry:n=gu,onComment:o,maxBufferSize:s}=e,i=[],a=0,c=!0,l,u="",d=0,f,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 L=y(v);L!==""&&(i.push(L),a=L.length),g();return}if(v.indexOf(`
36
- `)===-1&&v.indexOf("\r")===-1){i.push(v),a+=v.length,g();return}i.push(v);let x=i.join("");i.length=0,a=0;let R=y(x);R!==""&&(i.push(R),a=R.length),g()}function g(){s!==void 0&&(a+u.length<=s||(m=!0,i.length=0,a=0,l=void 0,u="",d=0,f=void 0,r(new uo(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let x=0;if(v.indexOf("\r")===-1){let R=v.indexOf(`
35
+ })));`),f.write(`newResult[${Ht(S)}] = ${$}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(S,$)=>w(d,S,$)},o,s=vr,i=!_o.jitless,c=i&&ri.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??(u=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&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let $=u.shape;for(let P of u.keys){let v=$[P],x=v._zod.run({value:m[P],issues:[]},f),R=v._zod.optin==="optional"&&v._zod.optout==="optional";x instanceof Promise?h.push(x.then(L=>R?Ul(L,d,P,m):ko(L,d,P))):R?Ul(x,d,P,m):ko(x,d,P)}}if(!l)return h.length?Promise.all(h).then(()=>d):d;let g=[],y=u.keySet,w=l._zod,S=w.def.type;for(let $ of Object.keys(m)){if(y.has($))continue;if(S==="never"){g.push($);continue}let P=w.run({value:m[$],issues:[]},f);P instanceof Promise?h.push(P.then(v=>ko(v,d,$))):ko(P,d,$)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:m,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function Dl(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=>tt(s,n,Fe())))}),t}var yi=_("$ZodUnion",(e,t)=>{X.init(e,t),oe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),oe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),oe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),oe(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=>sn(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=>Dl(i,r,e,n)):Dl(s,r,e,n)}}),zd=_("$ZodDiscriminatedUnion",(e,t)=>{yi.init(e,t);let r=e._zod.parse;oe(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 l of c)o[a].add(l)}}return o});let n=nn(()=>{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(!vr(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)}}),Pd=_("$ZodIntersection",(e,t)=>{X.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,l])=>Zl(r,c,l)):Zl(r,s,i)}});function gi(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(br(e)&&br(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=gi(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=gi(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 Zl(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Bt(e))return e;let n=gi(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 Td=_("$ZodRecord",(e,t)=>{X.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!br(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 l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...ut(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...ut(c,l.issues)),r.value[c]=l.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(l=>tt(l,n,Fe())),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(l=>{l.issues.length&&r.issues.push(...ut(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...ut(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Rd=_("$ZodEnum",(e,t)=>{X.init(e,t);let r=Qs(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>ni.has(typeof n)).map(n=>typeof n=="string"?Rt(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}}),Ed=_("$ZodLiteral",(e,t)=>{X.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Rt(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 Id=_("$ZodTransform",(e,t)=>{X.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 yt;return r.value=o,r}}),Od=_("$ZodOptional",(e,t)=>{X.init(e,t),e._zod.optin="optional",e._zod.optout="optional",oe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),oe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${sn(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)}),Ad=_("$ZodNullable",(e,t)=>{X.init(e,t),oe(e._zod,"optin",()=>t.innerType._zod.optin),oe(e._zod,"optout",()=>t.innerType._zod.optout),oe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${sn(r.source)}|null)$`):void 0}),oe(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)}),Cd=_("$ZodDefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",oe(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=>ql(s,t)):ql(o,t)}});function ql(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Nd=_("$ZodPrefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",oe(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))}),jd=_("$ZodNonOptional",(e,t)=>{X.init(e,t),oe(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=>Ll(s,e)):Ll(o,e)}});function Ll(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 Md=_("$ZodCatch",(e,t)=>{X.init(e,t),e._zod.optin="optional",oe(e._zod,"optout",()=>t.innerType._zod.optout),oe(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=>tt(i,n,Fe()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>tt(s,n,Fe()))},input:r.value}),r.issues=[]),r)}});var Ud=_("$ZodPipe",(e,t)=>{X.init(e,t),oe(e._zod,"values",()=>t.in._zod.values),oe(e._zod,"optin",()=>t.in._zod.optin),oe(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=>Fl(s,t,n)):Fl(o,t,n)}});function Fl(e,t,r){return Bt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Dd=_("$ZodReadonly",(e,t)=>{X.init(e,t),oe(e._zod,"propValues",()=>t.innerType._zod.propValues),oe(e._zod,"values",()=>t.innerType._zod.values),oe(e._zod,"optin",()=>t.innerType._zod.optin),oe(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(Vl):Vl(o)}});function Vl(e){return e.value=Object.freeze(e.value),e}var Zd=_("$ZodCustom",(e,t)=>{Te.init(e,t),X.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=>Hl(s,r,n,e));Hl(o,r,n,e)}});function Hl(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(ii(o))}}var dy=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},py=()=>{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 ${dy(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${bo(n.values[0])}`:`Invalid option: expected one of ${yo(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":""}: ${yo(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 qd(){return{localeError:py()}}var fy=Symbol("ZodOutput"),my=Symbol("ZodInput"),vi=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 Ld(){return new vi}var wr=Ld();function Fd(e,t){return new e({type:"string",...A(t)})}function Vd(e,t){return new e({type:"string",coerce:!0,...A(t)})}function Hd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...A(t)})}function bi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A(t)})}function Bd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...A(t)})}function Kd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(t)})}function Jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(t)})}function Gd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(t)})}function wi(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...A(t)})}function Wd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...A(t)})}function Yd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(t)})}function Qd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...A(t)})}function Xd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(t)})}function ep(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...A(t)})}function tp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...A(t)})}function rp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(t)})}function np(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(t)})}function op(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(t)})}function sp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(t)})}function ip(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(t)})}function ap(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...A(t)})}function cp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...A(t)})}function up(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...A(t)})}function lp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...A(t)})}function dp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(t)})}function pp(e,t){return new e({type:"string",format:"date",check:"string_format",...A(t)})}function fp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...A(t)})}function mp(e,t){return new e({type:"string",format:"duration",check:"string_format",...A(t)})}function hp(e,t){return new e({type:"number",checks:[],...A(t)})}function gp(e,t){return new e({type:"number",coerce:!0,checks:[],...A(t)})}function _p(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...A(t)})}function yp(e,t){return new e({type:"boolean",...A(t)})}function vp(e,t){return new e({type:"boolean",coerce:!0,...A(t)})}function bp(e,t){return new e({type:"bigint",coerce:!0,...A(t)})}function wp(e,t){return new e({type:"null",...A(t)})}function $p(e){return new e({type:"any"})}function Sp(e){return new e({type:"unknown"})}function xp(e,t){return new e({type:"never",...A(t)})}function kp(e,t){return new e({type:"date",coerce:!0,...A(t)})}function $r(e,t){return new mi({check:"less_than",...A(t),value:e,inclusive:!1})}function vt(e,t){return new mi({check:"less_than",...A(t),value:e,inclusive:!0})}function Sr(e,t){return new hi({check:"greater_than",...A(t),value:e,inclusive:!1})}function rt(e,t){return new hi({check:"greater_than",...A(t),value:e,inclusive:!0})}function ln(e,t){return new Sl({check:"multiple_of",...A(t),value:e})}function Po(e,t){return new kl({check:"max_length",...A(t),maximum:e})}function xr(e,t){return new zl({check:"min_length",...A(t),minimum:e})}function To(e,t){return new Pl({check:"length_equals",...A(t),length:e})}function $i(e,t){return new Tl({check:"string_format",format:"regex",...A(t),pattern:e})}function Si(e){return new Rl({check:"string_format",format:"lowercase",...A(e)})}function xi(e){return new El({check:"string_format",format:"uppercase",...A(e)})}function ki(e,t){return new Il({check:"string_format",format:"includes",...A(t),includes:e})}function zi(e,t){return new Ol({check:"string_format",format:"starts_with",...A(t),prefix:e})}function Pi(e,t){return new Al({check:"string_format",format:"ends_with",...A(t),suffix:e})}function Kt(e){return new Cl({check:"overwrite",tx:e})}function Ti(e){return Kt(t=>t.normalize(e))}function Ri(){return Kt(e=>e.trim())}function Ei(){return Kt(e=>e.toLowerCase())}function Ii(){return Kt(e=>e.toUpperCase())}function zp(e,t,r){return new e({type:"array",element:t,...A(r)})}function Pp(e,t,r){let n=A(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Tp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...A(r)})}function zr(e){return!!e._zod}function nt(e,t){return zr(e)?cn(e,t):e.safeParse(t)}function Ro(e){if(!e)return;let t;if(zr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Rp(e){if(zr(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 dn={};Js(dn,{ZodISODate:()=>Ip,ZodISODateTime:()=>Ep,ZodISODuration:()=>Ap,ZodISOTime:()=>Op,date:()=>Ai,datetime:()=>Oi,duration:()=>Ni,time:()=>Ci});var Ep=_("ZodISODateTime",(e,t)=>{nd.init(e,t),de.init(e,t)});function Oi(e){return dp(Ep,e)}var Ip=_("ZodISODate",(e,t)=>{od.init(e,t),de.init(e,t)});function Ai(e){return pp(Ip,e)}var Op=_("ZodISOTime",(e,t)=>{sd.init(e,t),de.init(e,t)});function Ci(e){return fp(Op,e)}var Ap=_("ZodISODuration",(e,t)=>{id.init(e,t),de.init(e,t)});function Ni(e){return mp(Ap,e)}var Np=(e,t)=>{wo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ui(e,r)},flatten:{value:r=>ci(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},NT=_("ZodError",Np),pn=_("ZodError",Np,{Parent:Error});var jp=Vu(pn),Mp=Hu(pn),Up=li(pn),Dp=di(pn);var se=_("ZodType",(e,t)=>(X.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)=>et(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>jp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Up(e,r,n),e.parseAsync=async(r,n)=>Mp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Dp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(cv(r,n)),e.superRefine=r=>e.check(uv(r)),e.overwrite=r=>e.check(Kt(r)),e.optional=()=>fe(e),e.nullable=()=>Lp(e),e.nullish=()=>fe(Lp(e)),e.nonoptional=r=>tv(e,r),e.array=()=>k(e),e.or=r=>ce([e,r]),e.and=r=>Oo(e,r),e.transform=r=>Mi(e,Qp(r)),e.default=r=>Qy(e,r),e.prefault=r=>ev(e,r),e.catch=r=>nv(e,r),e.pipe=r=>Mi(e,r),e.readonly=()=>iv(e),e.describe=r=>{let n=e.clone();return wr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return wr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return wr.get(e);let n=e.clone();return wr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Fp=_("_ZodString",(e,t)=>{zo.init(e,t),se.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($i(...n)),e.includes=(...n)=>e.check(ki(...n)),e.startsWith=(...n)=>e.check(zi(...n)),e.endsWith=(...n)=>e.check(Pi(...n)),e.min=(...n)=>e.check(xr(...n)),e.max=(...n)=>e.check(Po(...n)),e.length=(...n)=>e.check(To(...n)),e.nonempty=(...n)=>e.check(xr(1,...n)),e.lowercase=n=>e.check(Si(n)),e.uppercase=n=>e.check(xi(n)),e.trim=()=>e.check(Ri()),e.normalize=(...n)=>e.check(Ti(...n)),e.toLowerCase=()=>e.check(Ei()),e.toUpperCase=()=>e.check(Ii())}),Ui=_("ZodString",(e,t)=>{zo.init(e,t),Fp.init(e,t),e.email=r=>e.check(Hd($y,r)),e.url=r=>e.check(wi(Vp,r)),e.jwt=r=>e.check(lp(My,r)),e.emoji=r=>e.check(Wd(Sy,r)),e.guid=r=>e.check(bi(Zp,r)),e.uuid=r=>e.check(Bd(Eo,r)),e.uuidv4=r=>e.check(Kd(Eo,r)),e.uuidv6=r=>e.check(Jd(Eo,r)),e.uuidv7=r=>e.check(Gd(Eo,r)),e.nanoid=r=>e.check(Yd(xy,r)),e.guid=r=>e.check(bi(Zp,r)),e.cuid=r=>e.check(Qd(ky,r)),e.cuid2=r=>e.check(Xd(zy,r)),e.ulid=r=>e.check(ep(Py,r)),e.base64=r=>e.check(ap(Cy,r)),e.base64url=r=>e.check(cp(Ny,r)),e.xid=r=>e.check(tp(Ty,r)),e.ksuid=r=>e.check(rp(Ry,r)),e.ipv4=r=>e.check(np(Ey,r)),e.ipv6=r=>e.check(op(Iy,r)),e.cidrv4=r=>e.check(sp(Oy,r)),e.cidrv6=r=>e.check(ip(Ay,r)),e.e164=r=>e.check(up(jy,r)),e.datetime=r=>e.check(Oi(r)),e.date=r=>e.check(Ai(r)),e.time=r=>e.check(Ci(r)),e.duration=r=>e.check(Ni(r))});function p(e){return Fd(Ui,e)}var de=_("ZodStringFormat",(e,t)=>{ae.init(e,t),Fp.init(e,t)}),$y=_("ZodEmail",(e,t)=>{Jl.init(e,t),de.init(e,t)});var Zp=_("ZodGUID",(e,t)=>{Bl.init(e,t),de.init(e,t)});var Eo=_("ZodUUID",(e,t)=>{Kl.init(e,t),de.init(e,t)});var Vp=_("ZodURL",(e,t)=>{Gl.init(e,t),de.init(e,t)});function Hp(e){return wi(Vp,e)}var Sy=_("ZodEmoji",(e,t)=>{Wl.init(e,t),de.init(e,t)});var xy=_("ZodNanoID",(e,t)=>{Yl.init(e,t),de.init(e,t)});var ky=_("ZodCUID",(e,t)=>{Ql.init(e,t),de.init(e,t)});var zy=_("ZodCUID2",(e,t)=>{Xl.init(e,t),de.init(e,t)});var Py=_("ZodULID",(e,t)=>{ed.init(e,t),de.init(e,t)});var Ty=_("ZodXID",(e,t)=>{td.init(e,t),de.init(e,t)});var Ry=_("ZodKSUID",(e,t)=>{rd.init(e,t),de.init(e,t)});var Ey=_("ZodIPv4",(e,t)=>{ad.init(e,t),de.init(e,t)});var Iy=_("ZodIPv6",(e,t)=>{cd.init(e,t),de.init(e,t)});var Oy=_("ZodCIDRv4",(e,t)=>{ud.init(e,t),de.init(e,t)});var Ay=_("ZodCIDRv6",(e,t)=>{ld.init(e,t),de.init(e,t)});var Cy=_("ZodBase64",(e,t)=>{pd.init(e,t),de.init(e,t)});var Ny=_("ZodBase64URL",(e,t)=>{fd.init(e,t),de.init(e,t)});var jy=_("ZodE164",(e,t)=>{md.init(e,t),de.init(e,t)});var My=_("ZodJWT",(e,t)=>{hd.init(e,t),de.init(e,t)});var Io=_("ZodNumber",(e,t)=>{_i.init(e,t),se.init(e,t),e.gt=(n,o)=>e.check(Sr(n,o)),e.gte=(n,o)=>e.check(rt(n,o)),e.min=(n,o)=>e.check(rt(n,o)),e.lt=(n,o)=>e.check($r(n,o)),e.lte=(n,o)=>e.check(vt(n,o)),e.max=(n,o)=>e.check(vt(n,o)),e.int=n=>e.check(qp(n)),e.safe=n=>e.check(qp(n)),e.positive=n=>e.check(Sr(0,n)),e.nonnegative=n=>e.check(rt(0,n)),e.negative=n=>e.check($r(0,n)),e.nonpositive=n=>e.check(vt(0,n)),e.multipleOf=(n,o)=>e.check(ln(n,o)),e.step=(n,o)=>e.check(ln(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 K(e){return hp(Io,e)}var Uy=_("ZodNumberFormat",(e,t)=>{gd.init(e,t),Io.init(e,t)});function qp(e){return _p(Uy,e)}var Di=_("ZodBoolean",(e,t)=>{_d.init(e,t),se.init(e,t)});function te(e){return yp(Di,e)}var Bp=_("ZodBigInt",(e,t)=>{yd.init(e,t),se.init(e,t),e.gte=(n,o)=>e.check(rt(n,o)),e.min=(n,o)=>e.check(rt(n,o)),e.gt=(n,o)=>e.check(Sr(n,o)),e.gte=(n,o)=>e.check(rt(n,o)),e.min=(n,o)=>e.check(rt(n,o)),e.lt=(n,o)=>e.check($r(n,o)),e.lte=(n,o)=>e.check(vt(n,o)),e.max=(n,o)=>e.check(vt(n,o)),e.positive=n=>e.check(Sr(BigInt(0),n)),e.negative=n=>e.check($r(BigInt(0),n)),e.nonpositive=n=>e.check(vt(BigInt(0),n)),e.nonnegative=n=>e.check(rt(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(ln(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Dy=_("ZodNull",(e,t)=>{vd.init(e,t),se.init(e,t)});function Kp(e){return wp(Dy,e)}var Zy=_("ZodAny",(e,t)=>{bd.init(e,t),se.init(e,t)});function Jp(){return $p(Zy)}var qy=_("ZodUnknown",(e,t)=>{wd.init(e,t),se.init(e,t)});function pe(){return Sp(qy)}var Ly=_("ZodNever",(e,t)=>{$d.init(e,t),se.init(e,t)});function Fy(e){return xp(Ly,e)}var Gp=_("ZodDate",(e,t)=>{Sd.init(e,t),se.init(e,t),e.min=(n,o)=>e.check(rt(n,o)),e.max=(n,o)=>e.check(vt(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 Vy=_("ZodArray",(e,t)=>{xd.init(e,t),se.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(xr(r,n)),e.nonempty=r=>e.check(xr(1,r)),e.max=(r,n)=>e.check(Po(r,n)),e.length=(r,n)=>e.check(To(r,n)),e.unwrap=()=>e.element});function k(e,t){return zp(Vy,e,t)}var Wp=_("ZodObject",(e,t)=>{kd.init(e,t),se.init(e,t),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Me(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:pe()}),e.loose=()=>e.clone({...e._zod.def,catchall:pe()}),e.strict=()=>e.clone({...e._zod.def,catchall:Fy()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>G.extend(e,r),e.merge=r=>G.merge(e,r),e.pick=r=>G.pick(e,r),e.omit=r=>G.omit(e,r),e.partial=(...r)=>G.partial(Xp,e,r[0]),e.required=(...r)=>G.required(ef,e,r[0])});function z(e,t){let r={type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},...G.normalizeParams(t)};return new Wp(r)}function ye(e,t){return new Wp({type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},catchall:pe(),...G.normalizeParams(t)})}var Yp=_("ZodUnion",(e,t)=>{yi.init(e,t),se.init(e,t),e.options=t.options});function ce(e,t){return new Yp({type:"union",options:e,...G.normalizeParams(t)})}var Hy=_("ZodDiscriminatedUnion",(e,t)=>{Yp.init(e,t),zd.init(e,t)});function Zi(e,t,r){return new Hy({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}var By=_("ZodIntersection",(e,t)=>{Pd.init(e,t),se.init(e,t)});function Oo(e,t){return new By({type:"intersection",left:e,right:t})}var Ky=_("ZodRecord",(e,t)=>{Td.init(e,t),se.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ie(e,t,r){return new Ky({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}var ji=_("ZodEnum",(e,t)=>{Rd.init(e,t),se.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 ji({...t,checks:[],...G.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 ji({...t,checks:[],...G.normalizeParams(o),entries:s})}});function Me(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ji({type:"enum",entries:r,...G.normalizeParams(t)})}var Jy=_("ZodLiteral",(e,t)=>{Ed.init(e,t),se.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 Jy({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}var Gy=_("ZodTransform",(e,t)=>{Id.init(e,t),se.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.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(G.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 Qp(e){return new Gy({type:"transform",transform:e})}var Xp=_("ZodOptional",(e,t)=>{Od.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fe(e){return new Xp({type:"optional",innerType:e})}var Wy=_("ZodNullable",(e,t)=>{Ad.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Lp(e){return new Wy({type:"nullable",innerType:e})}var Yy=_("ZodDefault",(e,t)=>{Cd.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Qy(e,t){return new Yy({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Xy=_("ZodPrefault",(e,t)=>{Nd.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ev(e,t){return new Xy({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var ef=_("ZodNonOptional",(e,t)=>{jd.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tv(e,t){return new ef({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}var rv=_("ZodCatch",(e,t)=>{Md.init(e,t),se.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nv(e,t){return new rv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var ov=_("ZodPipe",(e,t)=>{Ud.init(e,t),se.init(e,t),e.in=t.in,e.out=t.out});function Mi(e,t){return new ov({type:"pipe",in:e,out:t})}var sv=_("ZodReadonly",(e,t)=>{Dd.init(e,t),se.init(e,t)});function iv(e){return new sv({type:"readonly",innerType:e})}var tf=_("ZodCustom",(e,t)=>{Zd.init(e,t),se.init(e,t)});function av(e){let t=new Te({check:"custom"});return t._zod.check=e,t}function rf(e,t){return Pp(tf,e??(()=>!0),t)}function cv(e,t={}){return Tp(tf,e,t)}function uv(e){let t=av(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(G.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(G.issue(o))}},e(r.value,r)));return t}function qi(e,t){return Mi(Qp(e),t)}var nf={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 Ao={};Js(Ao,{bigint:()=>fv,boolean:()=>pv,date:()=>mv,number:()=>dv,string:()=>lv});function lv(e){return Vd(Ui,e)}function dv(e){return gp(Io,e)}function pv(e){return vp(Di,e)}function fv(e){return bp(Bp,e)}function mv(e){return kp(Gp,e)}Fe(qd());var Tr="2025-11-25";var of=[Tr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Et="io.modelcontextprotocol/related-task",No="2.0",ve=rf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),sf=ce([p(),K().int()]),af=p(),RR=ye({ttl:K().optional(),pollInterval:K().optional()}),gv=z({ttl:K().optional()}),_v=z({taskId:p()}),Fi=ye({progressToken:sf.optional(),[Et]:_v.optional()}),Ve=z({_meta:Fi.optional()}),fn=Ve.extend({task:gv.optional()}),cf=e=>fn.safeParse(e).success,we=z({method:p(),params:Ve.loose().optional()}),Ke=z({_meta:Fi.optional()}),Je=z({method:p(),params:Ke.loose().optional()}),$e=ye({_meta:Fi.optional()}),jo=ce([p(),K().int()]),uf=z({jsonrpc:E(No),id:jo,...we.shape}).strict(),mn=e=>uf.safeParse(e).success,lf=z({jsonrpc:E(No),...Je.shape}).strict(),df=e=>lf.safeParse(e).success,Vi=z({jsonrpc:E(No),id:jo,result:$e}).strict(),Jt=e=>Vi.safeParse(e).success;var N;(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"})(N||(N={}));var Hi=z({jsonrpc:E(No),id:jo.optional(),error:z({code:K().int(),message:p(),data:pe().optional()})}).strict();var pf=e=>Hi.safeParse(e).success;var Rr=ce([uf,lf,Vi,Hi]),ER=ce([Vi,Hi]),Gt=$e.strict(),yv=Ke.extend({requestId:jo.optional(),reason:p().optional()}),Mo=Je.extend({method:E("notifications/cancelled"),params:yv}),vv=z({src:p(),mimeType:p().optional(),sizes:k(p()).optional(),theme:Me(["light","dark"]).optional()}),hn=z({icons:k(vv).optional()}),Pr=z({name:p(),title:p().optional()}),ff=Pr.extend({...Pr.shape,...hn.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),bv=Oo(z({applyDefaults:te().optional()}),ie(p(),pe())),wv=qi(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Oo(z({form:bv.optional(),url:ve.optional()}),ie(p(),pe()).optional())),$v=ye({list:ve.optional(),cancel:ve.optional(),requests:ye({sampling:ye({createMessage:ve.optional()}).optional(),elicitation:ye({create:ve.optional()}).optional()}).optional()}),Sv=ye({list:ve.optional(),cancel:ve.optional(),requests:ye({tools:ye({call:ve.optional()}).optional()}).optional()}),xv=z({experimental:ie(p(),ve).optional(),sampling:z({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:wv.optional(),roots:z({listChanged:te().optional()}).optional(),tasks:$v.optional(),extensions:ie(p(),ve).optional()}),kv=Ve.extend({protocolVersion:p(),capabilities:xv,clientInfo:ff}),zv=we.extend({method:E("initialize"),params:kv});var Pv=z({experimental:ie(p(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:z({listChanged:te().optional()}).optional(),resources:z({subscribe:te().optional(),listChanged:te().optional()}).optional(),tools:z({listChanged:te().optional()}).optional(),tasks:Sv.optional(),extensions:ie(p(),ve).optional()}),Bi=$e.extend({protocolVersion:p(),capabilities:Pv,serverInfo:ff,instructions:p().optional()}),mf=Je.extend({method:E("notifications/initialized"),params:Ke.optional()}),hf=e=>mf.safeParse(e).success,Uo=we.extend({method:E("ping"),params:Ve.optional()}),Tv=z({progress:K(),total:fe(K()),message:fe(p())}),Rv=z({...Ke.shape,...Tv.shape,progressToken:sf}),Do=Je.extend({method:E("notifications/progress"),params:Rv}),Ev=Ve.extend({cursor:af.optional()}),gn=we.extend({params:Ev.optional()}),_n=$e.extend({nextCursor:af.optional()}),Iv=Me(["working","input_required","completed","failed","cancelled"]),yn=z({taskId:p(),status:Iv,ttl:ce([K(),Kp()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:fe(K()),statusMessage:fe(p())}),Wt=$e.extend({task:yn}),Ov=Ke.merge(yn),vn=Je.extend({method:E("notifications/tasks/status"),params:Ov}),Zo=we.extend({method:E("tasks/get"),params:Ve.extend({taskId:p()})}),qo=$e.merge(yn),Lo=we.extend({method:E("tasks/result"),params:Ve.extend({taskId:p()})}),IR=$e.loose(),Fo=gn.extend({method:E("tasks/list")}),Vo=_n.extend({tasks:k(yn)}),Ho=we.extend({method:E("tasks/cancel"),params:Ve.extend({taskId:p()})}),gf=$e.merge(yn),_f=z({uri:p(),mimeType:fe(p()),_meta:ie(p(),pe()).optional()}),yf=_f.extend({text:p()}),Ki=p().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),vf=_f.extend({blob:Ki}),bn=Me(["user","assistant"]),Er=z({audience:k(bn).optional(),priority:K().min(0).max(1).optional(),lastModified:dn.datetime({offset:!0}).optional()}),bf=z({...Pr.shape,...hn.shape,uri:p(),description:fe(p()),mimeType:fe(p()),size:fe(K()),annotations:Er.optional(),_meta:fe(ye({}))}),Av=z({...Pr.shape,...hn.shape,uriTemplate:p(),description:fe(p()),mimeType:fe(p()),annotations:Er.optional(),_meta:fe(ye({}))}),Cv=gn.extend({method:E("resources/list")}),Ji=_n.extend({resources:k(bf)}),Nv=gn.extend({method:E("resources/templates/list")}),Gi=_n.extend({resourceTemplates:k(Av)}),Wi=Ve.extend({uri:p()}),jv=Wi,Mv=we.extend({method:E("resources/read"),params:jv}),Yi=$e.extend({contents:k(ce([yf,vf]))}),Qi=Je.extend({method:E("notifications/resources/list_changed"),params:Ke.optional()}),Uv=Wi,Dv=we.extend({method:E("resources/subscribe"),params:Uv}),Zv=Wi,qv=we.extend({method:E("resources/unsubscribe"),params:Zv}),Lv=Ke.extend({uri:p()}),Fv=Je.extend({method:E("notifications/resources/updated"),params:Lv}),Vv=z({name:p(),description:fe(p()),required:fe(te())}),Hv=z({...Pr.shape,...hn.shape,description:fe(p()),arguments:fe(k(Vv)),_meta:fe(ye({}))}),Bv=gn.extend({method:E("prompts/list")}),Xi=_n.extend({prompts:k(Hv)}),Kv=Ve.extend({name:p(),arguments:ie(p(),p()).optional()}),Jv=we.extend({method:E("prompts/get"),params:Kv}),ea=z({type:E("text"),text:p(),annotations:Er.optional(),_meta:ie(p(),pe()).optional()}),ta=z({type:E("image"),data:Ki,mimeType:p(),annotations:Er.optional(),_meta:ie(p(),pe()).optional()}),ra=z({type:E("audio"),data:Ki,mimeType:p(),annotations:Er.optional(),_meta:ie(p(),pe()).optional()}),Gv=z({type:E("tool_use"),name:p(),id:p(),input:ie(p(),pe()),_meta:ie(p(),pe()).optional()}),Wv=z({type:E("resource"),resource:ce([yf,vf]),annotations:Er.optional(),_meta:ie(p(),pe()).optional()}),Yv=bf.extend({type:E("resource_link")}),na=ce([ea,ta,ra,Yv,Wv]),Qv=z({role:bn,content:na}),oa=$e.extend({description:p().optional(),messages:k(Qv)}),sa=Je.extend({method:E("notifications/prompts/list_changed"),params:Ke.optional()}),Xv=z({title:p().optional(),readOnlyHint:te().optional(),destructiveHint:te().optional(),idempotentHint:te().optional(),openWorldHint:te().optional()}),eb=z({taskSupport:Me(["required","optional","forbidden"]).optional()}),wf=z({...Pr.shape,...hn.shape,description:p().optional(),inputSchema:z({type:E("object"),properties:ie(p(),ve).optional(),required:k(p()).optional()}).catchall(pe()),outputSchema:z({type:E("object"),properties:ie(p(),ve).optional(),required:k(p()).optional()}).catchall(pe()).optional(),annotations:Xv.optional(),execution:eb.optional(),_meta:ie(p(),pe()).optional()}),tb=gn.extend({method:E("tools/list")}),ia=_n.extend({tools:k(wf)}),Ir=$e.extend({content:k(na).default([]),structuredContent:ie(p(),pe()).optional(),isError:te().optional()}),OR=Ir.or($e.extend({toolResult:pe()})),rb=fn.extend({name:p(),arguments:ie(p(),pe()).optional()}),nb=we.extend({method:E("tools/call"),params:rb}),aa=Je.extend({method:E("notifications/tools/list_changed"),params:Ke.optional()}),$f=z({autoRefresh:te().default(!0),debounceMs:K().int().nonnegative().default(300)}),Sf=Me(["debug","info","notice","warning","error","critical","alert","emergency"]),ob=Ve.extend({level:Sf}),sb=we.extend({method:E("logging/setLevel"),params:ob}),ib=Ke.extend({level:Sf,logger:p().optional(),data:pe()}),ab=Je.extend({method:E("notifications/message"),params:ib}),cb=z({name:p().optional()}),ub=z({hints:k(cb).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),lb=z({mode:Me(["auto","required","none"]).optional()}),db=z({type:E("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:k(na).default([]),structuredContent:z({}).loose().optional(),isError:te().optional(),_meta:ie(p(),pe()).optional()}),pb=Zi("type",[ea,ta,ra]),Co=Zi("type",[ea,ta,ra,Gv,db]),fb=z({role:bn,content:ce([Co,k(Co)]),_meta:ie(p(),pe()).optional()}),mb=fn.extend({messages:k(fb),modelPreferences:ub.optional(),systemPrompt:p().optional(),includeContext:Me(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:k(p()).optional(),metadata:ve.optional(),tools:k(wf).optional(),toolChoice:lb.optional()}),ca=we.extend({method:E("sampling/createMessage"),params:mb}),ua=$e.extend({model:p(),stopReason:fe(Me(["endTurn","stopSequence","maxTokens"]).or(p())),role:bn,content:pb}),la=$e.extend({model:p(),stopReason:fe(Me(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:bn,content:ce([Co,k(Co)])}),hb=z({type:E("boolean"),title:p().optional(),description:p().optional(),default:te().optional()}),gb=z({type:E("string"),title:p().optional(),description:p().optional(),minLength:K().optional(),maxLength:K().optional(),format:Me(["email","uri","date","date-time"]).optional(),default:p().optional()}),_b=z({type:Me(["number","integer"]),title:p().optional(),description:p().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),yb=z({type:E("string"),title:p().optional(),description:p().optional(),enum:k(p()),default:p().optional()}),vb=z({type:E("string"),title:p().optional(),description:p().optional(),oneOf:k(z({const:p(),title:p()})),default:p().optional()}),bb=z({type:E("string"),title:p().optional(),description:p().optional(),enum:k(p()),enumNames:k(p()).optional(),default:p().optional()}),wb=ce([yb,vb]),$b=z({type:E("array"),title:p().optional(),description:p().optional(),minItems:K().optional(),maxItems:K().optional(),items:z({type:E("string"),enum:k(p())}),default:k(p()).optional()}),Sb=z({type:E("array"),title:p().optional(),description:p().optional(),minItems:K().optional(),maxItems:K().optional(),items:z({anyOf:k(z({const:p(),title:p()}))}),default:k(p()).optional()}),xb=ce([$b,Sb]),kb=ce([bb,wb,xb]),zb=ce([kb,hb,gb,_b]),Pb=fn.extend({mode:E("form").optional(),message:p(),requestedSchema:z({type:E("object"),properties:ie(p(),zb),required:k(p()).optional()})}),Tb=fn.extend({mode:E("url"),message:p(),elicitationId:p(),url:p().url()}),Rb=ce([Pb,Tb]),da=we.extend({method:E("elicitation/create"),params:Rb}),Eb=Ke.extend({elicitationId:p()}),Ib=Je.extend({method:E("notifications/elicitation/complete"),params:Eb}),pa=$e.extend({action:Me(["accept","decline","cancel"]),content:qi(e=>e===null?void 0:e,ie(p(),ce([p(),K(),te(),k(p())])).optional())}),Ob=z({type:E("ref/resource"),uri:p()});var Ab=z({type:E("ref/prompt"),name:p()}),Cb=Ve.extend({ref:ce([Ab,Ob]),argument:z({name:p(),value:p()}),context:z({arguments:ie(p(),p()).optional()}).optional()}),Nb=we.extend({method:E("completion/complete"),params:Cb});var fa=$e.extend({completion:ye({values:k(p()).max(100),total:fe(K().int()),hasMore:fe(te())})}),jb=z({uri:p().startsWith("file://"),name:p().optional(),_meta:ie(p(),pe()).optional()}),Mb=we.extend({method:E("roots/list"),params:Ve.optional()}),Ub=$e.extend({roots:k(jb)}),Db=Je.extend({method:E("notifications/roots/list_changed"),params:Ke.optional()}),AR=ce([Uo,zv,Nb,sb,Jv,Bv,Cv,Nv,Mv,Dv,qv,nb,tb,Zo,Lo,Fo,Ho]),CR=ce([Mo,Do,mf,Db,vn]),NR=ce([Gt,ua,la,pa,Ub,qo,Vo,Wt]),jR=ce([Uo,ca,da,Mb,Zo,Lo,Fo,Ho]),MR=ce([Mo,Do,ab,Fv,Qi,aa,sa,vn,Ib]),UR=ce([Gt,Bi,fa,oa,Xi,Ji,Gi,Yi,Ir,ia,qo,Vo,Wt]),C=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===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Li(o.elicitations,r)}return new e(t,r,n)}},Li=class extends C{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function It(e){return e==="completed"||e==="failed"||e==="cancelled"}var Zb=Symbol("Let zodToJsonSchema decide on which parser to use");var _E=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ma(e){let r=Ro(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Rp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ha(e,t){let r=nt(e,t);if(!r.success)throw r.error;return r.data}var Bb=6e4,Bo=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(Mo,r=>{this._oncancel(r)}),this.setNotificationHandler(Do,r=>{this._onprogress(r)}),this.setRequestHandler(Uo,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Zo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Lo,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,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,f=new C(d.error.code,d.error.message,d.error.data);u(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new C(N.InvalidParams,`Task not found: ${s}`);if(!It(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(It(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Et]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Fo,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 C(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ho,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(It(o.status))throw new C(N.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 C(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof C?o:new C(N.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),C.fromError(N.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),Jt(s)||pf(s)?this._onresponse(s):mn(s)?this._onrequest(s,i):df(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=C.fromError(N.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?.[Et]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).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=cf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:t.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(i.signal.aborted)throw new C(N.ConnectionClosed,"Request was cancelled");let m={...f,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(u,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,l)).then(async u=>{if(i.signal.aborted)return;let d={result:u,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 u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:N.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).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),Jt(t))n(t);else{let i=new C(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(Jt(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),Jt(t))o(t);else{let i=C.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 C?i:new C(N.InternalError,String(i))}}return}let s;try{let i=await this.request(t,Wt,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new C(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},It(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new C(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(N.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(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof C?i:new C(N.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=S=>{u(S)};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(S){d(S);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Et]:c}});let h=S=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let $=S instanceof C?S:new C(N.RequestTimeout,String(S));u($)};this._responseHandlers.set(f,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return u(S);try{let $=nt(r,S.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??Bb,y=()=>h(C.fromError(N.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(f,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let S=$=>{let P=this._responseHandlers.get(f);P?P($):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,S),this._enqueueTaskMessage(w,{type:"request",message:m,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(f),u($)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(f),u(S)})})}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},Vo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},gf,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||{},[Et]: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||{},[Et]: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||{},[Et]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=ma(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ha(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=ma(t);this._notificationHandlers.set(n,o=>{let s=ha(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"&&mn(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new C(N.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 C(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new C(N.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 C(N.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=vn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),It(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 C(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(It(a.status))throw new C(N.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 l=vn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),It(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function xf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kf(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];xf(i)&&xf(s)?r[o]={...i,...s}:r[o]=s}return r}var gg=Du(tu(),1),_g=Du(hg(),1);function Wk(){let e=new gg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_g.default)(e),e}var Ps=class{constructor(t){this._ajv=t??Wk()}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 Ts=class{constructor(t){this._client=t}async*callToolStream(t,r=Ir,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 l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new C(N.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new C(N.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof C){yield{type:"error",error:u};return}yield{type:"error",error:new C(N.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};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 yg(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 vg(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 Rs(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&&Rs(s,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Rs(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Rs(r,t)}}function Yk(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 Es=class extends Bo{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 Ps,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",aa,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",sa,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Qi,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ts(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=kf(this._capabilities,t)}setRequestHandler(t,r){let o=Ro(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(zr(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,l)=>{let u=nt(da,c);if(!u.success){let S=u.error instanceof Error?u.error.message:String(u.error);throw new C(N.InvalidParams,`Invalid elicitation request: ${S}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:m}=Yk(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new C(N.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!m)throw new C(N.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,l));if(d.task){let S=nt(Wt,h);if(!S.success){let $=S.error instanceof Error?S.error.message:String(S.error);throw new C(N.InvalidParams,`Invalid task creation result: ${$}`)}return S.data}let g=nt(pa,h);if(!g.success){let S=g.error instanceof Error?g.error.message:String(g.error);throw new C(N.InvalidParams,`Invalid elicitation result: ${S}`)}let y=g.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Rs(w,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){let a=async(c,l)=>{let u=nt(ca,c);if(!u.success){let y=u.error instanceof Error?u.error.message:String(u.error);throw new C(N.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let y=nt(Wt,f);if(!y.success){let w=y.error instanceof Error?y.error.message:String(y.error);throw new C(N.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}let h=d.tools||d.toolChoice?la:ua,g=nt(h,f);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new C(N.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:Tr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Bi,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!of.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){yg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&vg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Gt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},fa,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Gt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},oa,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Xi,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ji,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Gi,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Yi,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Gt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Gt,r)}async callTool(t,r=Ir,n){if(this.isToolTaskRequired(t.name))throw new C(N.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 C(N.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 C(N.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof C?i:new C(N.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},ia,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let s=$f.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,l=async()=>{if(!i){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let f=setTimeout(l,a);this._listChangedDebounceTimers.set(t,f)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Is(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function bg(e=fetch,t){return t?async(r,n)=>{let o={...t,...n,headers:n?.headers?{...Is(t.headers),...Is(n.headers)}:t.headers};return e(r,o)}:e}var uu;uu=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function Qk(e){return(await uu).getRandomValues(new Uint8Array(e))}async function Xk(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let o=await Qk(e-n.length);for(let s of o)s<r&&(n+=t[s%t.length])}return n}async function ez(e){return await Xk(e)}async function tz(e){let t=await(await uu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function lu(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ez(e),r=await tz(t);return{code_verifier:t,code_challenge:r}}var ze=Hp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:nf.custom,message:"URL must be parseable",fatal:!0}),Gs}).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"}),$g=ye({resource:p().url(),authorization_servers:k(ze).optional(),jwks_uri:p().url().optional(),scopes_supported:k(p()).optional(),bearer_methods_supported:k(p()).optional(),resource_signing_alg_values_supported:k(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:te().optional(),authorization_details_types_supported:k(p()).optional(),dpop_signing_alg_values_supported:k(p()).optional(),dpop_bound_access_tokens_required:te().optional()}),du=ye({issuer:p(),authorization_endpoint:ze,token_endpoint:ze,registration_endpoint:ze.optional(),scopes_supported:k(p()).optional(),response_types_supported:k(p()),response_modes_supported:k(p()).optional(),grant_types_supported:k(p()).optional(),token_endpoint_auth_methods_supported:k(p()).optional(),token_endpoint_auth_signing_alg_values_supported:k(p()).optional(),service_documentation:ze.optional(),revocation_endpoint:ze.optional(),revocation_endpoint_auth_methods_supported:k(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:k(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:k(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:k(p()).optional(),code_challenge_methods_supported:k(p()).optional(),client_id_metadata_document_supported:te().optional()}),rz=ye({issuer:p(),authorization_endpoint:ze,token_endpoint:ze,userinfo_endpoint:ze.optional(),jwks_uri:ze,registration_endpoint:ze.optional(),scopes_supported:k(p()).optional(),response_types_supported:k(p()),response_modes_supported:k(p()).optional(),grant_types_supported:k(p()).optional(),acr_values_supported:k(p()).optional(),subject_types_supported:k(p()),id_token_signing_alg_values_supported:k(p()),id_token_encryption_alg_values_supported:k(p()).optional(),id_token_encryption_enc_values_supported:k(p()).optional(),userinfo_signing_alg_values_supported:k(p()).optional(),userinfo_encryption_alg_values_supported:k(p()).optional(),userinfo_encryption_enc_values_supported:k(p()).optional(),request_object_signing_alg_values_supported:k(p()).optional(),request_object_encryption_alg_values_supported:k(p()).optional(),request_object_encryption_enc_values_supported:k(p()).optional(),token_endpoint_auth_methods_supported:k(p()).optional(),token_endpoint_auth_signing_alg_values_supported:k(p()).optional(),display_values_supported:k(p()).optional(),claim_types_supported:k(p()).optional(),claims_supported:k(p()).optional(),service_documentation:p().optional(),claims_locales_supported:k(p()).optional(),ui_locales_supported:k(p()).optional(),claims_parameter_supported:te().optional(),request_parameter_supported:te().optional(),request_uri_parameter_supported:te().optional(),require_request_uri_registration:te().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:te().optional()}),Sg=z({...rz.shape,...du.pick({code_challenge_methods_supported:!0}).shape}),xg=z({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:Ao.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),kg=z({error:p(),error_description:p().optional(),error_uri:p().optional()}),wg=ze.optional().or(E("").transform(()=>{})),nz=z({redirect_uris:k(ze),token_endpoint_auth_method:p().optional(),grant_types:k(p()).optional(),response_types:k(p()).optional(),client_name:p().optional(),client_uri:ze.optional(),logo_uri:wg,scope:p().optional(),contacts:k(p()).optional(),tos_uri:wg,policy_uri:p().optional(),jwks_uri:ze.optional(),jwks:Jp().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),oz=z({client_id:p(),client_secret:p().optional(),client_id_issued_at:K().optional(),client_secret_expires_at:K().optional()}).strip(),zg=nz.merge(oz),F1=z({error:p(),error_description:p().optional()}).strip(),V1=z({token:p(),token_type_hint:p().optional()}).strip();function Pg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Tg({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 ge=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}},Yn=class extends ge{};Yn.errorCode="invalid_request";var cr=class extends ge{};cr.errorCode="invalid_client";var ur=class extends ge{};ur.errorCode="invalid_grant";var lr=class extends ge{};lr.errorCode="unauthorized_client";var Qn=class extends ge{};Qn.errorCode="unsupported_grant_type";var Xn=class extends ge{};Xn.errorCode="invalid_scope";var eo=class extends ge{};eo.errorCode="access_denied";var kt=class extends ge{};kt.errorCode="server_error";var to=class extends ge{};to.errorCode="temporarily_unavailable";var ro=class extends ge{};ro.errorCode="unsupported_response_type";var no=class extends ge{};no.errorCode="unsupported_token_type";var oo=class extends ge{};oo.errorCode="invalid_token";var so=class extends ge{};so.errorCode="method_not_allowed";var io=class extends ge{};io.errorCode="too_many_requests";var dr=class extends ge{};dr.errorCode="invalid_client_metadata";var ao=class extends ge{};ao.errorCode="insufficient_scope";var co=class extends ge{};co.errorCode="invalid_target";var Rg={[Yn.errorCode]:Yn,[cr.errorCode]:cr,[ur.errorCode]:ur,[lr.errorCode]:lr,[Qn.errorCode]:Qn,[Xn.errorCode]:Xn,[eo.errorCode]:eo,[kt.errorCode]:kt,[to.errorCode]:to,[ro.errorCode]:ro,[no.errorCode]:no,[oo.errorCode]:oo,[so.errorCode]:so,[io.errorCode]:io,[dr.errorCode]:dr,[ao.errorCode]:ao,[co.errorCode]:co};var zt=class extends Error{constructor(t){super(t??"Unauthorized")}};function sz(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var pu="code",fu="S256";function iz(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&sz(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 az(e,t,r,n){let{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":cz(o,s,r);return;case"client_secret_post":uz(o,s,n);return;case"none":lz(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function cz(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 uz(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function lz(e,t){t.set("client_id",e)}async function Ig(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=kg.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Rg[o]||kt;return new a(s||"",i)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new kt(o)}}async function uo(e,t){try{return await mu(e,t)}catch(r){if(r instanceof cr||r instanceof lr)return await e.invalidateCredentials?.("all"),await mu(e,t);if(r instanceof ur)return await e.invalidateCredentials?.("tokens"),await mu(e,t);throw r}}async function mu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await e.discoveryState?.(),a,c,l,u=o;if(!u&&i?.resourceMetadataUrl&&(u=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,l=i.authorizationServerMetadata??await Ag(c,{fetchFn:s}),!a)try{a=await Og(t,{resourceMetadataUrl:u},s)}catch{}(l!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}else{let $=await _z(t,{resourceMetadataUrl:u,fetchFn:s});c=$.authorizationServerUrl,l=$.authorizationServerMetadata,a=$.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}let d=await pz(t,e,a),f=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 $=l?.client_id_metadata_document_supported===!0,P=e.clientMetadataUrl;if(P&&!dz(P))throw new dr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if($&&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 x=await $z(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:s});await e.saveClientInformation(x),m=x}}let h=!e.redirectUrl;if(r!==void 0||h){let $=await wz(e,c,{metadata:l,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens($),"AUTHORIZED"}let g=await e.tokens();if(g?.refresh_token)try{let $=await bz(c,{metadata:l,clientInformation:m,refreshToken:g.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens($),"AUTHORIZED"}catch($){if(!(!($ instanceof ge)||$ instanceof kt))throw $}let y=e.state?await e.state():void 0,{authorizationUrl:w,codeVerifier:S}=await yz(c,{metadata:l,clientInformation:m,state:y,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(S),await e.redirectToAuthorization(w),"REDIRECT"}function dz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function pz(e,t,r){let n=Pg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Tg({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 gu(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=hu(e,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=hu(e,"scope")||void 0,a=hu(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function hu(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 Og(e,t,r=fetch){let n=await hz(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 $g.parse(await n.json())}async function _u(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?_u(e,void 0,r):void 0;throw n}}function fz(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Eg(e,t,r=fetch){return await _u(e,{"MCP-Protocol-Version":t},r)}function mz(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function hz(e,t,r,n){let o=new URL(e),s=n?.protocolVersion??Tr,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=fz(t,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Eg(i,s,r);if(!n?.metadataUrl&&mz(a,o.pathname)){let c=new URL(`/.well-known/${t}`,o);a=await Eg(c,s,r)}return a}function gz(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 Ag(e,{fetchFn:t=fetch,protocolVersion:r=Tr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=gz(e);for(let{url:s,type:i}of o){let a=await _u(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"?du.parse(await a.json()):Sg.parse(await a.json())}}}async function _z(e,t){let r,n;try{r=await Og(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 Ag(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function yz(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(pu))throw new Error(`Incompatible auth server: does not support response type ${pu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(fu))throw new Error(`Incompatible auth server: does not support code challenge method ${fu}`)}else a=new URL("/authorize",e);let c=await lu(),l=c.code_verifier,u=c.code_challenge;return a.searchParams.set("response_type",pu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",fu),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:l}}function vz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Cg(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 u=t?.token_endpoint_auth_methods_supported??[],d=iz(n,u);az(d,n,c,r)}let l=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!l.ok)throw await Ig(l);return xg.parse(await l.json())}async function bz(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 Cg(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function wz(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 l=await e.codeVerifier();a=vz(o,l,e.redirectUrl)}let c=await e.clientInformation();return Cg(t,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function $z(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 Ig(i);return zg.parse(await i.json())}var lo=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}},Ng=10,Sz=13,pr=32;function yu(e){}function Ug(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=yu,onError:r=yu,onRetry:n=yu,onComment:o,maxBufferSize:s}=e,i=[],a=0,c=!0,l,u="",d=0,f,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 L=y(v);L!==""&&(i.push(L),a=L.length),g();return}if(v.indexOf(`
36
+ `)===-1&&v.indexOf("\r")===-1){i.push(v),a+=v.length,g();return}i.push(v);let x=i.join("");i.length=0,a=0;let R=y(x);R!==""&&(i.push(R),a=R.length),g()}function g(){s!==void 0&&(a+u.length<=s||(m=!0,i.length=0,a=0,l=void 0,u="",d=0,f=void 0,r(new lo(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let x=0;if(v.indexOf("\r")===-1){let R=v.indexOf(`
37
37
  `,x);for(;R!==-1;){if(x===R){d>0&&t({id:l,event:f,data:u}),l=void 0,u="",d=0,f=void 0,x=R+1,R=v.indexOf(`
38
- `,x);continue}let L=v.charCodeAt(x);if(Ag(v,x,L)){let Y=v.charCodeAt(x+5)===pr?x+6:x+5,me=v.slice(Y,R);if(d===0&&v.charCodeAt(R+1)===Og){t({id:l,event:f,data:me}),l=void 0,u="",f=void 0,x=R+2,R=v.indexOf(`
38
+ `,x);continue}let L=v.charCodeAt(x);if(jg(v,x,L)){let Y=v.charCodeAt(x+5)===pr?x+6:x+5,me=v.slice(Y,R);if(d===0&&v.charCodeAt(R+1)===Ng){t({id:l,event:f,data:me}),l=void 0,u="",f=void 0,x=R+2,R=v.indexOf(`
39
39
  `,x);continue}u=d===0?me:`${u}
40
- ${me}`,d++}else Cg(v,x,L)?f=v.slice(v.charCodeAt(x+6)===pr?x+7:x+6,R)||void 0:b(v,x,R);x=R+1,R=v.indexOf(`
40
+ ${me}`,d++}else Mg(v,x,L)?f=v.slice(v.charCodeAt(x+6)===pr?x+7:x+6,R)||void 0:w(v,x,R);x=R+1,R=v.indexOf(`
41
41
  `,x)}return v.slice(x)}for(;x<v.length;){let R=v.indexOf("\r",x),L=v.indexOf(`
42
- `,x),Y=-1;if(R!==-1&&L!==-1?Y=R<L?R:L:R!==-1?R===v.length-1?Y=-1:Y=R:L!==-1&&(Y=L),Y===-1)break;b(v,x,Y),x=Y+1,v.charCodeAt(x-1)===mk&&v.charCodeAt(x)===Og&&x++}return v.slice(x)}function b(v,x,R){if(x===R){$();return}let L=v.charCodeAt(x);if(Ag(v,x,L)){let Ne=v.charCodeAt(x+5)===pr?x+6:x+5,_r=v.slice(Ne,R);u=d===0?_r:`${u}
43
- ${_r}`,d++;return}if(Cg(v,x,L)){f=v.slice(v.charCodeAt(x+6)===pr?x+7:x+6,R)||void 0;return}if(L===105&&v.charCodeAt(x+1)===100&&v.charCodeAt(x+2)===58){let Ne=v.slice(v.charCodeAt(x+3)===pr?x+4:x+3,R);l=Ne.includes("\0")?void 0:Ne;return}if(L===58){if(o){let Ne=v.slice(x,R);o(Ne.slice(v.charCodeAt(x+1)===pr?2:1))}return}let Y=v.slice(x,R),me=Y.indexOf(":");if(me===-1){S(Y,"",Y);return}let Le=Y.slice(0,me),gr=Y.charCodeAt(me+1)===pr?2:1,Tt=Y.slice(me+gr);S(Le,Tt,Y)}function S(v,x,R){switch(v){case"event":f=x||void 0;break;case"data":u=d===0?x:`${u}
44
- ${x}`,d++;break;case"id":l=x.includes("\0")?void 0:x;break;case"retry":/^\d+$/.test(x)?n(parseInt(x,10)):r(new uo(`Invalid \`retry\` value: "${x}"`,{type:"invalid-retry",value:x,line:R}));break;default:r(new uo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:x,line:R}));break}}function $(){d>0&&t({id:l,event:f,data:u}),l=void 0,u="",d=0,f=void 0}function P(v={}){if(v.consume&&i.length>0){let x=i.join("");b(x,0,x.length)}c=!0,l=void 0,u="",d=0,f=void 0,i.length=0,a=0,m=!1}return{feed:h,reset:P}}function Ag(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 Cg(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 Es=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Ng({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 hk={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Zt=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Gr=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=_g(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??hk}async _authThenStart(){if(!this._authProvider)throw new zt("No auth provider");let t;try{t=await co(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 zt;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=Rs(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 Zt(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 u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Es({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:h}=await u.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=Tr.parse(JSON.parse(m.data));Jt(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(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(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 zt("No auth provider");if(await co(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:fn(t)?t.id:void 0}).catch(f=>this.onerror?.(f));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 f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Zt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:m,scope:h}=mu(a);if(this._resourceMetadataUrl=m,this._scope=h,await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:m,scope:h,error:g}=mu(a);if(g==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Zt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zt;return this.send(t)}}throw new Zt(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),pf(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(t)?t:[t]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(d?.includes("application/json")){let f=await a.json(),m=Array.isArray(f)?f.map(h=>Tr.parse(h)):[Tr.parse(f)];for(let h of m)this.onmessage?.(h)}else throw await a.body?.cancel(),new Zt(-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 Zt(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 Oe from"node:fs";import{randomBytes as gk}from"node:crypto";import{homedir as Mg}from"node:os";import{resolve as Os,join as _u,dirname as yu,basename as _k}from"node:path";var lo=["owner","shared","open"],Wr={brokerUrl:"wss://broker1.ours.network",port:3050,stateDir:Os(Mg(),".ours"),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function po(){return process.env.OURS_CONFIG??_u(Mg(),".ours","config.json")}function yk(){let e;try{e=Oe.readFileSync(po(),"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=Os(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"&&lo.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 vk(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&lo.includes(e)?e:void 0}function wk(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function jg(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function vu(){let e=yk();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??Wr.brokerUrl,port:jg("OURS_PORT")??e.port??Wr.port,stateDir:Os(process.env.OURS_STATE_DIR??e.stateDir??Wr.stateDir),gcIntervalMs:jg("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??Wr.gcIntervalMs,autoStart:wk("OURS_AUTOSTART")??e.autoStart??Wr.autoStart,apiVisibility:vk()??e.apiVisibility??Wr.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||e.apiToken,stt:bk(e.stt)}}function bk(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 $k="daemon-token";function Sk(e){return _u(e.stateDir,$k)}function Ug(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=Sk(e);try{let i=Oe.readFileSync(o,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!t.generate)return null;let s=gk(32).toString("hex");try{Oe.mkdirSync(yu(o),{recursive:!0}),Oe.writeFileSync(o,s+`
45
- `,{mode:384}),Oe.chmodSync(o,384)}catch{}return{token:s,source:"generated"}}function Dg(e){let t=po();Oe.mkdirSync(yu(t),{recursive:!0}),Oe.writeFileSync(t,JSON.stringify(e,null,2)+`
46
- `,{mode:384});try{Oe.chmodSync(t,384)}catch{}return t}var Is=".ours-identity";function As(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 wu(e){let t=Os(e);return _k(t)===Is?t:_u(t,Is)}function Zg(e,t,r=!1){let n=As(t),o=wu(e);if(!r&&Oe.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Oe.mkdirSync(yu(o),{recursive:!0}),Oe.writeFileSync(o,JSON.stringify(n,null,2)+`
47
- `),o}import Lg from"node:process";var Cs=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),xk(r)}clear(){this._buffer=void 0}};function xk(e){return Tr.parse(JSON.parse(e))}function qg(e){return JSON.stringify(e)+`
49
- `}var Ns=class{constructor(t=Lg.stdin,r=Lg.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Cs,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=qg(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function Fg(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 zk,writeFileSync as kk,readFileSync as Pk,readdirSync as Tk,statSync as Vg,unlinkSync as Rk,chmodSync as Hg}from"node:fs";import{join as js}from"node:path";import{homedir as Ek}from"node:os";var Ik="0.15.0",Ok=new Set(["choose_identity","create_identity","create_root_identity"]),Bg=e=>new Promise(t=>setTimeout(t,e)),Ak=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,Ck=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,Kg=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},Jg=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,Gg=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase());async function Yg(e){let t=new URL(e.url),r=(...I)=>process.stderr.write(`[ours-proxy] ${I.join(" ")}
50
- `),n=I=>Number.isInteger(I)&&I>1,o=Number(process.env.OURS_CLIENT_PID),s=n(o)?o:n(process.ppid)?process.ppid:process.pid,i=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${s}`,a=null,c=null,l,u=null,d=new Map,f=null,m=Gg?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,h=e.stateDir??process.env.OURS_STATE_DIR??js(Ek(),".ours"),g=js(h,"session-restore"),y=m&&/^[A-Za-z0-9._-]{1,200}$/.test(m)?m:null,b=y?js(g,`${y}.json`):null,S=!1,$=null;function P(I){if(b)try{zk(g,{recursive:!0,mode:448}),kk(b,JSON.stringify({claudeSessionId:m,identity:I,boundAt:new Date().toISOString()}),{mode:384}),Hg(g,448),Hg(b,384)}catch(V){r("restore persist failed (non-fatal):",String(V))}}function v(){if(!b)return null;try{if(Date.now()-Vg(b).mtimeMs>Jg)return null;let I=JSON.parse(Pk(b,"utf8"));return(typeof I.identity=="string"?I.identity.trim():"")||null}catch{return null}}function x(){try{let I=Date.now();for(let V of Tk(g)){if(!V.endsWith(".json"))continue;let Q=js(g,V);try{I-Vg(Q).mtimeMs>Jg&&(Rk(Q),r("session-restore: pruned expired record",V))}catch{}}}catch{}}let R=null,L=!1,Y=!1,me=!1,Le=[],gr="__ours_proxy_init__",Tt=0,Ne=new Set,_r=new Set,Vt=new Ns;Vt.onmessage=I=>{let V=[],Q=!1;for(let Xe of Wg(I)){let _e=Xe;if(_e.method==="notifications/initialized"&&(Q=!0),Ak(_e)){if(_e.method==="initialize"&&(a=_e,c)){r("absorbed re-initialize locally \u2014 upstream session kept stable"),Vt.send({jsonrpc:"2.0",id:_e.id,result:c}).catch(we=>r("local initialize reply failed:",String(we)));continue}if(_e.method==="tools/call"){let we=_e.params;we&&Ok.has(we.name??"")&&typeof we.arguments?.name=="string"&&d.set(_e.id,we.arguments.name)}}V.push(_e)}if(V.length){let Xe=Array.isArray(I)?V:V[0];Iu(Xe)}Q&&S_()},Vt.onclose=()=>void Fs(0),Vt.onerror=I=>r("downstream error:",String(I));function S_(){if(S||!u)return;S=!0;let I=`__ours_proxy_restore_${++Tt}__`;Ne.add(I),$=I,r("session-restore: self-recovering bound identity",`"${u}"`),Iu({jsonrpc:"2.0",id:I,method:"tools/call",params:{name:"choose_identity",arguments:{name:u}}})}function Iu(I){if(L&&R){let V=R;R.send(I).catch(Q=>{r("upstream send failed:",String(Q)),Le.push(I),Ou(V,"send failed")})}else Le.push(I)}function Ou(I,V){if(Y||me||R!==null&&I!==R)return;r(`upstream dropped (${V}) \u2014 reconnecting`),L=!1;let Q=R;R=null;try{Q?.close?.()}catch{}z_()}function x_(I){I.onmessage=V=>{let Q=[];for(let Xe of Wg(V)){let _e=Xe;if(Ck(_e)){let we=_e.id,Vs=_e.result?.protocolVersion;if(Vs&&(_r.has(we)||Au(we))){l=Vs;try{R?.setProtocolVersion?.(Vs)}catch{}if(c==null&&Au(we)&&!Ne.has(we)){let gt=_e.result??null;gt&&f&&(gt.instructions=`${gt.instructions?gt.instructions+`
42
+ `,x),Y=-1;if(R!==-1&&L!==-1?Y=R<L?R:L:R!==-1?R===v.length-1?Y=-1:Y=R:L!==-1&&(Y=L),Y===-1)break;w(v,x,Y),x=Y+1,v.charCodeAt(x-1)===Sz&&v.charCodeAt(x)===Ng&&x++}return v.slice(x)}function w(v,x,R){if(x===R){$();return}let L=v.charCodeAt(x);if(jg(v,x,L)){let je=v.charCodeAt(x+5)===pr?x+6:x+5,yr=v.slice(je,R);u=d===0?yr:`${u}
43
+ ${yr}`,d++;return}if(Mg(v,x,L)){f=v.slice(v.charCodeAt(x+6)===pr?x+7:x+6,R)||void 0;return}if(L===105&&v.charCodeAt(x+1)===100&&v.charCodeAt(x+2)===58){let je=v.slice(v.charCodeAt(x+3)===pr?x+4:x+3,R);l=je.includes("\0")?void 0:je;return}if(L===58){if(o){let je=v.slice(x,R);o(je.slice(v.charCodeAt(x+1)===pr?2:1))}return}let Y=v.slice(x,R),me=Y.indexOf(":");if(me===-1){S(Y,"",Y);return}let Le=Y.slice(0,me),_r=Y.charCodeAt(me+1)===pr?2:1,Tt=Y.slice(me+_r);S(Le,Tt,Y)}function S(v,x,R){switch(v){case"event":f=x||void 0;break;case"data":u=d===0?x:`${u}
44
+ ${x}`,d++;break;case"id":l=x.includes("\0")?void 0:x;break;case"retry":/^\d+$/.test(x)?n(parseInt(x,10)):r(new lo(`Invalid \`retry\` value: "${x}"`,{type:"invalid-retry",value:x,line:R}));break;default:r(new lo(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:x,line:R}));break}}function $(){d>0&&t({id:l,event:f,data:u}),l=void 0,u="",d=0,f=void 0}function P(v={}){if(v.consume&&i.length>0){let x=i.join("");w(x,0,x.length)}c=!0,l=void 0,u="",d=0,f=void 0,i.length=0,a=0,m=!1}return{feed:h,reset:P}}function jg(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 Mg(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 Os=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Ug({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 xz={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Zt=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Wr=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=bg(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??xz}async _authThenStart(){if(!this._authProvider)throw new zt("No auth provider");let t;try{t=await uo(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 zt;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=Is(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 Zt(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 u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Os({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:h}=await u.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=Rr.parse(JSON.parse(m.data));Jt(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(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(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 zt("No auth provider");if(await uo(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:mn(t)?t.id:void 0}).catch(f=>this.onerror?.(f));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 f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Zt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:m,scope:h}=gu(a);if(this._resourceMetadataUrl=m,this._scope=h,await uo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:m,scope:h,error:g}=gu(a);if(g==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Zt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await uo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zt;return this.send(t)}}throw new Zt(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),hf(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(t)?t:[t]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(d?.includes("application/json")){let f=await a.json(),m=Array.isArray(f)?f.map(h=>Rr.parse(h)):[Rr.parse(f)];for(let h of m)this.onmessage?.(h)}else throw await a.body?.cancel(),new Zt(-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 Zt(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 Oe from"node:fs";import{randomBytes as kz}from"node:crypto";import{homedir as Zg}from"node:os";import{resolve as Cs,join as vu,dirname as bu,basename as zz}from"node:path";var po=["owner","shared","open"],Yr={brokerUrl:"wss://broker1.ours.network",port:3050,stateDir:Cs(Zg(),".ours"),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function fo(){return process.env.OURS_CONFIG??vu(Zg(),".ours","config.json")}function Pz(){let e;try{e=Oe.readFileSync(fo(),"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=Cs(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"&&po.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 Tz(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&po.includes(e)?e:void 0}function Rz(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function Dg(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function wu(){let e=Pz();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??Yr.brokerUrl,port:Dg("OURS_PORT")??e.port??Yr.port,stateDir:Cs(process.env.OURS_STATE_DIR??e.stateDir??Yr.stateDir),gcIntervalMs:Dg("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??Yr.gcIntervalMs,autoStart:Rz("OURS_AUTOSTART")??e.autoStart??Yr.autoStart,apiVisibility:Tz()??e.apiVisibility??Yr.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||e.apiToken,stt:Ez(e.stt)}}function Ez(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 Iz="daemon-token";function Oz(e){return vu(e.stateDir,Iz)}function $u(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=Oz(e);try{let i=Oe.readFileSync(o,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!t.generate)return null;let s=kz(32).toString("hex");try{Oe.mkdirSync(bu(o),{recursive:!0}),Oe.writeFileSync(o,s+`
45
+ `,{mode:384}),Oe.chmodSync(o,384)}catch{}return{token:s,source:"generated"}}function qg(e){let t=fo();Oe.mkdirSync(bu(t),{recursive:!0}),Oe.writeFileSync(t,JSON.stringify(e,null,2)+`
46
+ `,{mode:384});try{Oe.chmodSync(t,384)}catch{}return t}var As=".ours-identity";function Ns(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 Su(e){let t=Cs(e);return zz(t)===As?t:vu(t,As)}function Lg(e,t,r=!1){let n=Ns(t),o=Su(e);if(!r&&Oe.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Oe.mkdirSync(bu(o),{recursive:!0}),Oe.writeFileSync(o,JSON.stringify(n,null,2)+`
47
+ `),o}import Vg from"node:process";var js=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),Az(r)}clear(){this._buffer=void 0}};function Az(e){return Rr.parse(JSON.parse(e))}function Fg(e){return JSON.stringify(e)+`
49
+ `}var Ms=class{constructor(t=Vg.stdin,r=Vg.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new js,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=Fg(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function Hg(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 Cz,writeFileSync as Nz,readFileSync as jz,readdirSync as Mz,statSync as Bg,unlinkSync as Uz,chmodSync as Kg}from"node:fs";import{join as Us}from"node:path";import{homedir as Dz}from"node:os";var Zz="0.15.1",qz=new Set(["choose_identity","create_identity","create_root_identity"]),Jg=e=>new Promise(t=>setTimeout(t,e)),Lz=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,Fz=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,Gg=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},Wg=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,Yg=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase());async function Xg(e){let t=new URL(e.url),r=(...I)=>process.stderr.write(`[ours-proxy] ${I.join(" ")}
50
+ `),n=I=>Number.isInteger(I)&&I>1,o=Number(process.env.OURS_CLIENT_PID),s=n(o)?o:n(process.ppid)?process.ppid:process.pid,i=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${s}`,a=null,c=null,l,u=null,d=new Map,f=null,m=Yg?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,h=e.stateDir??process.env.OURS_STATE_DIR??Us(Dz(),".ours"),g=Us(h,"session-restore"),y=m&&/^[A-Za-z0-9._-]{1,200}$/.test(m)?m:null,w=y?Us(g,`${y}.json`):null,S=!1,$=null;function P(I){if(w)try{Cz(g,{recursive:!0,mode:448}),Nz(w,JSON.stringify({claudeSessionId:m,identity:I,boundAt:new Date().toISOString()}),{mode:384}),Kg(g,448),Kg(w,384)}catch(V){r("restore persist failed (non-fatal):",String(V))}}function v(){if(!w)return null;try{if(Date.now()-Bg(w).mtimeMs>Wg)return null;let I=JSON.parse(jz(w,"utf8"));return(typeof I.identity=="string"?I.identity.trim():"")||null}catch{return null}}function x(){try{let I=Date.now();for(let V of Mz(g)){if(!V.endsWith(".json"))continue;let Q=Us(g,V);try{I-Bg(Q).mtimeMs>Wg&&(Uz(Q),r("session-restore: pruned expired record",V))}catch{}}}catch{}}let R=null,L=!1,Y=!1,me=!1,Le=[],_r="__ours_proxy_init__",Tt=0,je=new Set,yr=new Set,Vt=new Ms;Vt.onmessage=I=>{let V=[],Q=!1;for(let Xe of Qg(I)){let _e=Xe;if(_e.method==="notifications/initialized"&&(Q=!0),Lz(_e)){if(_e.method==="initialize"&&(a=_e,c)){r("absorbed re-initialize locally \u2014 upstream session kept stable"),Vt.send({jsonrpc:"2.0",id:_e.id,result:c}).catch(be=>r("local initialize reply failed:",String(be)));continue}if(_e.method==="tools/call"){let be=_e.params;be&&qz.has(be.name??"")&&typeof be.arguments?.name=="string"&&d.set(_e.id,be.arguments.name)}}V.push(_e)}if(V.length){let Xe=Array.isArray(I)?V:V[0];Cu(Xe)}Q&&O_()},Vt.onclose=()=>void Hs(0),Vt.onerror=I=>r("downstream error:",String(I));function O_(){if(S||!u)return;S=!0;let I=`__ours_proxy_restore_${++Tt}__`;je.add(I),$=I,r("session-restore: self-recovering bound identity",`"${u}"`),Cu({jsonrpc:"2.0",id:I,method:"tools/call",params:{name:"choose_identity",arguments:{name:u}}})}function Cu(I){if(L&&R){let V=R;R.send(I).catch(Q=>{r("upstream send failed:",String(Q)),Le.push(I),Nu(V,"send failed")})}else Le.push(I)}function Nu(I,V){if(Y||me||R!==null&&I!==R)return;r(`upstream dropped (${V}) \u2014 reconnecting`),L=!1;let Q=R;R=null;try{Q?.close?.()}catch{}C_()}function A_(I){I.onmessage=V=>{let Q=[];for(let Xe of Qg(V)){let _e=Xe;if(Fz(_e)){let be=_e.id,Bs=_e.result?.protocolVersion;if(Bs&&(yr.has(be)||ju(be))){l=Bs;try{R?.setProtocolVersion?.(Bs)}catch{}if(c==null&&ju(be)&&!je.has(be)){let _t=_e.result??null;_t&&f&&(_t.instructions=`${_t.instructions?_t.instructions+`
51
51
 
52
- `:""}${f}`),c=gt}_r.delete(we)}if(Ne.has(we)){Ne.delete(we),we===$&&($=null,Kg(_e)&&(u=null,r("session-restore: re-bind refused (identity live elsewhere) \u2014 staying unbound")));continue}if(d.has(we)){let gt=d.get(we);d.delete(we),Kg(_e)||(u=gt,r("bound identity tracked:",gt),P(gt))}}Q.push(_e)}if(Q.length){let Xe=Array.isArray(V)?Q:Q[0];Vt.send(Xe).catch(_e=>r("downstream send failed:",String(_e)))}},I.onerror=V=>r("upstream error:",String(V)),I.onclose=()=>Ou(I,"closed")}let Au=I=>a!=null&&a.id===I;async function Cu(){e.ensureDaemon&&await e.ensureDaemon().catch(V=>r("ensureDaemon:",String(V)));let I=new Gr(t,{requestInit:{headers:{"x-ours-lease-token":i,"x-ours-client-pid":String(s),...e.apiToken?{"x-ours-api-token":e.apiToken}:{}}}});if(x_(I),await I.start(),l)try{I.setProtocolVersion?.(l)}catch{}R=I}async function Nu(I,V){V&&I.id!==void 0&&Ne.add(I.id),await R.send(I)}async function z_(){if(me||Y)return;me=!0;let I=500;for(;;){if(Y){me=!1;return}try{if(await Cu(),a){let Q=`${gr}${Tt}`;_r.add(Q),await Nu({...a,id:Q},!0),await R.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(u){let Q=`__ours_proxy_rebind_${++Tt}__`;await Nu({jsonrpc:"2.0",id:Q,method:"tools/call",params:{name:"choose_identity",arguments:{name:u}}},!0)}L=!0;let V=Le.splice(0);for(let Q of V)await R.send(Q).catch(Xe=>r("flush failed:",String(Xe)));r("upstream reconnected",u?`(re-bound "${u}")`:""),me=!1;return}catch(V){r("reconnect attempt failed:",String(V)),await Bg(I),I=Math.min(Math.floor(I*1.5),1e4)}}}async function Fs(I){if(!Y){Y=!0;try{await R?.close()}catch{}try{await Vt.close()}catch{}process.exit(I)}}process.on("SIGINT",()=>void Fs(0)),process.on("SIGTERM",()=>void Fs(0));async function k_(){let I=new URL(t.href);I.pathname="/state-dir";let V;try{V=await(await fetch(I,{signal:AbortSignal.timeout(3e3)})).json()}catch(Q){r("compat handshake: could not read daemon /state-dir, proceeding:",String(Q));return}f=Fg({selfVersion:Ik,daemonVersion:typeof V?.version=="string"?V.version:null}),f&&r(f)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(Q=>r("ensureDaemon:",String(Q))),await k_();let I=500;for(;;)try{await Cu();break}catch(Q){r("initial upstream connect failed, retrying:",String(Q)),await Bg(I),I=Math.min(Math.floor(I*1.5),1e4)}L=!0;let V=Le.splice(0);for(let Q of V)await R.send(Q).catch(Xe=>r("flush failed:",String(Xe)));r(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),m){x();let I=v();I&&(u=I,r("session-restore: found prior binding for this session \u2014 will self-recover",`"${I}"`))}else Gg&&r("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");await Vt.start(),r("proxy started (stdio transport up)")}function Wg(e){return Array.isArray(e)?e:[e]}var bu=["openai-compatible","elevenlabs","deepgram","custom"],uC=5*1024*1024;function fo(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: ${bu.join(" | ")}) \u2014 ${t}`};let r=e.provider.trim().toLowerCase();if(!bu.includes(r))return{ready:!1,reason:`unknown STT provider "${e.provider}" (expected: ${bu.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 Nk(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 Qg(e){let t=Nk(e);return t==="Z"||t==="X"||t==="x"}import{chmodSync as Xg,closeSync as jk,existsSync as r_,mkdirSync as Mk,openSync as e_,readFileSync as n_,readSync as o_,renameSync as Uk,statSync as Dk,unlinkSync as s_,writeFileSync as Zk,writeSync as qk}from"node:fs";import{spawnSync as Ms}from"node:child_process";import{dirname as Lk}from"node:path";var He=[{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"}],Pe=class extends Error{constructor(r){super(r);this.reason=r}};function Fk(e){if(!r_(e))return{};let t=JSON.parse(n_(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("config root must be a JSON object");return t}function Vk(e){return r_(e)?{exists:!0,text:n_(e,"utf8"),mode:Dk(e).mode&511}:{exists:!1}}function Hk(e,t){i_(e,`${JSON.stringify(t,null,2)}
53
- `,384)}function i_(e,t,r){Mk(Lk(e),{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${Date.now()}`;try{Zk(n,t,{encoding:"utf8",mode:r,flag:"wx"}),Xg(n,r),Uk(n,e),Xg(e,r)}catch(o){try{s_(n)}catch{}throw o}}function Bk(e,t){if(!t.exists){try{s_(e)}catch{}return}i_(e,t.text,t.mode)}async function Kk(e,t,r,n){let o=Vk(e);try{Hk(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{Bk(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 t_(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 Jk(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 Gk(){try{return e_("/dev/tty","r+")}catch{if(process.stdin.isTTY&&process.stdout.isTTY)try{return e_("/dev/stdin","r+")}catch{}return null}}function Be(e,t){qk(e,t)}function $u(e){let t=Buffer.alloc(1);try{return o_(e,t,0,1,null)===1?t[0]:null}catch(r){throw r.code==="EINTR"?new Pe("cancel"):r}}function a_(e){let t="";for(let r=0;r<12;r++){let n=$u(e);if(n===null)break;let o=String.fromCharCode(n);if(t+=o,/[A-Za-z~]$/.test(t))break}return t}function c_(e,t){let r=Ms("stty",["-g"],{stdio:[e,"pipe","ignore"],encoding:"utf8"}),n=(r.stdout||"").trim();if(r.status!==0||!n)throw new Pe("unavailable");if(Ms("stty",["-icanon","-echo","-isig","min","1","time","0"],{stdio:[e,"ignore","ignore"]}).status!==0)throw new Pe("unavailable");let s=!1,i=()=>{if(s)return;s=!0,Ms("stty",[n],{stdio:[e,"ignore","ignore"]}).status!==0&&Ms("stty",["sane"],{stdio:[e,"ignore","ignore"]})};process.once("exit",i);try{return t()}finally{process.removeListener("exit",i),i()}}function Wk(e,t,r,n){return c_(e,()=>{Be(e,t);let o="";for(;;){let i=$u(e);if(i===null||i===4)throw new Pe("eof");if(i===3)throw new Pe("cancel");if(i===10||i===13){Be(e,`
54
- `);break}if(i===127||i===8){o.length&&(o=o.slice(0,-1),n||Be(e,"\b \b"));continue}if(i===27){a_(e);continue}if(i<32||o.length>=16384)continue;let a=String.fromCharCode(i);o+=a,n||Be(e,a)}let s=o.trim();return s===""?r:s})}function Us(e,t,r=""){Be(e,t);let n=[],o=0;for(;;){let i=Buffer.alloc(1024),a;try{a=o_(e,i,0,i.length,null)}catch(u){throw u.code==="EINTR"?new Pe("cancel"):u}if(a===0)throw new Pe("eof");let c=i.subarray(0,a).indexOf(10),l=c>=0?i.subarray(0,c):i.subarray(0,a);if(n.push(l),o+=l.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 ht(e,t,r="",n=!1){try{return Wk(e,t,r,n)}catch(o){if(o instanceof Pe&&o.reason==="unavailable"&&!n)return Us(e,t,r);throw o}}function Yk(e,t,r){let n=ht(e,`${t} ${r?"[Y/n]":"[y/N]"} `,r?"y":"n");return/^y(?:es)?$/i.test(n)}function Qk(e,t){let r=He.findIndex(n=>n.value===t);r<0&&(r=0);try{return c_(e,()=>{Be(e,`Choose one transcription provider (\u2191/\u2193 or j/k, then Enter; q cancels):
52
+ `:""}${f}`),c=_t}yr.delete(be)}if(je.has(be)){je.delete(be),be===$&&($=null,Gg(_e)&&(u=null,r("session-restore: re-bind refused (identity live elsewhere) \u2014 staying unbound")));continue}if(d.has(be)){let _t=d.get(be);d.delete(be),Gg(_e)||(u=_t,r("bound identity tracked:",_t),P(_t))}}Q.push(_e)}if(Q.length){let Xe=Array.isArray(V)?Q:Q[0];Vt.send(Xe).catch(_e=>r("downstream send failed:",String(_e)))}},I.onerror=V=>r("upstream error:",String(V)),I.onclose=()=>Nu(I,"closed")}let ju=I=>a!=null&&a.id===I;async function Mu(){e.ensureDaemon&&await e.ensureDaemon().catch(V=>r("ensureDaemon:",String(V)));let I=new Wr(t,{requestInit:{headers:{"x-ours-lease-token":i,"x-ours-client-pid":String(s),...e.apiToken?{"x-ours-api-token":e.apiToken}:{}}}});if(A_(I),await I.start(),l)try{I.setProtocolVersion?.(l)}catch{}R=I}async function Uu(I,V){V&&I.id!==void 0&&je.add(I.id),await R.send(I)}async function C_(){if(me||Y)return;me=!0;let I=500;for(;;){if(Y){me=!1;return}try{if(await Mu(),a){let Q=`${_r}${Tt}`;yr.add(Q),await Uu({...a,id:Q},!0),await R.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(u){let Q=`__ours_proxy_rebind_${++Tt}__`;await Uu({jsonrpc:"2.0",id:Q,method:"tools/call",params:{name:"choose_identity",arguments:{name:u}}},!0)}L=!0;let V=Le.splice(0);for(let Q of V)await R.send(Q).catch(Xe=>r("flush failed:",String(Xe)));r("upstream reconnected",u?`(re-bound "${u}")`:""),me=!1;return}catch(V){r("reconnect attempt failed:",String(V)),await Jg(I),I=Math.min(Math.floor(I*1.5),1e4)}}}async function Hs(I){if(!Y){Y=!0;try{await R?.close()}catch{}try{await Vt.close()}catch{}process.exit(I)}}process.on("SIGINT",()=>void Hs(0)),process.on("SIGTERM",()=>void Hs(0));async function N_(){let I=new URL(t.href);I.pathname="/state-dir";let V;try{V=await(await fetch(I,{signal:AbortSignal.timeout(3e3)})).json()}catch(Q){r("compat handshake: could not read daemon /state-dir, proceeding:",String(Q));return}f=Hg({selfVersion:Zz,daemonVersion:typeof V?.version=="string"?V.version:null}),f&&r(f)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(Q=>r("ensureDaemon:",String(Q))),await N_();let I=500;for(;;)try{await Mu();break}catch(Q){r("initial upstream connect failed, retrying:",String(Q)),await Jg(I),I=Math.min(Math.floor(I*1.5),1e4)}L=!0;let V=Le.splice(0);for(let Q of V)await R.send(Q).catch(Xe=>r("flush failed:",String(Xe)));r(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),m){x();let I=v();I&&(u=I,r("session-restore: found prior binding for this session \u2014 will self-recover",`"${I}"`))}else Yg&&r("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");await Vt.start(),r("proxy started (stdio transport up)")}function Qg(e){return Array.isArray(e)?e:[e]}var xu=["openai-compatible","elevenlabs","deepgram","custom"],zC=5*1024*1024;function mo(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: ${xu.join(" | ")}) \u2014 ${t}`};let r=e.provider.trim().toLowerCase();if(!xu.includes(r))return{ready:!1,reason:`unknown STT provider "${e.provider}" (expected: ${xu.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 Vz(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_(e){let t=Vz(e);return t==="Z"||t==="X"||t==="x"}import{chmodSync as t_,closeSync as Hz,existsSync as o_,mkdirSync as Bz,openSync as r_,readFileSync as s_,readSync as i_,renameSync as Kz,statSync as Jz,unlinkSync as a_,writeFileSync as Gz,writeSync as Wz}from"node:fs";import{spawnSync as Ds}from"node:child_process";import{dirname as Yz}from"node:path";var He=[{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"}],Pe=class extends Error{constructor(r){super(r);this.reason=r}};function Qz(e){if(!o_(e))return{};let t=JSON.parse(s_(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("config root must be a JSON object");return t}function Xz(e){return o_(e)?{exists:!0,text:s_(e,"utf8"),mode:Jz(e).mode&511}:{exists:!1}}function eP(e,t){c_(e,`${JSON.stringify(t,null,2)}
53
+ `,384)}function c_(e,t,r){Bz(Yz(e),{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${Date.now()}`;try{Gz(n,t,{encoding:"utf8",mode:r,flag:"wx"}),t_(n,r),Kz(n,e),t_(e,r)}catch(o){try{a_(n)}catch{}throw o}}function tP(e,t){if(!t.exists){try{a_(e)}catch{}return}c_(e,t.text,t.mode)}async function rP(e,t,r,n){let o=Xz(e);try{eP(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{tP(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 n_(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 nP(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 oP(){try{return r_("/dev/tty","r+")}catch{if(process.stdin.isTTY&&process.stdout.isTTY)try{return r_("/dev/stdin","r+")}catch{}return null}}function Be(e,t){Wz(e,t)}function ku(e){let t=Buffer.alloc(1);try{return i_(e,t,0,1,null)===1?t[0]:null}catch(r){throw r.code==="EINTR"?new Pe("cancel"):r}}function u_(e){let t="";for(let r=0;r<12;r++){let n=ku(e);if(n===null)break;let o=String.fromCharCode(n);if(t+=o,/[A-Za-z~]$/.test(t))break}return t}function l_(e,t){let r=Ds("stty",["-g"],{stdio:[e,"pipe","ignore"],encoding:"utf8"}),n=(r.stdout||"").trim();if(r.status!==0||!n)throw new Pe("unavailable");if(Ds("stty",["-icanon","-echo","-isig","min","1","time","0"],{stdio:[e,"ignore","ignore"]}).status!==0)throw new Pe("unavailable");let s=!1,i=()=>{if(s)return;s=!0,Ds("stty",[n],{stdio:[e,"ignore","ignore"]}).status!==0&&Ds("stty",["sane"],{stdio:[e,"ignore","ignore"]})};process.once("exit",i);try{return t()}finally{process.removeListener("exit",i),i()}}function sP(e,t,r,n){return l_(e,()=>{Be(e,t);let o="";for(;;){let i=ku(e);if(i===null||i===4)throw new Pe("eof");if(i===3)throw new Pe("cancel");if(i===10||i===13){Be(e,`
54
+ `);break}if(i===127||i===8){o.length&&(o=o.slice(0,-1),n||Be(e,"\b \b"));continue}if(i===27){u_(e);continue}if(i<32||o.length>=16384)continue;let a=String.fromCharCode(i);o+=a,n||Be(e,a)}let s=o.trim();return s===""?r:s})}function Zs(e,t,r=""){Be(e,t);let n=[],o=0;for(;;){let i=Buffer.alloc(1024),a;try{a=i_(e,i,0,i.length,null)}catch(u){throw u.code==="EINTR"?new Pe("cancel"):u}if(a===0)throw new Pe("eof");let c=i.subarray(0,a).indexOf(10),l=c>=0?i.subarray(0,c):i.subarray(0,a);if(n.push(l),o+=l.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 ht(e,t,r="",n=!1){try{return sP(e,t,r,n)}catch(o){if(o instanceof Pe&&o.reason==="unavailable"&&!n)return Zs(e,t,r);throw o}}function iP(e,t,r){let n=ht(e,`${t} ${r?"[Y/n]":"[y/N]"} `,r?"y":"n");return/^y(?:es)?$/i.test(n)}function aP(e,t){let r=He.findIndex(n=>n.value===t);r<0&&(r=0);try{return l_(e,()=>{Be(e,`Choose one transcription provider (\u2191/\u2193 or j/k, then Enter; q cancels):
55
55
  `);let n=!1,o=()=>{n&&Be(e,`\x1B[${He.length}A`),n=!0,He.forEach((s,i)=>{Be(e,`\r\x1B[K ${i===r?">":" "} ${i===r?"(*)":"( )"} ${s.label} \u2014 ${s.detail}
56
- `)})};for(o();;){let s=$u(e);if(s===null||s===4)throw new Pe("eof");if(s===3||s===113||s===81)throw new Pe("cancel");if(s===10||s===13)return Be(e,`
57
- `),He[r].value;if(s>=49&&s<=52)r=s-49;else if(s===107||s===75)r=(r-1+He.length)%He.length;else if(s===106||s===74)r=(r+1)%He.length;else if(s===27){let i=a_(e);i==="[A"||i==="OA"?r=(r-1+He.length)%He.length:(i==="[B"||i==="OB")&&(r=(r+1)%He.length)}else continue;o()}})}catch(n){if(!(n instanceof Pe)||n.reason!=="unavailable")throw n;Be(e,`Choose one transcription provider:
56
+ `)})};for(o();;){let s=ku(e);if(s===null||s===4)throw new Pe("eof");if(s===3||s===113||s===81)throw new Pe("cancel");if(s===10||s===13)return Be(e,`
57
+ `),He[r].value;if(s>=49&&s<=52)r=s-49;else if(s===107||s===75)r=(r-1+He.length)%He.length;else if(s===106||s===74)r=(r+1)%He.length;else if(s===27){let i=u_(e);i==="[A"||i==="OA"?r=(r-1+He.length)%He.length:(i==="[B"||i==="OB")&&(r=(r+1)%He.length)}else continue;o()}})}catch(n){if(!(n instanceof Pe)||n.reason!=="unavailable")throw n;Be(e,`Choose one transcription provider:
58
58
  `),He.forEach((s,i)=>{Be(e,` ${i+1}. ${s.label} \u2014 ${s.detail}
59
- `)});let o=Us(e,`Select 1-${He.length}: `);if(!/^[1-4]$/.test(o))throw new Pe("cancel");return He[Number(o)-1].value}}function Xk(e){let t=e.stt;return t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{}}async function u_(e){let t=e.env??process.env,r=e.stdout??(i=>process.stdout.write(i)),n=(i="")=>r(`${i}
60
- `),o=e.daemonState??"stopped",s=null;try{let i;try{i=Fk(e.configFile)}catch{return n(`voice setup: ${e.configFile} is not valid JSON; no changes made.`),1}let a=Xk(i),c=fo(t_(a,t)),l=t.OURS_STT_API_KEY?.trim()?"environment":a.apiKey?.trim()?"config":"missing";if(s=t.OURS_ASSUME_YES?null:Gk(),n(`ours-mcp voice-setup \u2014 ${e.configFile}`),c.ready){if(n(`voice transcription is already ready (${c.provider}; API key from ${l}).`),s===null)return 0;if(!Yk(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 u=String(t.OURS_STT_PROVIDER||a.provider||"").trim().toLowerCase(),d=Qk(s,u),f=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=ht(s,`Provider /v1 base URL${m?` [${m}]`:""}: `,m),f=ht(s,`Model name (sent verbatim)${f?` [${f}]`:""}: `,f)):d==="elevenlabs"?(f=ht(s,`ElevenLabs model id${f?` [${f}]`:""}: `,f),m=ht(s,`Custom base URL (Enter for provider default)${m?` [${m}]`:""}: `,m)):d==="deepgram"?(f=ht(s,`Model (optional; Enter for provider default)${f?` [${f}]`:""}: `,f),m=ht(s,`Custom base URL (optional)${m?` [${m}]`:""}: `,m)):(h=ht(s,`Full transcription endpoint URL${h?` [${h}]`:""}: `,h),f=ht(s,`Model (optional unless URL contains {model})${f?` [${f}]`:""}: `,f));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): ",x;try{x=ht(s,v,y,!0)}catch(L){if(!(L instanceof Pe)||L.reason!=="unavailable")throw L;if(Be(s,`
59
+ `)});let o=Zs(e,`Select 1-${He.length}: `);if(!/^[1-4]$/.test(o))throw new Pe("cancel");return He[Number(o)-1].value}}function cP(e){let t=e.stt;return t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{}}async function d_(e){let t=e.env??process.env,r=e.stdout??(i=>process.stdout.write(i)),n=(i="")=>r(`${i}
60
+ `),o=e.daemonState??"stopped",s=null;try{let i;try{i=Qz(e.configFile)}catch{return n(`voice setup: ${e.configFile} is not valid JSON; no changes made.`),1}let a=cP(i),c=mo(n_(a,t)),l=t.OURS_STT_API_KEY?.trim()?"environment":a.apiKey?.trim()?"config":"missing";if(s=t.OURS_ASSUME_YES?null:oP(),n(`ours-mcp voice-setup \u2014 ${e.configFile}`),c.ready){if(n(`voice transcription is already ready (${c.provider}; API key from ${l}).`),s===null)return 0;if(!iP(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 u=String(t.OURS_STT_PROVIDER||a.provider||"").trim().toLowerCase(),d=aP(s,u),f=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=ht(s,`Provider /v1 base URL${m?` [${m}]`:""}: `,m),f=ht(s,`Model name (sent verbatim)${f?` [${f}]`:""}: `,f)):d==="elevenlabs"?(f=ht(s,`ElevenLabs model id${f?` [${f}]`:""}: `,f),m=ht(s,`Custom base URL (Enter for provider default)${m?` [${m}]`:""}: `,m)):d==="deepgram"?(f=ht(s,`Model (optional; Enter for provider default)${f?` [${f}]`:""}: `,f),m=ht(s,`Custom base URL (optional)${m?` [${m}]`:""}: `,m)):(h=ht(s,`Full transcription endpoint URL${h?` [${h}]`:""}: `,h),f=ht(s,`Model (optional unless URL contains {model})${f?` [${f}]`:""}: `,f));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): ",x;try{x=ht(s,v,y,!0)}catch(L){if(!(L instanceof Pe)||L.reason!=="unavailable")throw L;if(Be(s,`
61
61
  Secure hidden input is unavailable on this terminal.
62
62
  `),Be(s,`Visible fallback will echo the token on screen and may leave it in scrollback.
63
- `),Us(s,"Type SHOW to enter the token visibly, or press Enter to cancel: ")!=="SHOW")throw new Pe("cancel");x=Us(s,"Provider API key (VISIBLE): ",y)}let R=Jk(x);if(!R.ok)return n(`Voice setup was not saved: ${R.reason}.`),1;y=R.value}let b={...a,provider:d,...y?{apiKey:y}:{},...f?{model:f}:{},...m?{baseUrl:m}:{},...d==="custom"&&h?{custom:{...a.custom??{},url:h}}:{}},S=fo(t_(b,t));if(!S.ready)return n(`Voice setup was not saved: ${S.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 $={...i,stt:b};o==="managed"&&n("Restarting ours-mcp to apply and verify voice transcription\u2026");let P=await Kk(e.configFile,$,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 Pe?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{jk(s)}catch{}}}var l_=`ours-mcp voice-setup \u2014 configure voice transcription securely
63
+ `),Zs(s,"Type SHOW to enter the token visibly, or press Enter to cancel: ")!=="SHOW")throw new Pe("cancel");x=Zs(s,"Provider API key (VISIBLE): ",y)}let R=nP(x);if(!R.ok)return n(`Voice setup was not saved: ${R.reason}.`),1;y=R.value}let w={...a,provider:d,...y?{apiKey:y}:{},...f?{model:f}:{},...m?{baseUrl:m}:{},...d==="custom"&&h?{custom:{...a.custom??{},url:h}}:{}},S=mo(n_(w,t));if(!S.ready)return n(`Voice setup was not saved: ${S.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 $={...i,stt:w};o==="managed"&&n("Restarting ours-mcp to apply and verify voice transcription\u2026");let P=await rP(e.configFile,$,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 Pe?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{Hz(s)}catch{}}}var p_=`ours-mcp voice-setup \u2014 configure voice transcription securely
64
64
 
65
65
  Usage: ours-mcp voice-setup [--dry-run]
66
66
 
@@ -75,12 +75,14 @@ exact prior config.
75
75
 
76
76
  Headless automation remains environment-driven through OURS_STT_PROVIDER,
77
77
  OURS_STT_API_KEY, OURS_STT_MODEL, OURS_STT_BASE_URL, and OURS_STT_LANGUAGE.
78
- Exit 2 means restart/readiness failed after a write and rollback was attempted.`;if(!process.env.XDG_RUNTIME_DIR&&typeof process.getuid=="function"){let e=`/run/user/${process.getuid()}`;q.existsSync(e)&&(process.env.XDG_RUNTIME_DIR=e)}var Pt=vu(),qe=Pt.stateDir,te=Pt.port,Pu=Ug(Pt,{generate:!1})?.token??null,qs=()=>Pu?{"x-ours-api-token":Pu}:{},Xr=Pt.brokerUrl,hr=kt(qe,"daemon.pid"),fr=kt(qe,"daemon.log"),Lt=tP(import.meta.url),w=(...e)=>process.stdout.write(`${e.join(" ")}
78
+ Exit 2 means restart/readiness failed after a write and rollback was attempted.`;import*as fr from"node:fs";import{join as uP}from"node:path";var lP="startup-progress.json",dP=1,f_={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 pP(e){return uP(e,lP)}function fP(e){return typeof e=="string"&&Object.hasOwn(f_,e)}function m_(e){try{let t=JSON.parse(fr.readFileSync(pP(e),"utf8"));return t.version!==dP||!Number.isInteger(t.pid)||(t.pid??0)<=0||typeof t.bootId!="string"||!t.bootId||!fP(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 zu(e){let t=f_[e.phase];return e.phase==="identities"&&e.completed!==void 0&&e.total!==void 0?`${t} ${e.completed}/${e.total}`:t}function h_(e,t){let r=`startup: ${zu(e)}`;return t?`\r${r}\x1B[K`:`${r}
79
+ `}async function g_(e){let t=e.now??Date.now,r=e.sleep??(c=>new Promise(l=>setTimeout(l,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 f=`${c.phase}:${c.completed??""}:${c.total??""}`;if(f!==i&&(i=f,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 l=t()-n;if(l>=e.absoluteMs)return{ok:!1,reason:"absolute-timeout",elapsedMs:l,lastProgress:a};if(t()-o>=e.inactivityMs)return{ok:!1,reason:"inactivity-timeout",elapsedMs:l,lastProgress:a};let u=e.absoluteMs-l,d=e.inactivityMs-(t()-o);await r(Math.max(1,Math.min(e.pollMs,u,d)))}}if(!process.env.XDG_RUNTIME_DIR&&typeof process.getuid=="function"){let e=`/run/user/${process.getuid()}`;q.existsSync(e)&&(process.env.XDG_RUNTIME_DIR=e)}var gt=wu(),Ne=gt.stateDir,ne=gt.port,go=()=>{let e=$u(gt,{generate:!1})?.token??null;return e?{"x-ours-api-token":e}:{}},en=gt.brokerUrl,gr=Pt(Ne,"daemon.pid"),mr=Pt(Ne,"daemon.log"),Lt=hP(import.meta.url),b=(...e)=>process.stdout.write(`${e.join(" ")}
79
80
  `),W=(...e)=>process.stderr.write(`${e.join(" ")}
80
- `),mr="0.15.0";async function Tu(){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:${te}${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 d_(e){if(w(` cli: v${mr}`),e?.version){let t=e.version!==mr;w(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${mr}`:""))}else w(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var Ls=e=>new Promise(t=>setTimeout(t,e));function nP(){try{let e=parseInt(q.readFileSync(hr,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Ru(e){try{if(process.kill(e,0),process.platform==="linux")try{if(Qg(q.readFileSync(`/proc/${e}/stat`,"utf8")))return!1}catch{try{process.kill(e,0)}catch{return!1}}return!0}catch{return!1}}function en(){let e=nP();if(e&&Ru(e))return e;if(e)try{q.rmSync(hr,{force:!0})}catch{}return null}function Ft(e,t=1e3){return new Promise(r=>{let n=eP({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 y_(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await Ft(e))return!0;await Ls(400)}return!1}async function p_(){let e=en();if(e){w(`ours-mcp is already running (pid ${e}, port ${te}).`);return}q.mkdirSync(qe,{recursive:!0});let t=q.openSync(fr,"a"),r=h_(process.execPath,[Lt,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(te),OURS_BROKER_URL:Xr,OURS_STATE_DIR:qe}});r.unref(),r.pid||(W("failed to spawn the daemon."),process.exit(1)),q.writeFileSync(hr,String(r.pid)),w(`starting ours-mcp (pid ${r.pid})\u2026`),await y_(te)?(w(`ours-mcp is up on http://localhost:${te}/mcp`),w(` broker: ${Xr}`),w(` state: ${qe}`),w(` logs: ${fr}`)):(W(`daemon started (pid ${r.pid}) but port ${te} did not open within 30s \u2014 check ${fr}.`),process.exit(1))}async function oP(){if(!await Ft(te)){if(!en()){q.mkdirSync(qe,{recursive:!0});let e=q.openSync(fr,"a"),t=h_(process.execPath,[Lt,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(te),OURS_BROKER_URL:Xr,OURS_STATE_DIR:qe}});if(t.unref(),t.pid)try{q.writeFileSync(hr,String(t.pid))}catch{}}await y_(te)}}async function Zs(){let e=en();if(!e){w("ours-mcp is not running.");return}w(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){W(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Ru(e);t++)await Ls(200);if(Ru(e)){W(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{q.rmSync(hr,{force:!0})}catch{}w("stopped.")}async function sP(){let e=en();if(!e){if(await Ft(te)){let n=await Tu();w("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),w(` url: http://localhost:${te}/mcp (reachable)`),d_(n);return}w("ours-mcp: stopped"),w(` cli: v${mr}`),process.exitCode=1;return}let t=await Ft(te),r=t?await Tu():null;w("ours-mcp: running"),w(` pid: ${e}`),w(` url: http://localhost:${te}/mcp ${t?"(reachable)":"(port not answering!)"}`),w(` broker: ${Xr}`),w(` state: ${qe}`),w(` logs: ${fr}`),d_(r)}async function iP(){if(w(`ours-mcp v${mr}`),await Ft(te)){let e=await Tu();e?.version?w(`running daemon: v${e.version}`+(e.version!==mr?" (differs \u2014 restart to update)":"")):w("running daemon: version unknown (predates /version)")}else w("daemon: not running")}async function aP(){let e=vu(),t=po();w(`ours-mcp setup \u2014 ${t}`),w("Enter a value, or press Enter to keep the current [bracketed] one."),w("");let r=Ds({input:process.stdin,output:process.stdout}),n;try{let u=async(Y,me)=>{let Le=(await r.question(` ${Y} [${me}]: `)).trim();return Le===""?me:Le},d=await u("broker URL",e.brokerUrl),f=await u("HTTP port",String(e.port)),m=await u("state dir",e.stateDir),h=await u("GC interval (ms)",String(e.gcIntervalMs)),g=await u("proxy auto-starts daemon (true/false)",String(e.autoStart)),y=await u("HTTP visibility (owner=same-user only / shared=cross-user w/ token / open=all local users)",e.apiVisibility);w(""),w(" Voice-message transcription (STT). Leave provider empty to keep it off \u2014"),w(" agents then deterministically tell users voice messages cannot be read."),w(" No provider or model is assumed; model strings pass to your provider verbatim.");let b=(await r.question(` STT provider (openai-compatible / elevenlabs / deepgram / custom, empty=off) [${e.stt?.provider??""}]: `)).trim()||(e.stt?.provider??""),S=e.stt?.model??"",$=e.stt?.baseUrl??"";b&&(S=await u("STT model (verbatim, e.g. whisper-large-v3-turbo / scribe_v1 / nova-2)",S),$=await u("STT base URL (required for openai-compatible; empty = provider default)",$),w(" (API key is not echoed here. Run `ours-mcp voice-setup` for guided hidden input,"),w(" or set OURS_STT_API_KEY for environment-only secret injection.)"));let P=parseInt(f,10);(!Number.isFinite(P)||P<=0)&&(W(`invalid port: ${f}`),process.exit(1));let v=parseInt(h,10);(!Number.isFinite(v)||v<=0)&&(W(`invalid GC interval: ${h}`),process.exit(1));let x=g.toLowerCase()==="true"||g==="1",R=y.trim().toLowerCase();lo.includes(R)||(W(`invalid visibility: ${y} (expected one of ${lo.join(", ")})`),process.exit(1));let L=b?{...e.stt??{},provider:b,...S?{model:S}:{},...$?{baseUrl:$}:{}}:e.stt;n={brokerUrl:d,port:P,stateDir:__(m),gcIntervalMs:v,autoStart:x,apiVisibility:R,...e.apiToken?{apiToken:e.apiToken}:{},...L?{stt:L}:{}}}finally{r.close()}Dg(n),w(""),w(`wrote ${t} (mode 0600):`);let o={...n,...n.apiToken?{apiToken:"[redacted]"}:{},...n.stt?{stt:{...n.stt,...n.stt.apiKey?{apiKey:"[redacted]"}:{}}}:{}};w(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(u=>process.env[u]!==void 0);s.length&&(w(""),w(`note: these env vars are set and OVERRIDE the file at runtime: ${s.join(", ")}`));let i=en();if(!i)return;let a=Ds({input:process.stdin,output:process.stdout}),c=!1;try{let u=(await a.question(`
81
- daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=u==="y"||u==="yes"}finally{a.close()}if(!c){w("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await Zs();let l=Qr(process.execPath,[Lt,"start"],{stdio:"inherit"});l.status!==0&&process.exit(l.status??1)}function cP(e){let t=fo(Pt.stt),r=Pt.stt?.provider?.trim().toLowerCase()||null,n=process.env.OURS_STT_API_KEY?.trim()?"environment":Pt.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")){w(JSON.stringify(o));return}o.ready?w(`voice transcription: ready (${o.provider}; API key from ${o.keySource})`):w(`voice transcription: not ready \u2014 ${o.reason}`)}async function uP(e){if(e.includes("--help")||e.includes("-h")){w(l_);return}let t=new Set(["--dry-run"]);if(e.filter(i=>!t.has(i)).length){W("voice-setup: unsupported command-line option or argument"),W("The provider key is never accepted as a CLI argument. Run `ours-mcp voice-setup --help`."),process.exitCode=1;return}let n=en()!==null,o=await Ft(te),s=await u_({configFile:po(),env:process.env,dryRun:e.includes("--dry-run"),daemonState:n?"managed":o?"external":"stopped",apply:async()=>{let i=Qr(process.execPath,[Lt,"restart"],{stdio:"inherit"});if(i.error||i.status!==0)return{ok:!1};let a=Qr(process.execPath,[Lt,"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 xu(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function zu(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function lP(e){let t=zu(e,"--name"),r=xu(e,"--force-bind","--no-force-bind"),n=xu(e,"--local-book","--no-local-book"),o=xu(e,"--auto-accept-local","--no-auto-accept-local"),s=e.includes("--overwrite"),i=e.includes("--print"),a=zu(e,"--path")??zu(e,"--dir")??process.cwd(),c=t!==void 0||r.set||n.set||o.set||i,l;if(c?((!t||!t.trim())&&(W("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),l={name:t.trim(),force:r.value??!1,exposeLocal:n.value??!0,localAutoAccept:o.value??!0}):l=await dP(),i){w(JSON.stringify(As(l),null,2));return}let u=wu(a);if(!s&&q.existsSync(u)){c&&(W(`define-local-identity-file: ${u} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let f=Ds({input:process.stdin,output:process.stdout}),m=!1;try{let h=(await f.question(`
82
- ${u} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();m=h==="y"||h==="yes"}finally{f.close()}if(!m){w("aborted \u2014 nothing written.");return}}let d=Zg(a,l,!0);w(""),w(`wrote ${d}:`),w(JSON.stringify(As(l),null,2))}async function dP(){w("ours-mcp define-local-identity-file \u2014 interactive"),w(`Answer the prompts; the result is written to ${kt(process.cwd(),Is)}.`),w("");let e=Ds({input:process.stdin,output:process.stdout});try{let t=async(i,a)=>{let c=a?"Y/n":"y/N",l=(await e.question(` ${i} [${c}]: `)).trim().toLowerCase();return l===""?a:l==="y"||l==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||w(" (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 pP(e){let t=(e[0]??"").trim();(!t||t.startsWith("--"))&&(W('usage: ours-mcp create-root "<your name>"'),process.exit(1)),await Ft(te)||(W(`create-root: the daemon is not running on port ${te} \u2014 start it with \`ours-mcp start\`.`),process.exit(1));let r=new Gr(new URL(`http://127.0.0.1:${te}/mcp`),{requestInit:{headers:qs()}}),n=new Ts({name:"ours-mcp-cli",version:mr});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)){w(`create-root: ${s.split("\u2014")[0].trim()} \u2014 nothing to do.`);return}W(`create-root failed: ${s}`),process.exit(1)}w(s)}finally{try{await r.terminateSession()}catch{}try{await n.close()}catch{}}}function v_(e,t){t.event==="message_received"?w(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="file_received"?w(`[${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"?w(`[${e}] pending local introduction from ${t.from??"?"} \u2014 respond_to_introduction to approve/reject`):t.event==="pending_message"&&w(`[${e}] ${t.from??"?"} queued a message awaiting introduction approval (${t.queued??"?"} queued)`)}function qt(e){W(`ours-mcp watch: ${e}`),process.exit(1)}async function fP(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${te}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let n=await r.json();return typeof n.stateDir=="string"&&n.stateDir?__(n.stateDir):qe}}catch{}return null}var mP=e=>`http://127.0.0.1:${te}/identities/${encodeURIComponent(e)}/notifications`;async function f_(e){let t=async o=>{let s=new AbortController,i=setTimeout(()=>s.abort(),35e3),a;try{a=await fetch(`${mP(e)}?since=${o}`,{headers:qs(),signal:s.signal})}finally{clearTimeout(i)}if(a.status===401&&qt(`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)v_(e,s);typeof o.cursor=="number"&&(r=o.cursor)}catch(o){n=Math.min(n+1e3,5e3),W(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(o?.message??o)}), retrying\u2026`),await Ls(n)}}async function hP(e){if(e){await f_(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${te}/identities`,{headers:qs()});if(r.status===401&&qt("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),f_(s))}}}catch{}await Ls(3e3)}}var ku=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function gP(e,t){try{q.readdirSync(e)}catch(i){qt(`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{q.readdirSync(kt(e,t))}catch(i){qt(`cannot watch identity "${t}" \u2014 ${kt(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=q.readdirSync(e,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name)}catch(c){ku(c)&&qt(`lost read access to ${e} (${c.code}) \u2014 cannot watch.`);return}for(let c of a){if(t&&c!==t)continue;let l=kt(e,c,"notifications.log"),u;try{u=q.statSync(l).size}catch(m){ku(m)&&qt(`cannot read ${l} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}let d=r.get(l);if(d===void 0&&(d=i?u:0,r.set(l,d),i))continue;if(u<=d){u<d&&r.set(l,u);continue}let f;try{let m=q.openSync(l,"r"),h=Buffer.alloc(u-d);q.readSync(m,h,0,h.length,d),q.closeSync(m),f=h.toString("utf8")}catch(m){ku(m)&&qt(`cannot read ${l} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}r.set(l,u);for(let m of f.split(`
83
- `))if(m.trim())try{v_(c,JSON.parse(m))}catch{}}};W(`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 _P(){try{let e=await fetch(`http://127.0.0.1:${te}/identities`,{headers:qs()});return e.status===401&&qt("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 yP(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await fP()!==null&&await _P()==="api"){W(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${te} (Ctrl-C to stop)`),await hP(e);return}gP(qe,e)}var mo="ours.service",w_="solutions.adaptframework.ours";function b_(){return kt(g_(),".config","systemd","user",mo)}function $_(){return kt(g_(),"Library","LaunchAgents",`${w_}.plist`)}function Yr(e,t){return Qr(e,t,{stdio:"inherit"}).status===0}function vP(){let e=b_();q.mkdirSync(Eu(e),{recursive:!0});let t=`[Unit]
81
+ `),hr="0.15.1";async function Iu(){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:${ne}${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 __(e){if(b(` cli: v${hr}`),e?.version){let t=e.version!==hr;b(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${hr}`:""))}else b(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var Vs=e=>new Promise(t=>setTimeout(t,e));function _P(){try{let e=parseInt(q.readFileSync(gr,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Ls(e){try{if(process.kill(e,0),process.platform==="linux")try{if(e_(q.readFileSync(`/proc/${e}/stat`,"utf8")))return!1}catch{try{process.kill(e,0)}catch{return!1}}return!0}catch{return!1}}function tn(){let e=_P();if(e&&Ls(e))return e;if(e)try{q.rmSync(gr,{force:!0})}catch{}return null}function Ft(e,t=1e3){return new Promise(r=>{let n=mP({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 yP(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await Ft(e))return!0;await Vs(400)}return!1}function Au(e,t){let r=Number(process.env[e]||"");return Number.isFinite(r)&&r>0?r:t}var k_=Au("OURS_TEST_STARTUP_ABSOLUTE_MS",18e4),z_=Au("OURS_TEST_STARTUP_INACTIVITY_MS",3e4),P_=Au("OURS_TEST_STARTUP_POLL_MS",400);async function vP(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Math.min(1e3,P_));try{let n=await fetch(`http://127.0.0.1:${e}/identities`,{signal:t.signal,headers:go()}),o=n.ok;try{await n.body?.cancel()}catch{}return o}catch{return!1}finally{clearTimeout(r)}}function y_(e){return e<1e3?`${Math.round(e)}ms`:e%6e4===0?`${e/6e4}m`:`${Math.round(e/1e3)}s`}function bP(e,t){let r=t?` Last phase: ${zu(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 ${y_(z_)}.${r} The process is still running, but startup is stalled.`:`daemon startup did not finish within ${y_(k_)}.${r} The bounded wait expired.`}async function v_(){let e=tn();if(e){b(`ours-mcp is already running (pid ${e}, port ${ne}).`);return}q.mkdirSync(Ne,{recursive:!0});let t=q.openSync(mr,"a"),r=$_(process.execPath,[Lt,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(ne),OURS_BROKER_URL:en,OURS_STATE_DIR:Ne}});r.unref(),r.pid||(W("failed to spawn the daemon."),process.exit(1)),q.writeFileSync(gr,String(r.pid)),b(`starting ours-mcp (pid ${r.pid})\u2026`);let n=!!process.stderr.isTTY,o=!1,s=await g_({pid:r.pid,absoluteMs:k_,inactivityMs:z_,pollMs:P_,isProcessAlive:()=>Ls(r.pid),isReady:()=>vP(ne),readProgress:()=>m_(Ne),onProgress:i=>{o=!0,process.stderr.write(h_(i,n))}});o&&n&&process.stderr.write(`
82
+ `),s.ok?(b(`ours-mcp is up on http://localhost:${ne}/mcp`),b(` broker: ${en}`),b(` state: ${Ne}`),b(` logs: ${mr}`)):(W(`${bP(s.reason,s.lastProgress)} Check ${mr}.`),process.exit(1))}async function wP(){if(!await Ft(ne)){if(!tn()){q.mkdirSync(Ne,{recursive:!0});let e=q.openSync(mr,"a"),t=$_(process.execPath,[Lt,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(ne),OURS_BROKER_URL:en,OURS_STATE_DIR:Ne}});if(t.unref(),t.pid)try{q.writeFileSync(gr,String(t.pid))}catch{}}await yP(ne)}}async function Fs(){let e=tn();if(!e){b("ours-mcp is not running.");return}b(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){W(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Ls(e);t++)await Vs(200);if(Ls(e)){W(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{q.rmSync(gr,{force:!0})}catch{}b("stopped.")}async function $P(){let e=tn();if(!e){if(await Ft(ne)){let n=await Iu();b("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),b(` url: http://localhost:${ne}/mcp (reachable)`),__(n);return}b("ours-mcp: stopped"),b(` cli: v${hr}`),process.exitCode=1;return}let t=await Ft(ne),r=t?await Iu():null;b("ours-mcp: running"),b(` pid: ${e}`),b(` url: http://localhost:${ne}/mcp ${t?"(reachable)":"(port not answering!)"}`),b(` broker: ${en}`),b(` state: ${Ne}`),b(` logs: ${mr}`),__(r)}async function SP(){if(b(`ours-mcp v${hr}`),await Ft(ne)){let e=await Iu();e?.version?b(`running daemon: v${e.version}`+(e.version!==hr?" (differs \u2014 restart to update)":"")):b("running daemon: version unknown (predates /version)")}else b("daemon: not running")}async function xP(){let e=wu(),t=fo();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 u=async(Y,me)=>{let Le=(await r.question(` ${Y} [${me}]: `)).trim();return Le===""?me:Le},d=await u("broker URL",e.brokerUrl),f=await u("HTTP port",String(e.port)),m=await u("state dir",e.stateDir),h=await u("GC interval (ms)",String(e.gcIntervalMs)),g=await u("proxy auto-starts daemon (true/false)",String(e.autoStart)),y=await u("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 w=(await r.question(` STT provider (openai-compatible / elevenlabs / deepgram / custom, empty=off) [${e.stt?.provider??""}]: `)).trim()||(e.stt?.provider??""),S=e.stt?.model??"",$=e.stt?.baseUrl??"";w&&(S=await u("STT model (verbatim, e.g. whisper-large-v3-turbo / scribe_v1 / nova-2)",S),$=await u("STT base URL (required for openai-compatible; empty = provider default)",$),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(f,10);(!Number.isFinite(P)||P<=0)&&(W(`invalid port: ${f}`),process.exit(1));let v=parseInt(h,10);(!Number.isFinite(v)||v<=0)&&(W(`invalid GC interval: ${h}`),process.exit(1));let x=g.toLowerCase()==="true"||g==="1",R=y.trim().toLowerCase();po.includes(R)||(W(`invalid visibility: ${y} (expected one of ${po.join(", ")})`),process.exit(1));let L=w?{...e.stt??{},provider:w,...S?{model:S}:{},...$?{baseUrl:$}:{}}:e.stt;n={brokerUrl:d,port:P,stateDir:x_(m),gcIntervalMs:v,autoStart:x,apiVisibility:R,...e.apiToken?{apiToken:e.apiToken}:{},...L?{stt:L}:{}}}finally{r.close()}qg(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(u=>process.env[u]!==void 0);s.length&&(b(""),b(`note: these env vars are set and OVERRIDE the file at runtime: ${s.join(", ")}`));let i=tn();if(!i)return;let a=qs({input:process.stdin,output:process.stdout}),c=!1;try{let u=(await a.question(`
83
+ daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=u==="y"||u==="yes"}finally{a.close()}if(!c){b("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await Fs();let l=Xr(process.execPath,[Lt,"start"],{stdio:"inherit"});l.status!==0&&process.exit(l.status??1)}function kP(e){let t=mo(gt.stt),r=gt.stt?.provider?.trim().toLowerCase()||null,n=process.env.OURS_STT_API_KEY?.trim()?"environment":gt.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 zP(e){if(e.includes("--help")||e.includes("-h")){b(p_);return}let t=new Set(["--dry-run"]);if(e.filter(i=>!t.has(i)).length){W("voice-setup: unsupported command-line option or argument"),W("The provider key is never accepted as a CLI argument. Run `ours-mcp voice-setup --help`."),process.exitCode=1;return}let n=tn()!==null,o=await Ft(ne),s=await d_({configFile:fo(),env:process.env,dryRun:e.includes("--dry-run"),daemonState:n?"managed":o?"external":"stopped",apply:async()=>{let i=Xr(process.execPath,[Lt,"restart"],{stdio:"inherit"});if(i.error||i.status!==0)return{ok:!1};let a=Xr(process.execPath,[Lt,"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 Tu(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function Ru(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function PP(e){let t=Ru(e,"--name"),r=Tu(e,"--force-bind","--no-force-bind"),n=Tu(e,"--local-book","--no-local-book"),o=Tu(e,"--auto-accept-local","--no-auto-accept-local"),s=e.includes("--overwrite"),i=e.includes("--print"),a=Ru(e,"--path")??Ru(e,"--dir")??process.cwd(),c=t!==void 0||r.set||n.set||o.set||i,l;if(c?((!t||!t.trim())&&(W("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),l={name:t.trim(),force:r.value??!1,exposeLocal:n.value??!0,localAutoAccept:o.value??!0}):l=await TP(),i){b(JSON.stringify(Ns(l),null,2));return}let u=Su(a);if(!s&&q.existsSync(u)){c&&(W(`define-local-identity-file: ${u} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let f=qs({input:process.stdin,output:process.stdout}),m=!1;try{let h=(await f.question(`
84
+ ${u} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();m=h==="y"||h==="yes"}finally{f.close()}if(!m){b("aborted \u2014 nothing written.");return}}let d=Lg(a,l,!0);b(""),b(`wrote ${d}:`),b(JSON.stringify(Ns(l),null,2))}async function TP(){b("ours-mcp define-local-identity-file \u2014 interactive"),b(`Answer the prompts; the result is written to ${Pt(process.cwd(),As)}.`),b("");let e=qs({input:process.stdin,output:process.stdout});try{let t=async(i,a)=>{let c=a?"Y/n":"y/N",l=(await e.question(` ${i} [${c}]: `)).trim().toLowerCase();return l===""?a:l==="y"||l==="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 RP(e){let t=(e[0]??"").trim();(!t||t.startsWith("--"))&&(W('usage: ours-mcp create-root "<your name>"'),process.exit(1)),await Ft(ne)||(W(`create-root: the daemon is not running on port ${ne} \u2014 start it with \`ours-mcp start\`.`),process.exit(1));let r=new Wr(new URL(`http://127.0.0.1:${ne}/mcp`),{requestInit:{headers:go()}}),n=new Es({name:"ours-mcp-cli",version:hr});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}W(`create-root failed: ${s}`),process.exit(1)}b(s)}finally{try{await r.terminateSession()}catch{}try{await n.close()}catch{}}}function T_(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 qt(e){W(`ours-mcp watch: ${e}`),process.exit(1)}async function EP(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${ne}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let n=await r.json();return typeof n.stateDir=="string"&&n.stateDir?x_(n.stateDir):Ne}}catch{}return null}var IP=e=>`http://127.0.0.1:${ne}/identities/${encodeURIComponent(e)}/notifications`;async function b_(e){let t=async o=>{let s=new AbortController,i=setTimeout(()=>s.abort(),35e3),a;try{a=await fetch(`${IP(e)}?since=${o}`,{headers:go(),signal:s.signal})}finally{clearTimeout(i)}if(a.status===401&&qt(`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)T_(e,s);typeof o.cursor=="number"&&(r=o.cursor)}catch(o){n=Math.min(n+1e3,5e3),W(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(o?.message??o)}), retrying\u2026`),await Vs(n)}}async function OP(e){if(e){await b_(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${ne}/identities`,{headers:go()});if(r.status===401&&qt("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),b_(s))}}}catch{}await Vs(3e3)}}var Eu=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function AP(e,t){try{q.readdirSync(e)}catch(i){qt(`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{q.readdirSync(Pt(e,t))}catch(i){qt(`cannot watch identity "${t}" \u2014 ${Pt(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=q.readdirSync(e,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name)}catch(c){Eu(c)&&qt(`lost read access to ${e} (${c.code}) \u2014 cannot watch.`);return}for(let c of a){if(t&&c!==t)continue;let l=Pt(e,c,"notifications.log"),u;try{u=q.statSync(l).size}catch(m){Eu(m)&&qt(`cannot read ${l} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}let d=r.get(l);if(d===void 0&&(d=i?u:0,r.set(l,d),i))continue;if(u<=d){u<d&&r.set(l,u);continue}let f;try{let m=q.openSync(l,"r"),h=Buffer.alloc(u-d);q.readSync(m,h,0,h.length,d),q.closeSync(m),f=h.toString("utf8")}catch(m){Eu(m)&&qt(`cannot read ${l} (${m.code}) \u2014 cannot watch identity "${c}".`);continue}r.set(l,u);for(let m of f.split(`
85
+ `))if(m.trim())try{T_(c,JSON.parse(m))}catch{}}};W(`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 CP(){try{let e=await fetch(`http://127.0.0.1:${ne}/identities`,{headers:go()});return e.status===401&&qt("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 NP(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await EP()!==null&&await CP()==="api"){W(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${ne} (Ctrl-C to stop)`),await OP(e);return}AP(Ne,e)}var ho="ours.service",R_="solutions.adaptframework.ours";function E_(){return Pt(S_(),".config","systemd","user",ho)}function I_(){return Pt(S_(),"Library","LaunchAgents",`${R_}.plist`)}function Qr(e,t){return Xr(e,t,{stdio:"inherit"}).status===0}function jP(){let e=E_();q.mkdirSync(Ou(e),{recursive:!0});let t=`[Unit]
84
86
  Description=ours MCP daemon (secure agent-to-agent messaging over ADAPT)
85
87
  After=network-online.target
86
88
  Wants=network-online.target
@@ -89,19 +91,19 @@ Wants=network-online.target
89
91
  Type=simple
90
92
  ExecStart=${process.execPath} ${Lt} serve
91
93
  Environment=OURS_TRANSPORT=http
92
- Environment=OURS_PORT=${te}
93
- Environment=OURS_BROKER_URL=${Xr}
94
- Environment=OURS_STATE_DIR=${qe}
94
+ Environment=OURS_PORT=${ne}
95
+ Environment=OURS_BROKER_URL=${en}
96
+ Environment=OURS_STATE_DIR=${Ne}
95
97
  Restart=on-failure
96
98
  RestartSec=2
97
99
 
98
100
  [Install]
99
101
  WantedBy=default.target
100
- `;q.writeFileSync(e,t),w(`wrote ${e}`),Yr("systemctl",["--user","daemon-reload"]),Yr("systemctl",["--user","enable","--now",mo])||(W("failed to enable/start the service via systemctl --user."),process.env.XDG_RUNTIME_DIR||(W(`hint: no user runtime dir \u2014 enable linger: sudo loginctl enable-linger ${Su().username}`),W(" (if linger is already on: export XDG_RUNTIME_DIR=/run/user/$(id -u))")),process.exit(1)),Yr("loginctl",["enable-linger",Su().username])||(W("warning: could not enable linger \u2014 the daemon may not start until you log in."),W(` run manually: loginctl enable-linger ${Su().username}`)),w(""),w("ours-mcp installed as a systemd user service and started."),w(` status: systemctl --user status ${mo}`),w(` logs: journalctl --user -u ${mo} -f`),w(" remove: ours-mcp uninstall-service")}function wP(){Yr("systemctl",["--user","disable","--now",mo]);let e=b_();try{q.rmSync(e,{force:!0}),w(`removed ${e}`)}catch(t){W(`failed to remove ${e}: ${String(t)}`)}Yr("systemctl",["--user","daemon-reload"]),w("ours-mcp service uninstalled.")}function bP(){let e=$_();q.mkdirSync(Eu(e),{recursive:!0});let t=`<?xml version="1.0" encoding="UTF-8"?>
102
+ `;q.writeFileSync(e,t),b(`wrote ${e}`),Qr("systemctl",["--user","daemon-reload"]),Qr("systemctl",["--user","enable","--now",ho])||(W("failed to enable/start the service via systemctl --user."),process.env.XDG_RUNTIME_DIR||(W(`hint: no user runtime dir \u2014 enable linger: sudo loginctl enable-linger ${Pu().username}`),W(" (if linger is already on: export XDG_RUNTIME_DIR=/run/user/$(id -u))")),process.exit(1)),Qr("loginctl",["enable-linger",Pu().username])||(W("warning: could not enable linger \u2014 the daemon may not start until you log in."),W(` run manually: loginctl enable-linger ${Pu().username}`)),b(""),b("ours-mcp installed as a systemd user service and started."),b(` status: systemctl --user status ${ho}`),b(` logs: journalctl --user -u ${ho} -f`),b(" remove: ours-mcp uninstall-service")}function MP(){Qr("systemctl",["--user","disable","--now",ho]);let e=E_();try{q.rmSync(e,{force:!0}),b(`removed ${e}`)}catch(t){W(`failed to remove ${e}: ${String(t)}`)}Qr("systemctl",["--user","daemon-reload"]),b("ours-mcp service uninstalled.")}function UP(){let e=I_();q.mkdirSync(Ou(e),{recursive:!0});let t=`<?xml version="1.0" encoding="UTF-8"?>
101
103
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
102
104
  <plist version="1.0">
103
105
  <dict>
104
- <key>Label</key><string>${w_}</string>
106
+ <key>Label</key><string>${R_}</string>
105
107
  <key>ProgramArguments</key>
106
108
  <array>
107
109
  <string>${process.execPath}</string>
@@ -111,15 +113,15 @@ WantedBy=default.target
111
113
  <key>EnvironmentVariables</key>
112
114
  <dict>
113
115
  <key>OURS_TRANSPORT</key><string>http</string>
114
- <key>OURS_PORT</key><string>${te}</string>
115
- <key>OURS_BROKER_URL</key><string>${Xr}</string>
116
- <key>OURS_STATE_DIR</key><string>${qe}</string>
116
+ <key>OURS_PORT</key><string>${ne}</string>
117
+ <key>OURS_BROKER_URL</key><string>${en}</string>
118
+ <key>OURS_STATE_DIR</key><string>${Ne}</string>
117
119
  </dict>
118
120
  <key>RunAtLoad</key><true/>
119
121
  <key>KeepAlive</key><true/>
120
- <key>StandardOutPath</key><string>${fr}</string>
121
- <key>StandardErrorPath</key><string>${fr}</string>
122
+ <key>StandardOutPath</key><string>${mr}</string>
123
+ <key>StandardErrorPath</key><string>${mr}</string>
122
124
  </dict>
123
125
  </plist>
124
- `;q.writeFileSync(e,t),w(`wrote ${e}`);let r=`gui/${process.getuid()}`;Qr("launchctl",["bootout",r,e],{stdio:"ignore"}),Yr("launchctl",["bootstrap",r,e])||(W("failed to load the launchd agent."),process.exit(1)),w(""),w("ours-mcp installed as a launchd agent and started."),w(" remove: ours-mcp uninstall-service")}function $P(){let e=$_(),t=`gui/${process.getuid()}`;Qr("launchctl",["bootout",t,e],{stdio:"ignore"});try{q.rmSync(e,{force:!0}),w(`removed ${e}`)}catch(r){W(`failed to remove ${e}: ${String(r)}`)}w("ours-mcp service uninstalled.")}async function SP(){if(await Zs(),process.platform==="linux")return vP();if(process.platform==="darwin")return bP();W(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function xP(){if(process.platform==="linux")return wP();if(process.platform==="darwin")return $P();W(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function m_(){w("ours-mcp \u2014 daemon for the ours MCP server"),w(""),w("Usage: ours-mcp <command>"),w(" start start the daemon in the background"),w(" stop stop the running daemon"),w(" restart stop then start"),w(" status show whether the daemon is running (incl. CLI + running-daemon version)"),w(" version print the CLI version and the running daemon version (GET /version)"),w(" setup interactively edit the config file (broker / port / state dir / gc)"),w(" voice-setup [--dry-run] securely choose a provider and configure its hidden API key"),w(" voice-status [--json] check voice-transcription readiness (never prints the API key)"),w(" serve run in the foreground (used by start; handy for debugging)"),w(" watch [identity] stream one line per new inbound message (wake source for a Monitor)"),w(" proxy per-session stdio shim \u2192 daemon (stable binding; for the MCP client config)"),w(""),w(' create-root "<name>" create THE root human identity (one per host) via the running'),w(" daemon \u2014 quiet no-op if a root already exists (installer seam)"),w(""),w(" define-local-identity-file write a .ours-identity workspace pin"),w(" interactive (default): 4-question survey, writes to CWD"),w(" scripted: --name <s> [--force-bind] [--local-book] [--auto-accept-local]"),w(" negate with --no-force-bind / --no-local-book / --no-auto-accept-local"),w(" --dir <path> | --path <file> (default CWD) \xB7 --overwrite \xB7 --print"),w(""),w(" install-service install + start a boot-persistent service (systemd/launchd)"),w(" uninstall-service stop + remove that service"),w(""),w("Config precedence (per field): env var > config.json > default."),w(" config.json: OURS_CONFIG, else ~/.ours/config.json \u2014 edit with `setup`."),w(" env: OURS_BROKER_URL, OURS_PORT (3050), OURS_STATE_DIR (~/.ours), OURS_GC_INTERVAL_MS (3600000), OURS_AUTOSTART (off)"),w("(install-service bakes the resolved config values into the service definition.)")}async function zP(){let e=process.argv[2]??"help";switch(e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),q.mkdirSync(qe,{recursive:!0}),q.writeFileSync(hr,String(process.pid));{let t=()=>{try{q.rmSync(hr,{force:!0})}catch{}};process.on("exit",t);for(let r of["SIGTERM","SIGINT"])process.on(r,()=>{t(),process.exit(0)})}await import(rP(kt(Eu(Lt),"index.js")).href);break;case"start":await p_();break;case"stop":await Zs();break;case"restart":await Zs(),await p_();break;case"status":await sP();break;case"version":case"--version":case"-v":await iP();break;case"setup":await aP();break;case"voice-status":case"stt-status":cP(process.argv.slice(3));break;case"voice-setup":case"stt-setup":await uP(process.argv.slice(3));break;case"create-root":await pP(process.argv.slice(3));break;case"define-local-identity-file":await lP(process.argv.slice(3));break;case"watch":await yP(process.argv[3]);break;case"proxy":!Pt.autoStart&&!await Ft(te)&&(W(`ours-mcp daemon is not running on port ${te} \u2014 start it with \`ours-mcp start\`.`),W("(or enable auto-start: `ours-mcp setup` \u2192 autoStart, or OURS_AUTOSTART=1)"),process.exit(1)),await Yg({url:`http://127.0.0.1:${te}/mcp`,ensureDaemon:Pt.autoStart?oP:void 0,stateDir:qe,apiToken:Pu??void 0});break;case"install-service":await SP();break;case"uninstall-service":xP();break;case"help":case"--help":case"-h":m_();break;default:W(`unknown command: ${e}
125
- `),m_(),process.exit(1)}}zP().catch(e=>{W(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});
126
+ `;q.writeFileSync(e,t),b(`wrote ${e}`);let r=`gui/${process.getuid()}`;Xr("launchctl",["bootout",r,e],{stdio:"ignore"}),Qr("launchctl",["bootstrap",r,e])||(W("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 DP(){let e=I_(),t=`gui/${process.getuid()}`;Xr("launchctl",["bootout",t,e],{stdio:"ignore"});try{q.rmSync(e,{force:!0}),b(`removed ${e}`)}catch(r){W(`failed to remove ${e}: ${String(r)}`)}b("ours-mcp service uninstalled.")}async function ZP(){if(await Fs(),process.platform==="linux")return jP();if(process.platform==="darwin")return UP();W(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function qP(){if(process.platform==="linux")return MP();if(process.platform==="darwin")return DP();W(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function w_(){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 LP(){let e=process.argv[2]??"help";switch(e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),q.mkdirSync(Ne,{recursive:!0}),q.writeFileSync(gr,String(process.pid));{let t=()=>{try{q.rmSync(gr,{force:!0})}catch{}};process.on("exit",t);for(let r of["SIGTERM","SIGINT"])process.on(r,()=>{t(),process.exit(0)})}await import(gP(Pt(Ou(Lt),"index.js")).href);break;case"start":await v_();break;case"stop":await Fs();break;case"restart":await Fs(),await v_();break;case"status":await $P();break;case"version":case"--version":case"-v":await SP();break;case"setup":await xP();break;case"voice-status":case"stt-status":kP(process.argv.slice(3));break;case"voice-setup":case"stt-setup":await zP(process.argv.slice(3));break;case"create-root":await RP(process.argv.slice(3));break;case"define-local-identity-file":await PP(process.argv.slice(3));break;case"watch":await NP(process.argv[3]);break;case"proxy":!gt.autoStart&&!await Ft(ne)&&(W(`ours-mcp daemon is not running on port ${ne} \u2014 start it with \`ours-mcp start\`.`),W("(or enable auto-start: `ours-mcp setup` \u2192 autoStart, or OURS_AUTOSTART=1)"),process.exit(1)),await Xg({url:`http://127.0.0.1:${ne}/mcp`,ensureDaemon:gt.autoStart?wP:void 0,stateDir:Ne,apiToken:$u(gt,{generate:!1})?.token});break;case"install-service":await ZP();break;case"uninstall-service":qP();break;case"help":case"--help":case"-h":w_();break;default:W(`unknown command: ${e}
127
+ `),w_(),process.exit(1)}}LP().catch(e=>{W(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});