@reddb-io/red-skills 2.87.7 → 2.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,79 +1,79 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var H_=Object.create;var Li=Object.defineProperty;var W_=Object.getOwnPropertyDescriptor;var G_=Object.getOwnPropertyNames;var J_=Object.getPrototypeOf,Q_=Object.prototype.hasOwnProperty;var gt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),il=(e,t)=>{for(var r in t)Li(e,r,{get:t[r],enumerable:!0})},Y_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of G_(t))!Q_.call(e,o)&&o!==r&&Li(e,o,{get:()=>t[o],enumerable:!(n=W_(t,o))||n.enumerable});return e};var Bi=(e,t,r)=>(r=e!=null?H_(J_(e)):{},Y_(t||!e||!e.__esModule?Li(r,"default",{value:e,enumerable:!0}):r,e));var cn=b(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var sn=class{};U._CodeOrName=sn;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Mt=class extends sn{constructor(t){if(super(),!U.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}}};U.Name=Mt;var De=class extends sn{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 Mt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=De;U.nil=new De("");function Op(e,...t){let r=[e[0]],n=0;for(;n<t.length;)aa(r,t[n]),r.push(e[++n]);return new De(r)}U._=Op;var sa=new De("+");function Ip(e,...t){let r=[an(e[0])],n=0;for(;n<t.length;)r.push(sa),aa(r,t[n]),r.push(sa,an(e[++n]));return ex(r),new De(r)}U.str=Ip;function aa(e,t){t instanceof De?e.push(...t._items):t instanceof Mt?e.push(t):e.push(nx(t))}U.addCodeArg=aa;function ex(e){let t=1;for(;t<e.length-1;){if(e[t]===sa){let r=tx(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function tx(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Mt||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 Mt))return`"${e}${t.slice(1)}`}function rx(e,t){return t.emptyStr()?e:e.emptyStr()?t:Ip`${e}${t}`}U.strConcat=rx;function nx(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:an(Array.isArray(e)?e.join(","):e)}function ox(e){return new De(an(e))}U.stringify=ox;function an(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=an;function ix(e){return typeof e=="string"&&U.IDENTIFIER.test(e)?new De(`.${e}`):Op`[${e}]`}U.getProperty=ix;function sx(e){if(typeof e=="string"&&U.IDENTIFIER.test(e))return new De(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}U.getEsmExportName=sx;function ax(e){return new De(e.toString())}U.regexpCode=ax});var la=b(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ValueScope=Te.ValueScopeName=Te.Scope=Te.varKinds=Te.UsedValueState=void 0;var Ee=cn(),ca=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},To;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(To||(Te.UsedValueState=To={}));Te.varKinds={const:new Ee.Name("const"),let:new Ee.Name("let"),var:new Ee.Name("var")};var Po=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ee.Name?t:this.name(t)}name(t){return new Ee.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}}};Te.Scope=Po;var Ro=class extends Ee.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ee._)`.${new Ee.Name(r)}[${n}]`}};Te.ValueScopeName=Ro;var cx=(0,Ee._)`\n`,ua=class extends Po{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?cx:Ee.nil}}get(){return this._scope}name(t){return new Ro(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:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,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,Ee._)`${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 i=Ee.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,To.Started);let u=r(l);if(u){let d=this.opts.es5?Te.varKinds.var:Te.varKinds.const;i=(0,Ee._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Ee._)`${i}${u}${this.opts._n}`;else throw new ca(l);c.set(l,To.Completed)})}return i}};Te.ValueScope=ua});var C=b(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 L=cn(),Fe=la(),vt=cn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return vt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return vt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return vt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return vt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return vt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return vt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return vt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return vt.Name}});var Ao=la();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Ao.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Ao.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Ao.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Ao.varKinds}});D.operators={GT:new L._Code(">"),GTE:new L._Code(">="),LT:new L._Code("<"),LTE:new L._Code("<="),EQ:new L._Code("==="),NEQ:new L._Code("!=="),NOT:new L._Code("!"),OR:new L._Code("||"),AND:new L._Code("&&"),ADD:new L._Code("+")};var ut=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},da=class extends ut{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Fe.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=cr(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},zo=class extends ut{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 L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=cr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return Io(t,this.rhs)}},fa=class extends zo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},pa=class extends ut{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ma=class extends ut{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},ha=class extends ut{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},ga=class extends ut{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=cr(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},un=class extends ut{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 i=n[o];i.optimizeNames(t,r)||(ux(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Bt(t,r.names),{})}},lt=class extends un{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ya=class extends un{},ar=class extends lt{};ar.kind="else";var qt=class e extends lt{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 ar(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Ap(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=cr(this.condition,t,r),this}get names(){let t=super.names;return Io(t,this.condition),this.else&&Bt(t,this.else.names),t}};qt.kind="if";var Lt=class extends lt{};Lt.kind="for";var _a=class extends Lt{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=cr(this.iteration,t,r),this}get names(){return Bt(super.names,this.iteration.names)}},wa=class extends Lt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Fe.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=Io(super.names,this.from);return Io(t,this.to)}},Oo=class extends Lt{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=cr(this.iterable,t,r),this}get names(){return Bt(super.names,this.iterable.names)}},ln=class extends lt{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)}};ln.kind="func";var dn=class extends un{render(t){return"return "+super.render(t)}};dn.kind="return";var ba=class extends lt{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&&Bt(t,this.catch.names),this.finally&&Bt(t,this.finally.names),t}},fn=class extends lt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};fn.kind="catch";var pn=class extends lt{render(t){return"finally"+super.render(t)}};pn.kind="finally";var va=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new Fe.Scope({parent:t}),this._nodes=[new ya]}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 i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new da(t,i,n)),i}const(t,r,n){return this._def(Fe.varKinds.const,t,r,n)}let(t,r,n){return this._def(Fe.varKinds.let,t,r,n)}var(t,r,n){return this._def(Fe.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new zo(t,r,n))}add(t,r){return this._leafNode(new fa(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new ga(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,L.addCodeArg)(r,o));return r.push("}"),new L._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 ar)}endIf(){return this._endBlockNode(qt,ar)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new _a(t),r)}forRange(t,r,n,o,i=this.opts.es5?Fe.varKinds.var:Fe.varKinds.let){let s=this._scope.toName(t);return this._for(new wa(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Fe.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof L.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,L._)`${s}.length`,a=>{this.var(i,(0,L._)`${s}[${a}]`),n(i)})}return this._for(new Oo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Fe.varKinds.var:Fe.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,L._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Oo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Lt)}label(t){return this._leafNode(new pa(t))}break(t){return this._leafNode(new ma(t))}return(t){let r=new dn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ba;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new fn(i),r(i)}return n&&(this._currNode=o.finally=new pn,this.code(n)),this._endBlockNode(fn,pn)}throw(t){return this._leafNode(new ha(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=L.nil,n,o){return this._blockNode(new ln(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ln)}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=va;function Bt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Io(e,t){return t instanceof L._CodeOrName?Bt(e,t.names):e}function cr(e,t,r){if(e instanceof L.Name)return n(e);if(!o(e))return e;return new L._Code(e._items.reduce((i,s)=>(s instanceof L.Name&&(s=n(s)),s instanceof L._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof L._Code&&i._items.some(s=>s instanceof L.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function ux(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Ap(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${xa(e)}`}D.not=Ap;var lx=Np(D.operators.AND);function dx(...e){return e.reduce(lx)}D.and=dx;var fx=Np(D.operators.OR);function px(...e){return e.reduce(fx)}D.or=px;function Np(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${xa(t)} ${e} ${xa(r)}`}function xa(e){return e instanceof L.Name?e:(0,L._)`(${e})`}});var B=b(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var H=C(),mx=cn();function hx(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=hx;function gx(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(jp(e,t),!Mp(t,e.self.RULES.all))}j.alwaysValidSchema=gx;function jp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||Bp(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=jp;function Mp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=Mp;function yx(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}j.schemaHasRulesButRef=yx;function _x({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,H._)`${r}`}return(0,H._)`${e}${t}${(0,H.getProperty)(n)}`}j.schemaRefOrVal=_x;function wx(e){return qp(decodeURIComponent(e))}j.unescapeFragment=wx;function bx(e){return encodeURIComponent($a(e))}j.escapeFragment=bx;function $a(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=$a;function qp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=qp;function vx(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=vx;function Cp({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof H.Name?(i instanceof H.Name?e(o,i,s):t(o,i,s),s):i instanceof H.Name?(t(o,s,i),i):r(i,s);return a===H.Name&&!(c instanceof H.Name)?n(o,c):c}}j.mergeEvaluated={props:Cp({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,H._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,H._)`${r} || {}`).code((0,H._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,H._)`${r} || {}`),Sa(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Lp}),items:Cp({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,H._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,H._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Lp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&Sa(e,r,t),r}j.evaluatedPropsToName=Lp;function Sa(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=Sa;var Dp={};function xx(e,t){return e.scopeValue("func",{ref:t,code:Dp[t.code]||(Dp[t.code]=new mx._Code(t.code))})}j.useFunc=xx;var ka;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ka||(j.Type=ka={}));function kx(e,t,r){if(e instanceof H.Name){let n=t===ka.Num;return r?n?(0,H._)`"[" + ${e} + "]"`:(0,H._)`"['" + ${e} + "']"`:n?(0,H._)`"/" + ${e}`:(0,H._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,H.getProperty)(e).toString():"/"+$a(e)}j.getErrorPath=kx;function Bp(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}j.checkStrictMode=Bp});var dt=b(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var he=C(),$x={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};Ea.default=$x});var mn=b(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.extendErrors=ge.resetErrorsCount=ge.reportExtraError=ge.reportError=ge.keyword$DataError=ge.keywordError=void 0;var Z=C(),No=B(),xe=dt();ge.keywordError={message:({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`};ge.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`};function Sx(e,t=ge.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=Fp(e,t,r);n??(s||a)?Zp(i,c):Up(o,(0,Z._)`[${c}]`)}ge.reportError=Sx;function Ex(e,t=ge.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=Fp(e,t,r);Zp(o,a),i||s||Up(n,xe.default.vErrors)}ge.reportExtraError=Ex;function Tx(e,t){e.assign(xe.default.errors,t),e.if((0,Z._)`${xe.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${xe.default.vErrors}.length`,t),()=>e.assign(xe.default.vErrors,null)))}ge.resetErrorsCount=Tx;function Px({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,xe.default.errors,a=>{e.const(s,(0,Z._)`${xe.default.vErrors}[${a}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(xe.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}ge.extendErrors=Px;function Zp(e,t){let r=e.const("err",t);e.if((0,Z._)`${xe.default.vErrors} === null`,()=>e.assign(xe.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${xe.default.vErrors}.push(${r})`),e.code((0,Z._)`${xe.default.errors}++`)}function Up(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}var Zt={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Fp(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:Rx(e,t,r)}function Rx(e,t,r={}){let{gen:n,it:o}=e,i=[zx(o,r),Ox(e,r)];return Ix(e,t,i),n.object(...i)}function zx({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,No.getErrorPath)(t,No.Type.Str)}`:e;return[xe.default.instancePath,(0,Z.strConcat)(xe.default.instancePath,r)]}function Ox({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Z.str)`${t}/${e}`;return r&&(o=(0,Z.str)`${o}${(0,No.getErrorPath)(r,No.Type.Str)}`),[Zt.schemaPath,o]}function Ix(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Zt.keyword,o],[Zt.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),c.messages&&n.push([Zt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Zt.schema,s],[Zt.parentSchema,(0,Z._)`${u}${d}`],[xe.default.data,i]),l&&n.push([Zt.propertyName,l])}});var Kp=b(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.boolOrEmptySchema=ur.topBoolOrEmptySchema=void 0;var Ax=mn(),Nx=C(),Cx=dt(),Dx={message:"boolean schema is false"};function jx(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Vp(e,!1):typeof r=="object"&&r.$async===!0?t.return(Cx.default.data):(t.assign((0,Nx._)`${n}.errors`,null),t.return(!0))}ur.topBoolOrEmptySchema=jx;function Mx(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Vp(e)):r.var(t,!0)}ur.boolOrEmptySchema=Mx;function Vp(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,Ax.reportError)(o,Dx,void 0,t)}});var Ta=b(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.getRules=lr.isJSONType=void 0;var qx=["string","number","integer","boolean","null","object","array"],Lx=new Set(qx);function Bx(e){return typeof e=="string"&&Lx.has(e)}lr.isJSONType=Bx;function Zx(){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:{}}}lr.getRules=Zx});var Pa=b(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.shouldUseRule=xt.shouldUseGroup=xt.schemaHasRulesForType=void 0;function Ux({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Hp(e,n)}xt.schemaHasRulesForType=Ux;function Hp(e,t){return t.rules.some(r=>Wp(e,r))}xt.shouldUseGroup=Hp;function Wp(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))}xt.shouldUseRule=Wp});var hn=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.reportTypeError=ye.checkDataTypes=ye.checkDataType=ye.coerceAndCheckDataType=ye.getJSONTypes=ye.getSchemaTypes=ye.DataType=void 0;var Fx=Ta(),Vx=Pa(),Kx=mn(),N=C(),Gp=B(),dr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(dr||(ye.DataType=dr={}));function Hx(e){let t=Jp(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}ye.getSchemaTypes=Hx;function Jp(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Fx.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ye.getJSONTypes=Jp;function Wx(e,t){let{gen:r,data:n,opts:o}=e,i=Gx(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,Vx.schemaHasRulesForType)(e,t[0]));if(s){let a=za(t,n,o.strictNumbers,dr.Wrong);r.if(a,()=>{i.length?Jx(e,t,i):Oa(e)})}return s}ye.coerceAndCheckDataType=Wx;var Qp=new Set(["string","number","integer","boolean","null"]);function Gx(e,t){return t?e.filter(r=>Qp.has(r)||t==="array"&&r==="array"):[]}function Jx(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(za(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(Qp.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),Oa(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),Qx(e,a)});function c(l){switch(l){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null
3
+ var Q_=Object.create;var Li=Object.defineProperty;var Y_=Object.getOwnPropertyDescriptor;var X_=Object.getOwnPropertyNames;var ew=Object.getPrototypeOf,tw=Object.prototype.hasOwnProperty;var gt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sl=(e,t)=>{for(var r in t)Li(e,r,{get:t[r],enumerable:!0})},rw=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of X_(t))!tw.call(e,o)&&o!==r&&Li(e,o,{get:()=>t[o],enumerable:!(n=Y_(t,o))||n.enumerable});return e};var Bi=(e,t,r)=>(r=e!=null?Q_(ew(e)):{},rw(t||!e||!e.__esModule?Li(r,"default",{value:e,enumerable:!0}):r,e));var cn=v(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var sn=class{};U._CodeOrName=sn;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Mt=class extends sn{constructor(t){if(super(),!U.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}}};U.Name=Mt;var De=class extends sn{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 Mt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=De;U.nil=new De("");function Ip(e,...t){let r=[e[0]],n=0;for(;n<t.length;)aa(r,t[n]),r.push(e[++n]);return new De(r)}U._=Ip;var sa=new De("+");function Ap(e,...t){let r=[an(e[0])],n=0;for(;n<t.length;)r.push(sa),aa(r,t[n]),r.push(sa,an(e[++n]));return ox(r),new De(r)}U.str=Ap;function aa(e,t){t instanceof De?e.push(...t._items):t instanceof Mt?e.push(t):e.push(ax(t))}U.addCodeArg=aa;function ox(e){let t=1;for(;t<e.length-1;){if(e[t]===sa){let r=ix(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function ix(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Mt||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 Mt))return`"${e}${t.slice(1)}`}function sx(e,t){return t.emptyStr()?e:e.emptyStr()?t:Ap`${e}${t}`}U.strConcat=sx;function ax(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:an(Array.isArray(e)?e.join(","):e)}function cx(e){return new De(an(e))}U.stringify=cx;function an(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=an;function ux(e){return typeof e=="string"&&U.IDENTIFIER.test(e)?new De(`.${e}`):Ip`[${e}]`}U.getProperty=ux;function lx(e){if(typeof e=="string"&&U.IDENTIFIER.test(e))return new De(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}U.getEsmExportName=lx;function dx(e){return new De(e.toString())}U.regexpCode=dx});var la=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ValueScope=Te.ValueScopeName=Te.Scope=Te.varKinds=Te.UsedValueState=void 0;var Ee=cn(),ca=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},To;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(To||(Te.UsedValueState=To={}));Te.varKinds={const:new Ee.Name("const"),let:new Ee.Name("let"),var:new Ee.Name("var")};var Ro=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ee.Name?t:this.name(t)}name(t){return new Ee.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}}};Te.Scope=Ro;var Po=class extends Ee.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ee._)`.${new Ee.Name(r)}[${n}]`}};Te.ValueScopeName=Po;var fx=(0,Ee._)`\n`,ua=class extends Ro{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?fx:Ee.nil}}get(){return this._scope}name(t){return new Po(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:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,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,Ee._)`${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 i=Ee.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,To.Started);let u=r(l);if(u){let d=this.opts.es5?Te.varKinds.var:Te.varKinds.const;i=(0,Ee._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,Ee._)`${i}${u}${this.opts._n}`;else throw new ca(l);c.set(l,To.Completed)})}return i}};Te.ValueScope=ua});var C=v(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 L=cn(),Ue=la(),bt=cn();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return bt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return bt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return bt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return bt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return bt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return bt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return bt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return bt.Name}});var Ao=la();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return Ao.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return Ao.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return Ao.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return Ao.varKinds}});D.operators={GT:new L._Code(">"),GTE:new L._Code(">="),LT:new L._Code("<"),LTE:new L._Code("<="),EQ:new L._Code("==="),NEQ:new L._Code("!=="),NOT:new L._Code("!"),OR:new L._Code("||"),AND:new L._Code("&&"),ADD:new L._Code("+")};var ct=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},da=class extends ct{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ue.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=cr(this.rhs,t,r)),this}get names(){return this.rhs instanceof L._CodeOrName?this.rhs.names:{}}},zo=class extends ct{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 L.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=cr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof L.Name?{}:{...this.lhs.names};return Io(t,this.rhs)}},fa=class extends zo{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},pa=class extends ct{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ma=class extends ct{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},ha=class extends ct{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},ga=class extends ct{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=cr(this.code,t,r),this}get names(){return this.code instanceof L._CodeOrName?this.code.names:{}}},un=class extends ct{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 i=n[o];i.optimizeNames(t,r)||(px(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Bt(t,r.names),{})}},ut=class extends un{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ya=class extends un{},ar=class extends ut{};ar.kind="else";var qt=class e extends ut{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 ar(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Np(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=cr(this.condition,t,r),this}get names(){let t=super.names;return Io(t,this.condition),this.else&&Bt(t,this.else.names),t}};qt.kind="if";var Lt=class extends ut{};Lt.kind="for";var _a=class extends Lt{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=cr(this.iteration,t,r),this}get names(){return Bt(super.names,this.iteration.names)}},wa=class extends Lt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ue.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=Io(super.names,this.from);return Io(t,this.to)}},Oo=class extends Lt{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=cr(this.iterable,t,r),this}get names(){return Bt(super.names,this.iterable.names)}},ln=class extends ut{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)}};ln.kind="func";var dn=class extends un{render(t){return"return "+super.render(t)}};dn.kind="return";var va=class extends ut{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&&Bt(t,this.catch.names),this.finally&&Bt(t,this.finally.names),t}},fn=class extends ut{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};fn.kind="catch";var pn=class extends ut{render(t){return"finally"+super.render(t)}};pn.kind="finally";var ba=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new Ue.Scope({parent:t}),this._nodes=[new ya]}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 i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new da(t,i,n)),i}const(t,r,n){return this._def(Ue.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ue.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ue.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new zo(t,r,n))}add(t,r){return this._leafNode(new fa(t,D.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==L.nil&&this._leafNode(new ga(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,L.addCodeArg)(r,o));return r.push("}"),new L._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 ar)}endIf(){return this._endBlockNode(qt,ar)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new _a(t),r)}forRange(t,r,n,o,i=this.opts.es5?Ue.varKinds.var:Ue.varKinds.let){let s=this._scope.toName(t);return this._for(new wa(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Ue.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof L.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,L._)`${s}.length`,a=>{this.var(i,(0,L._)`${s}[${a}]`),n(i)})}return this._for(new Oo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Ue.varKinds.var:Ue.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,L._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Oo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Lt)}label(t){return this._leafNode(new pa(t))}break(t){return this._leafNode(new ma(t))}return(t){let r=new dn;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dn)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new va;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new fn(i),r(i)}return n&&(this._currNode=o.finally=new pn,this.code(n)),this._endBlockNode(fn,pn)}throw(t){return this._leafNode(new ha(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=L.nil,n,o){return this._blockNode(new ln(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ln)}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=ba;function Bt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Io(e,t){return t instanceof L._CodeOrName?Bt(e,t.names):e}function cr(e,t,r){if(e instanceof L.Name)return n(e);if(!o(e))return e;return new L._Code(e._items.reduce((i,s)=>(s instanceof L.Name&&(s=n(s)),s instanceof L._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof L._Code&&i._items.some(s=>s instanceof L.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function px(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Np(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,L._)`!${xa(e)}`}D.not=Np;var mx=Cp(D.operators.AND);function hx(...e){return e.reduce(mx)}D.and=hx;var gx=Cp(D.operators.OR);function yx(...e){return e.reduce(gx)}D.or=yx;function Cp(e){return(t,r)=>t===L.nil?r:r===L.nil?t:(0,L._)`${xa(t)} ${e} ${xa(r)}`}function xa(e){return e instanceof L.Name?e:(0,L._)`(${e})`}});var B=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var H=C(),_x=cn();function wx(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=wx;function vx(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Mp(e,t),!qp(t,e.self.RULES.all))}j.alwaysValidSchema=vx;function Mp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||Zp(e,`unknown keyword: "${i}"`)}j.checkUnknownRules=Mp;function qp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=qp;function bx(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}j.schemaHasRulesButRef=bx;function xx({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,H._)`${r}`}return(0,H._)`${e}${t}${(0,H.getProperty)(n)}`}j.schemaRefOrVal=xx;function kx(e){return Lp(decodeURIComponent(e))}j.unescapeFragment=kx;function $x(e){return encodeURIComponent($a(e))}j.escapeFragment=$x;function $a(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=$a;function Lp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Lp;function Sx(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=Sx;function Dp({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof H.Name?(i instanceof H.Name?e(o,i,s):t(o,i,s),s):i instanceof H.Name?(t(o,s,i),i):r(i,s);return a===H.Name&&!(c instanceof H.Name)?n(o,c):c}}j.mergeEvaluated={props:Dp({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,H._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,H._)`${r} || {}`).code((0,H._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,H._)`${r} || {}`),Sa(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Bp}),items:Dp({mergeNames:(e,t,r)=>e.if((0,H._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,H._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,H._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,H._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Bp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,H._)`{}`);return t!==void 0&&Sa(e,r,t),r}j.evaluatedPropsToName=Bp;function Sa(e,t,r){Object.keys(r).forEach(n=>e.assign((0,H._)`${t}${(0,H.getProperty)(n)}`,!0))}j.setEvaluated=Sa;var jp={};function Ex(e,t){return e.scopeValue("func",{ref:t,code:jp[t.code]||(jp[t.code]=new _x._Code(t.code))})}j.useFunc=Ex;var ka;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ka||(j.Type=ka={}));function Tx(e,t,r){if(e instanceof H.Name){let n=t===ka.Num;return r?n?(0,H._)`"[" + ${e} + "]"`:(0,H._)`"['" + ${e} + "']"`:n?(0,H._)`"/" + ${e}`:(0,H._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,H.getProperty)(e).toString():"/"+$a(e)}j.getErrorPath=Tx;function Zp(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}j.checkStrictMode=Zp});var lt=v(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var he=C(),Rx={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};Ea.default=Rx});var mn=v(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.extendErrors=ge.resetErrorsCount=ge.reportExtraError=ge.reportError=ge.keyword$DataError=ge.keywordError=void 0;var Z=C(),No=B(),xe=lt();ge.keywordError={message:({keyword:e})=>(0,Z.str)`must pass "${e}" keyword validation`};ge.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Z.str)`"${e}" keyword must be ${t} ($data)`:(0,Z.str)`"${e}" keyword is invalid ($data)`};function Px(e,t=ge.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=Vp(e,t,r);n??(s||a)?Up(i,c):Fp(o,(0,Z._)`[${c}]`)}ge.reportError=Px;function zx(e,t=ge.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=Vp(e,t,r);Up(o,a),i||s||Fp(n,xe.default.vErrors)}ge.reportExtraError=zx;function Ox(e,t){e.assign(xe.default.errors,t),e.if((0,Z._)`${xe.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Z._)`${xe.default.vErrors}.length`,t),()=>e.assign(xe.default.vErrors,null)))}ge.resetErrorsCount=Ox;function Ix({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,xe.default.errors,a=>{e.const(s,(0,Z._)`${xe.default.vErrors}[${a}]`),e.if((0,Z._)`${s}.instancePath === undefined`,()=>e.assign((0,Z._)`${s}.instancePath`,(0,Z.strConcat)(xe.default.instancePath,i.errorPath))),e.assign((0,Z._)`${s}.schemaPath`,(0,Z.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Z._)`${s}.schema`,r),e.assign((0,Z._)`${s}.data`,n))})}ge.extendErrors=Ix;function Up(e,t){let r=e.const("err",t);e.if((0,Z._)`${xe.default.vErrors} === null`,()=>e.assign(xe.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${xe.default.vErrors}.push(${r})`),e.code((0,Z._)`${xe.default.errors}++`)}function Fp(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Z._)`new ${e.ValidationError}(${t})`):(r.assign((0,Z._)`${n}.errors`,t),r.return(!1))}var Zt={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Vp(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Z._)`{}`:Ax(e,t,r)}function Ax(e,t,r={}){let{gen:n,it:o}=e,i=[Nx(o,r),Cx(e,r)];return Dx(e,t,i),n.object(...i)}function Nx({errorPath:e},{instancePath:t}){let r=t?(0,Z.str)`${e}${(0,No.getErrorPath)(t,No.Type.Str)}`:e;return[xe.default.instancePath,(0,Z.strConcat)(xe.default.instancePath,r)]}function Cx({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Z.str)`${t}/${e}`;return r&&(o=(0,Z.str)`${o}${(0,No.getErrorPath)(r,No.Type.Str)}`),[Zt.schemaPath,o]}function Dx(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Zt.keyword,o],[Zt.params,typeof t=="function"?t(e):t||(0,Z._)`{}`]),c.messages&&n.push([Zt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Zt.schema,s],[Zt.parentSchema,(0,Z._)`${u}${d}`],[xe.default.data,i]),l&&n.push([Zt.propertyName,l])}});var Hp=v(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.boolOrEmptySchema=ur.topBoolOrEmptySchema=void 0;var jx=mn(),Mx=C(),qx=lt(),Lx={message:"boolean schema is false"};function Bx(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Kp(e,!1):typeof r=="object"&&r.$async===!0?t.return(qx.default.data):(t.assign((0,Mx._)`${n}.errors`,null),t.return(!0))}ur.topBoolOrEmptySchema=Bx;function Zx(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Kp(e)):r.var(t,!0)}ur.boolOrEmptySchema=Zx;function Kp(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,jx.reportError)(o,Lx,void 0,t)}});var Ta=v(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.getRules=lr.isJSONType=void 0;var Ux=["string","number","integer","boolean","null","object","array"],Fx=new Set(Ux);function Vx(e){return typeof e=="string"&&Fx.has(e)}lr.isJSONType=Vx;function Kx(){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:{}}}lr.getRules=Kx});var Ra=v(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.shouldUseRule=xt.shouldUseGroup=xt.schemaHasRulesForType=void 0;function Hx({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Wp(e,n)}xt.schemaHasRulesForType=Hx;function Wp(e,t){return t.rules.some(r=>Gp(e,r))}xt.shouldUseGroup=Wp;function Gp(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))}xt.shouldUseRule=Gp});var hn=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.reportTypeError=ye.checkDataTypes=ye.checkDataType=ye.coerceAndCheckDataType=ye.getJSONTypes=ye.getSchemaTypes=ye.DataType=void 0;var Wx=Ta(),Gx=Ra(),Jx=mn(),N=C(),Jp=B(),dr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(dr||(ye.DataType=dr={}));function Qx(e){let t=Qp(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}ye.getSchemaTypes=Qx;function Qp(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Wx.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ye.getJSONTypes=Qp;function Yx(e,t){let{gen:r,data:n,opts:o}=e,i=Xx(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,Gx.schemaHasRulesForType)(e,t[0]));if(s){let a=za(t,n,o.strictNumbers,dr.Wrong);r.if(a,()=>{i.length?e0(e,t,i):Oa(e)})}return s}ye.coerceAndCheckDataType=Yx;var Yp=new Set(["string","number","integer","boolean","null"]);function Xx(e,t){return t?e.filter(r=>Yp.has(r)||t==="array"&&r==="array"):[]}function e0(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(za(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(Yp.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),Oa(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),t0(e,a)});function c(l){switch(l){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null
5
5
  || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,N._)`+${o}`);return;case"integer":n.elseIf((0,N._)`${s} === "boolean" || ${o} === null
6
6
  || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,N._)`+${o}`);return;case"boolean":n.elseIf((0,N._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,N._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,N._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,N._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function Qx({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function Ra(e,t,r,n=dr.Correct){let o=n===dr.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===dr.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}ye.checkDataType=Ra;function za(e,t,r,n){if(e.length===1)return Ra(e[0],t,r,n);let o,i=(0,Gp.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,Ra(s,t,r,n));return o}ye.checkDataTypes=za;var Yx={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function Oa(e){let t=Xx(e);(0,Kx.reportError)(t,Yx)}ye.reportTypeError=Oa;function Xx(e){let{gen:t,data:r,schema:n}=e,o=(0,Gp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Xp=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.assignDefaults=void 0;var fr=C(),e0=B();function t0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Yp(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Yp(e,i,o.default))}Co.assignDefaults=t0;function Yp(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,fr._)`${i}${(0,fr.getProperty)(t)}`;if(o){(0,e0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,fr._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,fr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,fr._)`${a} = ${(0,fr.stringify)(r)}`)}});var je=b(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=C(),Ia=B(),kt=dt(),r0=B();function n0(e,t){let{gen:r,data:n,it:o}=e;r.if(Na(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,X._)`${t}`},!0),e.error()})}K.checkReportMissingProp=n0;function o0({gen:e,data:t,it:{opts:r}},n,o){return(0,X.or)(...n.map(i=>(0,X.and)(Na(e,t,i,r.ownProperties),(0,X._)`${o} = ${i}`)))}K.checkMissingProp=o0;function i0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=i0;function em(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=em;function Aa(e,t,r){return(0,X._)`${em(e)}.call(${t}, ${r})`}K.isOwnProperty=Aa;function s0(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${Aa(e,t,r)}`:o}K.propertyInData=s0;function Na(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(Aa(e,t,r))):o}K.noPropertyInData=Na;function tm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=tm;function a0(e,t){return tm(t).filter(r=>!(0,Ia.alwaysValidSchema)(e,t[r]))}K.schemaProperties=a0;function c0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,X._)`${e}, ${t}, ${n}${o}`:t,d=[[kt.default.instancePath,(0,X.strConcat)(kt.default.instancePath,i)],[kt.default.parentData,s.parentData],[kt.default.parentDataProperty,s.parentDataProperty],[kt.default.rootData,kt.default.rootData]];s.opts.dynamicRef&&d.push([kt.default.dynamicAnchors,kt.default.dynamicAnchors]);let f=(0,X._)`${u}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${f})`:(0,X._)`${a}(${f})`}K.callValidateCode=c0;var u0=(0,X._)`new RegExp`;function l0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,X._)`${o.code==="new RegExp"?u0:(0,r0.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=l0;function d0(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,X._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Ia.Type.Num},i),t.if((0,X.not)(i),a)})}}K.validateArray=d0;function f0(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,Ia.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=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(s,(0,X._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,X.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=f0});var om=b(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.validateKeywordUsage=et.validSchemaType=et.funcKeywordCode=et.macroKeywordCode=void 0;var ke=C(),Ut=dt(),p0=je(),m0=mn();function h0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=nm(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:ke.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}et.macroKeywordCode=h0;function g0(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;_0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=nm(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)h(),t.modifying&&rm(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&rm(e),_(()=>y0(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,ke._)`await `),v=>n.assign(d,!1).if((0,ke._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,ke._)`${v}.errors`),()=>n.throw(v))),w}function m(){let w=(0,ke._)`${u}.errors`;return n.assign(w,null),h(ke.nil),w}function h(w=t.async?(0,ke._)`await `:ke.nil){let v=c.opts.passContext?Ut.default.this:Ut.default.self,x=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,ke._)`${w}${(0,p0.callValidateCode)(e,u,v,x)}`,t.modifying)}function _(w){var v;n.if((0,ke.not)((v=t.valid)!==null&&v!==void 0?v:d),w)}}et.funcKeywordCode=g0;function rm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,ke._)`${n.parentData}[${n.parentDataProperty}]`))}function y0(e,t){let{gen:r}=e;r.if((0,ke._)`Array.isArray(${t})`,()=>{r.assign(Ut.default.vErrors,(0,ke._)`${Ut.default.vErrors} === null ? ${t} : ${Ut.default.vErrors}.concat(${t})`).assign(Ut.default.errors,(0,ke._)`${Ut.default.vErrors}.length`),(0,m0.extendErrors)(e)},()=>e.error())}function _0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function nm(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ke.stringify)(r)})}function w0(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")}et.validSchemaType=w0;function b0({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}et.validateKeywordUsage=b0});var sm=b($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.extendSubschemaMode=$t.extendSubschemaData=$t.getSubschema=void 0;var tt=C(),im=B();function v0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,tt._)`${e.schemaPath}${(0,tt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,tt._)`${e.schemaPath}${(0,tt.getProperty)(t)}${(0,tt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,im.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}$t.getSubschema=v0;function x0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){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,tt._)`${t.data}${(0,tt.getProperty)(r)}`,!0);c(f),e.errorPath=(0,tt.str)`${l}${(0,im.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,tt._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof tt.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);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]}}$t.extendSubschemaData=x0;function k0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}$t.extendSubschemaMode=k0});var Ca=b((YD,am)=>{"use strict";am.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,i;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(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var um=b((XD,cm)=>{"use strict";var St=cm.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(){};Do(t,n,o,e,"",e)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.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 Do(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in St.arrayKeywords)for(var f=0;f<d.length;f++)Do(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in St.propsKeywords){if(d&&typeof d=="object")for(var p in d)Do(e,t,r,d[p],o+"/"+u+"/"+$0(p),i,o,u,n,p)}else(u in St.keywords||e.allKeys&&!(u in St.skipKeywords))&&Do(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function $0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var gn=b(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getSchemaRefs=Pe.resolveUrl=Pe.normalizeId=Pe._getFullPath=Pe.getFullPath=Pe.inlineRef=void 0;var S0=B(),E0=Ca(),T0=um(),P0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function R0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Da(e):t?lm(e)<=t:!1}Pe.inlineRef=R0;var z0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Da(e){for(let t in e){if(z0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Da)||typeof r=="object"&&Da(r))return!0}return!1}function lm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!P0.has(r)&&(typeof e[r]=="object"&&(0,S0.eachItem)(e[r],n=>t+=lm(n)),t===1/0))return 1/0}return t}function dm(e,t="",r){r!==!1&&(t=pr(t));let n=e.parse(t);return fm(e,n)}Pe.getFullPath=dm;function fm(e,t){return e.serialize(t).split("#")[0]+"#"}Pe._getFullPath=fm;var O0=/#\/?$/;function pr(e){return e?e.replace(O0,""):""}Pe.normalizeId=pr;function I0(e,t,r){return r=pr(r),e.resolve(t,r)}Pe.resolveUrl=I0;var A0=/^[a-z_][-a-z0-9._]*$/i;function N0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=pr(e[r]||t),i={"":o},s=dm(n,o,!1),a={},c=new Set;return T0(e,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=s+f,_=i[m];typeof d[r]=="string"&&(_=w.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[f]=_;function w(x){let P=this.opts.uriResolver.resolve;if(x=pr(_?P(_,x):x),c.has(x))throw u(x);c.add(x);let O=this.refs[x];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(d,O.schema,x):x!==pr(h)&&(x[0]==="#"?(l(d,a[x],x),a[x]=d):this.refs[x]=h),x}function v(x){if(typeof x=="string"){if(!A0.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function l(d,f,p){if(f!==void 0&&!E0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Pe.getSchemaRefs=N0});var wn=b(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.getData=Et.KeywordCxt=Et.validateFunctionCode=void 0;var ym=Kp(),pm=hn(),Ma=Pa(),jo=hn(),C0=Xp(),_n=om(),ja=sm(),S=C(),A=dt(),D0=gn(),ft=B(),yn=mn();function j0(e){if(bm(e)&&(vm(e),wm(e))){L0(e);return}_m(e,()=>(0,ym.topBoolOrEmptySchema)(e))}Et.validateFunctionCode=j0;function _m({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${mm(r,o)}`),q0(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${M0(o)}`,n.$async,()=>e.code(mm(r,o)).code(i))}function M0(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function q0(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function L0(e){let{schema:t,opts:r,gen:n}=e;_m(e,()=>{r.$comment&&t.$comment&&km(e),V0(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&B0(e),xm(e),W0(e)})}function B0(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function mm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function Z0(e,t){if(bm(e)&&(vm(e),wm(e))){U0(e,t);return}(0,ym.boolOrEmptySchema)(e,t)}function wm({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 bm(e){return typeof e.schema!="boolean"}function U0(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&km(e),K0(e),H0(e);let i=n.const("_errs",A.default.errors);xm(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function vm(e){(0,ft.checkUnknownRules)(e),F0(e)}function xm(e,t){if(e.opts.jtd)return hm(e,[],!1,t);let r=(0,pm.getSchemaTypes)(e.schema),n=(0,pm.coerceAndCheckDataType)(e,r);hm(e,r,!n,t)}function F0(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ft.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function V0(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ft.checkStrictMode)(e,"default is ignored in the schema root")}function K0(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,D0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function H0(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function km({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function W0(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&G0(e),t.return((0,S._)`${A.default.errors} === 0`))}function G0({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function hm(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ft.schemaHasRulesButRef)(i,u))){o.block(()=>Sm(e,"$ref",u.all.$ref.definition));return}c.jtd||J0(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ma.shouldUseGroup)(i,f)&&(f.type?(o.if((0,jo.checkDataType)(f.type,s,c.strictNumbers)),gm(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,jo.reportTypeError)(e)),o.endIf()):gm(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function gm(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,C0.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ma.shouldUseRule)(n,i)&&Sm(e,i.keyword,i.definition,t.type)})}function J0(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Q0(e,t),e.opts.allowUnionTypes||Y0(e,t),X0(e,e.dataTypes))}function Q0(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{$m(e.dataTypes,r)||qa(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),tk(e,t)}}function Y0(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&qa(e,"use allowUnionTypes to allow union type keyword")}function X0(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ma.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>ek(t,s))&&qa(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function ek(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function $m(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function tk(e,t){let r=[];for(let n of e.dataTypes)$m(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function qa(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ft.checkStrictMode)(e,t,e.opts.strictTypes)}var Mo=class{constructor(t,r,n){if((0,_n.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,ft.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",Em(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,_n.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",A.default.errors))}result(t,r,n){this.failResult((0,S.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,S.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,S._)`${r} !== undefined && (${(0,S.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?yn.reportExtraError:yn.reportError)(this,this.def.error,r)}$dataError(){(0,yn.reportError)(this,this.def.$dataError||yn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yn.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=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,jo.checkDataTypes)(c,r,i.opts.strictNumbers,jo.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,ja.getSubschema)(this.it,t);(0,ja.extendSubschemaData)(n,this.it,t),(0,ja.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return Z0(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ft.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ft.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,S.Name)),!0}};Et.KeywordCxt=Mo;function Sm(e,t,r,n){let o=new Mo(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,_n.funcKeywordCode)(o,r):"macro"in r?(0,_n.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,_n.funcKeywordCode)(o,r)}var rk=/^\/(?:[^~]|~0|~1)*$/,nk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Em(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!rk.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=nk.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(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,ft.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Et.getData=Em});var qo=b(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});var La=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ba.default=La});var bn=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Za=gn(),Ua=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Za.resolveUrl)(t,r,n),this.missingSchema=(0,Za.normalizeId)((0,Za.getFullPath)(t,this.missingRef))}};Fa.default=Ua});var Bo=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.resolveSchema=Me.getCompilingSchema=Me.resolveRef=Me.compileSchema=Me.SchemaEnv=void 0;var Ve=C(),ok=qo(),Ft=dt(),Ke=gn(),Tm=B(),ik=wn(),mr=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,Ke.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Me.SchemaEnv=mr;function Ka(e){let t=Pm.call(this,e);if(t)return t;let r=(0,Ke.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Ve.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:ok.default,code:(0,Ve._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Ft.default.data,parentData:Ft.default.parentData,parentDataProperty:Ft.default.parentDataProperty,dataNames:[Ft.default.data],dataPathArr:[Ve.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ve.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ve.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ve._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,ik.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Ft.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Ft.default.self}`,`${Ft.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof Ve.Name?void 0:m,items:h instanceof Ve.Name?void 0:h,dynamicProps:m instanceof Ve.Name,dynamicItems:h instanceof Ve.Name},p.source&&(p.source.evaluated=(0,Ve.stringify)(p.evaluated))}return e.validate=p,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)}}Me.compileSchema=Ka;function sk(e,t,r){var n;r=(0,Ke.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=uk.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new mr({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=ak.call(this,i)}Me.resolveRef=sk;function ak(e){return(0,Ke.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Ka.call(this,e)}function Pm(e){for(let t of this._compilations)if(ck(t,e))return t}Me.getCompilingSchema=Pm;function ck(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function uk(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Lo.call(this,e,t)}function Lo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ke._getFullPath)(this.opts.uriResolver,r),o=(0,Ke.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Va.call(this,r,e);let i=(0,Ke.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Lo.call(this,e,s);return typeof a?.schema!="object"?void 0:Va.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Ka.call(this,s),i===(0,Ke.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ke.resolveUrl)(this.opts.uriResolver,o,l)),new mr({schema:a,schemaId:c,root:e,baseId:o})}return Va.call(this,r,s)}}Me.resolveSchema=Lo;var lk=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Va(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,Tm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!lk.has(a)&&l&&(t=(0,Ke.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Tm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ke.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Lo.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new mr({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var Rm=b((ij,dk)=>{dk.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 Ga=b((sj,Cm)=>{"use strict";var fk=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Om=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),Ha=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Im=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),pk=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Wa(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 mk=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function zm(e){return e.length=0,!0}function hk(e,t,r){if(e.length){let n=Wa(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function gk(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=hk;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=zm}else{o.push(l);continue}}return o.length&&(a===zm?r.zone=o.join(""):s?n.push(o.join("")):n.push(Wa(o))),r.address=n.join(""),r}function Am(e){if(yk(e,":")<2)return{host:e,isIPV6:!1};let t=gk(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 yk(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function _k(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 wk={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},bk=/[@/?#:]/g,vk=/[@/?#]/g;function Nm(e,t){let r=t?vk:bk;return r.lastIndex=0,e.replace(r,n=>wk[n])}function xk(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(Ha(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&Im(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function kk(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(Ha(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Im(i)?t+=i:t+="%"+o,r+=2;continue}}pk(e[r])?t+=e[r]:t+=escape(e[r])}return t}function $k(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(Ha(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Sk(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Om(r)){let n=Am(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Nm(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}Cm.exports={nonSimpleDomain:mk,recomposeAuthority:Sk,reescapeHostDelimiters:Nm,normalizePercentEncoding:xk,normalizePathEncoding:kk,escapePreservingEscapes:$k,removeDotSegments:_k,isIPv4:Om,isUUID:fk,normalizeIPv6:Am,stringArrayToHexStripped:Wa}});var Lm=b((aj,qm)=>{"use strict";var{isUUID:Ek}=Ga(),Tk=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Pk=["http","https","ws","wss","urn","urn:uuid"];function Rk(e){return Pk.indexOf(e)!==-1}function Ja(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 Dm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function jm(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 zk(e){return e.secure=Ja(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Ok(e){if((e.port===(Ja(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 Ik(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Tk);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}`,i=Qa(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Ak(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}`,i=Qa(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function Nk(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Ek(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Ck(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Mm={scheme:"http",domainHost:!0,parse:Dm,serialize:jm},Dk={scheme:"https",domainHost:Mm.domainHost,parse:Dm,serialize:jm},Zo={scheme:"ws",domainHost:!0,parse:zk,serialize:Ok},jk={scheme:"wss",domainHost:Zo.domainHost,parse:Zo.parse,serialize:Zo.serialize},Mk={scheme:"urn",parse:Ik,serialize:Ak,skipNormalize:!0},qk={scheme:"urn:uuid",parse:Nk,serialize:Ck,skipNormalize:!0},Uo={http:Mm,https:Dk,ws:Zo,wss:jk,urn:Mk,"urn:uuid":qk};Object.setPrototypeOf(Uo,null);function Qa(e){return e&&(Uo[e]||Uo[e.toLowerCase()])||void 0}qm.exports={wsIsSecure:Ja,SCHEMES:Uo,isValidSchemeName:Rk,getSchemeHandler:Qa}});var Km=b((cj,Fo)=>{"use strict";var{normalizeIPv6:Lk,removeDotSegments:vn,recomposeAuthority:Bk,normalizePercentEncoding:Zk,normalizePathEncoding:Uk,escapePreservingEscapes:Fk,reescapeHostDelimiters:Vk,isIPv4:Kk,nonSimpleDomain:Hk}=Ga(),{SCHEMES:Wk,getSchemeHandler:Zm}=Lm();function Gk(e,t){return typeof e=="string"?e=e$(e,t):typeof e=="object"&&(e=hr(Vt(e,t),t)),e}function Jk(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Um(hr(e,n),hr(t,n),n,!0);return n.skipEscape=!0,Vt(o,n)}function Um(e,t,r,n){let o={};return n||(e=hr(Vt(e,r),r),t=hr(Vt(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=vn(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=vn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=vn(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=vn(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 Qk(e,t,r){let n=Bm(e,r),o=Bm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Vt(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=[],i=Zm(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Zk(r.path):(r.path=Fk(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=Bk(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=vn(a)),s===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 Yk=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Xk(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 Fm(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,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(Yk);if(s){n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]);let a=Xk(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(Kk(n.host)===!1){let u=Lk(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!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 c=Zm(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&Hk(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Vk(unescape(n.host),i))),n.path&&(n.path=Uk(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function hr(e,t){return Fm(e,t).parsed}function e$(e,t){return Vm(e,t).normalized}function Vm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Fm(e,t);return{normalized:n?e:Vt(r,t),malformedAuthorityOrPort:n}}function Bm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Vm(e,t);return n?void 0:r}if(typeof e=="object")return Vt(e,t)}var Ya={SCHEMES:Wk,normalize:Gk,resolve:Jk,resolveComponent:Um,equal:Qk,serialize:Vt,parse:hr};Fo.exports=Ya;Fo.exports.default=Ya;Fo.exports.fastUri=Ya});var Wm=b(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var Hm=Km();Hm.code='require("ajv/dist/runtime/uri").default';Xa.default=Hm});var rh=b(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=void 0;var t$=wn();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return t$.KeywordCxt}});var gr=C();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return gr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return gr.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return gr.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return gr.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return gr.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return gr.CodeGen}});var r$=qo(),Xm=bn(),n$=Ta(),xn=Bo(),o$=C(),kn=gn(),Vo=hn(),tc=B(),Gm=Rm(),i$=Wm(),eh=(e,t)=>new RegExp(e,t);eh.code="new RegExp";var s$=["removeAdditional","useDefaults","coerceTypes"],a$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),c$={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},u$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Jm=200;function l$(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,v,x,P,O,be,Ie,er,Mi;let Dr=e.strict,qi=(t=e.code)===null||t===void 0?void 0:t.optimize,nl=qi===!0||qi===void 0?1:qi||0,ol=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:eh,K_=(o=e.uriResolver)!==null&&o!==void 0?o:i$.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Dr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Dr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Dr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Dr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Dr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:nl,regExp:ol}:{optimize:nl,regExp:ol},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Jm,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Jm,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(O=e.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(be=e.validateSchema)!==null&&be!==void 0?be:!0,validateFormats:(Ie=e.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(er=e.unicodeRegExp)!==null&&er!==void 0?er:!0,int32range:(Mi=e.int32range)!==null&&Mi!==void 0?Mi:!0,uriResolver:K_}}var $n=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,...l$(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new o$.ValueScope({scope:{},prefixes:a$,es5:r,lines:n}),this.logger=g$(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,n$.getRules)(),Qm.call(this,c$,t,"NOT SUPPORTED"),Qm.call(this,u$,t,"DEPRECATED","warn"),this._metaOpts=m$.call(this),t.formats&&f$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&p$.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),d$.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Gm;n==="id"&&(o={...Gm},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 i.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||s.call(this,f)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Xm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.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 i.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 s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,kn.normalizeId)(r||i),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 i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=Ym.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xn.SchemaEnv({schema:{},schemaId:n});if(r=xn.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=Ym.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,kn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(_$.call(this,n,r),!r)return(0,tc.eachItem)(n,i=>ec.call(this,i)),this;b$.call(this,r);let o={...r,type:(0,Vo.getJSONTypes)(r.type),schemaType:(0,Vo.getJSONTypes)(r.schemaType)};return(0,tc.eachItem)(n,o.type.length===0?i=>ec.call(this,i,o):i=>o.type.forEach(s=>ec.call(this,i,o,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(i=>i.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,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=th(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,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,kn.normalizeId)(s||n);let l=kn.getSchemaRefs.call(this,t,n);return c=new xn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!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):xn.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{xn.compileSchema.call(this,t)}finally{this.opts=r}}};$n.ValidationError=r$.default;$n.MissingRefError=Xm.default;fe.default=$n;function Qm(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function Ym(e){return e=(0,kn.normalizeId)(e),this.schemas[e]||this.refs[e]}function d$(){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 f$(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function p$(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 m$(){let e={...this.opts};for(let t of s$)delete e[t];return e}var h$={log(){},warn(){},error(){}};function g$(e){if(e===!1)return h$;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 y$=/^[a-z_$][a-z0-9_$:-]*$/i;function _$(e,t){let{RULES:r}=this;if((0,tc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!y$.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 ec(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Vo.getJSONTypes)(t.type),schemaType:(0,Vo.getJSONTypes)(t.schemaType)}};t.before?w$.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function w$(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 b$(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=th(t)),e.validateSchema=this.compile(t,!0))}var v$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function th(e){return{anyOf:[e,v$]}}});var nh=b(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var x$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rc.default=x$});var ah=b(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.callRef=Kt.getValidate=void 0;var k$=bn(),oh=je(),Re=C(),yr=dt(),ih=Bo(),Ko=B(),$$={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=ih.resolveRef.call(c,l,o,r);if(u===void 0)throw new k$.default(n.opts.uriResolver,o,r);if(u instanceof ih.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return Ho(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return Ho(e,(0,Re._)`${m}.validate`,l,l.$async)}function f(m){let h=sh(e,m);Ho(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Re.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Re.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function sh(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Re._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Kt.getValidate=sh;function Ho(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?yr.default.this:Re.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Re._)`await ${(0,oh.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Re._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,oh.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Re._)`${m}.errors`;o.assign(yr.default.vErrors,(0,Re._)`${yr.default.vErrors} === null ? ${h} : ${yr.default.vErrors}.concat(${h})`),o.assign(yr.default.errors,(0,Re._)`${yr.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let _=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=Ko.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Re._)`${m}.evaluated.props`);i.props=Ko.mergeEvaluated.props(o,w,i.props,Re.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=Ko.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Re._)`${m}.evaluated.items`);i.items=Ko.mergeEvaluated.items(o,w,i.items,Re.Name)}}}Kt.callRef=Ho;Kt.default=$$});var ch=b(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var S$=nh(),E$=ah(),T$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",S$.default,E$.default];nc.default=T$});var uh=b(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Wo=C(),Tt=Wo.operators,Go={maximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},minimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},exclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},exclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},P$={message:({keyword:e,schemaCode:t})=>(0,Wo.str)`must be ${Go[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Wo._)`{comparison: ${Go[e].okStr}, limit: ${t}}`},R$={keyword:Object.keys(Go),type:"number",schemaType:"number",$data:!0,error:P$,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Wo._)`${r} ${Go[t].fail} ${n} || isNaN(${r})`)}};oc.default=R$});var lh=b(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Sn=C(),z$={message:({schemaCode:e})=>(0,Sn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Sn._)`{multipleOf: ${e}}`},O$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:z$,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,Sn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Sn._)`${s} !== parseInt(${s})`;e.fail$data((0,Sn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};ic.default=O$});var fh=b(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});function dh(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}sc.default=dh;dh.code='require("ajv/dist/runtime/ucs2length").default'});var ph=b(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Ht=C(),I$=B(),A$=fh(),N$={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Ht.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Ht._)`{limit: ${e}}`},C$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:N$,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Ht.operators.GT:Ht.operators.LT,s=o.opts.unicode===!1?(0,Ht._)`${r}.length`:(0,Ht._)`${(0,I$.useFunc)(e.gen,A$.default)}(${r})`;e.fail$data((0,Ht._)`${s} ${i} ${n}`)}};ac.default=C$});var mh=b(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var D$=je(),j$=B(),_r=C(),M$={message:({schemaCode:e})=>(0,_r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,_r._)`{pattern: ${e}}`},q$={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:M$,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,_r._)`new RegExp`:(0,j$.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,_r._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,_r._)`!${u}`)}else{let c=(0,D$.usePattern)(e,o);e.fail$data((0,_r._)`!${c}.test(${r})`)}}};cc.default=q$});var hh=b(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var En=C(),L$={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,En.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,En._)`{limit: ${e}}`},B$={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:L$,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?En.operators.GT:En.operators.LT;e.fail$data((0,En._)`Object.keys(${r}).length ${o} ${n}`)}};uc.default=B$});var gh=b(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Tn=je(),Pn=C(),Z$=B(),U$={message:({params:{missingProperty:e}})=>(0,Pn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Pn._)`{missingProperty: ${e}}`},F$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:U$,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(p?.[h]===void 0&&!m.has(h)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${h}" is not defined at "${_}" (strictRequired)`;(0,Z$.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(Pn.nil,d);else for(let p of r)(0,Tn.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(c||i){let m=t.let("valid",!0);e.block$data(m,()=>f(p,m)),e.ok(m)}else t.if((0,Tn.checkMissingProp)(e,r,p)),(0,Tn.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Tn.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,Tn.propertyInData)(t,o,p,a.ownProperties)),t.if((0,Pn.not)(m),()=>{e.error(),t.break()})},Pn.nil)}}};lc.default=F$});var yh=b(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Rn=C(),V$={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Rn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Rn._)`{limit: ${e}}`},K$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:V$,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Rn.operators.GT:Rn.operators.LT;e.fail$data((0,Rn._)`${r}.length ${o} ${n}`)}};dc.default=K$});var Jo=b(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var _h=Ca();_h.code='require("ajv/dist/runtime/equal").default';fc.default=_h});var wh=b(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var pc=hn(),pe=C(),H$=B(),W$=Jo(),G$={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},J$={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:G$,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=i.items?(0,pc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,pe._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,pe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let _=t.name("item"),w=(0,pc.checkDataTypes)(l,_,a.opts.strictNumbers,pc.DataType.Wrong),v=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${m}--;`,()=>{t.let(_,(0,pe._)`${r}[${m}]`),t.if(w,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${v}[${_}] == "number"`,()=>{t.assign(h,(0,pe._)`${v}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${v}[${_}] = ${m}`)})}function p(m,h){let _=(0,H$.useFunc)(t,W$.default),w=t.name("outer");t.label(w).for((0,pe._)`;${m}--;`,()=>t.for((0,pe._)`${h} = ${m}; ${h}--;`,()=>t.if((0,pe._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};mc.default=J$});var bh=b(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var hc=C(),Q$=B(),Y$=Jo(),X$={message:"must be equal to constant",params:({schemaCode:e})=>(0,hc._)`{allowedValue: ${e}}`},eS={keyword:"const",$data:!0,error:X$,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,hc._)`!${(0,Q$.useFunc)(t,Y$.default)}(${r}, ${o})`):e.fail((0,hc._)`${i} !== ${r}`)}};gc.default=eS});var vh=b(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var zn=C(),tS=B(),rS=Jo(),nS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,zn._)`{allowedValues: ${e}}`},oS={keyword:"enum",schemaType:"array",$data:!0,error:nS,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,tS.useFunc)(t,rS.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 p=t.const("vSchema",i);u=(0,zn.or)(...o.map((m,h)=>f(p,h)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",i,p=>t.if((0,zn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,zn._)`${l()}(${r}, ${p}[${m}])`:(0,zn._)`${r} === ${h}`}}};yc.default=oS});var xh=b(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var iS=uh(),sS=lh(),aS=ph(),cS=mh(),uS=hh(),lS=gh(),dS=yh(),fS=wh(),pS=bh(),mS=vh(),hS=[iS.default,sS.default,aS.default,cS.default,uS.default,lS.default,dS.default,fS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},pS.default,mS.default];_c.default=hS});var bc=b(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.validateAdditionalItems=void 0;var Wt=C(),wc=B(),gS={message:({params:{len:e}})=>(0,Wt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Wt._)`{limit: ${e}}`},yS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:gS,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,wc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}kh(e,n)}};function kh(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Wt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Wt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,wc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Wt._)`${a} <= ${t.length}`);r.if((0,Wt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:wc.Type.Num},l),s.allErrors||r.if((0,Wt.not)(l),()=>r.break())})}}On.validateAdditionalItems=kh;On.default=yS});var vc=b(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.validateTuple=void 0;var $h=C(),Qo=B(),_S=je(),wS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Sh(e,"additionalItems",t);r.items=!0,!(0,Qo.alwaysValidSchema)(r,t)&&e.ok((0,_S.validateArray)(e))}};function Sh(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Qo.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,$h._)`${i}.length`);r.forEach((d,f)=>{(0,Qo.alwaysValidSchema)(a,d)||(n.if((0,$h._)`${l} > ${f}`,()=>e.subschema({keyword:s,schemaProp:f,dataProp:f},c)),e.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(f.strictTuples&&!h){let _=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,Qo.checkStrictMode)(a,_,f.strictTuples)}}}In.validateTuple=Sh;In.default=wS});var Eh=b(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var bS=vc(),vS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,bS.validateTuple)(e,"items")};xc.default=vS});var Ph=b(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var Th=C(),xS=B(),kS=je(),$S=bc(),SS={message:({params:{len:e}})=>(0,Th.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Th._)`{limit: ${e}}`},ES={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:SS,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,xS.alwaysValidSchema)(n,t)&&(o?(0,$S.validateAdditionalItems)(e,o):e.ok((0,kS.validateArray)(e)))}};kc.default=ES});var Rh=b($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var qe=C(),Yo=B(),TS={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}}`},PS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:TS,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:l}=n;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=t.const("len",(0,qe._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Yo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Yo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Yo.alwaysValidSchema)(i,r)){let h=(0,qe._)`${u} >= ${s}`;a!==void 0&&(h=(0,qe._)`${h} && ${u} <= ${a}`),e.pass(h);return}i.items=!0;let d=t.name("valid");a===void 0&&s===1?p(d,()=>t.if(d,()=>t.break())):s===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 h=t.name("_valid"),_=t.let("count",0);p(h,()=>t.if(h,()=>m(_)))}function p(h,_){t.forRange("i",0,u,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Yo.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,qe._)`${h}++`),a===void 0?t.if((0,qe._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,qe._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,qe._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};$c.default=PS});var Ih=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.validateSchemaDeps=rt.validatePropertyDeps=rt.error=void 0;var Sc=C(),RS=B(),An=je();rt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Sc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Sc._)`{property: ${e},
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function t0({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function Pa(e,t,r,n=dr.Correct){let o=n===dr.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===dr.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}ye.checkDataType=Pa;function za(e,t,r,n){if(e.length===1)return Pa(e[0],t,r,n);let o,i=(0,Jp.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,Pa(s,t,r,n));return o}ye.checkDataTypes=za;var r0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function Oa(e){let t=n0(e);(0,Jx.reportError)(t,r0)}ye.reportTypeError=Oa;function n0(e){let{gen:t,data:r,schema:n}=e,o=(0,Jp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var em=v(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.assignDefaults=void 0;var fr=C(),o0=B();function i0(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Xp(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Xp(e,i,o.default))}Co.assignDefaults=i0;function Xp(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,fr._)`${i}${(0,fr.getProperty)(t)}`;if(o){(0,o0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,fr._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,fr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,fr._)`${a} = ${(0,fr.stringify)(r)}`)}});var je=v(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=C(),Ia=B(),kt=lt(),s0=B();function a0(e,t){let{gen:r,data:n,it:o}=e;r.if(Na(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,X._)`${t}`},!0),e.error()})}K.checkReportMissingProp=a0;function c0({gen:e,data:t,it:{opts:r}},n,o){return(0,X.or)(...n.map(i=>(0,X.and)(Na(e,t,i,r.ownProperties),(0,X._)`${o} = ${i}`)))}K.checkMissingProp=c0;function u0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=u0;function tm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=tm;function Aa(e,t,r){return(0,X._)`${tm(e)}.call(${t}, ${r})`}K.isOwnProperty=Aa;function l0(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${Aa(e,t,r)}`:o}K.propertyInData=l0;function Na(e,t,r,n){let o=(0,X._)`${t}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(Aa(e,t,r))):o}K.noPropertyInData=Na;function rm(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=rm;function d0(e,t){return rm(t).filter(r=>!(0,Ia.alwaysValidSchema)(e,t[r]))}K.schemaProperties=d0;function f0({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,X._)`${e}, ${t}, ${n}${o}`:t,d=[[kt.default.instancePath,(0,X.strConcat)(kt.default.instancePath,i)],[kt.default.parentData,s.parentData],[kt.default.parentDataProperty,s.parentDataProperty],[kt.default.rootData,kt.default.rootData]];s.opts.dynamicRef&&d.push([kt.default.dynamicAnchors,kt.default.dynamicAnchors]);let f=(0,X._)`${u}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${f})`:(0,X._)`${a}(${f})`}K.callValidateCode=f0;var p0=(0,X._)`new RegExp`;function m0({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,X._)`${o.code==="new RegExp"?p0:(0,s0.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=m0;function h0(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,X._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Ia.Type.Num},i),t.if((0,X.not)(i),a)})}}K.validateArray=h0;function g0(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,Ia.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=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(s,(0,X._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,X.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=g0});var im=v(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateKeywordUsage=Xe.validSchemaType=Xe.funcKeywordCode=Xe.macroKeywordCode=void 0;var ke=C(),Ut=lt(),y0=je(),_0=mn();function w0(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=om(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:ke.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Xe.macroKeywordCode=w0;function v0(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;x0(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=om(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)h(),t.modifying&&nm(e),_(()=>e.error());else{let w=t.async?p():m();t.modifying&&nm(e),_(()=>b0(e,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,ke._)`await `),b=>n.assign(d,!1).if((0,ke._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,ke._)`${b}.errors`),()=>n.throw(b))),w}function m(){let w=(0,ke._)`${u}.errors`;return n.assign(w,null),h(ke.nil),w}function h(w=t.async?(0,ke._)`await `:ke.nil){let b=c.opts.passContext?Ut.default.this:Ut.default.self,x=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,ke._)`${w}${(0,y0.callValidateCode)(e,u,b,x)}`,t.modifying)}function _(w){var b;n.if((0,ke.not)((b=t.valid)!==null&&b!==void 0?b:d),w)}}Xe.funcKeywordCode=v0;function nm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,ke._)`${n.parentData}[${n.parentDataProperty}]`))}function b0(e,t){let{gen:r}=e;r.if((0,ke._)`Array.isArray(${t})`,()=>{r.assign(Ut.default.vErrors,(0,ke._)`${Ut.default.vErrors} === null ? ${t} : ${Ut.default.vErrors}.concat(${t})`).assign(Ut.default.errors,(0,ke._)`${Ut.default.vErrors}.length`),(0,_0.extendErrors)(e)},()=>e.error())}function x0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function om(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,ke.stringify)(r)})}function k0(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")}Xe.validSchemaType=k0;function $0({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Xe.validateKeywordUsage=$0});var am=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.extendSubschemaMode=$t.extendSubschemaData=$t.getSubschema=void 0;var et=C(),sm=B();function S0(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,et._)`${e.schemaPath}${(0,et.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,et._)`${e.schemaPath}${(0,et.getProperty)(t)}${(0,et.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,sm.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}$t.getSubschema=S0;function E0(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){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,et._)`${t.data}${(0,et.getProperty)(r)}`,!0);c(f),e.errorPath=(0,et.str)`${l}${(0,sm.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,et._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof et.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);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]}}$t.extendSubschemaData=E0;function T0(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}$t.extendSubschemaMode=T0});var Ca=v((oj,cm)=>{"use strict";cm.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,i;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(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var lm=v((ij,um)=>{"use strict";var St=um.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(){};Do(t,n,o,e,"",e)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.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 Do(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in St.arrayKeywords)for(var f=0;f<d.length;f++)Do(e,t,r,d[f],o+"/"+u+"/"+f,i,o,u,n,f)}else if(u in St.propsKeywords){if(d&&typeof d=="object")for(var p in d)Do(e,t,r,d[p],o+"/"+u+"/"+R0(p),i,o,u,n,p)}else(u in St.keywords||e.allKeys&&!(u in St.skipKeywords))&&Do(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function R0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var gn=v(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.getSchemaRefs=Re.resolveUrl=Re.normalizeId=Re._getFullPath=Re.getFullPath=Re.inlineRef=void 0;var P0=B(),z0=Ca(),O0=lm(),I0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function A0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Da(e):t?dm(e)<=t:!1}Re.inlineRef=A0;var N0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Da(e){for(let t in e){if(N0.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Da)||typeof r=="object"&&Da(r))return!0}return!1}function dm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!I0.has(r)&&(typeof e[r]=="object"&&(0,P0.eachItem)(e[r],n=>t+=dm(n)),t===1/0))return 1/0}return t}function fm(e,t="",r){r!==!1&&(t=pr(t));let n=e.parse(t);return pm(e,n)}Re.getFullPath=fm;function pm(e,t){return e.serialize(t).split("#")[0]+"#"}Re._getFullPath=pm;var C0=/#\/?$/;function pr(e){return e?e.replace(C0,""):""}Re.normalizeId=pr;function D0(e,t,r){return r=pr(r),e.resolve(t,r)}Re.resolveUrl=D0;var j0=/^[a-z_][-a-z0-9._]*$/i;function M0(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=pr(e[r]||t),i={"":o},s=fm(n,o,!1),a={},c=new Set;return O0(e,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=s+f,_=i[m];typeof d[r]=="string"&&(_=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[f]=_;function w(x){let R=this.opts.uriResolver.resolve;if(x=pr(_?R(_,x):x),c.has(x))throw u(x);c.add(x);let O=this.refs[x];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(d,O.schema,x):x!==pr(h)&&(x[0]==="#"?(l(d,a[x],x),a[x]=d):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!j0.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function l(d,f,p){if(f!==void 0&&!z0(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Re.getSchemaRefs=M0});var wn=v(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.getData=Et.KeywordCxt=Et.validateFunctionCode=void 0;var _m=Hp(),mm=hn(),Ma=Ra(),jo=hn(),q0=em(),_n=im(),ja=am(),S=C(),A=lt(),L0=gn(),dt=B(),yn=mn();function B0(e){if(bm(e)&&(xm(e),vm(e))){F0(e);return}wm(e,()=>(0,_m.topBoolOrEmptySchema)(e))}Et.validateFunctionCode=B0;function wm({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${hm(r,o)}`),U0(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${Z0(o)}`,n.$async,()=>e.code(hm(r,o)).code(i))}function Z0(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function U0(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function F0(e){let{schema:t,opts:r,gen:n}=e;wm(e,()=>{r.$comment&&t.$comment&&$m(e),G0(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&V0(e),km(e),Y0(e)})}function V0(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function hm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function K0(e,t){if(bm(e)&&(xm(e),vm(e))){H0(e,t);return}(0,_m.boolOrEmptySchema)(e,t)}function vm({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 bm(e){return typeof e.schema!="boolean"}function H0(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&$m(e),J0(e),Q0(e);let i=n.const("_errs",A.default.errors);km(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function xm(e){(0,dt.checkUnknownRules)(e),W0(e)}function km(e,t){if(e.opts.jtd)return gm(e,[],!1,t);let r=(0,mm.getSchemaTypes)(e.schema),n=(0,mm.coerceAndCheckDataType)(e,r);gm(e,r,!n,t)}function W0(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,dt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function G0(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,dt.checkStrictMode)(e,"default is ignored in the schema root")}function J0(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,L0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Q0(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function $m({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Y0(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&X0(e),t.return((0,S._)`${A.default.errors} === 0`))}function X0({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function gm(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,dt.schemaHasRulesButRef)(i,u))){o.block(()=>Em(e,"$ref",u.all.$ref.definition));return}c.jtd||ek(e,t),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Ma.shouldUseGroup)(i,f)&&(f.type?(o.if((0,jo.checkDataType)(f.type,s,c.strictNumbers)),ym(e,f),t.length===1&&t[0]===f.type&&r&&(o.else(),(0,jo.reportTypeError)(e)),o.endIf()):ym(e,f),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function ym(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,q0.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Ma.shouldUseRule)(n,i)&&Em(e,i.keyword,i.definition,t.type)})}function ek(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(tk(e,t),e.opts.allowUnionTypes||rk(e,t),nk(e,e.dataTypes))}function tk(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Sm(e.dataTypes,r)||qa(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),ik(e,t)}}function rk(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&qa(e,"use allowUnionTypes to allow union type keyword")}function nk(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ma.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>ok(t,s))&&qa(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function ok(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Sm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function ik(e,t){let r=[];for(let n of e.dataTypes)Sm(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function qa(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,dt.checkStrictMode)(e,t,e.opts.strictTypes)}var Mo=class{constructor(t,r,n){if((0,_n.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,dt.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",Tm(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,_n.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",A.default.errors))}result(t,r,n){this.failResult((0,S.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,S.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,S._)`${r} !== undefined && (${(0,S.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?yn.reportExtraError:yn.reportError)(this,this.def.error,r)}$dataError(){(0,yn.reportError)(this,this.def.$dataError||yn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yn.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=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,jo.checkDataTypes)(c,r,i.opts.strictNumbers,jo.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,ja.getSubschema)(this.it,t);(0,ja.extendSubschemaData)(n,this.it,t),(0,ja.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return K0(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=dt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=dt.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,S.Name)),!0}};Et.KeywordCxt=Mo;function Em(e,t,r,n){let o=new Mo(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,_n.funcKeywordCode)(o,r):"macro"in r?(0,_n.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,_n.funcKeywordCode)(o,r)}var sk=/^\/(?:[^~]|~0|~1)*$/,ak=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Tm(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!sk.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=ak.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(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,dt.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}Et.getData=Tm});var qo=v(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});var La=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Ba.default=La});var vn=v(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Za=gn(),Ua=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Za.resolveUrl)(t,r,n),this.missingSchema=(0,Za.normalizeId)((0,Za.getFullPath)(t,this.missingRef))}};Fa.default=Ua});var Bo=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.resolveSchema=Me.getCompilingSchema=Me.resolveRef=Me.compileSchema=Me.SchemaEnv=void 0;var Fe=C(),ck=qo(),Ft=lt(),Ve=gn(),Rm=B(),uk=wn(),mr=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,Ve.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Me.SchemaEnv=mr;function Ka(e){let t=Pm.call(this,e);if(t)return t;let r=(0,Ve.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Fe.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:ck.default,code:(0,Fe._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Ft.default.data,parentData:Ft.default.parentData,parentDataProperty:Ft.default.parentDataProperty,dataNames:[Ft.default.data],dataPathArr:[Fe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Fe.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Fe.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Fe._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,uk.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Ft.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${Ft.default.self}`,`${Ft.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof Fe.Name?void 0:m,items:h instanceof Fe.Name?void 0:h,dynamicProps:m instanceof Fe.Name,dynamicItems:h instanceof Fe.Name},p.source&&(p.source.evaluated=(0,Fe.stringify)(p.evaluated))}return e.validate=p,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)}}Me.compileSchema=Ka;function lk(e,t,r){var n;r=(0,Ve.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=pk.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new mr({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=dk.call(this,i)}Me.resolveRef=lk;function dk(e){return(0,Ve.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Ka.call(this,e)}function Pm(e){for(let t of this._compilations)if(fk(t,e))return t}Me.getCompilingSchema=Pm;function fk(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function pk(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Lo.call(this,e,t)}function Lo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ve._getFullPath)(this.opts.uriResolver,r),o=(0,Ve.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Va.call(this,r,e);let i=(0,Ve.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Lo.call(this,e,s);return typeof a?.schema!="object"?void 0:Va.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Ka.call(this,s),i===(0,Ve.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ve.resolveUrl)(this.opts.uriResolver,o,l)),new mr({schema:a,schemaId:c,root:e,baseId:o})}return Va.call(this,r,s)}}Me.resolveSchema=Lo;var mk=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Va(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,Rm.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!mk.has(a)&&l&&(t=(0,Ve.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Rm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ve.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Lo.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new mr({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var zm=v((dj,hk)=>{hk.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 Ga=v((fj,Dm)=>{"use strict";var gk=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Im=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),Ha=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Am=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),yk=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Wa(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 _k=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Om(e){return e.length=0,!0}function wk(e,t,r){if(e.length){let n=Wa(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function vk(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=wk;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Om}else{o.push(l);continue}}return o.length&&(a===Om?r.zone=o.join(""):s?n.push(o.join("")):n.push(Wa(o))),r.address=n.join(""),r}function Nm(e){if(bk(e,":")<2)return{host:e,isIPV6:!1};let t=vk(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 bk(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function xk(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 kk={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$k=/[@/?#:]/g,Sk=/[@/?#]/g;function Cm(e,t){let r=t?Sk:$k;return r.lastIndex=0,e.replace(r,n=>kk[n])}function Ek(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(Ha(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&Am(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function Tk(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(Ha(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Am(i)?t+=i:t+="%"+o,r+=2;continue}}yk(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Rk(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(Ha(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Pk(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Im(r)){let n=Nm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Cm(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}Dm.exports={nonSimpleDomain:_k,recomposeAuthority:Pk,reescapeHostDelimiters:Cm,normalizePercentEncoding:Ek,normalizePathEncoding:Tk,escapePreservingEscapes:Rk,removeDotSegments:xk,isIPv4:Im,isUUID:gk,normalizeIPv6:Nm,stringArrayToHexStripped:Wa}});var Bm=v((pj,Lm)=>{"use strict";var{isUUID:zk}=Ga(),Ok=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ik=["http","https","ws","wss","urn","urn:uuid"];function Ak(e){return Ik.indexOf(e)!==-1}function Ja(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 jm(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Mm(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 Nk(e){return e.secure=Ja(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Ck(e){if((e.port===(Ja(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 Dk(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Ok);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}`,i=Qa(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function jk(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}`,i=Qa(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function Mk(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!zk(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function qk(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var qm={scheme:"http",domainHost:!0,parse:jm,serialize:Mm},Lk={scheme:"https",domainHost:qm.domainHost,parse:jm,serialize:Mm},Zo={scheme:"ws",domainHost:!0,parse:Nk,serialize:Ck},Bk={scheme:"wss",domainHost:Zo.domainHost,parse:Zo.parse,serialize:Zo.serialize},Zk={scheme:"urn",parse:Dk,serialize:jk,skipNormalize:!0},Uk={scheme:"urn:uuid",parse:Mk,serialize:qk,skipNormalize:!0},Uo={http:qm,https:Lk,ws:Zo,wss:Bk,urn:Zk,"urn:uuid":Uk};Object.setPrototypeOf(Uo,null);function Qa(e){return e&&(Uo[e]||Uo[e.toLowerCase()])||void 0}Lm.exports={wsIsSecure:Ja,SCHEMES:Uo,isValidSchemeName:Ak,getSchemeHandler:Qa}});var Hm=v((mj,Fo)=>{"use strict";var{normalizeIPv6:Fk,removeDotSegments:bn,recomposeAuthority:Vk,normalizePercentEncoding:Kk,normalizePathEncoding:Hk,escapePreservingEscapes:Wk,reescapeHostDelimiters:Gk,isIPv4:Jk,nonSimpleDomain:Qk}=Ga(),{SCHEMES:Yk,getSchemeHandler:Um}=Bm();function Xk(e,t){return typeof e=="string"?e=o$(e,t):typeof e=="object"&&(e=hr(Vt(e,t),t)),e}function e$(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Fm(hr(e,n),hr(t,n),n,!0);return n.skipEscape=!0,Vt(o,n)}function Fm(e,t,r,n){let o={};return n||(e=hr(Vt(e,r),r),t=hr(Vt(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=bn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=bn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=bn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=bn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function t$(e,t,r){let n=Zm(e,r),o=Zm(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Vt(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=[],i=Um(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Kk(r.path):(r.path=Wk(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=Vk(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=bn(a)),s===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 r$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function n$(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 Vm(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,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(r$);if(s){n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]);let a=n$(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(Jk(n.host)===!1){let u=Fk(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!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 c=Um(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&Qk(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Gk(unescape(n.host),i))),n.path&&(n.path=Hk(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function hr(e,t){return Vm(e,t).parsed}function o$(e,t){return Km(e,t).normalized}function Km(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Vm(e,t);return{normalized:n?e:Vt(r,t),malformedAuthorityOrPort:n}}function Zm(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Km(e,t);return n?void 0:r}if(typeof e=="object")return Vt(e,t)}var Ya={SCHEMES:Yk,normalize:Xk,resolve:e$,resolveComponent:Fm,equal:t$,serialize:Vt,parse:hr};Fo.exports=Ya;Fo.exports.default=Ya;Fo.exports.fastUri=Ya});var Gm=v(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var Wm=Hm();Wm.code='require("ajv/dist/runtime/uri").default';Xa.default=Wm});var nh=v(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.CodeGen=fe.Name=fe.nil=fe.stringify=fe.str=fe._=fe.KeywordCxt=void 0;var i$=wn();Object.defineProperty(fe,"KeywordCxt",{enumerable:!0,get:function(){return i$.KeywordCxt}});var gr=C();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return gr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return gr.str}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return gr.stringify}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return gr.nil}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return gr.Name}});Object.defineProperty(fe,"CodeGen",{enumerable:!0,get:function(){return gr.CodeGen}});var s$=qo(),eh=vn(),a$=Ta(),xn=Bo(),c$=C(),kn=gn(),Vo=hn(),tc=B(),Jm=zm(),u$=Gm(),th=(e,t)=>new RegExp(e,t);th.code="new RegExp";var l$=["removeAdditional","useDefaults","coerceTypes"],d$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),f$={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},p$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Qm=200;function m$(e){var t,r,n,o,i,s,a,c,l,u,d,f,p,m,h,_,w,b,x,R,O,ve,Ie,er,Mi;let Dr=e.strict,qi=(t=e.code)===null||t===void 0?void 0:t.optimize,ol=qi===!0||qi===void 0?1:qi||0,il=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:th,J_=(o=e.uriResolver)!==null&&o!==void 0?o:u$.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Dr)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:Dr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:Dr)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=e.strictTuples)!==null&&d!==void 0?d:Dr)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:Dr)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:ol,regExp:il}:{optimize:ol,regExp:il},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Qm,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Qm,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(O=e.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(ve=e.validateSchema)!==null&&ve!==void 0?ve:!0,validateFormats:(Ie=e.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(er=e.unicodeRegExp)!==null&&er!==void 0?er:!0,int32range:(Mi=e.int32range)!==null&&Mi!==void 0?Mi:!0,uriResolver:J_}}var $n=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,...m$(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new c$.ValueScope({scope:{},prefixes:d$,es5:r,lines:n}),this.logger=v$(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,a$.getRules)(),Ym.call(this,f$,t,"NOT SUPPORTED"),Ym.call(this,p$,t,"DEPRECATED","warn"),this._metaOpts=_$.call(this),t.formats&&g$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&y$.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),h$.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Jm;n==="id"&&(o={...Jm},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 i.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||s.call(this,f)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof eh.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.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 i.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 s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,kn.normalizeId)(r||i),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 i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=Xm.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xn.SchemaEnv({schema:{},schemaId:n});if(r=xn.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=Xm.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,kn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(x$.call(this,n,r),!r)return(0,tc.eachItem)(n,i=>ec.call(this,i)),this;$$.call(this,r);let o={...r,type:(0,Vo.getJSONTypes)(r.type),schemaType:(0,Vo.getJSONTypes)(r.schemaType)};return(0,tc.eachItem)(n,o.type.length===0?i=>ec.call(this,i,o):i=>o.type.forEach(s=>ec.call(this,i,o,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(i=>i.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,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=rh(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,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,kn.normalizeId)(s||n);let l=kn.getSchemaRefs.call(this,t,n);return c=new xn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!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):xn.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{xn.compileSchema.call(this,t)}finally{this.opts=r}}};$n.ValidationError=s$.default;$n.MissingRefError=eh.default;fe.default=$n;function Ym(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function Xm(e){return e=(0,kn.normalizeId)(e),this.schemas[e]||this.refs[e]}function h$(){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 g$(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function y$(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 _$(){let e={...this.opts};for(let t of l$)delete e[t];return e}var w$={log(){},warn(){},error(){}};function v$(e){if(e===!1)return w$;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 b$=/^[a-z_$][a-z0-9_$:-]*$/i;function x$(e,t){let{RULES:r}=this;if((0,tc.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!b$.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 ec(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Vo.getJSONTypes)(t.type),schemaType:(0,Vo.getJSONTypes)(t.schemaType)}};t.before?k$.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function k$(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 $$(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=rh(t)),e.validateSchema=this.compile(t,!0))}var S$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rh(e){return{anyOf:[e,S$]}}});var oh=v(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var E$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rc.default=E$});var ch=v(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.callRef=Kt.getValidate=void 0;var T$=vn(),ih=je(),Pe=C(),yr=lt(),sh=Bo(),Ko=B(),R$={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=sh.resolveRef.call(c,l,o,r);if(u===void 0)throw new T$.default(n.opts.uriResolver,o,r);if(u instanceof sh.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return Ho(e,s,i,i.$async);let m=t.scopeValue("root",{ref:l});return Ho(e,(0,Pe._)`${m}.validate`,l,l.$async)}function f(m){let h=ah(e,m);Ho(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Pe.stringify)(m)}:{ref:m}),_=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:h,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function ah(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Kt.getValidate=ah;function Ho(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?yr.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,ih.callValidateCode)(e,t,l)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Pe._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),f(h),s||o.assign(m,!1)}),e.ok(m)}function d(){e.result((0,ih.callValidateCode)(e,t,l),()=>p(t),()=>f(t))}function f(m){let h=(0,Pe._)`${m}.errors`;o.assign(yr.default.vErrors,(0,Pe._)`${yr.default.vErrors} === null ? ${h} : ${yr.default.vErrors}.concat(${h})`),o.assign(yr.default.errors,(0,Pe._)`${yr.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let _=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=Ko.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Pe._)`${m}.evaluated.props`);i.props=Ko.mergeEvaluated.props(o,w,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=Ko.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Pe._)`${m}.evaluated.items`);i.items=Ko.mergeEvaluated.items(o,w,i.items,Pe.Name)}}}Kt.callRef=Ho;Kt.default=R$});var uh=v(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var P$=oh(),z$=ch(),O$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",P$.default,z$.default];nc.default=O$});var lh=v(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Wo=C(),Tt=Wo.operators,Go={maximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},minimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},exclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},exclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},I$={message:({keyword:e,schemaCode:t})=>(0,Wo.str)`must be ${Go[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Wo._)`{comparison: ${Go[e].okStr}, limit: ${t}}`},A$={keyword:Object.keys(Go),type:"number",schemaType:"number",$data:!0,error:I$,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Wo._)`${r} ${Go[t].fail} ${n} || isNaN(${r})`)}};oc.default=A$});var dh=v(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Sn=C(),N$={message:({schemaCode:e})=>(0,Sn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Sn._)`{multipleOf: ${e}}`},C$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:N$,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,Sn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Sn._)`${s} !== parseInt(${s})`;e.fail$data((0,Sn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};ic.default=C$});var ph=v(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});function fh(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}sc.default=fh;fh.code='require("ajv/dist/runtime/ucs2length").default'});var mh=v(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Ht=C(),D$=B(),j$=ph(),M$={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Ht.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Ht._)`{limit: ${e}}`},q$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:M$,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Ht.operators.GT:Ht.operators.LT,s=o.opts.unicode===!1?(0,Ht._)`${r}.length`:(0,Ht._)`${(0,D$.useFunc)(e.gen,j$.default)}(${r})`;e.fail$data((0,Ht._)`${s} ${i} ${n}`)}};ac.default=q$});var hh=v(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var L$=je(),B$=B(),_r=C(),Z$={message:({schemaCode:e})=>(0,_r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,_r._)`{pattern: ${e}}`},U$={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Z$,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,_r._)`new RegExp`:(0,B$.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,_r._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,_r._)`!${u}`)}else{let c=(0,L$.usePattern)(e,o);e.fail$data((0,_r._)`!${c}.test(${r})`)}}};cc.default=U$});var gh=v(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var En=C(),F$={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,En.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,En._)`{limit: ${e}}`},V$={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:F$,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?En.operators.GT:En.operators.LT;e.fail$data((0,En._)`Object.keys(${r}).length ${o} ${n}`)}};uc.default=V$});var yh=v(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Tn=je(),Rn=C(),K$=B(),H$={message:({params:{missingProperty:e}})=>(0,Rn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Rn._)`{missingProperty: ${e}}`},W$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:H$,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(p?.[h]===void 0&&!m.has(h)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${h}" is not defined at "${_}" (strictRequired)`;(0,K$.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(Rn.nil,d);else for(let p of r)(0,Tn.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(c||i){let m=t.let("valid",!0);e.block$data(m,()=>f(p,m)),e.ok(m)}else t.if((0,Tn.checkMissingProp)(e,r,p)),(0,Tn.reportMissingProp)(e,p),t.else()}function d(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Tn.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function f(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,Tn.propertyInData)(t,o,p,a.ownProperties)),t.if((0,Rn.not)(m),()=>{e.error(),t.break()})},Rn.nil)}}};lc.default=W$});var _h=v(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Pn=C(),G$={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Pn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Pn._)`{limit: ${e}}`},J$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:G$,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Pn.operators.GT:Pn.operators.LT;e.fail$data((0,Pn._)`${r}.length ${o} ${n}`)}};dc.default=J$});var Jo=v(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var wh=Ca();wh.code='require("ajv/dist/runtime/equal").default';fc.default=wh});var vh=v(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var pc=hn(),pe=C(),Q$=B(),Y$=Jo(),X$={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},eS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:X$,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=i.items?(0,pc.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let m=t.let("i",(0,pe._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,pe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let _=t.name("item"),w=(0,pc.checkDataTypes)(l,_,a.opts.strictNumbers,pc.DataType.Wrong),b=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${m}--;`,()=>{t.let(_,(0,pe._)`${r}[${m}]`),t.if(w,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(h,(0,pe._)`${b}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${b}[${_}] = ${m}`)})}function p(m,h){let _=(0,Q$.useFunc)(t,Y$.default),w=t.name("outer");t.label(w).for((0,pe._)`;${m}--;`,()=>t.for((0,pe._)`${h} = ${m}; ${h}--;`,()=>t.if((0,pe._)`${_}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};mc.default=eS});var bh=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var hc=C(),tS=B(),rS=Jo(),nS={message:"must be equal to constant",params:({schemaCode:e})=>(0,hc._)`{allowedValue: ${e}}`},oS={keyword:"const",$data:!0,error:nS,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,hc._)`!${(0,tS.useFunc)(t,rS.default)}(${r}, ${o})`):e.fail((0,hc._)`${i} !== ${r}`)}};gc.default=oS});var xh=v(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var zn=C(),iS=B(),sS=Jo(),aS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,zn._)`{allowedValues: ${e}}`},cS={keyword:"enum",schemaType:"array",$data:!0,error:aS,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,iS.useFunc)(t,sS.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 p=t.const("vSchema",i);u=(0,zn.or)(...o.map((m,h)=>f(p,h)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",i,p=>t.if((0,zn._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function f(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,zn._)`${l()}(${r}, ${p}[${m}])`:(0,zn._)`${r} === ${h}`}}};yc.default=cS});var kh=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var uS=lh(),lS=dh(),dS=mh(),fS=hh(),pS=gh(),mS=yh(),hS=_h(),gS=vh(),yS=bh(),_S=xh(),wS=[uS.default,lS.default,dS.default,fS.default,pS.default,mS.default,hS.default,gS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yS.default,_S.default];_c.default=wS});var vc=v(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.validateAdditionalItems=void 0;var Wt=C(),wc=B(),vS={message:({params:{len:e}})=>(0,Wt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Wt._)`{limit: ${e}}`},bS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:vS,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,wc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}$h(e,n)}};function $h(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Wt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Wt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,wc.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Wt._)`${a} <= ${t.length}`);r.if((0,Wt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:wc.Type.Num},l),s.allErrors||r.if((0,Wt.not)(l),()=>r.break())})}}On.validateAdditionalItems=$h;On.default=bS});var bc=v(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.validateTuple=void 0;var Sh=C(),Qo=B(),xS=je(),kS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Eh(e,"additionalItems",t);r.items=!0,!(0,Qo.alwaysValidSchema)(r,t)&&e.ok((0,xS.validateArray)(e))}};function Eh(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Qo.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Sh._)`${i}.length`);r.forEach((d,f)=>{(0,Qo.alwaysValidSchema)(a,d)||(n.if((0,Sh._)`${l} > ${f}`,()=>e.subschema({keyword:s,schemaProp:f,dataProp:f},c)),e.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(f.strictTuples&&!h){let _=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,Qo.checkStrictMode)(a,_,f.strictTuples)}}}In.validateTuple=Eh;In.default=kS});var Th=v(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var $S=bc(),SS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,$S.validateTuple)(e,"items")};xc.default=SS});var Ph=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var Rh=C(),ES=B(),TS=je(),RS=vc(),PS={message:({params:{len:e}})=>(0,Rh.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Rh._)`{limit: ${e}}`},zS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:PS,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,ES.alwaysValidSchema)(n,t)&&(o?(0,RS.validateAdditionalItems)(e,o):e.ok((0,TS.validateArray)(e)))}};kc.default=zS});var zh=v($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var qe=C(),Yo=B(),OS={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}}`},IS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:OS,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:l}=n;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=t.const("len",(0,qe._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Yo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Yo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Yo.alwaysValidSchema)(i,r)){let h=(0,qe._)`${u} >= ${s}`;a!==void 0&&(h=(0,qe._)`${h} && ${u} <= ${a}`),e.pass(h);return}i.items=!0;let d=t.name("valid");a===void 0&&s===1?p(d,()=>t.if(d,()=>t.break())):s===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 h=t.name("_valid"),_=t.let("count",0);p(h,()=>t.if(h,()=>m(_)))}function p(h,_){t.forRange("i",0,u,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Yo.Type.Num,compositeRule:!0},h),_()})}function m(h){t.code((0,qe._)`${h}++`),a===void 0?t.if((0,qe._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,qe._)`${h} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,qe._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};$c.default=IS});var Ah=v(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.validateSchemaDeps=tt.validatePropertyDeps=tt.error=void 0;var Sc=C(),AS=B(),An=je();tt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Sc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Sc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var zS={keyword:"dependencies",type:"object",schemaType:"object",error:rt.error,code(e){let[t,r]=OS(e);zh(e,t),Oh(e,r)}};function OS({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 zh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,An.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,An.checkReportMissingProp)(e,l)}):(r.if((0,Sc._)`${c} && (${(0,An.checkMissingProp)(e,a,i)})`),(0,An.reportMissingProp)(e,i),r.else())}}rt.validatePropertyDeps=zh;function Oh(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,RS.alwaysValidSchema)(i,t[a])||(r.if((0,An.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}rt.validateSchemaDeps=Oh;rt.default=zS});var Nh=b(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Ah=C(),IS=B(),AS={message:"property name must be valid",params:({params:e})=>(0,Ah._)`{propertyName: ${e.propertyName}}`},NS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:AS,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,IS.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,Ah.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Ec.default=NS});var Pc=b(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Xo=je(),He=C(),CS=dt(),ei=B(),DS={message:"must NOT have additional properties",params:({params:e})=>(0,He._)`{additionalProperty: ${e.additionalProperty}}`},jS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:DS,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,ei.alwaysValidSchema)(s,r))return;let l=(0,Xo.allSchemaProperties)(n.properties),u=(0,Xo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,He._)`${i} === ${CS.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?m(_):t.if(f(_),()=>m(_))})}function f(_){let w;if(l.length>8){let v=(0,ei.schemaRefOrVal)(s,n.properties,"properties");w=(0,Xo.isOwnProperty)(t,v,_)}else l.length?w=(0,He.or)(...l.map(v=>(0,He._)`${_} === ${v}`)):w=He.nil;return u.length&&(w=(0,He.or)(w,...u.map(v=>(0,He._)`${(0,Xo.usePattern)(e,v)}.test(${_})`))),(0,He.not)(w)}function p(_){t.code((0,He._)`delete ${o}[${_}]`)}function m(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,ei.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,He.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,He.not)(w),()=>t.break()))}}function h(_,w,v){let x={keyword:"additionalProperties",dataProp:_,dataPropType:ei.Type.Str};v===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(x,w)}}};Tc.default=jS});var jh=b(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var MS=wn(),Ch=je(),Rc=B(),Dh=Pc(),qS={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Dh.default.code(new MS.KeywordCxt(i,Dh.default,"additionalProperties"));let s=(0,Ch.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Rc.mergeEvaluated.props(t,(0,Rc.toHash)(s),i.props));let a=s.filter(d=>!(0,Rc.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Ch.propertyInData)(t,o,d,i.opts.ownProperties)),u(d),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};zc.default=qS});var Bh=b(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Mh=je(),ti=C(),qh=B(),Lh=B(),LS={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,Mh.allSchemaProperties)(r),c=a.filter(h=>(0,qh.alwaysValidSchema)(i,r[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof ti.Name)&&(i.props=(0,Lh.evaluatedPropsToName)(t,i.props));let{props:d}=i;f();function f(){for(let h of a)l&&p(h),i.allErrors?m(h):(t.var(u,!0),m(h),t.if(u))}function p(h){for(let _ in l)new RegExp(h).test(_)&&(0,qh.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,ti._)`${(0,Mh.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:Lh.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,ti._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,ti.not)(u),()=>t.break())})})}}};Oc.default=LS});var Zh=b(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var BS=B(),ZS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,BS.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"}};Ic.default=ZS});var Uh=b(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var US=je(),FS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:US.validateUnion,error:{message:"must match a schema in anyOf"}};Ac.default=FS});var Fh=b(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var ri=C(),VS=B(),KS={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ri._)`{passingSchemas: ${e.passing}}`},HS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:KS,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 i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((u,d)=>{let f;(0,VS.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,ri._)`${c} && ${s}`).assign(s,!1).assign(a,(0,ri._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,ri.Name)})})}}};Nc.default=HS});var Vh=b(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var WS=B(),GS={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((i,s)=>{if((0,WS.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Cc.default=GS});var Wh=b(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ni=C(),Hh=B(),JS={message:({params:e})=>(0,ni.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,ni._)`{failingKeyword: ${e.ifClause}}`},QS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JS,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Hh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Kh(n,"then"),i=Kh(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){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,ni.not)(a),l("else"));e.pass(s,()=>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(s,a),e.mergeValidEvaluated(f,s),d?t.assign(d,(0,ni._)`${u}`):e.setParams({ifClause:u})}}}};function Kh(e,t){let r=e.schema[t];return r!==void 0&&!(0,Hh.alwaysValidSchema)(e,r)}Dc.default=QS});var Gh=b(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var YS=B(),XS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,YS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};jc.default=XS});var Jh=b(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var eE=bc(),tE=Eh(),rE=vc(),nE=Ph(),oE=Rh(),iE=Ih(),sE=Nh(),aE=Pc(),cE=jh(),uE=Bh(),lE=Zh(),dE=Uh(),fE=Fh(),pE=Vh(),mE=Wh(),hE=Gh();function gE(e=!1){let t=[lE.default,dE.default,fE.default,pE.default,mE.default,hE.default,sE.default,aE.default,iE.default,cE.default,uE.default];return e?t.push(tE.default,nE.default):t.push(eE.default,rE.default),t.push(oE.default),t}Mc.default=gE});var Qh=b(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var ie=C(),yE={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},_E={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:yE,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${m}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,ie._)`${h}.type || "string"`).assign(w,(0,ie._)`${h}.validate`),()=>r.assign(_,(0,ie._)`"string"`).assign(w,h)),e.fail$data((0,ie.or)(v(),x()));function v(){return c.strictSchema===!1?ie.nil:(0,ie._)`${s} && !${w}`}function x(){let P=u.$async?(0,ie._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ie._)`${w}(${n})`,O=(0,ie._)`(typeof ${w} == "function" ? ${P} : ${w}.test(${n}))`;return(0,ie._)`${w} && ${w} !== true && ${_} === ${t} && !${O}`}}function p(){let m=d.formats[i];if(!m){v();return}if(m===!0)return;let[h,_,w]=x(m);h===t&&e.pass(P());function v(){if(c.strictSchema===!1){d.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function x(O){let be=O instanceof RegExp?(0,ie.regexpCode)(O):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(i)}`:void 0,Ie=r.scopeValue("formats",{key:i,ref:O,code:be});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,ie._)`${Ie}.validate`]:["string",O,Ie]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${w}(${n})`}return typeof _=="function"?(0,ie._)`${w}(${n})`:(0,ie._)`${w}.test(${n})`}}}};qc.default=_E});var Yh=b(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var wE=Qh(),bE=[wE.default];Lc.default=bE});var Xh=b(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.contentVocabulary=wr.metadataVocabulary=void 0;wr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var tg=b(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var vE=ch(),xE=xh(),kE=Jh(),$E=Yh(),eg=Xh(),SE=[vE.default,xE.default,(0,kE.default)(),$E.default,eg.metadataVocabulary,eg.contentVocabulary];Bc.default=SE});var ng=b(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.DiscrError=void 0;var rg;(function(e){e.Tag="tag",e.Mapping="mapping"})(rg||(oi.DiscrError=rg={}))});var ig=b(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var br=C(),Zc=ng(),og=Bo(),EE=bn(),TE=B(),PE={message:({params:{discrError:e,tagName:t}})=>e===Zc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,br._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},RE={keyword:"discriminator",type:"object",schemaType:"object",error:PE,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.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(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,br._)`${r}${(0,br.getProperty)(a)}`);t.if((0,br._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Zc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let p=f();t.if(!1);for(let m in p)t.elseIf((0,br._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Zc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(p){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(h,br.Name),m}function f(){var p;let m={},h=w(o),_=!0;for(let P=0;P<s.length;P++){let O=s[P];if(O?.$ref&&!(0,TE.schemaHasRulesButRef)(O,i.self.RULES)){let Ie=O.$ref;if(O=og.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ie),O instanceof og.SchemaEnv&&(O=O.schema),O===void 0)throw new EE.default(i.opts.uriResolver,i.baseId,Ie)}let be=(p=O?.properties)===null||p===void 0?void 0:p[a];if(typeof be!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(O)),v(be,P)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:P}){return Array.isArray(P)&&P.includes(a)}function v(P,O){if(P.const)x(P.const,O);else if(P.enum)for(let be of P.enum)x(be,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(P,O){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=O}}}};Uc.default=RE});var sg=b((Jj,zE)=>{zE.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 Vc=b((ee,Fc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var OE=rh(),IE=tg(),AE=ig(),ag=sg(),NE=["/properties"],ii="http://json-schema.org/draft-07/schema",vr=class extends OE.default{_addVocabularies(){super._addVocabularies(),IE.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(AE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(ag,NE):ag;this.addMetaSchema(t,ii,!1),this.refs["http://json-schema.org/schema"]=ii}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ii)?ii:void 0)}};ee.Ajv=vr;Fc.exports=ee=vr;Fc.exports.Ajv=vr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=vr;var CE=wn();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return CE.KeywordCxt}});var xr=C();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return xr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return xr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return xr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return xr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return xr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return xr.CodeGen}});var DE=qo();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return DE.default}});var jE=bn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return jE.default}})});var hg=b(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.formatNames=ot.fastFormats=ot.fullFormats=void 0;function nt(e,t){return{validate:e,compare:t}}ot.fullFormats={date:nt(dg,Gc),time:nt(Hc(!0),Jc),"date-time":nt(cg(!0),pg),"iso-time":nt(Hc(),fg),"iso-date-time":nt(cg(),mg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:UE,"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:JE,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:FE,int32:{type:"number",validate:HE},int64:{type:"number",validate:WE},float:{type:"number",validate:lg},double:{type:"number",validate:lg},password:!0,binary:!0};ot.fastFormats={...ot.fullFormats,date:nt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Gc),time:nt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jc),"date-time":nt(/^\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,pg),"iso-time":nt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,fg),"iso-date-time":nt(/^\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,mg),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};ot.formatNames=Object.keys(ot.fullFormats);function ME(e){return e%4===0&&(e%100!==0||e%400===0)}var qE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,LE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function dg(e){let t=qE.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&&ME(r)?29:LE[n])}function Gc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Kc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hc(e){return function(r){let n=Kc.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+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&&i<=59&&s<60)return!0;let d=i-u*c,f=o-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&s<61}}function Jc(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 fg(e,t){if(!(e&&t))return;let r=Kc.exec(e),n=Kc.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 Wc=/t|\s/i;function cg(e){let t=Hc(e);return function(n){let o=n.split(Wc);return o.length===2&&dg(o[0])&&t(o[1])}}function pg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function mg(e,t){if(!(e&&t))return;let[r,n]=e.split(Wc),[o,i]=t.split(Wc),s=Gc(r,o);if(s!==void 0)return s||Jc(n,i)}var BE=/\/|:/,ZE=/^(?:[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 UE(e){return BE.test(e)&&ZE.test(e)}var ug=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function FE(e){return ug.lastIndex=0,ug.test(e)}var VE=-(2**31),KE=2**31-1;function HE(e){return Number.isInteger(e)&&e<=KE&&e>=VE}function WE(e){return Number.isInteger(e)}function lg(){return!0}var GE=/[^\\]\\Z/;function JE(e){if(GE.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var gg=b(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.formatLimitDefinition=void 0;var QE=Vc(),We=C(),Pt=We.operators,si={formatMaximum:{okStr:"<=",ok:Pt.LTE,fail:Pt.GT},formatMinimum:{okStr:">=",ok:Pt.GTE,fail:Pt.LT},formatExclusiveMaximum:{okStr:"<",ok:Pt.LT,fail:Pt.GTE},formatExclusiveMinimum:{okStr:">",ok:Pt.GT,fail:Pt.LTE}},YE={message:({keyword:e,schemaCode:t})=>(0,We.str)`should be ${si[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,We._)`{comparison: ${si[e].okStr}, limit: ${t}}`};kr.formatLimitDefinition={keyword:Object.keys(si),type:"string",schemaType:"string",$data:!0,error:YE,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new QE.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,We._)`${f}[${c.schemaCode}]`);e.fail$data((0,We.or)((0,We._)`typeof ${p} != "object"`,(0,We._)`${p} instanceof RegExp`,(0,We._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=t.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,We._)`${s.code.formats}${(0,We.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,We._)`${f}.compare(${r}, ${n}) ${si[o].fail} 0`}},dependencies:["format"]};var XE=e=>(e.addKeyword(kr.formatLimitDefinition),e);kr.default=XE});var bg=b((Nn,wg)=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});var $r=hg(),eT=gg(),Qc=C(),yg=new Qc.Name("fullFormats"),tT=new Qc.Name("fastFormats"),Yc=(e,t={keywords:!0})=>{if(Array.isArray(t))return _g(e,t,$r.fullFormats,yg),e;let[r,n]=t.mode==="fast"?[$r.fastFormats,tT]:[$r.fullFormats,yg],o=t.formats||$r.formatNames;return _g(e,o,r,n),t.keywords&&(0,eT.default)(e),e};Yc.get=(e,t="full")=>{let n=(t==="fast"?$r.fastFormats:$r.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function _g(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Qc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}wg.exports=Nn=Yc;Object.defineProperty(Nn,"__esModule",{value:!0});Nn.default=Yc});var Rg=b((lM,Pg)=>{Pg.exports=Tg;Tg.sync=iT;var Sg=gt("fs");function oT(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function Eg(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:oT(t,r)}function Tg(e,t,r){Sg.stat(e,function(n,o){r(n,n?!1:Eg(o,e,t))})}function iT(e,t){return Eg(Sg.statSync(e),e,t)}});var Ng=b((dM,Ag)=>{Ag.exports=Og;Og.sync=sT;var zg=gt("fs");function Og(e,t,r){zg.stat(e,function(n,o){r(n,n?!1:Ig(o,t))})}function sT(e,t){return Ig(zg.statSync(e),t)}function Ig(e,t){return e.isFile()&&aT(e,t)}function aT(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c,d=r&l||r&c&&o===s||r&a&&n===i||r&u&&i===0;return d}});var Dg=b((pM,Cg)=>{var fM=gt("fs"),di;process.platform==="win32"||global.TESTING_WINDOWS?di=Rg():di=Ng();Cg.exports=Xc;Xc.sync=cT;function Xc(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Xc(e,t||{},function(i,s){i?o(i):n(s)})})}di(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function cT(e,t){try{return di.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var Ug=b((mM,Zg)=>{var Sr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",jg=gt("path"),uT=Sr?";":":",Mg=Dg(),qg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Lg=(e,t)=>{let r=t.colon||uT,n=e.match(/\//)||Sr&&e.match(/\\/)?[""]:[...Sr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=Sr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Sr?o.split(r):[""];return Sr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},Bg=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=Lg(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(qg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=jg.join(p,e),h=!p&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;u(c(h,l,0))}),c=(l,u,d)=>new Promise((f,p)=>{if(d===o.length)return f(a(u+1));let m=o[d];Mg(l+m,{pathExt:i},(h,_)=>{if(!h&&_)if(t.all)s.push(l+m);else return f(l+m);return f(c(l,u,d+1))})});return r?a(0).then(l=>r(null,l),r):a(0)},lT=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Lg(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=jg.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let d=0;d<n.length;d++){let f=u+n[d];try{if(Mg.sync(f,{pathExt:o}))if(t.all)i.push(f);else return f}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw qg(e)};Zg.exports=Bg;Bg.sync=lT});var Vg=b((hM,eu)=>{"use strict";var Fg=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};eu.exports=Fg;eu.exports.default=Fg});var Gg=b((gM,Wg)=>{"use strict";var Kg=gt("path"),dT=Ug(),fT=Vg();function Hg(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=dT.sync(e.command,{path:r[fT({env:r})],pathExt:t?Kg.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Kg.resolve(o?e.options.cwd:"",s)),s}function pT(e){return Hg(e)||Hg(e,!0)}Wg.exports=pT});var Jg=b((yM,ru)=>{"use strict";var tu=/([()\][%!^"`<>&|;, *?])/g;function mT(e){return e=e.replace(tu,"^$1"),e}function hT(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(tu,"^$1"),t&&(e=e.replace(tu,"^$1")),e}ru.exports.command=mT;ru.exports.argument=hT});var Yg=b((_M,Qg)=>{"use strict";Qg.exports=/^#!(.*)/});var ey=b((wM,Xg)=>{"use strict";var gT=Yg();Xg.exports=(e="")=>{let t=e.match(gT);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var ry=b((bM,ty)=>{"use strict";var nu=gt("fs"),yT=ey();function _T(e){let r=Buffer.alloc(150),n;try{n=nu.openSync(e,"r"),nu.readSync(n,r,0,150,0),nu.closeSync(n)}catch{}return yT(r.toString())}ty.exports=_T});var sy=b((vM,iy)=>{"use strict";var wT=gt("path"),ny=Gg(),oy=Jg(),bT=ry(),vT=process.platform==="win32",xT=/\.(?:com|exe)$/i,kT=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function $T(e){e.file=ny(e);let t=e.file&&bT(e.file);return t?(e.args.unshift(e.file),e.command=t,ny(e)):e.file}function ST(e){if(!vT)return e;let t=$T(e),r=!xT.test(t);if(e.options.forceShell||r){let n=kT.test(t);e.command=wT.normalize(e.command),e.command=oy.command(e.command),e.args=e.args.map(i=>oy.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function ET(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:ST(n)}iy.exports=ET});var uy=b((xM,cy)=>{"use strict";var ou=process.platform==="win32";function iu(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function TT(e,t){if(!ou)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=ay(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function ay(e,t){return ou&&e===1&&!t.file?iu(t.original,"spawn"):null}function PT(e,t){return ou&&e===1&&!t.file?iu(t.original,"spawnSync"):null}cy.exports={hookChildProcess:TT,verifyENOENT:ay,verifyENOENTSync:PT,notFoundError:iu}});var fy=b((kM,Er)=>{"use strict";var ly=gt("child_process"),su=sy(),au=uy();function dy(e,t,r){let n=su(e,t,r),o=ly.spawn(n.command,n.args,n.options);return au.hookChildProcess(o,n),o}function RT(e,t,r){let n=su(e,t,r),o=ly.spawnSync(n.command,n.args,n.options);return o.error=o.error||au.verifyENOENTSync(o.status,n),o}Er.exports=dy;Er.exports.spawn=dy;Er.exports.sync=RT;Er.exports._parse=su;Er.exports._enoent=au});import{readFile as BO,mkdir as ZO,writeFile as UO}from"node:fs/promises";import{dirname as FO,join as V_}from"node:path";var uI=Object.freeze({status:"aborted"});function y(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 s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var lI=Symbol("zod_brand"),at=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jn={};function Ae(e){return e&&Object.assign(Jn,e),Jn}var F={};il(F,{BIGINT_FORMAT_RANGES:()=>al,Class:()=>Ui,NUMBER_FORMAT_RANGES:()=>Qi,aborted:()=>Nt,allowsEval:()=>Wi,assert:()=>nw,assertEqual:()=>X_,assertIs:()=>tw,assertNever:()=>rw,assertNotEqual:()=>ew,assignProp:()=>Hi,cached:()=>Mr,captureStackTrace:()=>Yn,cleanEnum:()=>gw,cleanRegex:()=>Lr,clone:()=>Ye,createTransparentProxy:()=>uw,defineLazy:()=>W,esc:()=>At,escapeRegex:()=>yt,extend:()=>fw,finalizeIssue:()=>Ze,floatSafeRemainder:()=>Ki,getElementAtPath:()=>ow,getEnumValues:()=>Fi,getLengthableOrigin:()=>Br,getParsedType:()=>cw,getSizableOrigin:()=>cl,isObject:()=>tr,isPlainObject:()=>rr,issue:()=>Yi,joinValues:()=>Qn,jsonStringifyReplacer:()=>Vi,merge:()=>pw,normalizeParams:()=>R,nullish:()=>qr,numKeys:()=>aw,omit:()=>dw,optionalKeys:()=>Ji,partial:()=>mw,pick:()=>lw,prefixIssues:()=>Xe,primitiveTypes:()=>sl,promiseAllObject:()=>iw,propertyKeyTypes:()=>Gi,randomString:()=>sw,required:()=>hw,stringifyPrimitive:()=>Xn,unwrapMessage:()=>jr});function X_(e){return e}function ew(e){return e}function tw(e){}function rw(e){throw new Error}function nw(e){}function Fi(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 Qn(e,t="|"){return e.map(r=>Xn(r)).join(t)}function Vi(e,t){return typeof t=="bigint"?t.toString():t}function Mr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function qr(e){return e==null}function Lr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ki(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function W(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 Hi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ow(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function iw(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function sw(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function At(e){return JSON.stringify(e)}var Yn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Wi=Mr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function rr(e){if(tr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(tr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function aw(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var cw=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Gi=new Set(["string","number","symbol"]),sl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function yt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ye(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function R(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 uw(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},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 Xn(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ji(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Qi={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]},al={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function lw(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 Ye(e,{...e._zod.def,shape:r,checks:[]})}function dw(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 Ye(e,{...e._zod.def,shape:r,checks:[]})}function fw(e,t){if(!rr(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 Hi(this,"shape",n),n},checks:[]};return Ye(e,r)}function pw(e,t){return Ye(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Hi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function mw(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Ye(t,{...t._zod.def,shape:o,checks:[]})}function hw(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Ye(t,{...t._zod.def,shape:o,checks:[]})}function Nt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Xe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function jr(e){return typeof e=="string"?e:e?.message}function Ze(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=jr(e.inst?._zod.def?.error?.(e))??jr(t?.error?.(e))??jr(r.customError?.(e))??jr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function cl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Br(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Yi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function gw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ui=class{constructor(...t){}};var ul=(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,Vi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},eo=y("$ZodError",ul),Xi=y("$ZodError",ul,{Parent:Error});function ll(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 dl(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var fl=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new at;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ze(c,i,Ae())));throw Yn(a,o?.callee),a}return s.value};var pl=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ze(c,i,Ae())));throw Yn(a,o?.callee),a}return s.value};var es=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new at;return i.issues.length?{success:!1,error:new(e??eo)(i.issues.map(s=>Ze(s,o,Ae())))}:{success:!0,data:i.value}},Zr=es(Xi),ts=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Ze(s,o,Ae())))}:{success:!0,data:i.value}},to=ts(Xi);var ml=/^[cC][^\s-]{8,}$/,hl=/^[0-9a-z]+$/,gl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yl=/^[0-9a-vA-V]{20}$/,_l=/^[A-Za-z0-9]{27}$/,wl=/^[a-zA-Z0-9_-]{21}$/,bl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var vl=/^([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})$/,rs=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 xl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var _w="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function kl(){return new RegExp(_w,"u")}var $l=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,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})$/,El=/^((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])$/,Tl=/^(([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])$/,Pl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ns=/^[A-Za-z0-9_-]*$/,Rl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var zl=/^\+(?:[0-9]){6,14}[0-9]$/,Ol="(?:(?:\\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])))",Il=new RegExp(`^${Ol}$`);function Al(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 Nl(e){return new RegExp(`^${Al(e)}$`)}function Cl(e){let t=Al({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(`^${Ol}T(?:${n})$`)}var Dl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var jl=/^\d+$/,Ml=/^-?\d+(?:\.\d+)?/i,ql=/true|false/i,Ll=/null/i;var Bl=/^[^A-Z]*$/,Zl=/^[^a-z]*$/;var me=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ul={number:"number",bigint:"bigint",object:"date"},is=y("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let r=Ul[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(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})}}),ss=y("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let r=Ul[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(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})}}),Fl=y("$ZodCheckMultipleOf",(e,t)=>{me.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):Ki(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})}}),Vl=y("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Qi[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=jl)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.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}):s.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&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var Kl=y("$ZodCheckMaxLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(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 s=Br(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Hl=y("$ZodCheckMinLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(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 s=Br(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Wl=y("$ZodCheckLengthEquals",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(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,i=o.length;if(i===t.length)return;let s=Br(o),a=i>t.length;n.issues.push({origin:s,...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})}}),Ur=y("$ZodCheckStringFormat",(e,t)=>{var r,n;me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.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=()=>{})}),Gl=y("$ZodCheckRegex",(e,t)=>{Ur.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})}}),Jl=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Bl),Ur.init(e,t)}),Ql=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Zl),Ur.init(e,t)}),Yl=y("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let r=yt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Xl=y("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`^${yt(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})}}),ed=y("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`.*${yt(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 td=y("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var ro=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 NS={keyword:"dependencies",type:"object",schemaType:"object",error:tt.error,code(e){let[t,r]=CS(e);Oh(e,t),Ih(e,r)}};function CS({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 Oh(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,An.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,An.checkReportMissingProp)(e,l)}):(r.if((0,Sc._)`${c} && (${(0,An.checkMissingProp)(e,a,i)})`),(0,An.reportMissingProp)(e,i),r.else())}}tt.validatePropertyDeps=Oh;function Ih(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,AS.alwaysValidSchema)(i,t[a])||(r.if((0,An.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}tt.validateSchemaDeps=Ih;tt.default=NS});var Ch=v(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Nh=C(),DS=B(),jS={message:"property name must be valid",params:({params:e})=>(0,Nh._)`{propertyName: ${e.propertyName}}`},MS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jS,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,DS.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,Nh.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Ec.default=MS});var Rc=v(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Xo=je(),Ke=C(),qS=lt(),ei=B(),LS={message:"must NOT have additional properties",params:({params:e})=>(0,Ke._)`{additionalProperty: ${e.additionalProperty}}`},BS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:LS,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,ei.alwaysValidSchema)(s,r))return;let l=(0,Xo.allSchemaProperties)(n.properties),u=(0,Xo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Ke._)`${i} === ${qS.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?m(_):t.if(f(_),()=>m(_))})}function f(_){let w;if(l.length>8){let b=(0,ei.schemaRefOrVal)(s,n.properties,"properties");w=(0,Xo.isOwnProperty)(t,b,_)}else l.length?w=(0,Ke.or)(...l.map(b=>(0,Ke._)`${_} === ${b}`)):w=Ke.nil;return u.length&&(w=(0,Ke.or)(w,...u.map(b=>(0,Ke._)`${(0,Xo.usePattern)(e,b)}.test(${_})`))),(0,Ke.not)(w)}function p(_){t.code((0,Ke._)`delete ${o}[${_}]`)}function m(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,ei.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(h(_,w,!1),t.if((0,Ke.not)(w),()=>{e.reset(),p(_)})):(h(_,w),a||t.if((0,Ke.not)(w),()=>t.break()))}}function h(_,w,b){let x={keyword:"additionalProperties",dataProp:_,dataPropType:ei.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(x,w)}}};Tc.default=BS});var Mh=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var ZS=wn(),Dh=je(),Pc=B(),jh=Rc(),US={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&jh.default.code(new ZS.KeywordCxt(i,jh.default,"additionalProperties"));let s=(0,Dh.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Pc.mergeEvaluated.props(t,(0,Pc.toHash)(s),i.props));let a=s.filter(d=>!(0,Pc.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Dh.propertyInData)(t,o,d,i.opts.ownProperties)),u(d),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};zc.default=US});var Zh=v(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var qh=je(),ti=C(),Lh=B(),Bh=B(),FS={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,qh.allSchemaProperties)(r),c=a.filter(h=>(0,Lh.alwaysValidSchema)(i,r[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof ti.Name)&&(i.props=(0,Bh.evaluatedPropsToName)(t,i.props));let{props:d}=i;f();function f(){for(let h of a)l&&p(h),i.allErrors?m(h):(t.var(u,!0),m(h),t.if(u))}function p(h){for(let _ in l)new RegExp(h).test(_)&&(0,Lh.checkStrictMode)(i,`property ${_} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,_=>{t.if((0,ti._)`${(0,qh.usePattern)(e,h)}.test(${_})`,()=>{let w=c.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:_,dataPropType:Bh.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,ti._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,ti.not)(u),()=>t.break())})})}}};Oc.default=FS});var Uh=v(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var VS=B(),KS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,VS.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"}};Ic.default=KS});var Fh=v(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var HS=je(),WS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:HS.validateUnion,error:{message:"must match a schema in anyOf"}};Ac.default=WS});var Vh=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var ri=C(),GS=B(),JS={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ri._)`{passingSchemas: ${e.passing}}`},QS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:JS,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 i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((u,d)=>{let f;(0,GS.alwaysValidSchema)(o,u)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,ri._)`${c} && ${s}`).assign(s,!1).assign(a,(0,ri._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),f&&e.mergeEvaluated(f,ri.Name)})})}}};Nc.default=QS});var Kh=v(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var YS=B(),XS={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((i,s)=>{if((0,YS.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Cc.default=XS});var Gh=v(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ni=C(),Wh=B(),eE={message:({params:e})=>(0,ni.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,ni._)`{failingKeyword: ${e.ifClause}}`},tE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:eE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Wh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Hh(n,"then"),i=Hh(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){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,ni.not)(a),l("else"));e.pass(s,()=>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(s,a),e.mergeValidEvaluated(f,s),d?t.assign(d,(0,ni._)`${u}`):e.setParams({ifClause:u})}}}};function Hh(e,t){let r=e.schema[t];return r!==void 0&&!(0,Wh.alwaysValidSchema)(e,r)}Dc.default=tE});var Jh=v(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var rE=B(),nE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,rE.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};jc.default=nE});var Qh=v(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var oE=vc(),iE=Th(),sE=bc(),aE=Ph(),cE=zh(),uE=Ah(),lE=Ch(),dE=Rc(),fE=Mh(),pE=Zh(),mE=Uh(),hE=Fh(),gE=Vh(),yE=Kh(),_E=Gh(),wE=Jh();function vE(e=!1){let t=[mE.default,hE.default,gE.default,yE.default,_E.default,wE.default,lE.default,dE.default,uE.default,fE.default,pE.default];return e?t.push(iE.default,aE.default):t.push(oE.default,sE.default),t.push(cE.default),t}Mc.default=vE});var Yh=v(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var ie=C(),bE={message:({schemaCode:e})=>(0,ie.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ie._)`{format: ${e}}`},xE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:bE,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${m}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(_,(0,ie._)`${h}.type || "string"`).assign(w,(0,ie._)`${h}.validate`),()=>r.assign(_,(0,ie._)`"string"`).assign(w,h)),e.fail$data((0,ie.or)(b(),x()));function b(){return c.strictSchema===!1?ie.nil:(0,ie._)`${s} && !${w}`}function x(){let R=u.$async?(0,ie._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ie._)`${w}(${n})`,O=(0,ie._)`(typeof ${w} == "function" ? ${R} : ${w}.test(${n}))`;return(0,ie._)`${w} && ${w} !== true && ${_} === ${t} && !${O}`}}function p(){let m=d.formats[i];if(!m){b();return}if(m===!0)return;let[h,_,w]=x(m);h===t&&e.pass(R());function b(){if(c.strictSchema===!1){d.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function x(O){let ve=O instanceof RegExp?(0,ie.regexpCode)(O):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(i)}`:void 0,Ie=r.scopeValue("formats",{key:i,ref:O,code:ve});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,ie._)`${Ie}.validate`]:["string",O,Ie]}function R(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${w}(${n})`}return typeof _=="function"?(0,ie._)`${w}(${n})`:(0,ie._)`${w}.test(${n})`}}}};qc.default=xE});var Xh=v(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var kE=Yh(),$E=[kE.default];Lc.default=$E});var eg=v(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.contentVocabulary=wr.metadataVocabulary=void 0;wr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rg=v(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var SE=uh(),EE=kh(),TE=Qh(),RE=Xh(),tg=eg(),PE=[SE.default,EE.default,(0,TE.default)(),RE.default,tg.metadataVocabulary,tg.contentVocabulary];Bc.default=PE});var og=v(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.DiscrError=void 0;var ng;(function(e){e.Tag="tag",e.Mapping="mapping"})(ng||(oi.DiscrError=ng={}))});var sg=v(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var vr=C(),Zc=og(),ig=Bo(),zE=vn(),OE=B(),IE={message:({params:{discrError:e,tagName:t}})=>e===Zc.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}}`},AE={keyword:"discriminator",type:"object",schemaType:"object",error:IE,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.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(!s)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:Zc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let p=f();t.if(!1);for(let m in p)t.elseIf((0,vr._)`${l} === ${m}`),t.assign(c,d(p[m]));t.else(),e.error(!1,{discrError:Zc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(p){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(h,vr.Name),m}function f(){var p;let m={},h=w(o),_=!0;for(let R=0;R<s.length;R++){let O=s[R];if(O?.$ref&&!(0,OE.schemaHasRulesButRef)(O,i.self.RULES)){let Ie=O.$ref;if(O=ig.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Ie),O instanceof ig.SchemaEnv&&(O=O.schema),O===void 0)throw new zE.default(i.opts.uriResolver,i.baseId,Ie)}let ve=(p=O?.properties)===null||p===void 0?void 0:p[a];if(typeof ve!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(h||w(O)),b(ve,R)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(a)}function b(R,O){if(R.const)x(R.const,O);else if(R.enum)for(let ve of R.enum)x(ve,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(R,O){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[R]=O}}}};Uc.default=AE});var ag=v((rM,NE)=>{NE.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 Vc=v((ee,Fc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var CE=nh(),DE=rg(),jE=sg(),cg=ag(),ME=["/properties"],ii="http://json-schema.org/draft-07/schema",br=class extends CE.default{_addVocabularies(){super._addVocabularies(),DE.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(jE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(cg,ME):cg;this.addMetaSchema(t,ii,!1),this.refs["http://json-schema.org/schema"]=ii}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ii)?ii:void 0)}};ee.Ajv=br;Fc.exports=ee=br;Fc.exports.Ajv=br;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=br;var qE=wn();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return qE.KeywordCxt}});var xr=C();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return xr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return xr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return xr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return xr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return xr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return xr.CodeGen}});var LE=qo();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return LE.default}});var BE=vn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return BE.default}})});var gg=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.formatNames=nt.fastFormats=nt.fullFormats=void 0;function rt(e,t){return{validate:e,compare:t}}nt.fullFormats={date:rt(fg,Gc),time:rt(Hc(!0),Jc),"date-time":rt(ug(!0),mg),"iso-time":rt(Hc(),pg),"iso-date-time":rt(ug(),hg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:HE,"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:eT,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:WE,int32:{type:"number",validate:QE},int64:{type:"number",validate:YE},float:{type:"number",validate:dg},double:{type:"number",validate:dg},password:!0,binary:!0};nt.fastFormats={...nt.fullFormats,date:rt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Gc),time:rt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jc),"date-time":rt(/^\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,mg),"iso-time":rt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,pg),"iso-date-time":rt(/^\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,hg),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};nt.formatNames=Object.keys(nt.fullFormats);function ZE(e){return e%4===0&&(e%100!==0||e%400===0)}var UE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,FE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fg(e){let t=UE.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&&ZE(r)?29:FE[n])}function Gc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Kc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hc(e){return function(r){let n=Kc.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+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&&i<=59&&s<60)return!0;let d=i-u*c,f=o-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&s<61}}function Jc(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 pg(e,t){if(!(e&&t))return;let r=Kc.exec(e),n=Kc.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 Wc=/t|\s/i;function ug(e){let t=Hc(e);return function(n){let o=n.split(Wc);return o.length===2&&fg(o[0])&&t(o[1])}}function mg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function hg(e,t){if(!(e&&t))return;let[r,n]=e.split(Wc),[o,i]=t.split(Wc),s=Gc(r,o);if(s!==void 0)return s||Jc(n,i)}var VE=/\/|:/,KE=/^(?:[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 HE(e){return VE.test(e)&&KE.test(e)}var lg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function WE(e){return lg.lastIndex=0,lg.test(e)}var GE=-(2**31),JE=2**31-1;function QE(e){return Number.isInteger(e)&&e<=JE&&e>=GE}function YE(e){return Number.isInteger(e)}function dg(){return!0}var XE=/[^\\]\\Z/;function eT(e){if(XE.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var yg=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.formatLimitDefinition=void 0;var tT=Vc(),He=C(),Rt=He.operators,si={formatMaximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},formatMinimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},formatExclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},formatExclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},rT={message:({keyword:e,schemaCode:t})=>(0,He.str)`should be ${si[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,He._)`{comparison: ${si[e].okStr}, limit: ${t}}`};kr.formatLimitDefinition={keyword:Object.keys(si),type:"string",schemaType:"string",$data:!0,error:rT,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new tT.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,He._)`${f}[${c.schemaCode}]`);e.fail$data((0,He.or)((0,He._)`typeof ${p} != "object"`,(0,He._)`${p} instanceof RegExp`,(0,He._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=t.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,He._)`${s.code.formats}${(0,He.getProperty)(f)}`:void 0});e.fail$data(d(m))}function d(f){return(0,He._)`${f}.compare(${r}, ${n}) ${si[o].fail} 0`}},dependencies:["format"]};var nT=e=>(e.addKeyword(kr.formatLimitDefinition),e);kr.default=nT});var bg=v((Nn,vg)=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});var $r=gg(),oT=yg(),Qc=C(),_g=new Qc.Name("fullFormats"),iT=new Qc.Name("fastFormats"),Yc=(e,t={keywords:!0})=>{if(Array.isArray(t))return wg(e,t,$r.fullFormats,_g),e;let[r,n]=t.mode==="fast"?[$r.fastFormats,iT]:[$r.fullFormats,_g],o=t.formats||$r.formatNames;return wg(e,o,r,n),t.keywords&&(0,oT.default)(e),e};Yc.get=(e,t="full")=>{let n=(t==="fast"?$r.fastFormats:$r.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function wg(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Qc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}vg.exports=Nn=Yc;Object.defineProperty(Nn,"__esModule",{value:!0});Nn.default=Yc});var zg=v((gM,Pg)=>{Pg.exports=Rg;Rg.sync=uT;var Eg=gt("fs");function cT(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function Tg(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:cT(t,r)}function Rg(e,t,r){Eg.stat(e,function(n,o){r(n,n?!1:Tg(o,e,t))})}function uT(e,t){return Tg(Eg.statSync(e),e,t)}});var Cg=v((yM,Ng)=>{Ng.exports=Ig;Ig.sync=lT;var Og=gt("fs");function Ig(e,t,r){Og.stat(e,function(n,o){r(n,n?!1:Ag(o,t))})}function lT(e,t){return Ag(Og.statSync(e),t)}function Ag(e,t){return e.isFile()&&dT(e,t)}function dT(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c,d=r&l||r&c&&o===s||r&a&&n===i||r&u&&i===0;return d}});var jg=v((wM,Dg)=>{var _M=gt("fs"),di;process.platform==="win32"||global.TESTING_WINDOWS?di=zg():di=Cg();Dg.exports=Xc;Xc.sync=fT;function Xc(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Xc(e,t||{},function(i,s){i?o(i):n(s)})})}di(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function fT(e,t){try{return di.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var Fg=v((vM,Ug)=>{var Sr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Mg=gt("path"),pT=Sr?";":":",qg=jg(),Lg=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Bg=(e,t)=>{let r=t.colon||pT,n=e.match(/\//)||Sr&&e.match(/\\/)?[""]:[...Sr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=Sr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Sr?o.split(r):[""];return Sr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},Zg=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=Bg(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(Lg(e));let f=n[l],p=/^".*"$/.test(f)?f.slice(1,-1):f,m=Mg.join(p,e),h=!p&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;u(c(h,l,0))}),c=(l,u,d)=>new Promise((f,p)=>{if(d===o.length)return f(a(u+1));let m=o[d];qg(l+m,{pathExt:i},(h,_)=>{if(!h&&_)if(t.all)s.push(l+m);else return f(l+m);return f(c(l,u,d+1))})});return r?a(0).then(l=>r(null,l),r):a(0)},mT=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Bg(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=Mg.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let d=0;d<n.length;d++){let f=u+n[d];try{if(qg.sync(f,{pathExt:o}))if(t.all)i.push(f);else return f}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw Lg(e)};Ug.exports=Zg;Zg.sync=mT});var Kg=v((bM,eu)=>{"use strict";var Vg=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};eu.exports=Vg;eu.exports.default=Vg});var Jg=v((xM,Gg)=>{"use strict";var Hg=gt("path"),hT=Fg(),gT=Kg();function Wg(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=hT.sync(e.command,{path:r[gT({env:r})],pathExt:t?Hg.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Hg.resolve(o?e.options.cwd:"",s)),s}function yT(e){return Wg(e)||Wg(e,!0)}Gg.exports=yT});var Qg=v((kM,ru)=>{"use strict";var tu=/([()\][%!^"`<>&|;, *?])/g;function _T(e){return e=e.replace(tu,"^$1"),e}function wT(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(tu,"^$1"),t&&(e=e.replace(tu,"^$1")),e}ru.exports.command=_T;ru.exports.argument=wT});var Xg=v(($M,Yg)=>{"use strict";Yg.exports=/^#!(.*)/});var ty=v((SM,ey)=>{"use strict";var vT=Xg();ey.exports=(e="")=>{let t=e.match(vT);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var ny=v((EM,ry)=>{"use strict";var nu=gt("fs"),bT=ty();function xT(e){let r=Buffer.alloc(150),n;try{n=nu.openSync(e,"r"),nu.readSync(n,r,0,150,0),nu.closeSync(n)}catch{}return bT(r.toString())}ry.exports=xT});var ay=v((TM,sy)=>{"use strict";var kT=gt("path"),oy=Jg(),iy=Qg(),$T=ny(),ST=process.platform==="win32",ET=/\.(?:com|exe)$/i,TT=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function RT(e){e.file=oy(e);let t=e.file&&$T(e.file);return t?(e.args.unshift(e.file),e.command=t,oy(e)):e.file}function PT(e){if(!ST)return e;let t=RT(e),r=!ET.test(t);if(e.options.forceShell||r){let n=TT.test(t);e.command=kT.normalize(e.command),e.command=iy.command(e.command),e.args=e.args.map(i=>iy.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function zT(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:PT(n)}sy.exports=zT});var ly=v((RM,uy)=>{"use strict";var ou=process.platform==="win32";function iu(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function OT(e,t){if(!ou)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=cy(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function cy(e,t){return ou&&e===1&&!t.file?iu(t.original,"spawn"):null}function IT(e,t){return ou&&e===1&&!t.file?iu(t.original,"spawnSync"):null}uy.exports={hookChildProcess:OT,verifyENOENT:cy,verifyENOENTSync:IT,notFoundError:iu}});var py=v((PM,Er)=>{"use strict";var dy=gt("child_process"),su=ay(),au=ly();function fy(e,t,r){let n=su(e,t,r),o=dy.spawn(n.command,n.args,n.options);return au.hookChildProcess(o,n),o}function AT(e,t,r){let n=su(e,t,r),o=dy.spawnSync(n.command,n.args,n.options);return o.error=o.error||au.verifyENOENTSync(o.status,n),o}Er.exports=fy;Er.exports.spawn=fy;Er.exports.sync=AT;Er.exports._parse=su;Er.exports._enoent=au});import{readFile as HO,mkdir as WO,writeFile as GO}from"node:fs/promises";import{dirname as JO,join as G_}from"node:path";var hI=Object.freeze({status:"aborted"});function y(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 s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var gI=Symbol("zod_brand"),st=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jn={};function Ae(e){return e&&Object.assign(Jn,e),Jn}var F={};sl(F,{BIGINT_FORMAT_RANGES:()=>cl,Class:()=>Ui,NUMBER_FORMAT_RANGES:()=>Qi,aborted:()=>Nt,allowsEval:()=>Wi,assert:()=>aw,assertEqual:()=>nw,assertIs:()=>iw,assertNever:()=>sw,assertNotEqual:()=>ow,assignProp:()=>Hi,cached:()=>Mr,captureStackTrace:()=>Yn,cleanEnum:()=>vw,cleanRegex:()=>Lr,clone:()=>Qe,createTransparentProxy:()=>pw,defineLazy:()=>W,esc:()=>At,escapeRegex:()=>yt,extend:()=>gw,finalizeIssue:()=>Be,floatSafeRemainder:()=>Ki,getElementAtPath:()=>cw,getEnumValues:()=>Fi,getLengthableOrigin:()=>Br,getParsedType:()=>fw,getSizableOrigin:()=>ul,isObject:()=>tr,isPlainObject:()=>rr,issue:()=>Yi,joinValues:()=>Qn,jsonStringifyReplacer:()=>Vi,merge:()=>yw,normalizeParams:()=>P,nullish:()=>qr,numKeys:()=>dw,omit:()=>hw,optionalKeys:()=>Ji,partial:()=>_w,pick:()=>mw,prefixIssues:()=>Ye,primitiveTypes:()=>al,promiseAllObject:()=>uw,propertyKeyTypes:()=>Gi,randomString:()=>lw,required:()=>ww,stringifyPrimitive:()=>Xn,unwrapMessage:()=>jr});function nw(e){return e}function ow(e){return e}function iw(e){}function sw(e){throw new Error}function aw(e){}function Fi(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 Qn(e,t="|"){return e.map(r=>Xn(r)).join(t)}function Vi(e,t){return typeof t=="bigint"?t.toString():t}function Mr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function qr(e){return e==null}function Lr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ki(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function W(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 Hi(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cw(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function uw(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function lw(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function At(e){return JSON.stringify(e)}var Yn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Wi=Mr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function rr(e){if(tr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(tr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function dw(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var fw=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Gi=new Set(["string","number","symbol"]),al=new Set(["string","number","bigint","boolean","symbol","undefined"]);function yt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qe(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function P(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 pw(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},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 Xn(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ji(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Qi={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]},cl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function mw(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 Qe(e,{...e._zod.def,shape:r,checks:[]})}function hw(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 Qe(e,{...e._zod.def,shape:r,checks:[]})}function gw(e,t){if(!rr(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 Hi(this,"shape",n),n},checks:[]};return Qe(e,r)}function yw(e,t){return Qe(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Hi(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function _w(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Qe(t,{...t._zod.def,shape:o,checks:[]})}function ww(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Qe(t,{...t._zod.def,shape:o,checks:[]})}function Nt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ye(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function jr(e){return typeof e=="string"?e:e?.message}function Be(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=jr(e.inst?._zod.def?.error?.(e))??jr(t?.error?.(e))??jr(r.customError?.(e))??jr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function ul(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Br(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Yi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function vw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ui=class{constructor(...t){}};var ll=(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,Vi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},eo=y("$ZodError",ll),Xi=y("$ZodError",ll,{Parent:Error});function dl(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 fl(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var pl=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new st;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Be(c,i,Ae())));throw Yn(a,o?.callee),a}return s.value};var ml=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Be(c,i,Ae())));throw Yn(a,o?.callee),a}return s.value};var es=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new st;return i.issues.length?{success:!1,error:new(e??eo)(i.issues.map(s=>Be(s,o,Ae())))}:{success:!0,data:i.value}},Zr=es(Xi),ts=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Be(s,o,Ae())))}:{success:!0,data:i.value}},to=ts(Xi);var hl=/^[cC][^\s-]{8,}$/,gl=/^[0-9a-z]+$/,yl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_l=/^[0-9a-vA-V]{20}$/,wl=/^[A-Za-z0-9]{27}$/,vl=/^[a-zA-Z0-9_-]{21}$/,bl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var xl=/^([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})$/,rs=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 kl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var xw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $l(){return new RegExp(xw,"u")}var Sl=/^(?:(?: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])$/,Pl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ns=/^[A-Za-z0-9_-]*$/,zl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Ol=/^\+(?:[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 Nl(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 Cl(e){return new RegExp(`^${Nl(e)}$`)}function Dl(e){let t=Nl({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 jl=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ml=/^\d+$/,ql=/^-?\d+(?:\.\d+)?/i,Ll=/true|false/i,Bl=/null/i;var Zl=/^[^A-Z]*$/,Ul=/^[^a-z]*$/;var me=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Fl={number:"number",bigint:"bigint",object:"date"},is=y("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let r=Fl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(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})}}),ss=y("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let r=Fl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(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})}}),Vl=y("$ZodCheckMultipleOf",(e,t)=>{me.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):Ki(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})}}),Kl=y("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Qi[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=Ml)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.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}):s.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&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var Hl=y("$ZodCheckMaxLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(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 s=Br(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Wl=y("$ZodCheckMinLength",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(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 s=Br(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Gl=y("$ZodCheckLengthEquals",(e,t)=>{var r;me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(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,i=o.length;if(i===t.length)return;let s=Br(o),a=i>t.length;n.issues.push({origin:s,...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})}}),Ur=y("$ZodCheckStringFormat",(e,t)=>{var r,n;me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.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=()=>{})}),Jl=y("$ZodCheckRegex",(e,t)=>{Ur.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})}}),Ql=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Zl),Ur.init(e,t)}),Yl=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ul),Ur.init(e,t)}),Xl=y("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let r=yt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),ed=y("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`^${yt(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})}}),td=y("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let r=new RegExp(`.*${yt(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 rd=y("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var ro=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(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
12
- `))}};var nd={major:4,minor:0,patch:0};var G=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=nd;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=Nt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new at;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Nt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Nt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new at;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Zr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return to(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),oo=y("$ZodString",(e,t)=>{G.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}}),Q=y("$ZodStringFormat",(e,t)=>{Ur.init(e,t),oo.init(e,t)}),pd=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=vl),Q.init(e,t)}),md=y("$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=rs(n))}else t.pattern??(t.pattern=rs());Q.init(e,t)}),hd=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=xl),Q.init(e,t)}),gd=y("$ZodURL",(e,t)=>{Q.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=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:Rl.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("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),yd=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=kl()),Q.init(e,t)}),_d=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=wl),Q.init(e,t)}),wd=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ml),Q.init(e,t)}),bd=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=hl),Q.init(e,t)}),vd=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=gl),Q.init(e,t)}),xd=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=yl),Q.init(e,t)}),kd=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=_l),Q.init(e,t)}),$d=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Cl(t)),Q.init(e,t)}),Sd=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Il),Q.init(e,t)}),Ed=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Nl(t)),Q.init(e,t)}),Td=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bl),Q.init(e,t)}),Pd=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$l),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Rd=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Sl),Q.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})}}}),zd=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=El),Q.init(e,t)}),Od=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Tl),Q.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>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 Id(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ad=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Pl),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Id(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ww(e){if(!ns.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Id(r)}var Nd=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ns),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ww(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Cd=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zl),Q.init(e,t)});function bw(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 Dd=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{bw(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var cs=y("$ZodNumber",(e,t)=>{G.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 i=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,...i?{received:i}:{}}),r}}),jd=y("$ZodNumber",(e,t)=>{Vl.init(e,t),cs.init(e,t)}),Md=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=ql,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}});var qd=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=Ll,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}});var Ld=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),Bd=y("$ZodNever",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function od(e,t,r){e.issues.length&&t.issues.push(...Xe(r,e.issues)),t.value[r]=e.value}var Zd=y("$ZodArray",(e,t)=>{G.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 i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>od(l,r,s))):od(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function no(e,t,r){e.issues.length&&t.issues.push(...Xe(r,e.issues)),t.value[r]=e.value}function id(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(...Xe(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Ud=y("$ZodObject",(e,t)=>{G.init(e,t);let r=Mr(()=>{let d=Object.keys(t.shape);for(let p of d)if(!(t.shape[p]instanceof G))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=Ji(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});W(e._zod,"propValues",()=>{let d=t.shape,f={};for(let p in d){let m=d[p]._zod;if(m.values){f[p]??(f[p]=new Set);for(let h of m.values)f[p].add(h)}}return f});let n=d=>{let f=new ro(["shape","payload","ctx"]),p=r.value,m=v=>{let x=At(v);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let v of p.keys)h[v]=`key_${_++}`;f.write("const newResult = {}");for(let v of p.keys)if(p.optionalKeys.has(v)){let x=h[v];f.write(`const ${x} = ${m(v)};`);let P=At(v);f.write(`
12
+ `))}};var od={major:4,minor:0,patch:0};var G=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=od;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=Nt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new st;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Nt(i,d)))});else{if(i.issues.length===d)continue;c||(c=Nt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new st;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Zr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return to(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),oo=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??jl(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}}),Q=y("$ZodStringFormat",(e,t)=>{Ur.init(e,t),oo.init(e,t)}),md=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=xl),Q.init(e,t)}),hd=y("$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=rs(n))}else t.pattern??(t.pattern=rs());Q.init(e,t)}),gd=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=kl),Q.init(e,t)}),yd=y("$ZodURL",(e,t)=>{Q.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=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:zl.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("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),_d=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$l()),Q.init(e,t)}),wd=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=vl),Q.init(e,t)}),vd=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=hl),Q.init(e,t)}),bd=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=gl),Q.init(e,t)}),xd=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=yl),Q.init(e,t)}),kd=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=_l),Q.init(e,t)}),$d=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=wl),Q.init(e,t)}),Sd=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Dl(t)),Q.init(e,t)}),Ed=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Al),Q.init(e,t)}),Td=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Cl(t)),Q.init(e,t)}),Rd=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bl),Q.init(e,t)}),Pd=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Sl),Q.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),zd=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=El),Q.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})}}}),Od=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Tl),Q.init(e,t)}),Id=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Rl),Q.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>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 Ad(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Nd=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Pl),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Ad(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function kw(e){if(!ns.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ad(r)}var Cd=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ns),Q.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{kw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Dd=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ol),Q.init(e,t)});function $w(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 jd=y("$ZodJWT",(e,t)=>{Q.init(e,t),e._zod.check=r=>{$w(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var cs=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??ql,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 i=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,...i?{received:i}:{}}),r}}),Md=y("$ZodNumber",(e,t)=>{Kl.init(e,t),cs.init(e,t)}),qd=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=Ll,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}});var Ld=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=Bl,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}});var Bd=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),Zd=y("$ZodNever",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function id(e,t,r){e.issues.length&&t.issues.push(...Ye(r,e.issues)),t.value[r]=e.value}var Ud=y("$ZodArray",(e,t)=>{G.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 i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>id(l,r,s))):id(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function no(e,t,r){e.issues.length&&t.issues.push(...Ye(r,e.issues)),t.value[r]=e.value}function sd(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(...Ye(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Fd=y("$ZodObject",(e,t)=>{G.init(e,t);let r=Mr(()=>{let d=Object.keys(t.shape);for(let p of d)if(!(t.shape[p]instanceof G))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=Ji(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});W(e._zod,"propValues",()=>{let d=t.shape,f={};for(let p in d){let m=d[p]._zod;if(m.values){f[p]??(f[p]=new Set);for(let h of m.values)f[p].add(h)}}return f});let n=d=>{let f=new ro(["shape","payload","ctx"]),p=r.value,m=b=>{let x=At(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),_=0;for(let b of p.keys)h[b]=`key_${_++}`;f.write("const newResult = {}");for(let b of p.keys)if(p.optionalKeys.has(b)){let x=h[b];f.write(`const ${x} = ${m(b)};`);let R=At(b);f.write(`
13
13
  if (${x}.issues.length) {
14
- if (input[${P}] === undefined) {
15
- if (${P} in input) {
16
- newResult[${P}] = undefined;
14
+ if (input[${R}] === undefined) {
15
+ if (${R} in input) {
16
+ newResult[${R}] = undefined;
17
17
  }
18
18
  } else {
19
19
  payload.issues = payload.issues.concat(
20
20
  ${x}.issues.map((iss) => ({
21
21
  ...iss,
22
- path: iss.path ? [${P}, ...iss.path] : [${P}],
22
+ path: iss.path ? [${R}, ...iss.path] : [${R}],
23
23
  }))
24
24
  );
25
25
  }
26
26
  } else if (${x}.value === undefined) {
27
- if (${P} in input) newResult[${P}] = undefined;
27
+ if (${R} in input) newResult[${R}] = undefined;
28
28
  } else {
29
- newResult[${P}] = ${x}.value;
29
+ newResult[${R}] = ${x}.value;
30
30
  }
31
- `)}else{let x=h[v];f.write(`const ${x} = ${m(v)};`),f.write(`
31
+ `)}else{let x=h[b];f.write(`const ${x} = ${m(b)};`),f.write(`
32
32
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
33
33
  ...iss,
34
- path: iss.path ? [${At(v)}, ...iss.path] : [${At(v)}]
35
- })));`),f.write(`newResult[${At(v)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(v,x)=>w(d,v,x)},o,i=tr,s=!Jn.jitless,c=s&&Wi.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??(u=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;let m=[];if(s&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let x=u.shape;for(let P of u.keys){let O=x[P],be=O._zod.run({value:p[P],issues:[]},f),Ie=O._zod.optin==="optional"&&O._zod.optout==="optional";be instanceof Promise?m.push(be.then(er=>Ie?id(er,d,P,p):no(er,d,P))):Ie?id(be,d,P,p):no(be,d,P)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,v=w.def.type;for(let x of Object.keys(p)){if(_.has(x))continue;if(v==="never"){h.push(x);continue}let P=w.run({value:p[x],issues:[]},f);P instanceof Promise?m.push(P.then(O=>no(O,d,x))):no(P,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function sd(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(i=>Ze(i,n,Ae())))}),t}var us=y("$ZodUnion",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),W(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),W(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),W(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=>Lr(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>sd(s,r,e,n)):sd(i,r,e,n)}}),Fd=y("$ZodDiscriminatedUnion",(e,t)=>{us.init(e,t);let r=e._zod.parse;W(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=Mr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!tr(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),Vd=y("$ZodIntersection",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>ad(r,c,l)):ad(r,i,s)}});function as(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(rr(e)&&rr(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=as(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.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],i=t[n],s=as(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ad(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Nt(e))return e;let n=as(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 Kd=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!rr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Xe(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Xe(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.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 s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,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=>Ze(l,n,Ae())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Xe(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Xe(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Hd=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=Fi(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Gi.has(typeof n)).map(n=>typeof n=="string"?yt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),Wd=y("$ZodLiteral",(e,t)=>{G.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?yt(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var Gd=y("$ZodTransform",(e,t)=>{G.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(s=>(r.value=s,r));if(o instanceof Promise)throw new at;return r.value=o,r}}),Jd=y("$ZodOptional",(e,t)=>{G.init(e,t),e._zod.optin="optional",e._zod.optout="optional",W(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Lr(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)}),Qd=y("$ZodNullable",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.innerType._zod.optin),W(e._zod,"optout",()=>t.innerType._zod.optout),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Lr(r.source)}|null)$`):void 0}),W(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)}),Yd=y("$ZodDefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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(i=>cd(i,t)):cd(o,t)}});function cd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Xd=y("$ZodPrefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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))}),ef=y("$ZodNonOptional",(e,t)=>{G.init(e,t),W(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(i=>ud(i,e)):ud(o,e)}});function ud(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 tf=y("$ZodCatch",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(e._zod,"optout",()=>t.innerType._zod.optout),W(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(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Ze(s,n,Ae()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Ze(i,n,Ae()))},input:r.value}),r.issues=[]),r)}});var rf=y("$ZodPipe",(e,t)=>{G.init(e,t),W(e._zod,"values",()=>t.in._zod.values),W(e._zod,"optin",()=>t.in._zod.optin),W(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(i=>ld(i,t,n)):ld(o,t,n)}});function ld(e,t,r){return Nt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var nf=y("$ZodReadonly",(e,t)=>{G.init(e,t),W(e._zod,"propValues",()=>t.innerType._zod.propValues),W(e._zod,"values",()=>t.innerType._zod.values),W(e._zod,"optin",()=>t.innerType._zod.optin),W(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(dd):dd(o)}});function dd(e){return e.value=Object.freeze(e.value),e}var of=y("$ZodCustom",(e,t)=>{me.init(e,t),G.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(i=>fd(i,r,n,e));fd(o,r,n,e)}});function fd(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(Yi(o))}}var vw=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},xw=()=>{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 ${vw(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Xn(n.values[0])}`:`Invalid option: expected one of ${Qn(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.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":""}: ${Qn(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 sf(){return{localeError:xw()}}var $I=Symbol("ZodOutput"),SI=Symbol("ZodInput"),ls=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 kw(){return new ls}var Fr=kw();function af(e,t){return new e({type:"string",...R(t)})}function cf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function ds(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function uf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function lf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function df(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function ff(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function pf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function mf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function hf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function gf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function yf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function _f(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function wf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function bf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function vf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function xf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function kf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function $f(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function Sf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function Ef(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function Tf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function Pf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function Rf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function zf(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function Of(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function If(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function Af(e,t){return new e({type:"number",checks:[],...R(t)})}function Nf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function Cf(e,t){return new e({type:"boolean",...R(t)})}function Df(e,t){return new e({type:"null",...R(t)})}function jf(e){return new e({type:"unknown"})}function Mf(e,t){return new e({type:"never",...R(t)})}function io(e,t){return new is({check:"less_than",...R(t),value:e,inclusive:!1})}function Vr(e,t){return new is({check:"less_than",...R(t),value:e,inclusive:!0})}function so(e,t){return new ss({check:"greater_than",...R(t),value:e,inclusive:!1})}function Kr(e,t){return new ss({check:"greater_than",...R(t),value:e,inclusive:!0})}function ao(e,t){return new Fl({check:"multiple_of",...R(t),value:e})}function co(e,t){return new Kl({check:"max_length",...R(t),maximum:e})}function nr(e,t){return new Hl({check:"min_length",...R(t),minimum:e})}function uo(e,t){return new Wl({check:"length_equals",...R(t),length:e})}function fs(e,t){return new Gl({check:"string_format",format:"regex",...R(t),pattern:e})}function ps(e){return new Jl({check:"string_format",format:"lowercase",...R(e)})}function ms(e){return new Ql({check:"string_format",format:"uppercase",...R(e)})}function hs(e,t){return new Yl({check:"string_format",format:"includes",...R(t),includes:e})}function gs(e,t){return new Xl({check:"string_format",format:"starts_with",...R(t),prefix:e})}function ys(e,t){return new ed({check:"string_format",format:"ends_with",...R(t),suffix:e})}function Ct(e){return new td({check:"overwrite",tx:e})}function _s(e){return Ct(t=>t.normalize(e))}function ws(){return Ct(e=>e.trim())}function bs(){return Ct(e=>e.toLowerCase())}function vs(){return Ct(e=>e.toUpperCase())}function qf(e,t,r){return new e({type:"array",element:t,...R(r)})}function Lf(e,t,r){let n=R(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Bf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...R(r)})}function or(e){return!!e._zod}function Ue(e,t){return or(e)?Zr(e,t):e.safeParse(t)}function lo(e){if(!e)return;let t;if(or(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Zf(e){if(or(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var Wr={};il(Wr,{ZodISODate:()=>Ff,ZodISODateTime:()=>Uf,ZodISODuration:()=>Kf,ZodISOTime:()=>Vf,date:()=>ks,datetime:()=>xs,duration:()=>Ss,time:()=>$s});var Uf=y("ZodISODateTime",(e,t)=>{$d.init(e,t),te.init(e,t)});function xs(e){return Rf(Uf,e)}var Ff=y("ZodISODate",(e,t)=>{Sd.init(e,t),te.init(e,t)});function ks(e){return zf(Ff,e)}var Vf=y("ZodISOTime",(e,t)=>{Ed.init(e,t),te.init(e,t)});function $s(e){return Of(Vf,e)}var Kf=y("ZodISODuration",(e,t)=>{Td.init(e,t),te.init(e,t)});function Ss(e){return If(Kf,e)}var Hf=(e,t)=>{eo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>dl(e,r)},flatten:{value:r=>ll(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},iA=y("ZodError",Hf),Gr=y("ZodError",Hf,{Parent:Error});var Wf=fl(Gr),Gf=pl(Gr),Jf=es(Gr),Qf=ts(Gr);var oe=y("ZodType",(e,t)=>(G.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)=>Ye(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Wf(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Jf(e,r,n),e.parseAsync=async(r,n)=>Gf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Qf(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(bb(r,n)),e.superRefine=r=>e.check(vb(r)),e.overwrite=r=>e.check(Ct(r)),e.optional=()=>ne(e),e.nullable=()=>ep(e),e.nullish=()=>ne(ep(e)),e.nonoptional=r=>pb(e,r),e.array=()=>q(e),e.or=r=>Y([e,r]),e.and=r=>po(e,r),e.transform=r=>Ts(e,sp(r)),e.default=r=>lb(e,r),e.prefault=r=>fb(e,r),e.catch=r=>hb(e,r),e.pipe=r=>Ts(e,r),e.readonly=()=>_b(e),e.describe=r=>{let n=e.clone();return Fr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Fr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Fr.get(e);let n=e.clone();return Fr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),tp=y("_ZodString",(e,t)=>{oo.init(e,t),oe.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(fs(...n)),e.includes=(...n)=>e.check(hs(...n)),e.startsWith=(...n)=>e.check(gs(...n)),e.endsWith=(...n)=>e.check(ys(...n)),e.min=(...n)=>e.check(nr(...n)),e.max=(...n)=>e.check(co(...n)),e.length=(...n)=>e.check(uo(...n)),e.nonempty=(...n)=>e.check(nr(1,...n)),e.lowercase=n=>e.check(ps(n)),e.uppercase=n=>e.check(ms(n)),e.trim=()=>e.check(ws()),e.normalize=(...n)=>e.check(_s(...n)),e.toLowerCase=()=>e.check(bs()),e.toUpperCase=()=>e.check(vs())}),Iw=y("ZodString",(e,t)=>{oo.init(e,t),tp.init(e,t),e.email=r=>e.check(cf(Aw,r)),e.url=r=>e.check(pf(Nw,r)),e.jwt=r=>e.check(Pf(Gw,r)),e.emoji=r=>e.check(mf(Cw,r)),e.guid=r=>e.check(ds(Yf,r)),e.uuid=r=>e.check(uf(fo,r)),e.uuidv4=r=>e.check(lf(fo,r)),e.uuidv6=r=>e.check(df(fo,r)),e.uuidv7=r=>e.check(ff(fo,r)),e.nanoid=r=>e.check(hf(Dw,r)),e.guid=r=>e.check(ds(Yf,r)),e.cuid=r=>e.check(gf(jw,r)),e.cuid2=r=>e.check(yf(Mw,r)),e.ulid=r=>e.check(_f(qw,r)),e.base64=r=>e.check(Sf(Kw,r)),e.base64url=r=>e.check(Ef(Hw,r)),e.xid=r=>e.check(wf(Lw,r)),e.ksuid=r=>e.check(bf(Bw,r)),e.ipv4=r=>e.check(vf(Zw,r)),e.ipv6=r=>e.check(xf(Uw,r)),e.cidrv4=r=>e.check(kf(Fw,r)),e.cidrv6=r=>e.check($f(Vw,r)),e.e164=r=>e.check(Tf(Ww,r)),e.datetime=r=>e.check(xs(r)),e.date=r=>e.check(ks(r)),e.time=r=>e.check($s(r)),e.duration=r=>e.check(Ss(r))});function g(e){return af(Iw,e)}var te=y("ZodStringFormat",(e,t)=>{Q.init(e,t),tp.init(e,t)}),Aw=y("ZodEmail",(e,t)=>{hd.init(e,t),te.init(e,t)});var Yf=y("ZodGUID",(e,t)=>{pd.init(e,t),te.init(e,t)});var fo=y("ZodUUID",(e,t)=>{md.init(e,t),te.init(e,t)});var Nw=y("ZodURL",(e,t)=>{gd.init(e,t),te.init(e,t)});var Cw=y("ZodEmoji",(e,t)=>{yd.init(e,t),te.init(e,t)});var Dw=y("ZodNanoID",(e,t)=>{_d.init(e,t),te.init(e,t)});var jw=y("ZodCUID",(e,t)=>{wd.init(e,t),te.init(e,t)});var Mw=y("ZodCUID2",(e,t)=>{bd.init(e,t),te.init(e,t)});var qw=y("ZodULID",(e,t)=>{vd.init(e,t),te.init(e,t)});var Lw=y("ZodXID",(e,t)=>{xd.init(e,t),te.init(e,t)});var Bw=y("ZodKSUID",(e,t)=>{kd.init(e,t),te.init(e,t)});var Zw=y("ZodIPv4",(e,t)=>{Pd.init(e,t),te.init(e,t)});var Uw=y("ZodIPv6",(e,t)=>{Rd.init(e,t),te.init(e,t)});var Fw=y("ZodCIDRv4",(e,t)=>{zd.init(e,t),te.init(e,t)});var Vw=y("ZodCIDRv6",(e,t)=>{Od.init(e,t),te.init(e,t)});var Kw=y("ZodBase64",(e,t)=>{Ad.init(e,t),te.init(e,t)});var Hw=y("ZodBase64URL",(e,t)=>{Nd.init(e,t),te.init(e,t)});var Ww=y("ZodE164",(e,t)=>{Cd.init(e,t),te.init(e,t)});var Gw=y("ZodJWT",(e,t)=>{Dd.init(e,t),te.init(e,t)});var rp=y("ZodNumber",(e,t)=>{cs.init(e,t),oe.init(e,t),e.gt=(n,o)=>e.check(so(n,o)),e.gte=(n,o)=>e.check(Kr(n,o)),e.min=(n,o)=>e.check(Kr(n,o)),e.lt=(n,o)=>e.check(io(n,o)),e.lte=(n,o)=>e.check(Vr(n,o)),e.max=(n,o)=>e.check(Vr(n,o)),e.int=n=>e.check(Xf(n)),e.safe=n=>e.check(Xf(n)),e.positive=n=>e.check(so(0,n)),e.nonnegative=n=>e.check(Kr(0,n)),e.negative=n=>e.check(io(0,n)),e.nonpositive=n=>e.check(Vr(0,n)),e.multipleOf=(n,o)=>e.check(ao(n,o)),e.step=(n,o)=>e.check(ao(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 V(e){return Af(rp,e)}var Jw=y("ZodNumberFormat",(e,t)=>{jd.init(e,t),rp.init(e,t)});function Xf(e){return Nf(Jw,e)}var Qw=y("ZodBoolean",(e,t)=>{Md.init(e,t),oe.init(e,t)});function ce(e){return Cf(Qw,e)}var Yw=y("ZodNull",(e,t)=>{qd.init(e,t),oe.init(e,t)});function np(e){return Df(Yw,e)}var Xw=y("ZodUnknown",(e,t)=>{Ld.init(e,t),oe.init(e,t)});function re(){return jf(Xw)}var eb=y("ZodNever",(e,t)=>{Bd.init(e,t),oe.init(e,t)});function tb(e){return Mf(eb,e)}var rb=y("ZodArray",(e,t)=>{Zd.init(e,t),oe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(nr(r,n)),e.nonempty=r=>e.check(nr(1,r)),e.max=(r,n)=>e.check(co(r,n)),e.length=(r,n)=>e.check(uo(r,n)),e.unwrap=()=>e.element});function q(e,t){return qf(rb,e,t)}var op=y("ZodObject",(e,t)=>{Ud.init(e,t),oe.init(e,t),F.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Se(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:re()}),e.loose=()=>e.clone({...e._zod.def,catchall:re()}),e.strict=()=>e.clone({...e._zod.def,catchall:tb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F.extend(e,r),e.merge=r=>F.merge(e,r),e.pick=r=>F.pick(e,r),e.omit=r=>F.omit(e,r),e.partial=(...r)=>F.partial(ap,e,r[0]),e.required=(...r)=>F.required(cp,e,r[0])});function k(e,t){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},...F.normalizeParams(t)};return new op(r)}function ve(e,t){return new op({type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},catchall:re(),...F.normalizeParams(t)})}var ip=y("ZodUnion",(e,t)=>{us.init(e,t),oe.init(e,t),e.options=t.options});function Y(e,t){return new ip({type:"union",options:e,...F.normalizeParams(t)})}var nb=y("ZodDiscriminatedUnion",(e,t)=>{ip.init(e,t),Fd.init(e,t)});function Ps(e,t,r){return new nb({type:"union",options:t,discriminator:e,...F.normalizeParams(r)})}var ob=y("ZodIntersection",(e,t)=>{Vd.init(e,t),oe.init(e,t)});function po(e,t){return new ob({type:"intersection",left:e,right:t})}var ib=y("ZodRecord",(e,t)=>{Kd.init(e,t),oe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new ib({type:"record",keyType:e,valueType:t,...F.normalizeParams(r)})}var Es=y("ZodEnum",(e,t)=>{Hd.init(e,t),oe.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 i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Es({...t,checks:[],...F.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Es({...t,checks:[],...F.normalizeParams(o),entries:i})}});function Se(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Es({type:"enum",entries:r,...F.normalizeParams(t)})}var sb=y("ZodLiteral",(e,t)=>{Wd.init(e,t),oe.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,t){return new sb({type:"literal",values:Array.isArray(e)?e:[e],...F.normalizeParams(t)})}var ab=y("ZodTransform",(e,t)=>{Gd.init(e,t),oe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(F.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(F.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function sp(e){return new ab({type:"transform",transform:e})}var ap=y("ZodOptional",(e,t)=>{Jd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new ap({type:"optional",innerType:e})}var cb=y("ZodNullable",(e,t)=>{Qd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ep(e){return new cb({type:"nullable",innerType:e})}var ub=y("ZodDefault",(e,t)=>{Yd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function lb(e,t){return new ub({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var db=y("ZodPrefault",(e,t)=>{Xd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fb(e,t){return new db({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var cp=y("ZodNonOptional",(e,t)=>{ef.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pb(e,t){return new cp({type:"nonoptional",innerType:e,...F.normalizeParams(t)})}var mb=y("ZodCatch",(e,t)=>{tf.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function hb(e,t){return new mb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var gb=y("ZodPipe",(e,t)=>{rf.init(e,t),oe.init(e,t),e.in=t.in,e.out=t.out});function Ts(e,t){return new gb({type:"pipe",in:e,out:t})}var yb=y("ZodReadonly",(e,t)=>{nf.init(e,t),oe.init(e,t)});function _b(e){return new yb({type:"readonly",innerType:e})}var up=y("ZodCustom",(e,t)=>{of.init(e,t),oe.init(e,t)});function wb(e){let t=new me({check:"custom"});return t._zod.check=e,t}function lp(e,t){return Lf(up,e??(()=>!0),t)}function bb(e,t={}){return Bf(up,e,t)}function vb(e){let t=wb(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(F.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(F.issue(o))}},e(r.value,r)));return t}function Rs(e,t){return Ts(sp(e),t)}Ae(sf());var Os="2025-11-25";var dp=[Os,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],_t="io.modelcontextprotocol/related-task",ho="2.0",ae=lp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),fp=Y([g(),V().int()]),pp=g(),YA=ve({ttl:V().optional(),pollInterval:V().optional()}),xb=k({ttl:V().optional()}),kb=k({taskId:g()}),Is=ve({progressToken:fp.optional(),[_t]:kb.optional()}),Oe=k({_meta:Is.optional()}),Jr=Oe.extend({task:xb.optional()}),mp=e=>Jr.safeParse(e).success,ue=k({method:g(),params:Oe.loose().optional()}),Ne=k({_meta:Is.optional()}),Ce=k({method:g(),params:Ne.loose().optional()}),le=ve({_meta:Is.optional()}),go=Y([g(),V().int()]),hp=k({jsonrpc:$(ho),id:go,...ue.shape}).strict(),As=e=>hp.safeParse(e).success,gp=k({jsonrpc:$(ho),...Ce.shape}).strict(),yp=e=>gp.safeParse(e).success,Ns=k({jsonrpc:$(ho),id:go,result:le}).strict(),Qr=e=>Ns.safeParse(e).success;var I;(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"})(I||(I={}));var Cs=k({jsonrpc:$(ho),id:go.optional(),error:k({code:V().int(),message:g(),data:re().optional()})}).strict();var _p=e=>Cs.safeParse(e).success;var wp=Y([hp,gp,Ns,Cs]),XA=Y([Ns,Cs]),Dt=le.strict(),$b=Ne.extend({requestId:go.optional(),reason:g().optional()}),yo=Ce.extend({method:$("notifications/cancelled"),params:$b}),Sb=k({src:g(),mimeType:g().optional(),sizes:q(g()).optional(),theme:Se(["light","dark"]).optional()}),Yr=k({icons:q(Sb).optional()}),ir=k({name:g(),title:g().optional()}),bp=ir.extend({...ir.shape,...Yr.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),Eb=po(k({applyDefaults:ce().optional()}),J(g(),re())),Tb=Rs(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,po(k({form:Eb.optional(),url:ae.optional()}),J(g(),re()).optional())),Pb=ve({list:ae.optional(),cancel:ae.optional(),requests:ve({sampling:ve({createMessage:ae.optional()}).optional(),elicitation:ve({create:ae.optional()}).optional()}).optional()}),Rb=ve({list:ae.optional(),cancel:ae.optional(),requests:ve({tools:ve({call:ae.optional()}).optional()}).optional()}),zb=k({experimental:J(g(),ae).optional(),sampling:k({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:Tb.optional(),roots:k({listChanged:ce().optional()}).optional(),tasks:Pb.optional(),extensions:J(g(),ae).optional()}),Ob=Oe.extend({protocolVersion:g(),capabilities:zb,clientInfo:bp}),Ib=ue.extend({method:$("initialize"),params:Ob});var Ab=k({experimental:J(g(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:k({listChanged:ce().optional()}).optional(),resources:k({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:k({listChanged:ce().optional()}).optional(),tasks:Rb.optional(),extensions:J(g(),ae).optional()}),Ds=le.extend({protocolVersion:g(),capabilities:Ab,serverInfo:bp,instructions:g().optional()}),Nb=Ce.extend({method:$("notifications/initialized"),params:Ne.optional()});var _o=ue.extend({method:$("ping"),params:Oe.optional()}),Cb=k({progress:V(),total:ne(V()),message:ne(g())}),Db=k({...Ne.shape,...Cb.shape,progressToken:fp}),wo=Ce.extend({method:$("notifications/progress"),params:Db}),jb=Oe.extend({cursor:pp.optional()}),Xr=ue.extend({params:jb.optional()}),en=le.extend({nextCursor:pp.optional()}),Mb=Se(["working","input_required","completed","failed","cancelled"]),tn=k({taskId:g(),status:Mb,ttl:Y([V(),np()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ne(V()),statusMessage:ne(g())}),jt=le.extend({task:tn}),qb=Ne.merge(tn),rn=Ce.extend({method:$("notifications/tasks/status"),params:qb}),bo=ue.extend({method:$("tasks/get"),params:Oe.extend({taskId:g()})}),vo=le.merge(tn),xo=ue.extend({method:$("tasks/result"),params:Oe.extend({taskId:g()})}),eN=le.loose(),ko=Xr.extend({method:$("tasks/list")}),$o=en.extend({tasks:q(tn)}),So=ue.extend({method:$("tasks/cancel"),params:Oe.extend({taskId:g()})}),vp=le.merge(tn),xp=k({uri:g(),mimeType:ne(g()),_meta:J(g(),re()).optional()}),kp=xp.extend({text:g()}),js=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$p=xp.extend({blob:js}),nn=Se(["user","assistant"]),sr=k({audience:q(nn).optional(),priority:V().min(0).max(1).optional(),lastModified:Wr.datetime({offset:!0}).optional()}),Sp=k({...ir.shape,...Yr.shape,uri:g(),description:ne(g()),mimeType:ne(g()),size:ne(V()),annotations:sr.optional(),_meta:ne(ve({}))}),Lb=k({...ir.shape,...Yr.shape,uriTemplate:g(),description:ne(g()),mimeType:ne(g()),annotations:sr.optional(),_meta:ne(ve({}))}),Bb=Xr.extend({method:$("resources/list")}),Ms=en.extend({resources:q(Sp)}),Zb=Xr.extend({method:$("resources/templates/list")}),qs=en.extend({resourceTemplates:q(Lb)}),Ls=Oe.extend({uri:g()}),Ub=Ls,Fb=ue.extend({method:$("resources/read"),params:Ub}),Bs=le.extend({contents:q(Y([kp,$p]))}),Zs=Ce.extend({method:$("notifications/resources/list_changed"),params:Ne.optional()}),Vb=Ls,Kb=ue.extend({method:$("resources/subscribe"),params:Vb}),Hb=Ls,Wb=ue.extend({method:$("resources/unsubscribe"),params:Hb}),Gb=Ne.extend({uri:g()}),Jb=Ce.extend({method:$("notifications/resources/updated"),params:Gb}),Qb=k({name:g(),description:ne(g()),required:ne(ce())}),Yb=k({...ir.shape,...Yr.shape,description:ne(g()),arguments:ne(q(Qb)),_meta:ne(ve({}))}),Xb=Xr.extend({method:$("prompts/list")}),Us=en.extend({prompts:q(Yb)}),ev=Oe.extend({name:g(),arguments:J(g(),g()).optional()}),tv=ue.extend({method:$("prompts/get"),params:ev}),Fs=k({type:$("text"),text:g(),annotations:sr.optional(),_meta:J(g(),re()).optional()}),Vs=k({type:$("image"),data:js,mimeType:g(),annotations:sr.optional(),_meta:J(g(),re()).optional()}),Ks=k({type:$("audio"),data:js,mimeType:g(),annotations:sr.optional(),_meta:J(g(),re()).optional()}),rv=k({type:$("tool_use"),name:g(),id:g(),input:J(g(),re()),_meta:J(g(),re()).optional()}),nv=k({type:$("resource"),resource:Y([kp,$p]),annotations:sr.optional(),_meta:J(g(),re()).optional()}),ov=Sp.extend({type:$("resource_link")}),Hs=Y([Fs,Vs,Ks,ov,nv]),iv=k({role:nn,content:Hs}),Ws=le.extend({description:g().optional(),messages:q(iv)}),Gs=Ce.extend({method:$("notifications/prompts/list_changed"),params:Ne.optional()}),sv=k({title:g().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),av=k({taskSupport:Se(["required","optional","forbidden"]).optional()}),Ep=k({...ir.shape,...Yr.shape,description:g().optional(),inputSchema:k({type:$("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()),outputSchema:k({type:$("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()).optional(),annotations:sv.optional(),execution:av.optional(),_meta:J(g(),re()).optional()}),cv=Xr.extend({method:$("tools/list")}),Js=en.extend({tools:q(Ep)}),wt=le.extend({content:q(Hs).default([]),structuredContent:J(g(),re()).optional(),isError:ce().optional()}),tN=wt.or(le.extend({toolResult:re()})),uv=Jr.extend({name:g(),arguments:J(g(),re()).optional()}),lv=ue.extend({method:$("tools/call"),params:uv}),Qs=Ce.extend({method:$("notifications/tools/list_changed"),params:Ne.optional()}),Tp=k({autoRefresh:ce().default(!0),debounceMs:V().int().nonnegative().default(300)}),Pp=Se(["debug","info","notice","warning","error","critical","alert","emergency"]),dv=Oe.extend({level:Pp}),fv=ue.extend({method:$("logging/setLevel"),params:dv}),pv=Ne.extend({level:Pp,logger:g().optional(),data:re()}),mv=Ce.extend({method:$("notifications/message"),params:pv}),hv=k({name:g().optional()}),gv=k({hints:q(hv).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),yv=k({mode:Se(["auto","required","none"]).optional()}),_v=k({type:$("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:q(Hs).default([]),structuredContent:k({}).loose().optional(),isError:ce().optional(),_meta:J(g(),re()).optional()}),wv=Ps("type",[Fs,Vs,Ks]),mo=Ps("type",[Fs,Vs,Ks,rv,_v]),bv=k({role:nn,content:Y([mo,q(mo)]),_meta:J(g(),re()).optional()}),vv=Jr.extend({messages:q(bv),modelPreferences:gv.optional(),systemPrompt:g().optional(),includeContext:Se(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:q(g()).optional(),metadata:ae.optional(),tools:q(Ep).optional(),toolChoice:yv.optional()}),Ys=ue.extend({method:$("sampling/createMessage"),params:vv}),Xs=le.extend({model:g(),stopReason:ne(Se(["endTurn","stopSequence","maxTokens"]).or(g())),role:nn,content:wv}),ea=le.extend({model:g(),stopReason:ne(Se(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:nn,content:Y([mo,q(mo)])}),xv=k({type:$("boolean"),title:g().optional(),description:g().optional(),default:ce().optional()}),kv=k({type:$("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Se(["email","uri","date","date-time"]).optional(),default:g().optional()}),$v=k({type:Se(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),Sv=k({type:$("string"),title:g().optional(),description:g().optional(),enum:q(g()),default:g().optional()}),Ev=k({type:$("string"),title:g().optional(),description:g().optional(),oneOf:q(k({const:g(),title:g()})),default:g().optional()}),Tv=k({type:$("string"),title:g().optional(),description:g().optional(),enum:q(g()),enumNames:q(g()).optional(),default:g().optional()}),Pv=Y([Sv,Ev]),Rv=k({type:$("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({type:$("string"),enum:q(g())}),default:q(g()).optional()}),zv=k({type:$("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({anyOf:q(k({const:g(),title:g()}))}),default:q(g()).optional()}),Ov=Y([Rv,zv]),Iv=Y([Tv,Pv,Ov]),Av=Y([Iv,xv,kv,$v]),Nv=Jr.extend({mode:$("form").optional(),message:g(),requestedSchema:k({type:$("object"),properties:J(g(),Av),required:q(g()).optional()})}),Cv=Jr.extend({mode:$("url"),message:g(),elicitationId:g(),url:g().url()}),Dv=Y([Nv,Cv]),ta=ue.extend({method:$("elicitation/create"),params:Dv}),jv=Ne.extend({elicitationId:g()}),Mv=Ce.extend({method:$("notifications/elicitation/complete"),params:jv}),ra=le.extend({action:Se(["accept","decline","cancel"]),content:Rs(e=>e===null?void 0:e,J(g(),Y([g(),V(),ce(),q(g())])).optional())}),qv=k({type:$("ref/resource"),uri:g()});var Lv=k({type:$("ref/prompt"),name:g()}),Bv=Oe.extend({ref:Y([Lv,qv]),argument:k({name:g(),value:g()}),context:k({arguments:J(g(),g()).optional()}).optional()}),Zv=ue.extend({method:$("completion/complete"),params:Bv});var na=le.extend({completion:ve({values:q(g()).max(100),total:ne(V().int()),hasMore:ne(ce())})}),Uv=k({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),re()).optional()}),Fv=ue.extend({method:$("roots/list"),params:Oe.optional()}),Vv=le.extend({roots:q(Uv)}),Kv=Ce.extend({method:$("notifications/roots/list_changed"),params:Ne.optional()}),rN=Y([_o,Ib,Zv,fv,tv,Xb,Bb,Zb,Fb,Kb,Wb,lv,cv,bo,xo,ko,So]),nN=Y([yo,wo,Nb,Kv,rn]),oN=Y([Dt,Xs,ea,ra,Vv,vo,$o,jt]),iN=Y([_o,Ys,ta,Fv,bo,xo,ko,So]),sN=Y([yo,wo,mv,Jb,Zs,Qs,Gs,rn,Mv]),aN=Y([Dt,Ds,na,Ws,Us,Ms,qs,Bs,wt,Js,vo,$o,jt]),T=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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new zs(o.elicitations,r)}return new e(t,r,n)}},zs=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function bt(e){return e==="completed"||e==="failed"||e==="cancelled"}var Hv=Symbol("Let zodToJsonSchema decide on which parser to use");var LN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oa(e){let r=lo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ia(e,t){let r=Ue(e,t);if(!r.success)throw r.error;return r.data}var Xv=6e4,Eo=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(yo,r=>{this._oncancel(r)}),this.setNotificationHandler(wo,r=>{this._onprogress(r)}),this.setRequestHandler(_o,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(bo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(xo,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,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 T(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 s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new T(I.InvalidParams,`Task not found: ${i}`);if(!bt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(bt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[_t]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(ko,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new T(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(So,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(bt(o.status))throw new T(I.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 i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new T(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(I.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,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),T.fromError(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Qr(i)||_p(i)?this._onresponse(i):As(i)?this._onrequest(i,s):yp(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=T.fromError(I.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,i=t.params?._meta?.[_t]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{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 s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=mp(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(s.signal.aborted)throw new T(I.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,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(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{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)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Qr(t))n(t);else{let s=new T(t.error.code,t.error.message,t.error.data);n(s)}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 i=!1;if(Qr(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Qr(t))o(t);else{let s=T.fromError(t.error.code,t.error.message,t.error.data);o(s)}}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(s){yield{type:"error",error:s instanceof T?s:new T(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,jt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},bt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof T?s:new T(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=v=>{u(v)};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(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[_t]:c}});let m=v=>{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(v)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let x=v instanceof T?v:new T(I.RequestTimeout,String(v));u(x)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{let x=Ue(r,v.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??Xv,_=()=>m(T.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let v=x=>{let P=this._responseHandlers.get(f);P?P(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),u(x)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(v=>{this._cleanupTimeout(f),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},vo,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},$o,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},vp,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||{},[_t]: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||{},[_t]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[_t]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=oa(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ia(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=oa(t);this._notificationHandlers.set(n,o=>{let i=ia(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let 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"&&As(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new T(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(I.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 i=await n.getTask(o,r);if(!i)throw new T(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=rn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),bt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new T(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(bt(a.status))throw new T(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=rn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),bt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Rp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zp(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];Rp(s)&&Rp(i)?r[o]={...s,...i}:r[o]=i}return r}var vg=Bi(Vc(),1),xg=Bi(bg(),1);function rT(){let e=new vg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,xg.default)(e),e}var ai=class{constructor(t){this._ajv=t??rT()}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 ci=class{constructor(t){this._client=t}async*callToolStream(t,r=wt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new T(I.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 T(I.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof T){yield{type:"error",error:u};return}yield{type:"error",error:new T(I.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 kg(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 $g(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 ui(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 i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&ui(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&ui(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&ui(r,t)}}function nT(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 li=class extends Eo{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 ai,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Qs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Gs,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Zs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ci(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zp(this._capabilities,t)}setRequestHandler(t,r){let o=lo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(or(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=Ue(ta,c);if(!u.success){let v=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid elicitation request: ${v}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=nT(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(I.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let v=Ue(jt,m);if(!v.success){let x=v.error instanceof Error?v.error.message:String(v.error);throw new T(I.InvalidParams,`Invalid task creation result: ${x}`)}return v.data}let h=Ue(ra,m);if(!h.success){let v=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid elicitation result: ${v}`)}let _=h.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{ui(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Ue(Ys,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Ue(jt,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(I.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?ea:Xs,h=Ue(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid sampling result: ${_}`)}return h.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:Os,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ds,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!dp.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){kg(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&$g(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Dt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},na,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Dt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Ws,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Us,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ms,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},qs,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Bs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Dt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Dt,r)}async callTool(t,r=wt,n){if(this.isToolTaskRequired(t.name))throw new T(I.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),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new T(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new T(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}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},Js,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=Tp.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!s){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"})}};var my=Bi(fy(),1);import cu from"node:process";import{PassThrough as OT}from"node:stream";var fi=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),zT(r)}clear(){this._buffer=void 0}};function zT(e){return wp.parse(JSON.parse(e))}function py(e){return JSON.stringify(e)+`
37
- `}var IT=cu.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function AT(){let e={};for(let t of IT){let r=cu.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var pi=class{constructor(t){this._readBuffer=new fi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new OT)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,my.default)(this._serverParams.command,this._serverParams.args??[],{env:{...AT(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:cu.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=py(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var NT=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Gt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new pi({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??CT(),stderr:t.stderr??"pipe"}),n=new li({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:jT(r).map(MT),nextCursor:hy(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!mi(n,["error"])&&BT(n,["ok","success"],!0),target:t,messageId:Ge(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:qT(r).map(LT).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=NT.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:DT(r)},wt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
- `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function CT(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function DT(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function jT(e){if(Array.isArray(e))return e;if(!Tr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&Tr(r)?[r]:[]}function MT(e){return Tr(e)?{id:Ge(e,["id","message_id","messageId"]),cursor:hy(e,["cursor"]),type:Ge(e,["type","event_type","eventType"]),platform:Ge(e,["platform"]),target:Ge(e,["target"]),sessionKey:Ge(e,["session_key","sessionKey"]),timestamp:Ge(e,["timestamp","created_at","createdAt"]),message:Ge(e,["message","text","content"]),raw:e}:{raw:e}}function qT(e){if(Array.isArray(e))return e;if(!Tr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function LT(e){if(!Tr(e))return null;let t=Ge(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Ge(e,["platform"]),name:Ge(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Ge(e,t){let r=mi(e,t);return typeof r=="string"?r:void 0}function BT(e,t,r){let n=mi(e,t);return typeof n=="boolean"?n:r}function hy(e,t){let r=mi(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function mi(e,t){if(Tr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function Tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as yO,writeFile as _O}from"node:fs/promises";import{join as O_}from"node:path";var hi=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function E(e,t){return new hi(e,t)}var _e=",";function uu(e){let t=e.split(`
39
- `);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(r=>r.endsWith("\r")?r.slice(0,-1):r)}function it(e){return E(e,"invalid quoted string")}function Rt(e,t){if(e==="")return"";if(e.startsWith('"'))return gy(e,t);if(e.includes('"'))throw it(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:ZT(e)?Number(e):e}function Jt(e,t){let r=e.trim();if(r.startsWith('"'))return[gy(r,t),!0];if(r.includes('"')||/\s/.test(r))throw E(t,"expected non-empty field name");return[r,!1]}function gy(e,t){if(e[0]!=='"')throw it(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw it(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw it(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw it(t);r+=String.fromCharCode(a),n+=4;break}default:throw it(t)}continue}if(o<" "&&o!==" ")throw it(t);r+=o}throw it(t)}function Cn(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw it(r);return n.push(e.slice(o).trim()),n}function ze(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw it(r);return-1}function ZT(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function UT(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function FT(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw E(0,"number is not representable in TOON");return String(e)}function gi(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function zt(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return FT(e);if(typeof e=="string")return KT(e,t);throw E(0,"not a primitive")}function VT(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function st(e){return VT(e)?e:yy(e)}function KT(e,t){return HT(e,t)?yy(e):e}function HT(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||UT(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function yy(e){let t='"';for(let r of e)switch(r){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
41
- `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:r<" "?t+=`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=r}return`${t}"`}function Dn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var gu=2;function WT(e={}){return{indent:Math.max(1,e.indent??gu),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function GT(e,t){let r=[],n=!1;return uu(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){n=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw E(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw E(s,"invalid indentation");r.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:n}),n=!1}),r}function pt(e,t){let r=WT(t),n=GT(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw E(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let l;try{l=wu(o.content,ze(o.content,":",o.number))}catch(u){if(r.strict)throw mu(u,o.number);l=void 0}if(l!==void 0)return YT(l,n,r)}if(i&&ze(o.content,":",o.number)===-1)return Rt(o.content.trim(),o.number);let s={index:0},a=yu(n,s,0,r),c=n[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function yu(e,t,r,n){let o={};for(;t.index<e.length;){let i=e[t.index];if(i.depth<r)break;if(i.depth>r)throw E(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=JT(e,t,r,n);by(o,s,a,c,n,i.number)}return o}function JT(e,t,r,n){let o=e[t.index],i=o.content,s=ze(i,":",o.number);if(s===-1)throw E(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1),l=ze(a,"[",o.number),u=ze(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){let m;try{m=rP(a)}catch(_){if(n.strict)throw mu(_,o.number);t.index+=1;let w=lu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw E(o.number,"expected keyed map rows");let h=QT(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){let m;try{m=wu(a,s)}catch(_){if(n.strict)throw mu(_,o.number);t.index+=1;let w=lu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(m.key===""&&!m.keyQuoted)throw E(o.number,"expected non-empty field name");let h=_u(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=Jt(a,o.number);if(d===""&&!f)throw E(o.number,"expected non-empty field name");t.index+=1;let p=lu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function lu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return Rt(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?yu(e,t,r+1,i):{}}function QT(e,t,r,n,o){let i={};for(r.index+=1;r.index<t.length;){let s=t[r.index];if(s.depth<n)break;if(s.depth>n)throw E(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw E(s.number,"blank line inside keyed map");let a=ze(s.content,":",s.number);if(a===-1)throw E(s.number,"expected `key: value`");let[c,l]=Jt(s.content.slice(0,a),s.number);if(c===""&&!l)throw E(s.number,"expected non-empty field name");let u=Cn(s.content.slice(a+1).trim(),e.delimiter,s.number);if(u.length!==e.fields.length)throw E(s.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,p)=>{jn(d,f,Rt(u[p],s.number),o,s.number)}),by(i,c,l,d,o,s.number),r.index+=1}return i}function YT(e,t,r){let n=t[0],o=ze(n.content,":",n.number);if(o===-1)throw E(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=_u(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function _u(e,t,r,n,o,i){let s=r[n.index].number,a=t.trim();if(n.index+=1,e.fields!==void 0){if(a!=="")throw E(s,"expected tabular rows");return XT(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Cn(a,e.delimiter,s).map(l=>Rt(l,s));if(c.length!==e.len)throw E(s,"array length mismatch");return c}return eP(e,r,n,o+1,i)}function XT(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw fu(r,n.index);if(c.depth<o)break;if(c.depth>o)throw E(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw E(c.number,"blank line inside array");if(!_y(c.content,e.delimiter,c.number))break;let l=Cn(c.content,e.delimiter,c.number);if(l.length!==t.length)throw E(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{jn(u,d,Rt(l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw fu(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&_y(a.content,e.delimiter,a.number))throw E(a.number,"array length mismatch");return s}function _y(e,t,r){let n=ze(e,":",r);if(n===-1)return!0;let o=ze(e,t,r);return o===-1?!1:o<n}function eP(e,t,r,n,o){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0||a.depth<n)throw fu(t,r.index);if(a.depth>n)throw E(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw E(a.number,"blank line inside array");i.push(tP(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw E(s.number,"array length mismatch");return i}function tP(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw E(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=ze(i,":",o.number),a;try{a=wu(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return _u(a,c,e,t,r,n)}}if(ze(i,":",o.number)!==-1){let s=[{number:o.number,depth:r+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=r)break;s.push(a),t.index+=1}return yu(s,{index:0},r+1,n)}return t.index+=1,Rt(i,o.number)}function fu(e,t){let r=e[t]??e[e.length-1];return E(r===void 0?1:r.number,"array length mismatch")}function wu(e,t){if(t===-1)throw E(0,"array header missing colon");let r=e.slice(0,t),n=ze(r,"[",0);if(n===-1)throw E(0,"invalid array header");let o,i;try{[o,i]=Jt(r.slice(0,n),0)}catch{throw E(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw E(0,"invalid array header");let c=s.slice(0,a),l=/^[0-9]*/.exec(c)[0];if(l===""||l.length>1&&l.startsWith("0"))throw E(0,"invalid array header");let u=Number.parseInt(l,10),d;switch(c.slice(l.length)){case"":d=",";break;case" ":d=" ";break;case"|":d="|";break;default:throw E(0,"invalid array header")}let f=s.slice(a+1),p;if(f==="")p=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{p=wy(f.slice(1,-1),d)}catch(m){throw E(0,m.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw E(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p}}function rP(e){let t=ze(e,"{",0);if(t===-1||!e.endsWith("}"))throw E(0,"invalid keyed map header");let r,n;try{[r,n]=Jt(e.slice(0,t),0)}catch{throw E(0,"invalid keyed map header")}if(r===""&&!n)throw E(0,"expected non-empty field name");let o;try{o=wy(e.slice(t+1,-1),_e)}catch(i){throw E(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:_e,fields:o}}function wy(e,t){let r=[],n=0;function o(a,c){let l=0;for(;n<e.length&&!(c&&e[n]==="}");){if(e[n]===t||e[n]==="}")throw E(0,"invalid array header");let u=n;for(;n<e.length;){let f=e[n];if(f==='"'){i();continue}if(f===t||f==="{"||f==="}")break;n+=1}let[d]=Jt(e.slice(u,n),0);if(d==="")throw E(0,"invalid array header");if(l+=1,e[n]==="{"){n+=1;let f=r.length;if(o([...a,d],!0),e[n]!=="}"||r.length===f)throw E(0,"invalid array header");n+=1}else r.push([...a,d]);if(e[n]===t){if(n+=1,n>=e.length||e[n]==="}")throw E(0,"invalid array header");continue}if(c?e[n]==="}":n===e.length)break;throw E(0,"invalid array header")}if(l===0)throw E(0,"invalid array header")}function i(){for(n+=1;n<e.length;){let a=e[n];if(n+=1,a==="\\")n+=1;else if(a==='"')return}}if(o([],!1),n!==e.length)throw E(0,"invalid array header");let s=new Set;for(let a=0;a<r.length;a+=1)for(let c=a+1;c<r.length;c+=1)if(nP(r[a],r[c])||pu(r[a],r[c])||pu(r[c],r[a]))throw E(0,"duplicate key");for(let a of r){let c=a.join("\0");if(s.has(c))throw E(0,"duplicate key");s.add(c)}return r}function nP(e,t){return e.length===t.length&&pu(e,t)}function pu(e,t){return t.every((r,n)=>e[n]===r)}function mu(e,t){return E(t,e.reason??String(e.message))}function by(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(oP)){jn(e,s,n,o,i);return}}jn(e,[t],n,o,i)}function jn(e,t,r,n,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw E(o,"duplicate key");Dn(e,i,r);return}if(s&&!Pr(e[i])){if(n.strict)throw E(o,"path expansion conflict");Dn(e,i,{})}else s||Dn(e,i,{});jn(e[i],t.slice(1),r,n,o)}function oP(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mt(e,t={}){let r={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},n=[];return Array.isArray(e)?bu(n,void 0,e,0,!1,r):Pr(e)?vy(n,e,0,r):n.push(zt(e,_e)),n.join("")}function Mn(e,t){e.push(" ".repeat(t*gu))}function vy(e,t,r,n){for(let[o,i]of Object.entries(t))Mn(e,r),hu(e,o,i,r,n)}function hu(e,t,r,n,o){if(Array.isArray(r)){bu(e,t,r,n,!1,o);return}if(Pr(r)){let i=o.keyedMapCollapse?sP(r,o):void 0;if(i!==void 0){e.push(st(t),"{",i.fields.map(vu).join(_e),`}:
42
- `);for(let[s,a]of Object.entries(r))Mn(e,n+1),e.push(st(s),": ",i.paths.map(c=>zt(Sy(a,c),_e)).join(_e),`
43
- `);return}e.push(st(t),`:
44
- `),vy(e,r,n+1,o);return}e.push(st(t),": ",zt(r,_e),`
45
- `)}function bu(e,t,r,n,o,i){if(r.length===0){t!==void 0?e.push(st(t),`: []
34
+ path: iss.path ? [${At(b)}, ...iss.path] : [${At(b)}]
35
+ })));`),f.write(`newResult[${At(b)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,x)=>w(d,b,x)},o,i=tr,s=!Jn.jitless,c=s&&Wi.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??(u=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;let m=[];if(s&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let x=u.shape;for(let R of u.keys){let O=x[R],ve=O._zod.run({value:p[R],issues:[]},f),Ie=O._zod.optin==="optional"&&O._zod.optout==="optional";ve instanceof Promise?m.push(ve.then(er=>Ie?sd(er,d,R,p):no(er,d,R))):Ie?sd(ve,d,R,p):no(ve,d,R)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],_=u.keySet,w=l._zod,b=w.def.type;for(let x of Object.keys(p)){if(_.has(x))continue;if(b==="never"){h.push(x);continue}let R=w.run({value:p[x],issues:[]},f);R instanceof Promise?m.push(R.then(O=>no(O,d,x))):no(R,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function ad(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(i=>Be(i,n,Ae())))}),t}var us=y("$ZodUnion",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),W(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),W(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),W(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=>Lr(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>ad(s,r,e,n)):ad(i,r,e,n)}}),Vd=y("$ZodDiscriminatedUnion",(e,t)=>{us.init(e,t);let r=e._zod.parse;W(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=Mr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!tr(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),Kd=y("$ZodIntersection",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>cd(r,c,l)):cd(r,i,s)}});function as(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(rr(e)&&rr(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=as(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.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],i=t[n],s=as(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function cd(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Nt(e))return e;let n=as(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 Hd=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!rr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Ye(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Ye(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.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 s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,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=>Be(l,n,Ae())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Ye(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Ye(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Wd=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=Fi(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Gi.has(typeof n)).map(n=>typeof n=="string"?yt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),Gd=y("$ZodLiteral",(e,t)=>{G.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?yt(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 Jd=y("$ZodTransform",(e,t)=>{G.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(s=>(r.value=s,r));if(o instanceof Promise)throw new st;return r.value=o,r}}),Qd=y("$ZodOptional",(e,t)=>{G.init(e,t),e._zod.optin="optional",e._zod.optout="optional",W(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Lr(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Yd=y("$ZodNullable",(e,t)=>{G.init(e,t),W(e._zod,"optin",()=>t.innerType._zod.optin),W(e._zod,"optout",()=>t.innerType._zod.optout),W(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Lr(r.source)}|null)$`):void 0}),W(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)}),Xd=y("$ZodDefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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(i=>ud(i,t)):ud(o,t)}});function ud(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ef=y("$ZodPrefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(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))}),tf=y("$ZodNonOptional",(e,t)=>{G.init(e,t),W(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(i=>ld(i,e)):ld(o,e)}});function ld(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 rf=y("$ZodCatch",(e,t)=>{G.init(e,t),e._zod.optin="optional",W(e._zod,"optout",()=>t.innerType._zod.optout),W(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(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Be(s,n,Ae()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Be(i,n,Ae()))},input:r.value}),r.issues=[]),r)}});var nf=y("$ZodPipe",(e,t)=>{G.init(e,t),W(e._zod,"values",()=>t.in._zod.values),W(e._zod,"optin",()=>t.in._zod.optin),W(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(i=>dd(i,t,n)):dd(o,t,n)}});function dd(e,t,r){return Nt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var of=y("$ZodReadonly",(e,t)=>{G.init(e,t),W(e._zod,"propValues",()=>t.innerType._zod.propValues),W(e._zod,"values",()=>t.innerType._zod.values),W(e._zod,"optin",()=>t.innerType._zod.optin),W(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(fd):fd(o)}});function fd(e){return e.value=Object.freeze(e.value),e}var sf=y("$ZodCustom",(e,t)=>{me.init(e,t),G.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(i=>pd(i,r,n,e));pd(o,r,n,e)}});function pd(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(Yi(o))}}var Sw=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},Ew=()=>{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 ${Sw(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Xn(n.values[0])}`:`Invalid option: expected one of ${Qn(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.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":""}: ${Qn(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 af(){return{localeError:Ew()}}var zI=Symbol("ZodOutput"),OI=Symbol("ZodInput"),ls=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 Tw(){return new ls}var Fr=Tw();function cf(e,t){return new e({type:"string",...P(t)})}function uf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function ds(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function lf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function df(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function ff(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function pf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function mf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function hf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function gf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function yf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function _f(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function wf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function vf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function bf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function xf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function kf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function $f(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Sf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function Ef(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function Tf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function Rf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function Pf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function zf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Of(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function If(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function Af(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function Nf(e,t){return new e({type:"number",checks:[],...P(t)})}function Cf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function Df(e,t){return new e({type:"boolean",...P(t)})}function jf(e,t){return new e({type:"null",...P(t)})}function Mf(e){return new e({type:"unknown"})}function qf(e,t){return new e({type:"never",...P(t)})}function io(e,t){return new is({check:"less_than",...P(t),value:e,inclusive:!1})}function Vr(e,t){return new is({check:"less_than",...P(t),value:e,inclusive:!0})}function so(e,t){return new ss({check:"greater_than",...P(t),value:e,inclusive:!1})}function Kr(e,t){return new ss({check:"greater_than",...P(t),value:e,inclusive:!0})}function ao(e,t){return new Vl({check:"multiple_of",...P(t),value:e})}function co(e,t){return new Hl({check:"max_length",...P(t),maximum:e})}function nr(e,t){return new Wl({check:"min_length",...P(t),minimum:e})}function uo(e,t){return new Gl({check:"length_equals",...P(t),length:e})}function fs(e,t){return new Jl({check:"string_format",format:"regex",...P(t),pattern:e})}function ps(e){return new Ql({check:"string_format",format:"lowercase",...P(e)})}function ms(e){return new Yl({check:"string_format",format:"uppercase",...P(e)})}function hs(e,t){return new Xl({check:"string_format",format:"includes",...P(t),includes:e})}function gs(e,t){return new ed({check:"string_format",format:"starts_with",...P(t),prefix:e})}function ys(e,t){return new td({check:"string_format",format:"ends_with",...P(t),suffix:e})}function Ct(e){return new rd({check:"overwrite",tx:e})}function _s(e){return Ct(t=>t.normalize(e))}function ws(){return Ct(e=>e.trim())}function vs(){return Ct(e=>e.toLowerCase())}function bs(){return Ct(e=>e.toUpperCase())}function Lf(e,t,r){return new e({type:"array",element:t,...P(r)})}function Bf(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Zf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function or(e){return!!e._zod}function Ze(e,t){return or(e)?Zr(e,t):e.safeParse(t)}function lo(e){if(!e)return;let t;if(or(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Uf(e){if(or(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var Wr={};sl(Wr,{ZodISODate:()=>Vf,ZodISODateTime:()=>Ff,ZodISODuration:()=>Hf,ZodISOTime:()=>Kf,date:()=>ks,datetime:()=>xs,duration:()=>Ss,time:()=>$s});var Ff=y("ZodISODateTime",(e,t)=>{Sd.init(e,t),te.init(e,t)});function xs(e){return zf(Ff,e)}var Vf=y("ZodISODate",(e,t)=>{Ed.init(e,t),te.init(e,t)});function ks(e){return Of(Vf,e)}var Kf=y("ZodISOTime",(e,t)=>{Td.init(e,t),te.init(e,t)});function $s(e){return If(Kf,e)}var Hf=y("ZodISODuration",(e,t)=>{Rd.init(e,t),te.init(e,t)});function Ss(e){return Af(Hf,e)}var Wf=(e,t)=>{eo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>fl(e,r)},flatten:{value:r=>dl(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},dA=y("ZodError",Wf),Gr=y("ZodError",Wf,{Parent:Error});var Gf=pl(Gr),Jf=ml(Gr),Qf=es(Gr),Yf=ts(Gr);var oe=y("ZodType",(e,t)=>(G.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)=>Qe(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Gf(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Qf(e,r,n),e.parseAsync=async(r,n)=>Jf(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Yf(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check($v(r,n)),e.superRefine=r=>e.check(Sv(r)),e.overwrite=r=>e.check(Ct(r)),e.optional=()=>ne(e),e.nullable=()=>tp(e),e.nullish=()=>ne(tp(e)),e.nonoptional=r=>yv(e,r),e.array=()=>q(e),e.or=r=>Y([e,r]),e.and=r=>po(e,r),e.transform=r=>Ts(e,ap(r)),e.default=r=>mv(e,r),e.prefault=r=>gv(e,r),e.catch=r=>wv(e,r),e.pipe=r=>Ts(e,r),e.readonly=()=>xv(e),e.describe=r=>{let n=e.clone();return Fr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Fr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Fr.get(e);let n=e.clone();return Fr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),rp=y("_ZodString",(e,t)=>{oo.init(e,t),oe.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(fs(...n)),e.includes=(...n)=>e.check(hs(...n)),e.startsWith=(...n)=>e.check(gs(...n)),e.endsWith=(...n)=>e.check(ys(...n)),e.min=(...n)=>e.check(nr(...n)),e.max=(...n)=>e.check(co(...n)),e.length=(...n)=>e.check(uo(...n)),e.nonempty=(...n)=>e.check(nr(1,...n)),e.lowercase=n=>e.check(ps(n)),e.uppercase=n=>e.check(ms(n)),e.trim=()=>e.check(ws()),e.normalize=(...n)=>e.check(_s(...n)),e.toLowerCase=()=>e.check(vs()),e.toUpperCase=()=>e.check(bs())}),Dw=y("ZodString",(e,t)=>{oo.init(e,t),rp.init(e,t),e.email=r=>e.check(uf(jw,r)),e.url=r=>e.check(mf(Mw,r)),e.jwt=r=>e.check(Pf(Xw,r)),e.emoji=r=>e.check(hf(qw,r)),e.guid=r=>e.check(ds(Xf,r)),e.uuid=r=>e.check(lf(fo,r)),e.uuidv4=r=>e.check(df(fo,r)),e.uuidv6=r=>e.check(ff(fo,r)),e.uuidv7=r=>e.check(pf(fo,r)),e.nanoid=r=>e.check(gf(Lw,r)),e.guid=r=>e.check(ds(Xf,r)),e.cuid=r=>e.check(yf(Bw,r)),e.cuid2=r=>e.check(_f(Zw,r)),e.ulid=r=>e.check(wf(Uw,r)),e.base64=r=>e.check(Ef(Jw,r)),e.base64url=r=>e.check(Tf(Qw,r)),e.xid=r=>e.check(vf(Fw,r)),e.ksuid=r=>e.check(bf(Vw,r)),e.ipv4=r=>e.check(xf(Kw,r)),e.ipv6=r=>e.check(kf(Hw,r)),e.cidrv4=r=>e.check($f(Ww,r)),e.cidrv6=r=>e.check(Sf(Gw,r)),e.e164=r=>e.check(Rf(Yw,r)),e.datetime=r=>e.check(xs(r)),e.date=r=>e.check(ks(r)),e.time=r=>e.check($s(r)),e.duration=r=>e.check(Ss(r))});function g(e){return cf(Dw,e)}var te=y("ZodStringFormat",(e,t)=>{Q.init(e,t),rp.init(e,t)}),jw=y("ZodEmail",(e,t)=>{gd.init(e,t),te.init(e,t)});var Xf=y("ZodGUID",(e,t)=>{md.init(e,t),te.init(e,t)});var fo=y("ZodUUID",(e,t)=>{hd.init(e,t),te.init(e,t)});var Mw=y("ZodURL",(e,t)=>{yd.init(e,t),te.init(e,t)});var qw=y("ZodEmoji",(e,t)=>{_d.init(e,t),te.init(e,t)});var Lw=y("ZodNanoID",(e,t)=>{wd.init(e,t),te.init(e,t)});var Bw=y("ZodCUID",(e,t)=>{vd.init(e,t),te.init(e,t)});var Zw=y("ZodCUID2",(e,t)=>{bd.init(e,t),te.init(e,t)});var Uw=y("ZodULID",(e,t)=>{xd.init(e,t),te.init(e,t)});var Fw=y("ZodXID",(e,t)=>{kd.init(e,t),te.init(e,t)});var Vw=y("ZodKSUID",(e,t)=>{$d.init(e,t),te.init(e,t)});var Kw=y("ZodIPv4",(e,t)=>{Pd.init(e,t),te.init(e,t)});var Hw=y("ZodIPv6",(e,t)=>{zd.init(e,t),te.init(e,t)});var Ww=y("ZodCIDRv4",(e,t)=>{Od.init(e,t),te.init(e,t)});var Gw=y("ZodCIDRv6",(e,t)=>{Id.init(e,t),te.init(e,t)});var Jw=y("ZodBase64",(e,t)=>{Nd.init(e,t),te.init(e,t)});var Qw=y("ZodBase64URL",(e,t)=>{Cd.init(e,t),te.init(e,t)});var Yw=y("ZodE164",(e,t)=>{Dd.init(e,t),te.init(e,t)});var Xw=y("ZodJWT",(e,t)=>{jd.init(e,t),te.init(e,t)});var np=y("ZodNumber",(e,t)=>{cs.init(e,t),oe.init(e,t),e.gt=(n,o)=>e.check(so(n,o)),e.gte=(n,o)=>e.check(Kr(n,o)),e.min=(n,o)=>e.check(Kr(n,o)),e.lt=(n,o)=>e.check(io(n,o)),e.lte=(n,o)=>e.check(Vr(n,o)),e.max=(n,o)=>e.check(Vr(n,o)),e.int=n=>e.check(ep(n)),e.safe=n=>e.check(ep(n)),e.positive=n=>e.check(so(0,n)),e.nonnegative=n=>e.check(Kr(0,n)),e.negative=n=>e.check(io(0,n)),e.nonpositive=n=>e.check(Vr(0,n)),e.multipleOf=(n,o)=>e.check(ao(n,o)),e.step=(n,o)=>e.check(ao(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 V(e){return Nf(np,e)}var ev=y("ZodNumberFormat",(e,t)=>{Md.init(e,t),np.init(e,t)});function ep(e){return Cf(ev,e)}var tv=y("ZodBoolean",(e,t)=>{qd.init(e,t),oe.init(e,t)});function ce(e){return Df(tv,e)}var rv=y("ZodNull",(e,t)=>{Ld.init(e,t),oe.init(e,t)});function op(e){return jf(rv,e)}var nv=y("ZodUnknown",(e,t)=>{Bd.init(e,t),oe.init(e,t)});function re(){return Mf(nv)}var ov=y("ZodNever",(e,t)=>{Zd.init(e,t),oe.init(e,t)});function iv(e){return qf(ov,e)}var sv=y("ZodArray",(e,t)=>{Ud.init(e,t),oe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(nr(r,n)),e.nonempty=r=>e.check(nr(1,r)),e.max=(r,n)=>e.check(co(r,n)),e.length=(r,n)=>e.check(uo(r,n)),e.unwrap=()=>e.element});function q(e,t){return Lf(sv,e,t)}var ip=y("ZodObject",(e,t)=>{Fd.init(e,t),oe.init(e,t),F.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Se(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:re()}),e.loose=()=>e.clone({...e._zod.def,catchall:re()}),e.strict=()=>e.clone({...e._zod.def,catchall:iv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F.extend(e,r),e.merge=r=>F.merge(e,r),e.pick=r=>F.pick(e,r),e.omit=r=>F.omit(e,r),e.partial=(...r)=>F.partial(cp,e,r[0]),e.required=(...r)=>F.required(up,e,r[0])});function k(e,t){let r={type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},...F.normalizeParams(t)};return new ip(r)}function be(e,t){return new ip({type:"object",get shape(){return F.assignProp(this,"shape",{...e}),this.shape},catchall:re(),...F.normalizeParams(t)})}var sp=y("ZodUnion",(e,t)=>{us.init(e,t),oe.init(e,t),e.options=t.options});function Y(e,t){return new sp({type:"union",options:e,...F.normalizeParams(t)})}var av=y("ZodDiscriminatedUnion",(e,t)=>{sp.init(e,t),Vd.init(e,t)});function Rs(e,t,r){return new av({type:"union",options:t,discriminator:e,...F.normalizeParams(r)})}var cv=y("ZodIntersection",(e,t)=>{Kd.init(e,t),oe.init(e,t)});function po(e,t){return new cv({type:"intersection",left:e,right:t})}var uv=y("ZodRecord",(e,t)=>{Hd.init(e,t),oe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function J(e,t,r){return new uv({type:"record",keyType:e,valueType:t,...F.normalizeParams(r)})}var Es=y("ZodEnum",(e,t)=>{Wd.init(e,t),oe.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 i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Es({...t,checks:[],...F.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Es({...t,checks:[],...F.normalizeParams(o),entries:i})}});function Se(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Es({type:"enum",entries:r,...F.normalizeParams(t)})}var lv=y("ZodLiteral",(e,t)=>{Gd.init(e,t),oe.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,t){return new lv({type:"literal",values:Array.isArray(e)?e:[e],...F.normalizeParams(t)})}var dv=y("ZodTransform",(e,t)=>{Jd.init(e,t),oe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(F.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(F.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function ap(e){return new dv({type:"transform",transform:e})}var cp=y("ZodOptional",(e,t)=>{Qd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new cp({type:"optional",innerType:e})}var fv=y("ZodNullable",(e,t)=>{Yd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tp(e){return new fv({type:"nullable",innerType:e})}var pv=y("ZodDefault",(e,t)=>{Xd.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function mv(e,t){return new pv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var hv=y("ZodPrefault",(e,t)=>{ef.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function gv(e,t){return new hv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var up=y("ZodNonOptional",(e,t)=>{tf.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function yv(e,t){return new up({type:"nonoptional",innerType:e,...F.normalizeParams(t)})}var _v=y("ZodCatch",(e,t)=>{rf.init(e,t),oe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function wv(e,t){return new _v({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var vv=y("ZodPipe",(e,t)=>{nf.init(e,t),oe.init(e,t),e.in=t.in,e.out=t.out});function Ts(e,t){return new vv({type:"pipe",in:e,out:t})}var bv=y("ZodReadonly",(e,t)=>{of.init(e,t),oe.init(e,t)});function xv(e){return new bv({type:"readonly",innerType:e})}var lp=y("ZodCustom",(e,t)=>{sf.init(e,t),oe.init(e,t)});function kv(e){let t=new me({check:"custom"});return t._zod.check=e,t}function dp(e,t){return Bf(lp,e??(()=>!0),t)}function $v(e,t={}){return Zf(lp,e,t)}function Sv(e){let t=kv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(F.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(F.issue(o))}},e(r.value,r)));return t}function Ps(e,t){return Ts(ap(e),t)}Ae(af());var Os="2025-11-25";var fp=[Os,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],_t="io.modelcontextprotocol/related-task",ho="2.0",ae=dp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),pp=Y([g(),V().int()]),mp=g(),oN=be({ttl:V().optional(),pollInterval:V().optional()}),Ev=k({ttl:V().optional()}),Tv=k({taskId:g()}),Is=be({progressToken:pp.optional(),[_t]:Tv.optional()}),Oe=k({_meta:Is.optional()}),Jr=Oe.extend({task:Ev.optional()}),hp=e=>Jr.safeParse(e).success,ue=k({method:g(),params:Oe.loose().optional()}),Ne=k({_meta:Is.optional()}),Ce=k({method:g(),params:Ne.loose().optional()}),le=be({_meta:Is.optional()}),go=Y([g(),V().int()]),gp=k({jsonrpc:$(ho),id:go,...ue.shape}).strict(),As=e=>gp.safeParse(e).success,yp=k({jsonrpc:$(ho),...Ce.shape}).strict(),_p=e=>yp.safeParse(e).success,Ns=k({jsonrpc:$(ho),id:go,result:le}).strict(),Qr=e=>Ns.safeParse(e).success;var I;(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"})(I||(I={}));var Cs=k({jsonrpc:$(ho),id:go.optional(),error:k({code:V().int(),message:g(),data:re().optional()})}).strict();var wp=e=>Cs.safeParse(e).success;var vp=Y([gp,yp,Ns,Cs]),iN=Y([Ns,Cs]),Dt=le.strict(),Rv=Ne.extend({requestId:go.optional(),reason:g().optional()}),yo=Ce.extend({method:$("notifications/cancelled"),params:Rv}),Pv=k({src:g(),mimeType:g().optional(),sizes:q(g()).optional(),theme:Se(["light","dark"]).optional()}),Yr=k({icons:q(Pv).optional()}),ir=k({name:g(),title:g().optional()}),bp=ir.extend({...ir.shape,...Yr.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),zv=po(k({applyDefaults:ce().optional()}),J(g(),re())),Ov=Ps(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,po(k({form:zv.optional(),url:ae.optional()}),J(g(),re()).optional())),Iv=be({list:ae.optional(),cancel:ae.optional(),requests:be({sampling:be({createMessage:ae.optional()}).optional(),elicitation:be({create:ae.optional()}).optional()}).optional()}),Av=be({list:ae.optional(),cancel:ae.optional(),requests:be({tools:be({call:ae.optional()}).optional()}).optional()}),Nv=k({experimental:J(g(),ae).optional(),sampling:k({context:ae.optional(),tools:ae.optional()}).optional(),elicitation:Ov.optional(),roots:k({listChanged:ce().optional()}).optional(),tasks:Iv.optional(),extensions:J(g(),ae).optional()}),Cv=Oe.extend({protocolVersion:g(),capabilities:Nv,clientInfo:bp}),Dv=ue.extend({method:$("initialize"),params:Cv});var jv=k({experimental:J(g(),ae).optional(),logging:ae.optional(),completions:ae.optional(),prompts:k({listChanged:ce().optional()}).optional(),resources:k({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:k({listChanged:ce().optional()}).optional(),tasks:Av.optional(),extensions:J(g(),ae).optional()}),Ds=le.extend({protocolVersion:g(),capabilities:jv,serverInfo:bp,instructions:g().optional()}),Mv=Ce.extend({method:$("notifications/initialized"),params:Ne.optional()});var _o=ue.extend({method:$("ping"),params:Oe.optional()}),qv=k({progress:V(),total:ne(V()),message:ne(g())}),Lv=k({...Ne.shape,...qv.shape,progressToken:pp}),wo=Ce.extend({method:$("notifications/progress"),params:Lv}),Bv=Oe.extend({cursor:mp.optional()}),Xr=ue.extend({params:Bv.optional()}),en=le.extend({nextCursor:mp.optional()}),Zv=Se(["working","input_required","completed","failed","cancelled"]),tn=k({taskId:g(),status:Zv,ttl:Y([V(),op()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ne(V()),statusMessage:ne(g())}),jt=le.extend({task:tn}),Uv=Ne.merge(tn),rn=Ce.extend({method:$("notifications/tasks/status"),params:Uv}),vo=ue.extend({method:$("tasks/get"),params:Oe.extend({taskId:g()})}),bo=le.merge(tn),xo=ue.extend({method:$("tasks/result"),params:Oe.extend({taskId:g()})}),sN=le.loose(),ko=Xr.extend({method:$("tasks/list")}),$o=en.extend({tasks:q(tn)}),So=ue.extend({method:$("tasks/cancel"),params:Oe.extend({taskId:g()})}),xp=le.merge(tn),kp=k({uri:g(),mimeType:ne(g()),_meta:J(g(),re()).optional()}),$p=kp.extend({text:g()}),js=g().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Sp=kp.extend({blob:js}),nn=Se(["user","assistant"]),sr=k({audience:q(nn).optional(),priority:V().min(0).max(1).optional(),lastModified:Wr.datetime({offset:!0}).optional()}),Ep=k({...ir.shape,...Yr.shape,uri:g(),description:ne(g()),mimeType:ne(g()),size:ne(V()),annotations:sr.optional(),_meta:ne(be({}))}),Fv=k({...ir.shape,...Yr.shape,uriTemplate:g(),description:ne(g()),mimeType:ne(g()),annotations:sr.optional(),_meta:ne(be({}))}),Vv=Xr.extend({method:$("resources/list")}),Ms=en.extend({resources:q(Ep)}),Kv=Xr.extend({method:$("resources/templates/list")}),qs=en.extend({resourceTemplates:q(Fv)}),Ls=Oe.extend({uri:g()}),Hv=Ls,Wv=ue.extend({method:$("resources/read"),params:Hv}),Bs=le.extend({contents:q(Y([$p,Sp]))}),Zs=Ce.extend({method:$("notifications/resources/list_changed"),params:Ne.optional()}),Gv=Ls,Jv=ue.extend({method:$("resources/subscribe"),params:Gv}),Qv=Ls,Yv=ue.extend({method:$("resources/unsubscribe"),params:Qv}),Xv=Ne.extend({uri:g()}),eb=Ce.extend({method:$("notifications/resources/updated"),params:Xv}),tb=k({name:g(),description:ne(g()),required:ne(ce())}),rb=k({...ir.shape,...Yr.shape,description:ne(g()),arguments:ne(q(tb)),_meta:ne(be({}))}),nb=Xr.extend({method:$("prompts/list")}),Us=en.extend({prompts:q(rb)}),ob=Oe.extend({name:g(),arguments:J(g(),g()).optional()}),ib=ue.extend({method:$("prompts/get"),params:ob}),Fs=k({type:$("text"),text:g(),annotations:sr.optional(),_meta:J(g(),re()).optional()}),Vs=k({type:$("image"),data:js,mimeType:g(),annotations:sr.optional(),_meta:J(g(),re()).optional()}),Ks=k({type:$("audio"),data:js,mimeType:g(),annotations:sr.optional(),_meta:J(g(),re()).optional()}),sb=k({type:$("tool_use"),name:g(),id:g(),input:J(g(),re()),_meta:J(g(),re()).optional()}),ab=k({type:$("resource"),resource:Y([$p,Sp]),annotations:sr.optional(),_meta:J(g(),re()).optional()}),cb=Ep.extend({type:$("resource_link")}),Hs=Y([Fs,Vs,Ks,cb,ab]),ub=k({role:nn,content:Hs}),Ws=le.extend({description:g().optional(),messages:q(ub)}),Gs=Ce.extend({method:$("notifications/prompts/list_changed"),params:Ne.optional()}),lb=k({title:g().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),db=k({taskSupport:Se(["required","optional","forbidden"]).optional()}),Tp=k({...ir.shape,...Yr.shape,description:g().optional(),inputSchema:k({type:$("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()),outputSchema:k({type:$("object"),properties:J(g(),ae).optional(),required:q(g()).optional()}).catchall(re()).optional(),annotations:lb.optional(),execution:db.optional(),_meta:J(g(),re()).optional()}),fb=Xr.extend({method:$("tools/list")}),Js=en.extend({tools:q(Tp)}),wt=le.extend({content:q(Hs).default([]),structuredContent:J(g(),re()).optional(),isError:ce().optional()}),aN=wt.or(le.extend({toolResult:re()})),pb=Jr.extend({name:g(),arguments:J(g(),re()).optional()}),mb=ue.extend({method:$("tools/call"),params:pb}),Qs=Ce.extend({method:$("notifications/tools/list_changed"),params:Ne.optional()}),Rp=k({autoRefresh:ce().default(!0),debounceMs:V().int().nonnegative().default(300)}),Pp=Se(["debug","info","notice","warning","error","critical","alert","emergency"]),hb=Oe.extend({level:Pp}),gb=ue.extend({method:$("logging/setLevel"),params:hb}),yb=Ne.extend({level:Pp,logger:g().optional(),data:re()}),_b=Ce.extend({method:$("notifications/message"),params:yb}),wb=k({name:g().optional()}),vb=k({hints:q(wb).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),bb=k({mode:Se(["auto","required","none"]).optional()}),xb=k({type:$("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:q(Hs).default([]),structuredContent:k({}).loose().optional(),isError:ce().optional(),_meta:J(g(),re()).optional()}),kb=Rs("type",[Fs,Vs,Ks]),mo=Rs("type",[Fs,Vs,Ks,sb,xb]),$b=k({role:nn,content:Y([mo,q(mo)]),_meta:J(g(),re()).optional()}),Sb=Jr.extend({messages:q($b),modelPreferences:vb.optional(),systemPrompt:g().optional(),includeContext:Se(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:q(g()).optional(),metadata:ae.optional(),tools:q(Tp).optional(),toolChoice:bb.optional()}),Ys=ue.extend({method:$("sampling/createMessage"),params:Sb}),Xs=le.extend({model:g(),stopReason:ne(Se(["endTurn","stopSequence","maxTokens"]).or(g())),role:nn,content:kb}),ea=le.extend({model:g(),stopReason:ne(Se(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:nn,content:Y([mo,q(mo)])}),Eb=k({type:$("boolean"),title:g().optional(),description:g().optional(),default:ce().optional()}),Tb=k({type:$("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Se(["email","uri","date","date-time"]).optional(),default:g().optional()}),Rb=k({type:Se(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),Pb=k({type:$("string"),title:g().optional(),description:g().optional(),enum:q(g()),default:g().optional()}),zb=k({type:$("string"),title:g().optional(),description:g().optional(),oneOf:q(k({const:g(),title:g()})),default:g().optional()}),Ob=k({type:$("string"),title:g().optional(),description:g().optional(),enum:q(g()),enumNames:q(g()).optional(),default:g().optional()}),Ib=Y([Pb,zb]),Ab=k({type:$("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({type:$("string"),enum:q(g())}),default:q(g()).optional()}),Nb=k({type:$("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({anyOf:q(k({const:g(),title:g()}))}),default:q(g()).optional()}),Cb=Y([Ab,Nb]),Db=Y([Ob,Ib,Cb]),jb=Y([Db,Eb,Tb,Rb]),Mb=Jr.extend({mode:$("form").optional(),message:g(),requestedSchema:k({type:$("object"),properties:J(g(),jb),required:q(g()).optional()})}),qb=Jr.extend({mode:$("url"),message:g(),elicitationId:g(),url:g().url()}),Lb=Y([Mb,qb]),ta=ue.extend({method:$("elicitation/create"),params:Lb}),Bb=Ne.extend({elicitationId:g()}),Zb=Ce.extend({method:$("notifications/elicitation/complete"),params:Bb}),ra=le.extend({action:Se(["accept","decline","cancel"]),content:Ps(e=>e===null?void 0:e,J(g(),Y([g(),V(),ce(),q(g())])).optional())}),Ub=k({type:$("ref/resource"),uri:g()});var Fb=k({type:$("ref/prompt"),name:g()}),Vb=Oe.extend({ref:Y([Fb,Ub]),argument:k({name:g(),value:g()}),context:k({arguments:J(g(),g()).optional()}).optional()}),Kb=ue.extend({method:$("completion/complete"),params:Vb});var na=le.extend({completion:be({values:q(g()).max(100),total:ne(V().int()),hasMore:ne(ce())})}),Hb=k({uri:g().startsWith("file://"),name:g().optional(),_meta:J(g(),re()).optional()}),Wb=ue.extend({method:$("roots/list"),params:Oe.optional()}),Gb=le.extend({roots:q(Hb)}),Jb=Ce.extend({method:$("notifications/roots/list_changed"),params:Ne.optional()}),cN=Y([_o,Dv,Kb,gb,ib,nb,Vv,Kv,Wv,Jv,Yv,mb,fb,vo,xo,ko,So]),uN=Y([yo,wo,Mv,Jb,rn]),lN=Y([Dt,Xs,ea,ra,Gb,bo,$o,jt]),dN=Y([_o,Ys,ta,Wb,vo,xo,ko,So]),fN=Y([yo,wo,_b,eb,Zs,Qs,Gs,rn,Zb]),pN=Y([Dt,Ds,na,Ws,Us,Ms,qs,Bs,wt,Js,bo,$o,jt]),T=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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new zs(o.elicitations,r)}return new e(t,r,n)}},zs=class extends T{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function vt(e){return e==="completed"||e==="failed"||e==="cancelled"}var Qb=Symbol("Let zodToJsonSchema decide on which parser to use");var KN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oa(e){let r=lo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Uf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ia(e,t){let r=Ze(e,t);if(!r.success)throw r.error;return r.data}var nx=6e4,Eo=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(yo,r=>{this._oncancel(r)}),this.setNotificationHandler(wo,r=>{this._onprogress(r)}),this.setRequestHandler(_o,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(vo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(xo,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,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 T(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 s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new T(I.InvalidParams,`Task not found: ${i}`);if(!vt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(vt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[_t]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(ko,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new T(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(So,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(vt(o.status))throw new T(I.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 i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new T(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T(I.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,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),T.fromError(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Qr(i)||wp(i)?this._onresponse(i):As(i)?this._onrequest(i,s):_p(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=T.fromError(I.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,i=t.params?._meta?.[_t]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{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 s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=hp(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(s.signal.aborted)throw new T(I.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,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(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{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)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Qr(t))n(t);else{let s=new T(t.error.code,t.error.message,t.error.data);n(s)}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 i=!1;if(Qr(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Qr(t))o(t);else{let s=T.fromError(t.error.code,t.error.message,t.error.data);o(s)}}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(s){yield{type:"error",error:s instanceof T?s:new T(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,jt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},vt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof T?s:new T(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};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(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[_t]:c}});let m=b=>{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(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let x=b instanceof T?b:new T(I.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=Ze(r,b.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??nx,_=()=>m(T.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=x=>{let R=this._responseHandlers.get(f);R?R(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),u(x)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},bo,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},$o,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},xp,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||{},[_t]: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||{},[_t]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[_t]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=oa(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ia(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=oa(t);this._notificationHandlers.set(n,o=>{let i=ia(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let 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"&&As(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new T(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T(I.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 i=await n.getTask(o,r);if(!i)throw new T(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=rn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),vt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new T(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(vt(a.status))throw new T(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=rn.parse({method:"notifications/tasks/status",params:c});await this.notification(l),vt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function zp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Op(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];zp(s)&&zp(i)?r[o]={...s,...i}:r[o]=i}return r}var xg=Bi(Vc(),1),kg=Bi(bg(),1);function sT(){let e=new xg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,kg.default)(e),e}var ai=class{constructor(t){this._ajv=t??sT()}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 ci=class{constructor(t){this._client=t}async*callToolStream(t,r=wt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new T(I.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 T(I.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof T){yield{type:"error",error:u};return}yield{type:"error",error:new T(I.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 $g(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 Sg(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 ui(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 i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&ui(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&ui(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&ui(r,t)}}function aT(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 li=class extends Eo{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 ai,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Qs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Gs,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Zs,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ci(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Op(this._capabilities,t)}setRequestHandler(t,r){let o=lo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(or(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=Ze(ta,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=aT(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new T(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new T(I.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,l));if(d.task){let b=Ze(jt,m);if(!b.success){let x=b.error instanceof Error?b.error.message:String(b.error);throw new T(I.InvalidParams,`Invalid task creation result: ${x}`)}return b.data}let h=Ze(ra,m);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid elicitation result: ${b}`)}let _=h.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{ui(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=Ze(Ys,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new T(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let _=Ze(jt,f);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new T(I.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let m=d.tools||d.toolChoice?ea:Xs,h=Ze(m,f);if(!h.success){let _=h.error instanceof Error?h.error.message:String(h.error);throw new T(I.InvalidParams,`Invalid sampling result: ${_}`)}return h.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:Os,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ds,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!fp.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){$g(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Sg(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Dt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},na,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Dt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Ws,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Us,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Ms,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},qs,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Bs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Dt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Dt,r)}async callTool(t,r=wt,n){if(this.isToolTaskRequired(t.name))throw new T(I.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),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new T(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new T(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}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},Js,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=Rp.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!s){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"})}};var hy=Bi(py(),1);import cu from"node:process";import{PassThrough as CT}from"node:stream";var fi=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
+ `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),NT(r)}clear(){this._buffer=void 0}};function NT(e){return vp.parse(JSON.parse(e))}function my(e){return JSON.stringify(e)+`
37
+ `}var DT=cu.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function jT(){let e={};for(let t of DT){let r=cu.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var pi=class{constructor(t){this._readBuffer=new fi,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new CT)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,hy.default)(this._serverParams.command,this._serverParams.args??[],{env:{...jT(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:cu.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=my(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var MT=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Gt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new pi({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??qT(),stderr:t.stderr??"pipe"}),n=new li({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:BT(r).map(ZT),nextCursor:gy(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!mi(n,["error"])&&VT(n,["ok","success"],!0),target:t,messageId:We(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:UT(r).map(FT).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=MT.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:LT(r)},wt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
+ `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function qT(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function LT(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function BT(e){if(Array.isArray(e))return e;if(!Tr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&Tr(r)?[r]:[]}function ZT(e){return Tr(e)?{id:We(e,["id","message_id","messageId"]),cursor:gy(e,["cursor"]),type:We(e,["type","event_type","eventType"]),platform:We(e,["platform"]),target:We(e,["target"]),sessionKey:We(e,["session_key","sessionKey"]),timestamp:We(e,["timestamp","created_at","createdAt"]),message:We(e,["message","text","content"]),raw:e}:{raw:e}}function UT(e){if(Array.isArray(e))return e;if(!Tr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function FT(e){if(!Tr(e))return null;let t=We(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:We(e,["platform"]),name:We(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function We(e,t){let r=mi(e,t);return typeof r=="string"?r:void 0}function VT(e,t,r){let n=mi(e,t);return typeof n=="boolean"?n:r}function gy(e,t){let r=mi(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function mi(e,t){if(Tr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function Tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as kO,writeFile as $O}from"node:fs/promises";import{join as C_}from"node:path";var hi=class extends Error{constructor(t,r){super(t===0?r:`line ${t}: ${r}`),this.name="ToonError",this.line=t,this.reason=r}};function E(e,t){return new hi(e,t)}var _e=",";function uu(e){let t=e.split(`
39
+ `);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(r=>r.endsWith("\r")?r.slice(0,-1):r)}function ot(e){return E(e,"invalid quoted string")}function Pt(e,t){if(e==="")return"";if(e.startsWith('"'))return yy(e,t);if(e.includes('"'))throw ot(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:KT(e)?Number(e):e}function Jt(e,t){let r=e.trim();if(r.startsWith('"'))return[yy(r,t),!0];if(r.includes('"')||/\s/.test(r))throw E(t,"expected non-empty field name");return[r,!1]}function yy(e,t){if(e[0]!=='"')throw ot(t);let r="",n=1;for(;n<e.length;){let o=e[n];if(n+=1,o==='"'){if(e.slice(n).trim()==="")return r;throw ot(t)}if(o==="\\"){let i=e[n];switch(n+=1,i){case'"':r+='"';break;case"\\":r+="\\";break;case"n":r+=`
40
+ `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"u":{let s=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw ot(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw ot(t);r+=String.fromCharCode(a),n+=4;break}default:throw ot(t)}continue}if(o<" "&&o!==" ")throw ot(t);r+=o}throw ot(t)}function Cn(e,t,r){if(e==="")return[];let n=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(s){s=!1;continue}c==="\\"&&i?s=!0:c==='"'?i=!i:c===t&&!i&&(n.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw ot(r);return n.push(e.slice(o).trim()),n}function ze(e,t,r){let n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&n)o=!0;else if(s==='"')n=!n;else if(s===t&&!n)return i}if(n||o)throw ot(r);return-1}function KT(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function HT(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function WT(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw E(0,"number is not representable in TOON");return String(e)}function gi(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function zt(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return WT(e);if(typeof e=="string")return JT(e,t);throw E(0,"not a primitive")}function GT(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function it(e){return GT(e)?e:_y(e)}function JT(e,t){return QT(e,t)?_y(e):e}function QT(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||HT(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function _y(e){let t='"';for(let r of e)switch(r){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
41
+ `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:r<" "?t+=`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=r}return`${t}"`}function Dn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var gu=2;function YT(e={}){return{indent:Math.max(1,e.indent??gu),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function XT(e,t){let r=[],n=!1;return uu(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){n=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw E(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw E(s,"invalid indentation");r.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:n}),n=!1}),r}function ft(e,t){let r=YT(t),n=XT(e,r),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw E(o.number,"invalid indentation");let i=n.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let l;try{l=wu(o.content,ze(o.content,":",o.number))}catch(u){if(r.strict)throw mu(u,o.number);l=void 0}if(l!==void 0)return rR(l,n,r)}if(i&&ze(o.content,":",o.number)===-1)return Pt(o.content.trim(),o.number);let s={index:0},a=yu(n,s,0,r),c=n[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function yu(e,t,r,n){let o={};for(;t.index<e.length;){let i=e[t.index];if(i.depth<r)break;if(i.depth>r)throw E(i.number,"invalid indentation");let{key:s,quoted:a,value:c}=eR(e,t,r,n);by(o,s,a,c,n,i.number)}return o}function eR(e,t,r,n){let o=e[t.index],i=o.content,s=ze(i,":",o.number);if(s===-1)throw E(o.number,"expected `key: value`");let a=i.slice(0,s),c=i.slice(s+1),l=ze(a,"[",o.number),u=ze(a,"{",o.number);if(u!==-1&&(l===-1||u<l)){let m;try{m=sR(a)}catch(_){if(n.strict)throw mu(_,o.number);t.index+=1;let w=lu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw E(o.number,"expected keyed map rows");let h=tR(m,e,t,r+1,n);return{key:m.key,quoted:m.keyQuoted,value:h}}if(l!==-1){let m;try{m=wu(a,s)}catch(_){if(n.strict)throw mu(_,o.number);t.index+=1;let w=lu(e,t,r,c,o.number,n);return{key:a.trim(),quoted:!1,value:w}}if(m.key===""&&!m.keyQuoted)throw E(o.number,"expected non-empty field name");let h=_u(m,c,e,t,r,n);return{key:m.key,quoted:m.keyQuoted,value:h}}let[d,f]=Jt(a,o.number);if(d===""&&!f)throw E(o.number,"expected non-empty field name");t.index+=1;let p=lu(e,t,r,c,o.number,n);return{key:d,quoted:f,value:p}}function lu(e,t,r,n,o,i){let s=n.trim();if(s==="[]")return[];if(s!=="")return Pt(s,o);let a=e[t.index];return a!==void 0&&a.depth>r?yu(e,t,r+1,i):{}}function tR(e,t,r,n,o){let i={};for(r.index+=1;r.index<t.length;){let s=t[r.index];if(s.depth<n)break;if(s.depth>n)throw E(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw E(s.number,"blank line inside keyed map");let a=ze(s.content,":",s.number);if(a===-1)throw E(s.number,"expected `key: value`");let[c,l]=Jt(s.content.slice(0,a),s.number);if(c===""&&!l)throw E(s.number,"expected non-empty field name");let u=Cn(s.content.slice(a+1).trim(),e.delimiter,s.number);if(u.length!==e.fields.length)throw E(s.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,p)=>{jn(d,f,Pt(u[p],s.number),o,s.number)}),by(i,c,l,d,o,s.number),r.index+=1}return i}function rR(e,t,r){let n=t[0],o=ze(n.content,":",n.number);if(o===-1)throw E(n.number,"expected `key: value`");let i=n.content.slice(o+1),s={index:0},a=_u(e,i,t,s,0,r),c=t[s.index];if(c!==void 0)throw E(c.number,"expected end of document");return a}function _u(e,t,r,n,o,i){let s=r[n.index].number,a=t.trim();if(n.index+=1,e.fields!==void 0){if(a!=="")throw E(s,"expected tabular rows");return nR(e,e.fields,r,n,o+1,i)}if(a!==""){let c=Cn(a,e.delimiter,s).map(l=>Pt(l,s));if(c.length!==e.len)throw E(s,"array length mismatch");return c}return oR(e,r,n,o+1,i)}function nR(e,t,r,n,o,i){let s=[];for(;s.length<e.len;){let c=r[n.index];if(c===void 0)throw fu(r,n.index);if(c.depth<o)break;if(c.depth>o)throw E(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw E(c.number,"blank line inside array");if(!wy(c.content,e.delimiter,c.number))break;let l=Cn(c.content,e.delimiter,c.number);if(l.length!==t.length)throw E(c.number,"array row length mismatch");let u={};t.forEach((d,f)=>{jn(u,d,Pt(l[f],c.number),i,c.number)}),s.push(u),n.index+=1}if(s.length!==e.len)throw fu(r,n.index);let a=r[n.index];if(a!==void 0&&a.depth>=o&&wy(a.content,e.delimiter,a.number))throw E(a.number,"array length mismatch");return s}function wy(e,t,r){let n=ze(e,":",r);if(n===-1)return!0;let o=ze(e,t,r);return o===-1?!1:o<n}function oR(e,t,r,n,o){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0||a.depth<n)throw fu(t,r.index);if(a.depth>n)throw E(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw E(a.number,"blank line inside array");i.push(iR(t,r,n,o))}let s=t[r.index];if(s!==void 0&&s.depth>=n)throw E(s.number,"array length mismatch");return i}function iR(e,t,r,n){let o=e[t.index];if(!o.content.startsWith("-"))throw E(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=ze(i,":",o.number),a;try{a=wu(i,s)}catch{a=void 0}if(a!==void 0){let c=i.slice(s+1);return _u(a,c,e,t,r,n)}}if(ze(i,":",o.number)!==-1){let s=[{number:o.number,depth:r+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=r)break;s.push(a),t.index+=1}return yu(s,{index:0},r+1,n)}return t.index+=1,Pt(i,o.number)}function fu(e,t){let r=e[t]??e[e.length-1];return E(r===void 0?1:r.number,"array length mismatch")}function wu(e,t){if(t===-1)throw E(0,"array header missing colon");let r=e.slice(0,t),n=ze(r,"[",0);if(n===-1)throw E(0,"invalid array header");let o,i;try{[o,i]=Jt(r.slice(0,n),0)}catch{throw E(0,"invalid array header")}let s=r.slice(n+1),a=s.indexOf("]");if(a===-1)throw E(0,"invalid array header");let c=s.slice(0,a),l=/^[0-9]*/.exec(c)[0];if(l===""||l.length>1&&l.startsWith("0"))throw E(0,"invalid array header");let u=Number.parseInt(l,10),d;switch(c.slice(l.length)){case"":d=",";break;case" ":d=" ";break;case"|":d="|";break;default:throw E(0,"invalid array header")}let f=s.slice(a+1),p;if(f==="")p=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{p=vy(f.slice(1,-1),d)}catch(m){throw E(0,m.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw E(0,"invalid array header");return{key:o,keyQuoted:i,len:u,delimiter:d,fields:p}}function sR(e){let t=ze(e,"{",0);if(t===-1||!e.endsWith("}"))throw E(0,"invalid keyed map header");let r,n;try{[r,n]=Jt(e.slice(0,t),0)}catch{throw E(0,"invalid keyed map header")}if(r===""&&!n)throw E(0,"expected non-empty field name");let o;try{o=vy(e.slice(t+1,-1),_e)}catch(i){throw E(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:r,keyQuoted:n,delimiter:_e,fields:o}}function vy(e,t){let r=[],n=0;function o(a,c){let l=0;for(;n<e.length&&!(c&&e[n]==="}");){if(e[n]===t||e[n]==="}")throw E(0,"invalid array header");let u=n;for(;n<e.length;){let f=e[n];if(f==='"'){i();continue}if(f===t||f==="{"||f==="}")break;n+=1}let[d]=Jt(e.slice(u,n),0);if(d==="")throw E(0,"invalid array header");if(l+=1,e[n]==="{"){n+=1;let f=r.length;if(o([...a,d],!0),e[n]!=="}"||r.length===f)throw E(0,"invalid array header");n+=1}else r.push([...a,d]);if(e[n]===t){if(n+=1,n>=e.length||e[n]==="}")throw E(0,"invalid array header");continue}if(c?e[n]==="}":n===e.length)break;throw E(0,"invalid array header")}if(l===0)throw E(0,"invalid array header")}function i(){for(n+=1;n<e.length;){let a=e[n];if(n+=1,a==="\\")n+=1;else if(a==='"')return}}if(o([],!1),n!==e.length)throw E(0,"invalid array header");let s=new Set;for(let a=0;a<r.length;a+=1)for(let c=a+1;c<r.length;c+=1)if(aR(r[a],r[c])||pu(r[a],r[c])||pu(r[c],r[a]))throw E(0,"duplicate key");for(let a of r){let c=a.join("\0");if(s.has(c))throw E(0,"duplicate key");s.add(c)}return r}function aR(e,t){return e.length===t.length&&pu(e,t)}function pu(e,t){return t.every((r,n)=>e[n]===r)}function mu(e,t){return E(t,e.reason??String(e.message))}function by(e,t,r,n,o,i){if(o.expandPaths&&!r&&t.includes(".")){let s=t.split(".");if(s.every(cR)){jn(e,s,n,o,i);return}}jn(e,[t],n,o,i)}function jn(e,t,r,n,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&n.strict)throw E(o,"duplicate key");Dn(e,i,r);return}if(s&&!Rr(e[i])){if(n.strict)throw E(o,"path expansion conflict");Dn(e,i,{})}else s||Dn(e,i,{});jn(e[i],t.slice(1),r,n,o)}function cR(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pt(e,t={}){let r={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},n=[];return Array.isArray(e)?vu(n,void 0,e,0,!1,r):Rr(e)?xy(n,e,0,r):n.push(zt(e,_e)),n.join("")}function Mn(e,t){e.push(" ".repeat(t*gu))}function xy(e,t,r,n){for(let[o,i]of Object.entries(t))Mn(e,r),hu(e,o,i,r,n)}function hu(e,t,r,n,o){if(Array.isArray(r)){vu(e,t,r,n,!1,o);return}if(Rr(r)){let i=o.keyedMapCollapse?lR(r,o):void 0;if(i!==void 0){e.push(it(t),"{",i.fields.map(bu).join(_e),`}:
42
+ `);for(let[s,a]of Object.entries(r))Mn(e,n+1),e.push(it(s),": ",i.paths.map(c=>zt(Ey(a,c),_e)).join(_e),`
43
+ `);return}e.push(it(t),`:
44
+ `),xy(e,r,n+1,o);return}e.push(it(t),": ",zt(r,_e),`
45
+ `)}function vu(e,t,r,n,o,i){if(r.length===0){t!==void 0?e.push(it(t),`: []
46
46
  `):o?e.push(`[0]:
47
47
  `):e.push(`[]
48
48
  `);return}if(r.every(gi)){du(e,t,r.length,void 0),e.push(" "),e.push(r.map(a=>zt(a,_e)).join(_e)),e.push(`
49
- `);return}let s=o?void 0:xy(r,i);if(s!==void 0){du(e,t,r.length,s.fields),e.push(`
50
- `);for(let a of r)Mn(e,n+1),e.push(s.paths.map(c=>zt(Sy(a,c),_e)).join(_e)),e.push(`
49
+ `);return}let s=o?void 0:ky(r,i);if(s!==void 0){du(e,t,r.length,s.fields),e.push(`
50
+ `);for(let a of r)Mn(e,n+1),e.push(s.paths.map(c=>zt(Ey(a,c),_e)).join(_e)),e.push(`
51
51
  `);return}du(e,t,r.length,void 0),e.push(`
52
- `);for(let a of r)Mn(e,n+1),iP(e,a,n+1,i)}function iP(e,t,r,n){if(Array.isArray(t)){e.push("- "),bu(e,void 0,t,r,!0,n);return}if(Pr(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
52
+ `);for(let a of r)Mn(e,n+1),uR(e,a,n+1,i)}function uR(e,t,r,n){if(Array.isArray(t)){e.push("- "),vu(e,void 0,t,r,!0,n);return}if(Rr(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
53
53
  `);return}e.push("- "),hu(e,o[0][0],o[0][1],r+1,n);for(let[i,s]of o.slice(1))Mn(e,r+1),hu(e,i,s,r+1,n);return}e.push("- ",zt(t,_e),`
54
- `)}function du(e,t,r,n){t!==void 0&&e.push(st(t)),e.push("[",String(r),"]"),n!==void 0&&e.push("{",n.map(vu).join(_e),"}"),e.push(":")}function xy(e,t){let r=ky(e.map(n=>({value:n})),t);return r===void 0?void 0:{fields:r,paths:$y(r)}}function sP(e,t){let r=Object.values(e);if(!(r.length<2))return xy(r,t)}function ky(e,t){let r=e[0]?.value;if(!Pr(r))return;let n=Object.keys(r).map(o=>({key:o}));if(n.length!==0){for(let{value:o}of e)if(!Pr(o)||Object.keys(o).length!==n.length||n.some(s=>!Object.prototype.hasOwnProperty.call(o,s.key)))return;for(let o of n){let i=e.map(({value:a})=>({value:a[o.key]}));if(i.every(({value:a})=>gi(a)))continue;if(!t.nestedTabularHeaders)return;let s=ky(i,t);if(s===void 0)return;o.children=s}return n}}function $y(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.children===void 0?[n]:$y(r.children,n)})}function Sy(e,t){let r=e;for(let n of t)r=r[n];return r}function vu(e){return e.children===void 0?st(e.key):`${st(e.key)}{${e.children.map(vu).join(_e)}}`}var HM=new TextEncoder,WM=new TextDecoder;import{basename as z_}from"node:path";import{createHash as TP,randomUUID as Ou}from"node:crypto";import{spawn as PP}from"node:child_process";import{constants as Pu}from"node:fs";import{readFileSync as RP}from"node:fs";import{mkdir as My,open as zP,readFile as OP,rename as Dq,rm as qn,stat as jq,writeFile as Mq}from"node:fs/promises";import{tmpdir as IP}from"node:os";import{dirname as zr,join as Be,resolve as Iu}from"node:path";import{isAbsolute as kq,join as Rr,resolve as cP}from"node:path";var uP=".red";function lP(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function Ey(e){return Rr(lP(e),uP)}function Ty(e){return Rr(Ey(e),"state")}function dP(e){return Rr(Ey(e),"tmp")}function xu(e){return Rr(Ty(e),"rsp")}function ku(e){return Rr(Ty(e),"red-skills.rdb")}var fP=".red/tmp/red-skills.rdb";function Py(e){return Rr(dP(e),"red-skills.rdb")}function Ry(e,t){let r=ku(e);if(t(r))return r;let n=Py(e);if(t(n))throw $u();return r}function zy(e,t){return t===fP||cP(e,t)===Py(e)}function $u(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}import{createConnection as pP}from"node:net";async function yi(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=pP(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
55
- `)}),i.on("data",u=>{a+=u.toString("utf8");let d=a.indexOf(`
56
- `);if(d<0)return;let f=a.slice(0,d);l(()=>{try{n(JSON.parse(f))}catch(p){o(p)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}import{existsSync as mP,readdirSync as hP}from"node:fs";import{homedir as gP}from"node:os";import{basename as Eu,dirname as Su,join as Le,resolve as _i}from"node:path";var wi="rsp-resident-entry-unresolved";function yP(e){return"command"in e}var bi=class extends Error{code=wi;searched;callerEntry;constructor(t){super(`${wi}: no rsp entrypoint found for the resident auto-spawn${t.callerEntry?` (caller entry: ${t.callerEntry})`:""}
54
+ `)}function du(e,t,r,n){t!==void 0&&e.push(it(t)),e.push("[",String(r),"]"),n!==void 0&&e.push("{",n.map(bu).join(_e),"}"),e.push(":")}function ky(e,t){let r=$y(e.map(n=>({value:n})),t);return r===void 0?void 0:{fields:r,paths:Sy(r)}}function lR(e,t){let r=Object.values(e);if(!(r.length<2))return ky(r,t)}function $y(e,t){let r=e[0]?.value;if(!Rr(r))return;let n=Object.keys(r).map(o=>({key:o}));if(n.length!==0){for(let{value:o}of e)if(!Rr(o)||Object.keys(o).length!==n.length||n.some(s=>!Object.prototype.hasOwnProperty.call(o,s.key)))return;for(let o of n){let i=e.map(({value:a})=>({value:a[o.key]}));if(i.every(({value:a})=>gi(a)))continue;if(!t.nestedTabularHeaders)return;let s=$y(i,t);if(s===void 0)return;o.children=s}return n}}function Sy(e,t=[]){return e.flatMap(r=>{let n=[...t,r.key];return r.children===void 0?[n]:Sy(r.children,n)})}function Ey(e,t){let r=e;for(let n of t)r=r[n];return r}function bu(e){return e.children===void 0?it(e.key):`${it(e.key)}{${e.children.map(bu).join(_e)}}`}var XM=new TextEncoder,eq=new TextDecoder;import{basename as N_}from"node:path";import{randomUUID as Iu}from"node:crypto";import{spawn as jR}from"node:child_process";import{readFileSync as MR}from"node:fs";import{mkdir as qR,readFile as LR,rename as Wq,rm as qn,stat as Gq,writeFile as Jq}from"node:fs/promises";import{dirname as Ln,join as mt,resolve as Au}from"node:path";import{isAbsolute as Pq,join as Pr,resolve as fR}from"node:path";var pR=".red";function mR(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function Ty(e){return Pr(mR(e),pR)}function Ry(e){return Pr(Ty(e),"state")}function hR(e){return Pr(Ty(e),"tmp")}function xu(e){return Pr(Ry(e),"rsp")}function ku(e){return Pr(Ry(e),"red-skills.rdb")}var gR=".red/tmp/red-skills.rdb";function Py(e){return Pr(hR(e),"red-skills.rdb")}function zy(e,t){let r=ku(e);if(t(r))return r;let n=Py(e);if(t(n))throw $u();return r}function Oy(e,t){return t===gR||fR(e,t)===Py(e)}function $u(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}import{createHash as yR}from"node:crypto";import{constants as Su}from"node:fs";import{mkdir as _R,open as wR}from"node:fs/promises";import{createConnection as vR}from"node:net";import{tmpdir as bR}from"node:os";import{dirname as xR,join as Eu}from"node:path";var kR=108;async function Iy(e,t,r="resident server"){let n=e.timeoutMs??1e3;return await new Promise((o,i)=>{let s=vR(e.socketPath),a=!1,c="",l=setTimeout(()=>{u(()=>i(new Error(`${r} timed out`))),s.destroy()},n);function u(d){a||(a=!0,clearTimeout(l),d())}s.on("connect",()=>{s.write(`${JSON.stringify(t)}
55
+ `)}),s.on("data",d=>{c+=d.toString("utf8");let f=c.indexOf(`
56
+ `);if(f<0)return;let p=c.slice(0,f);u(()=>{try{o(JSON.parse(p))}catch(m){i(m)}}),s.end()}),s.on("error",d=>u(()=>i(d))),s.on("close",()=>{a||u(()=>i(new Error(`${r} closed without response`)))})})}async function Ay(e){await _R(xR(e),{recursive:!0,mode:448});try{return await wR(e,Su.O_CREAT|Su.O_EXCL|Su.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function zr(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function Ny(e,t=1e3){if(!zr(e))return;try{process.kill(e,"SIGTERM")}catch{return}let r=Date.now()+t;for(;Date.now()<r;){if(!zr(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}function Cy(e){let t=e.env??process.env,r=yR("sha256").update(e.key).digest("hex").slice(0,20),n=t.XDG_RUNTIME_DIR;if(n){let i=Eu(n,"red-skills",r);if(Eu(i,e.socketFileName).length<kR)return i}let o=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid");return Eu(bR(),`red-skills-${o}`,r)}async function yi(e,t){return await Iy(e,t,"resident rsp server")}import{existsSync as $R,readdirSync as SR}from"node:fs";import{homedir as ER}from"node:os";import{basename as Ru,dirname as Tu,join as Le,resolve as _i}from"node:path";var wi="rsp-resident-entry-unresolved";function TR(e){return"command"in e}var vi=class extends Error{code=wi;searched;callerEntry;constructor(t){super(`${wi}: no rsp entrypoint found for the resident auto-spawn${t.callerEntry?` (caller entry: ${t.callerEntry})`:""}
57
57
  searched:
58
58
  ${t.searched.map(r=>` ${r}`).join(`
59
- `)}`),this.name="RspResidentEntryError",this.searched=t.searched,this.callerEntry=t.callerEntry}},Qt="rsp.bundle.min.mjs",_P=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Tu=/^rsp-(.+)\.bundle\.min\.mjs$/,wP=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"];function Iy(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let r=t.env??process.env,n=t.exists??mP,o=t.execPath??process.execPath,i=t.execArgv??process.execArgv,s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,a=(l,u)=>({command:o,args:[...i,l],source:u});if(r.RSP_BIN)return{command:r.RSP_BIN,args:[],source:"env-rsp-bin"};if(s&&bP(s))return a(_i(s),"caller-entry");let c=[];for(let[l,u]of xP(s,t.rootDir,r,t.listDir??EP))if(c.push(l),n(l))return a(l,u);return{diagnostic:wi,searched:c,...s?{callerEntry:_i(s)}:{}}}function Ay(e={},t={}){let r=Iy(e,t);if(yP(r))return r;throw new bi(r)}function bP(e){let t=Eu(e);return t===Qt||Tu.test(t)||t==="rsp"||t==="rsp.mjs"||t==="rsp.js"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:vP(_i(e))}function vP(e){let t=Su(e);for(let r=0;r<4;r++){if(Eu(t)==="rsp")return!0;let n=Su(t);if(n===t)return!1;t=n}return!1}function*xP(e,t,r,n){if(e){let i=Su(_i(e));yield[Le(i,Qt),"caller-sibling-bundle"];let s=_P.exec(Eu(e));s&&(yield[Le(i,`rsp-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Le(i,"..","dist",Qt),"caller-sibling-bundle"]}for(let i of wP){let s=r[i];s&&(yield[Le(s,"dist",Qt),"plugin-root-bundle"],yield[Le(s,"..","..","dist",Qt),"plugin-root-bundle"])}t&&(yield[Le(t,"dist",Qt),"repo-bundle"],yield[Le(t,"apps","rsp","dist","cli.js"),"workspace-entry"],yield[Le(t,"node_modules","@reddb-io","rsp","dist","cli.js"),"node-modules-entry"]);let o=kP(r);yield[Le(o,Qt),"bundle-cache"];for(let i of $P(o,n))yield[Le(o,i),"bundle-cache"]}function kP(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||Le(e.HOME||gP(),".cache");return Le(t,"red-skills","bundles")}function $P(e,t){return t(e).filter(r=>Tu.test(r)).sort((r,n)=>SP(Oy(n),Oy(r)))}function Oy(e){return Tu.exec(e)?.[1]??""}function SP(e,t){let r=i=>i.split(".").map(s=>Number.parseInt(s,10)),[n,o]=[r(e),r(t)];for(let i=0;i<Math.max(n.length,o.length);i++){let[s,a]=[n[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(t):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function EP(e){try{return hP(e)}catch{return[]}}var AP=108,NP=1,CP=5e3;function xi(e){let t=GP(e)??Iu(e),r=WP(t),n=xu(t);return{rootDir:t,socketPath:Be(r,"rsp.sock"),pidPath:Be(r,"rsp.pid"),lockPath:Be(r,"rsp.lock"),wakeLockPath:Be(t,".red","tmp","rsp","wake.lock"),summaryPath:Be(n,"rsp-status-summary.json"),registryPath:Be(n,"rsp-resident.pid.json")}}var vi=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await DP(this.paths,this.config);let r=await yi(this.paths,{...t,id:Ou()});if(!r.ok)throw new Error(r.error);return r.value}};async function DP(e,t){if(await My(zr(e.socketPath),{recursive:!0,mode:448}),await Dy(e.socketPath,t))return;await Cy(e,t);let r=await LP(e.lockPath);if(r)try{if(await Dy(e.socketPath,t))return;await Cy(e,t),await qP(e.socketPath);let n=BP(e,t);await Ny(e.socketPath,n);return}finally{await r.close(),await qn(e.lockPath,{force:!0})}await Ny(e.socketPath)}async function Bn(e,t=200){try{return await qy(e,t)!=null}catch{return!1}}async function qy(e,t=200){let r=await yi({socketPath:e,timeoutMs:t},{id:Ou(),op:"ping"});return r.ok?By(r.value)?{version:XP(r.value.version)}:{}:null}async function jP(e){try{let t=FP(await OP(e,"utf8"));return eR(t)?t:null}catch{return null}}async function Ny(e,t){let r=Date.now()+MP(),n;for(;Date.now()<r;){if(await Bn(e))return;if(t){let o=t.spawnError();if(o)throw new Error(Ru("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(Ru("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?Ru("resident rsp server did not start",t):"resident rsp server did not start")}function MP(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:CP}async function qP(e){await qn(e,{force:!0})}async function LP(e){await My(zr(e),{recursive:!0,mode:448});try{return await zP(e,Pu.O_CREAT|Pu.O_EXCL|Pu.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function BP(e,t){let[r,n]=HP(e,t),o=process.env.RSP_DEBUG==="1",i,s="",a=PP(r,[...n,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours??6),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:o?["ignore","ignore","pipe"]:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return a.on("error",c=>{i=c}),o&&(a.stderr?.setEncoding("utf8"),a.stderr?.on("data",c=>{s=UP(`${s}${c}`,ZP)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var ZP=8*1024;function Ru(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
59
+ `)}`),this.name="RspResidentEntryError",this.searched=t.searched,this.callerEntry=t.callerEntry}},Qt="rsp.bundle.min.mjs",RR=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Pu=/^rsp-(.+)\.bundle\.min\.mjs$/,PR=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"];function jy(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let r=t.env??process.env,n=t.exists??$R,o=t.execPath??process.execPath,i=t.execArgv??process.execArgv,s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,a=(l,u)=>({command:o,args:[...i,l],source:u});if(r.RSP_BIN)return{command:r.RSP_BIN,args:[],source:"env-rsp-bin"};if(s&&zR(s))return a(_i(s),"caller-entry");let c=[];for(let[l,u]of IR(s,t.rootDir,r,t.listDir??DR))if(c.push(l),n(l))return a(l,u);return{diagnostic:wi,searched:c,...s?{callerEntry:_i(s)}:{}}}function My(e={},t={}){let r=jy(e,t);if(TR(r))return r;throw new vi(r)}function zR(e){let t=Ru(e);return t===Qt||Pu.test(t)||t==="rsp"||t==="rsp.mjs"||t==="rsp.js"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:OR(_i(e))}function OR(e){let t=Tu(e);for(let r=0;r<4;r++){if(Ru(t)==="rsp")return!0;let n=Tu(t);if(n===t)return!1;t=n}return!1}function*IR(e,t,r,n){if(e){let i=Tu(_i(e));yield[Le(i,Qt),"caller-sibling-bundle"];let s=RR.exec(Ru(e));s&&(yield[Le(i,`rsp-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Le(i,"..","dist",Qt),"caller-sibling-bundle"]}for(let i of PR){let s=r[i];s&&(yield[Le(s,"dist",Qt),"plugin-root-bundle"],yield[Le(s,"..","..","dist",Qt),"plugin-root-bundle"])}t&&(yield[Le(t,"dist",Qt),"repo-bundle"],yield[Le(t,"apps","rsp","dist","cli.js"),"workspace-entry"],yield[Le(t,"node_modules","@reddb-io","rsp","dist","cli.js"),"node-modules-entry"]);let o=AR(r);yield[Le(o,Qt),"bundle-cache"];for(let i of NR(o,n))yield[Le(o,i),"bundle-cache"]}function AR(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||Le(e.HOME||ER(),".cache");return Le(t,"red-skills","bundles")}function NR(e,t){return t(e).filter(r=>Pu.test(r)).sort((r,n)=>CR(Dy(n),Dy(r)))}function Dy(e){return Pu.exec(e)?.[1]??""}function CR(e,t){let r=i=>i.split(".").map(s=>Number.parseInt(s,10)),[n,o]=[r(e),r(t)];for(let i=0;i<Math.max(n.length,o.length);i++){let[s,a]=[n[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(t):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function DR(e){try{return SR(e)}catch{return[]}}var BR=1,ZR=5e3;function xi(e){let t=tP(e)??Au(e),r=eP(t),n=xu(t);return{rootDir:t,socketPath:mt(r,"rsp.sock"),pidPath:mt(r,"rsp.pid"),lockPath:mt(r,"rsp.lock"),wakeLockPath:mt(t,".red","tmp","rsp","wake.lock"),summaryPath:mt(n,"rsp-status-summary.json"),registryPath:mt(n,"rsp-resident.pid.json")}}var bi=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await UR(this.paths,this.config);let r=await yi(this.paths,{...t,id:Iu()});if(!r.ok)throw new Error(r.error);return r.value}};async function UR(e,t){if(await qR(Ln(e.socketPath),{recursive:!0,mode:448}),await By(e.socketPath,t))return;await Ly(e,t);let r=await HR(e.lockPath);if(r)try{if(await By(e.socketPath,t))return;await Ly(e,t),await KR(e.socketPath);let n=WR(e,t);await qy(e.socketPath,n);return}finally{await r.close(),await qn(e.lockPath,{force:!0})}await qy(e.socketPath)}async function Bn(e,t=200){try{return await Uy(e,t)!=null}catch{return!1}}async function Uy(e,t=200){let r=await yi({socketPath:e,timeoutMs:t},{id:Iu(),op:"ping"});return r.ok?Vy(r.value)?{version:iP(r.value.version)}:{}:null}async function FR(e){try{let t=QR(await LR(e,"utf8"));return sP(t)?t:null}catch{return null}}async function qy(e,t){let r=Date.now()+VR(),n;for(;Date.now()<r;){if(await Bn(e))return;if(t){let o=t.spawnError();if(o)throw new Error(zu("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(zu("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?zu("resident rsp server did not start",t):"resident rsp server did not start")}function VR(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:ZR}async function KR(e){await qn(e,{force:!0})}var HR=Ay;function WR(e,t){let[r,n]=XR(e,t),o=process.env.RSP_DEBUG==="1",i,s="",a=jR(r,[...n,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours??6),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:o?["ignore","ignore","pipe"]:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return a.on("error",c=>{i=c}),o&&(a.stderr?.setEncoding("utf8"),a.stderr?.on("data",c=>{s=JR(`${s}${c}`,GR)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var GR=8*1024;function zu(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
60
60
  ${o}`),n.join(`
61
- `)}function UP(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function FP(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return pt(t)}}async function Cy(e,t){try{let r=await jP(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!Ln(r.pid)){await qn(e.registryPath,{force:!0});return}if(await Bn(r.socket_path,100))return;if(Ly(t.clientVersion,r.resident_version)&&(await KP(r.pid,1500),!Ln(r.pid))){await qn(e.registryPath,{force:!0});return}await VP(r.pid),await qn(e.registryPath,{force:!0})}catch{}}function Ln(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function VP(e){if(!Ln(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!Ln(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function KP(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!Ln(e))return;await new Promise(n=>setTimeout(n,50))}}function HP(e,t){let r=Ay(t,{rootDir:e.rootDir});return[r.command,r.args]}function WP(e){let t=TP("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=Be(r,"red-skills",t);if(Be(o,"rsp.sock").length<AP)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return Be(IP(),`red-skills-${n}`,t)}function GP(e){let t=Iu(e);for(let r=0;r<32;r++){try{let o=zu(Be(t,".git"));if(o!=null)return JP(t,o)??t;if(zu(Be(t,".git","HEAD"))!=null||zu(Be(t,".red","config.yaml"))!=null)return t}catch{}let n=zr(t);if(n===t)return null;t=n}return null}function JP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=Iu(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?zr(zr(zr(n))):null}function zu(e){try{return RP(e,"utf8")}catch{return null}}async function Dy(e,t){let r=await qy(e).catch(()=>null);return r?Ly(t.clientVersion,r.version)?(await QP(e,t.clientVersion),await tR(e),!1):!0:!1}async function QP(e,t){try{await yi({socketPath:e,timeoutMs:200},{id:Ou(),op:"handover",clientVersion:t})}catch{}}function Ly(e,t){return!e||!t?!1:YP(e,t)>0}function YP(e,t){let r=jy(e),n=jy(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function jy(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function By(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function XP(e){return typeof e=="string"&&e.length>0?e:void 0}function eR(e){return By(e)&&e.version===NP&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function tR(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Bn(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as rR}from"node:child_process";var Nu=["supports","contradicts","related_to"];function Cu(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function Du(e){return typeof e=="string"&&Nu.includes(e)}function Or(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function Zy(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
62
- `)}function nR(e){return{deriveConnections(t){return iR(e,t)}}}function Uy(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return nR({command:t,args:sR(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:aR(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function oR(e){let t=JSON.parse(cR(e));return(Array.isArray(t)?t:Au(t)&&Array.isArray(t.connections)?t.connections:[]).filter(uR).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Au(n.metadata)?n.metadata:void 0}))}async function iR(e,t){let r=rR(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return oR(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function sR(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function aR(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function cR(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function uR(e){return Au(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&Du(e.kind)}function Au(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as ki}from"node:fs";import{mkdir as lR,readFile as ju,writeFile as dR}from"node:fs/promises";import{dirname as Mu,isAbsolute as fR,join as Ir,resolve as Ot}from"node:path";var $i="file://./.red/brain/brain.rdb",pR="RED_BRAIN_ROOT",mR="brain.root";async function hR(e=process.cwd(),t={}){let n=(t.env??process.env)[pR];if(n)return Ot(e,n);let o=await gR(e);if(o)return o;let i=Ot(e),s=null;for(;;){let a=Ir(i,".red");if(ki(a)&&(s??=i,ki(Ir(a,"brain"))||ki(Ir(a,mR))))return i;let c=Mu(i);if(c===i)return s??Ot(e);i=c}}async function gR(e){let t=Ot(e);for(;;){let r=Ir(t,".red","config.yaml");try{let o=await ju(r,"utf8"),i=yR(o);if(i)return Ot(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=Mu(t);if(n===t)return null;t=n}}function yR(e){let t=_R(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function _R(e){let t={},r=[],n=[];for(let o of e.split(`
63
- `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let f=i.indexOf("#");f>=0&&(i=i.slice(0,f))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function Fy(e){return Ir(Ot(e),".red","brain","config.yaml")}function wR(e){return Ir(Ot(e),".env")}async function bR(e){let t=Fy(e);return ki(t)||(await lR(Mu(t),{recursive:!0}),await dR(t,`connection_string: ${$i}
64
- `,"utf8")),t}async function vR(e){let t=Fy(e);try{let r=await ju(t,"utf8");return xR(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function xR(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:$i};let r=t.slice(18).trim();return{connection_string:Vy(r)||$i}}function Vy(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function Ky(e=process.cwd()){let t=await hR(e),r=await bR(t),n=await vR(t)??{connection_string:$i},o=await kR(t),i=n.connection_string,s=$R(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:SR(t,s)}}async function kR(e){let t={...process.env};try{let r=await ju(wR(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=Vy(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function $R(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function SR(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return fR(r)?t:`file://${Ot(e,r)}`}import{existsSync as ER}from"node:fs";import{resolve as TR}from"node:path";var PR=7,RR=64*1024*1024;function Wy(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);if(zy(e.rootDir,t))throw $u();return t===ku(e.rootDir)}async function Gy(e){let t=xi(e.rootDir),r=new vi(t,OR(e.rootDir));return await r.request({op:"ping"}),new qu(r)}function zR(e){return`file://${Ry(TR(e),ER)}`}function OR(e){return{storeUri:zR(e),ttlDays:PR,byteBudget:RR}}var qu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return IR(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:Hy(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:Hy(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function Hy(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function IR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var AR=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",NR=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function Jy(e,t){return AR?DR(e,t):NR?MR(e,t):CR(e,t)}async function CR(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function DR(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:jR(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*jR(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function MR(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:qR(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*qR(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as ZR}from"node:url";import{dirname as UR,resolve as FR,join as dL}from"node:path";import{existsSync as LR}from"node:fs";import{join as BR}from"node:path";function Qy(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=BR(r,"bin",t);if(LR(i))return i;throw new Error(`reddb: binary "${t}" not found.
61
+ `)}function JR(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}function QR(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return ft(t)}}async function Ly(e,t){try{let r=await FR(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!zr(r.pid)){await qn(e.registryPath,{force:!0});return}if(await Bn(r.socket_path,100))return;if(Fy(t.clientVersion,r.resident_version)&&(await YR(r.pid,1500),!zr(r.pid))){await qn(e.registryPath,{force:!0});return}await Ny(r.pid),await qn(e.registryPath,{force:!0})}catch{}}async function YR(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!zr(e))return;await new Promise(n=>setTimeout(n,50))}}function XR(e,t){let r=My(t,{rootDir:e.rootDir});return[r.command,r.args]}function eP(e){return Cy({key:e,socketFileName:"rsp.sock"})}function tP(e){let t=Au(e);for(let r=0;r<32;r++){try{let o=Ou(mt(t,".git"));if(o!=null)return rP(t,o)??t;if(Ou(mt(t,".git","HEAD"))!=null||Ou(mt(t,".red","config.yaml"))!=null)return t}catch{}let n=Ln(t);if(n===t)return null;t=n}return null}function rP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=Au(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?Ln(Ln(Ln(n))):null}function Ou(e){try{return MR(e,"utf8")}catch{return null}}async function By(e,t){let r=await Uy(e).catch(()=>null);return r?Fy(t.clientVersion,r.version)?(await nP(e,t.clientVersion),await aP(e),!1):!0:!1}async function nP(e,t){try{await yi({socketPath:e,timeoutMs:200},{id:Iu(),op:"handover",clientVersion:t})}catch{}}function Fy(e,t){return!e||!t?!1:oP(e,t)>0}function oP(e,t){let r=Zy(e),n=Zy(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function Zy(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function Vy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iP(e){return typeof e=="string"&&e.length>0?e:void 0}function sP(e){return Vy(e)&&e.version===BR&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function aP(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Bn(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as cP}from"node:child_process";var Cu=["supports","contradicts","related_to"];function Du(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function ju(e){return typeof e=="string"&&Cu.includes(e)}function Or(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function Ky(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
62
+ `)}function uP(e){return{deriveConnections(t){return dP(e,t)}}}function Hy(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return uP({command:t,args:fP(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:pP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function lP(e){let t=JSON.parse(mP(e));return(Array.isArray(t)?t:Nu(t)&&Array.isArray(t.connections)?t.connections:[]).filter(hP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Nu(n.metadata)?n.metadata:void 0}))}async function dP(e,t){let r=cP(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return lP(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function fP(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function pP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function mP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function hP(e){return Nu(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&ju(e.kind)}function Nu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as ki}from"node:fs";import{mkdir as gP,readFile as Mu,writeFile as yP}from"node:fs/promises";import{dirname as qu,isAbsolute as _P,join as Ir,resolve as Ot}from"node:path";var $i="file://./.red/brain/brain.rdb",wP="RED_BRAIN_ROOT",vP="brain.root";async function bP(e=process.cwd(),t={}){let n=(t.env??process.env)[wP];if(n)return Ot(e,n);let o=await xP(e);if(o)return o;let i=Ot(e),s=null;for(;;){let a=Ir(i,".red");if(ki(a)&&(s??=i,ki(Ir(a,"brain"))||ki(Ir(a,vP))))return i;let c=qu(i);if(c===i)return s??Ot(e);i=c}}async function xP(e){let t=Ot(e);for(;;){let r=Ir(t,".red","config.yaml");try{let o=await Mu(r,"utf8"),i=kP(o);if(i)return Ot(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=qu(t);if(n===t)return null;t=n}}function kP(e){let t=$P(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function $P(e){let t={},r=[],n=[];for(let o of e.split(`
63
+ `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let f=i.indexOf("#");f>=0&&(i=i.slice(0,f))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function Wy(e){return Ir(Ot(e),".red","brain","config.yaml")}function SP(e){return Ir(Ot(e),".env")}async function EP(e){let t=Wy(e);return ki(t)||(await gP(qu(t),{recursive:!0}),await yP(t,`connection_string: ${$i}
64
+ `,"utf8")),t}async function TP(e){let t=Wy(e);try{let r=await Mu(t,"utf8");return RP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function RP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:$i};let r=t.slice(18).trim();return{connection_string:Gy(r)||$i}}function Gy(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function Jy(e=process.cwd()){let t=await bP(e),r=await EP(t),n=await TP(t)??{connection_string:$i},o=await PP(t),i=n.connection_string,s=zP(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:OP(t,s)}}async function PP(e){let t={...process.env};try{let r=await Mu(SP(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=Gy(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function zP(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function OP(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return _P(r)?t:`file://${Ot(e,r)}`}import{existsSync as IP}from"node:fs";import{resolve as AP}from"node:path";var NP=7,CP=64*1024*1024;function Yy(e){if(!e.connectionString.startsWith("file://"))return!1;let t=e.connectionString.slice(7);if(Oy(e.rootDir,t))throw $u();return t===ku(e.rootDir)}async function Xy(e){let t=xi(e.rootDir),r=new bi(t,jP(e.rootDir));return await r.request({op:"ping"}),new Lu(r)}function DP(e){return`file://${zy(AP(e),IP)}`}function jP(e){return{storeUri:DP(e),ttlDays:NP,byteBudget:CP}}var Lu=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return MP(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:Qy(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:Qy(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function Qy(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function MP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",LP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function e_(e,t){return qP?ZP(e,t):LP?FP(e,t):BP(e,t)}async function BP(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function ZP(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:UP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*UP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function FP(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:VP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*VP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as WP}from"node:url";import{dirname as GP,resolve as JP,join as kL}from"node:path";import{existsSync as KP}from"node:fs";import{join as HP}from"node:path";function t_(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=HP(r,"bin",t);if(KP(i))return i;throw new Error(`reddb: binary "${t}" not found.
65
65
  expected at: ${i}
66
66
  override: set ${n}=/path/to/${t}
67
67
  fix: re-run \`pnpm install\` (the postinstall script downloads it),
68
- or check the postinstall log for a download error.`)}var VR=UR(ZR(import.meta.url)),KR=FR(VR,"..");function HR(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function Yy(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:Qy({name:HR(),packageRoot:KR,envVar:"REDDB_BIN"})}var WR=new TextEncoder,GR=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},Si=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(WR.encode(o+`
69
- `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(GR.decode(s)),o=i+1}o>0&&(t=t.subarray(o))}}catch(r){this.#e(`stdout reader error: ${r.message}`);return}this.#e("server stdout closed")}#r(t){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let n=r.id;if(n==null)return;let o=this.pending.get(n);o&&(this.pending.delete(n),r.error?o.reject(new z(r.error.code??"UNKNOWN",r.error.message??"unknown error",r.error.data)):o.resolve(r.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let r=new z("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function Bu(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?JR(e):QR(e)}function JR(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let r;try{r=new URL(t)}catch(u){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),i=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let s=YR(o),a=r.port?Number(r.port):Lu(s),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:s,host:r.hostname,port:a,path:i||void 0,username:c,password:l,token:n.get("token")??void 0,apiKey:n.get("apiKey")??n.get("api_key")??void 0,loginUrl:n.get("loginUrl")??n.get("login_url")??void 0,params:n,originalUri:e}}function QR(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],r;try{r=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!r.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let n=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",o=r.searchParams;return{kind:n,host:r.hostname,port:r.port?Number(r.port):Lu(n),username:r.username?decodeURIComponent(r.username):void 0,password:r.password?decodeURIComponent(r.password):void 0,token:o.get("token")??void 0,apiKey:o.get("apiKey")??o.get("api_key")??void 0,loginUrl:o.get("loginUrl")??o.get("login_url")??void 0,params:o,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):Lu(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new z("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function YR(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new z("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function Lu(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var XR=new Set(["embedded"]),Zn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&XR.has(this._transport))throw new z("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,r){this._guard("get");let n=await this._client.call("cache.get",{namespace:t,key:r});return n==null||n.value==null?null:tz(n.value)}async put(t,r,n,o={}){this._guard("put");let i=ez(n);await this._client.call("cache.put",{namespace:t,key:r,value:i,...o})}async exists(t,r){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:r}))?.status??"maybe"}async invalidate(t,r){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:r})}async invalidatePrefix(t,r){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:r}))?.removed??0}async invalidateTags(t,r){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:r}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}};function ez(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return Xy(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return Xy(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function Xy(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function tz(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var Ar=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(e_).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${Zu(o,t)} = ${nz(r)}${s}${i}`})}set(t,r,n={}){return this.put(t,r,n)}async get(t,r={}){let n=r.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${Zu(n,t)}`}))?.rows?.[0]?.value??null}async getMany(t,r={}){let n=[];for(let o of t)n.push(await this.get(o,r));return n}async exists(t,r={}){return{exists:await this.get(t,r)!==null}}async delete(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`KV DELETE ${Zu(n,t)}`}),i=o.affected??o.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let r=t.collection??this.collection,n=t.limit==null?100:Number(t.limit);if(!Number.isInteger(n)||n<=0)throw new z("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),s=(await this.client.call("query",{sql:`SELECT key, value FROM ${Uu(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?s.filter(c=>String(c.key).startsWith(o)):s}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(e_).join(", ")}] FROM ${Uu(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
68
+ or check the postinstall log for a download error.`)}var QP=GP(WP(import.meta.url)),YP=JP(QP,"..");function XP(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function r_(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:t_({name:XP(),packageRoot:YP,envVar:"REDDB_BIN"})}var ez=new TextEncoder,tz=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},Si=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(ez.encode(o+`
69
+ `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(tz.decode(s)),o=i+1}o>0&&(t=t.subarray(o))}}catch(r){this.#e(`stdout reader error: ${r.message}`);return}this.#e("server stdout closed")}#r(t){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let n=r.id;if(n==null)return;let o=this.pending.get(n);o&&(this.pending.delete(n),r.error?o.reject(new z(r.error.code??"UNKNOWN",r.error.message??"unknown error",r.error.data)):o.resolve(r.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let r=new z("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function Zu(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?rz(e):nz(e)}function rz(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let r;try{r=new URL(t)}catch(u){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),i=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let s=oz(o),a=r.port?Number(r.port):Bu(s),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:s,host:r.hostname,port:a,path:i||void 0,username:c,password:l,token:n.get("token")??void 0,apiKey:n.get("apiKey")??n.get("api_key")??void 0,loginUrl:n.get("loginUrl")??n.get("login_url")??void 0,params:n,originalUri:e}}function nz(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],r;try{r=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!r.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let n=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",o=r.searchParams;return{kind:n,host:r.hostname,port:r.port?Number(r.port):Bu(n),username:r.username?decodeURIComponent(r.username):void 0,password:r.password?decodeURIComponent(r.password):void 0,token:o.get("token")??void 0,apiKey:o.get("apiKey")??o.get("api_key")??void 0,loginUrl:o.get("loginUrl")??o.get("login_url")??void 0,params:o,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):Bu(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new z("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function oz(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new z("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function Bu(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var iz=new Set(["embedded"]),Zn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&iz.has(this._transport))throw new z("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,r){this._guard("get");let n=await this._client.call("cache.get",{namespace:t,key:r});return n==null||n.value==null?null:az(n.value)}async put(t,r,n,o={}){this._guard("put");let i=sz(n);await this._client.call("cache.put",{namespace:t,key:r,value:i,...o})}async exists(t,r){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:r}))?.status??"maybe"}async invalidate(t,r){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:r})}async invalidatePrefix(t,r){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:r}))?.removed??0}async invalidateTags(t,r){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:r}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}};function sz(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return n_(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return n_(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function n_(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function az(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var Ar=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(o_).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${Uu(o,t)} = ${uz(r)}${s}${i}`})}set(t,r,n={}){return this.put(t,r,n)}async get(t,r={}){let n=r.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${Uu(n,t)}`}))?.rows?.[0]?.value??null}async getMany(t,r={}){let n=[];for(let o of t)n.push(await this.get(o,r));return n}async exists(t,r={}){return{exists:await this.get(t,r)!==null}}async delete(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`KV DELETE ${Uu(n,t)}`}),i=o.affected??o.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let r=t.collection??this.collection,n=t.limit==null?100:Number(t.limit);if(!Number.isInteger(n)||n<=0)throw new z("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),s=(await this.client.call("query",{sql:`SELECT key, value FROM ${Fu(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?s.filter(c=>String(c.key).startsWith(o)):s}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(o_).join(", ")}] FROM ${Fu(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
70
70
 
71
71
  `)){let u=l.split(`
72
- `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function Zu(e,t){return`${Uu(e)}.${rz(t)}`}function Uu(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new z("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function rz(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function nz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function e_(e){return`'${String(e).replace(/'/g,"''")}'`}var Un=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${ht(t)}`})}push(t,r,n={}){let o=sz(n);return this.client.call("query",{sql:`QUEUE PUSH ${ht(t)} ${az(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${ht(t)}${Vu(r)}`});return Fu(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${ht(t)}${Vu(r)}`});return Fu(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${ht(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${ht(t)}`})}async readWait(t,r,n={}){let o=oz(t,r,n),i=await this.client.call("query",{sql:o});return Fu(i)}};function oz(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=ht(e),a=ht(t),c=o!=null?` GROUP ${ht(o)}`:"",l=i!=null?Vu(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function ht(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Vu(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new z("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function iz(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function sz(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new z("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${iz(e.priority)}`),e.key!=null&&(t+=` KEY ${Ku(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Ku(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function az(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Ku(e):JSON.stringify(e)}function Ku(e){return`'${String(e).replace(/'/g,"''")}'`}function Fu(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Fn=class{constructor(t){this.db=t}async insert(t,r){t_(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Ei(t)} DOCUMENT VALUES (${lz(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new z("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:n.affected??1,rid:o.rid,item:o}}async get(t,r){let n=await this.db.get(t,r);if(!n.entity)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=cz(r.limit),o=r.orderBy??r.order_by??"rid ASC",i=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${Ei(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){t_(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new z("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new z("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=o.map(([c,l])=>`${r_(c)} = ${dz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Ei(t)} SET ${i} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return a}async delete(t,r){let o=(await this.db.delete(t,r)).affected??0;return{affected:o,deleted:o>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${Ei(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function t_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function cz(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new z("INVALID_ARGUMENT","limit must be a positive integer");return e}function Ei(e){return String(e).split(".").map(r_).join(".")}function r_(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function uz(e){return n_(JSON.stringify(e))}function lz(e){return JSON.stringify(e)}function dz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?uz(e):n_(e)}function n_(e){return`'${String(e).replace(/'/g,"''")}'`}var Vn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){pz(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(o_).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${It(o)} ${It(t)} = ${fz(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${It(n)} ${It(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${It(n)} ${It(t)}`})}};function fz(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${It(r)}.${It(n)})`}return mz(e)}function pz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function It(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function mz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):o_(e)}function o_(e){return`'${String(e).replace(/'/g,"''")}'`}var Kn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){hz(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(i_).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Nr(o)}.${Nr(t)} = ${gz(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Nr(n)}.${Nr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Nr(n)}.${Nr(t)}`})}};function hz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Nr(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function gz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):i_(e)}function i_(e){return`'${String(e).replace(/'/g,"''")}'`}async function a_(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(yz)}async function c_(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${wz(t)}`)).rows??[]).some(n=>n.name===String(t))}var Hn=class e{constructor(t,r,n=null,o=[],i=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=i}select(...t){let r=t.length===1&&Array.isArray(t[0])?t[0]:t,n=r.length===1&&r[0]==="*"?null:r;return new e(this.db,this.collection,n!=null&&n.length>0?n:null,this.whereClauses,this.params)}where(t,...r){if(typeof t!="string"||t.trim().length===0)throw new z("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...n])}async run(){let t=this.columns==null?"*":this.columns.map(s_).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${s_(this.collection)}${r}`,i=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?i:i.map(s=>{let a={};for(let c of this.columns)a[c]=s[c];return a})}};function yz(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function s_(e){return String(e).split(".").map(_z).join(".")}function _z(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function wz(e){return`'${String(e).replace(/'/g,"''")}'`}var bz="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",vz="1.0",d_="1.0.9",u_="NESTED_TX_NOT_SUPPORTED";async function f_(e,t={}){let r=Bu(e);if(Rz(r),r.kind==="embedded"){let n=Pz(r,t.auth);if(n.token||n.username)throw new z("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=Tz(r),i=t.binary??Yy(),s=await Jy(i,o),a=new Si(s);return await a.call("version",{}),new Wu(a,{transport:"embedded"})}}function l_(e){return xz(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:$z(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&Ez(e)?{$uuid:e}:e}function xz(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new z("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new z("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new z("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function kz(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(l_):e.map(l_)}function $z(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}function Sz(e){if(typeof Buffer<"u"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Ez(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Ti(e){if(Array.isArray(e))return e.map(Ti);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return Sz(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let n=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(n/1000000n))}}let r={};for(let[n,o]of Object.entries(e))r[n]=Ti(o);return r}return e}function Tz(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function Pz(e,t){let r={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return r;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");r.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");r.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");r.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");r.password=t.password}return t.loginUrl!=null&&(r.loginUrl=t.loginUrl),r}function Rz(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",bz)}var Pi=class{constructor(t){this.db=t}query(t,...r){return this.db.query(t,...r)}execute(t,...r){return this.db.execute(t,...r)}insert(t,r){return this.db.insert(t,r)}bulkInsert(t,r){return this.db.bulkInsert(t,r)}async transaction(){throw Gu()}},Hu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Gu();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new z("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new Pi(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){p_(r,n)}throw r}}},Wu=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=vz,this.cache=new Zn(t,this.transport),this.queue=new Un(t),this.queues=this.queue,this.documents=new Fn(this);let n=new Ar(t);this.kv=Object.assign((o="kv_default")=>new Ar(t,o),{put:n.put.bind(n),invalidateTags:n.invalidateTags.bind(n),watch:n.watch.bind(n),watchPrefix:n.watchPrefix.bind(n)}),this.config=(o="red.config")=>new Vn(t,o),this.vault=(o="red.vault")=>new Kn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new z("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=kz(r);return n==null?this.client.call("query",{sql:t}).then(Ti):this.client.call("query",{sql:t,params:n}).then(Ti)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return zz(n,"insert")}async bulkInsert(t,r){if(Array.isArray(r)&&r.length===0)return{affected:0,rids:[],ids:[]};let n=await this.client.call("bulk_insert",{collection:t,payloads:r});return Oz(n,r.length)}tx(){return new Hu(this)}async transaction(t){if(this.inTransaction)throw Gu();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let r=!1;try{await this.query("BEGIN"),r=!0;let n=await t(new Pi(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){p_(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return c_(this,t)}list(){return a_(this)}from(t){return new Hn(this,t)}get(t,r){return this.client.call("get",{collection:t,id:String(r)})}delete(t,r){return this.client.call("delete",{collection:t,id:String(r)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,r){return this.client.call("auth.login",{username:t,password:r})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,r){return this.client.call("auth.change_password",{current_password:t,new_password:r})}createApiKey({username:t,role:r}={}){return this.client.call("auth.create_api_key",{username:t,role:r})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}};function Gu(){return new z(u_,`${u_}: nested transactions are not supported on one connection`)}function p_(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function zz(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${d_} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function Oz(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new z("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${d_} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new z("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}function Wn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&Iz(t.chosenOption)&&Az(t.outcome)&&Nz(t.cost)}function Iz(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function Az(e){return e==="success"||e==="failure"||e==="escalated"}function Nz(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}import{createHash as Cz}from"node:crypto";function Ju(e){return Cz("sha256").update(e).digest("hex")}function m_(e){return Ju(JSON.stringify(e))}function h_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Qu="unknown",Ri=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=el(t.from),i=el(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>Dz(p,n)).filter(p=>p!=null).filter(p=>Mz(p,t)).filter(p=>qz(p.ts,o,i)).sort((p,m)=>p.ts-m.ts),a=s.length,c=o??(s.length>0?s[0].ts:null),l=i??(s.length>0?s[s.length-1].ts:null),u=Zz(c,l,r),f=[g_(null,s,u,r)];if(t.groupBy){let m=[...Lz(s,t.groupBy).entries()].map(([h,_])=>g_(h,_,u,r)).sort((h,_)=>_.total-h.total||Fz(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function Dz(e,t){let r=e.properties.metadata??{},n=jz(e,r,t);return n==null?null:{ts:n,platform:Yu(r,"platform")??Qu,eventType:Yu(r,"event_type")??Qu,target:Yu(r,"target")??Qu}}function jz(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:el(t.timestamp)??n}function Yu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Mz(e,t){return!(t.platform!=null&&e.platform!==t.platform||t.eventType!=null&&e.eventType!==t.eventType||t.target!=null&&e.target!==t.target)}function qz(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function Lz(e,t){let r=new Map;for(let n of e){let o=Bz(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function Bz(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function g_(e,t,r,n){let o=new Map;for(let s of t){let a=Xu(s.ts,n);o.set(a,(o.get(a)??0)+1)}let i=r.map(s=>({start:s,startIso:new Date(s).toISOString(),count:o.get(s)??0}));return{group:e,total:t.length,buckets:i}}function Zz(e,t,r){if(e==null||t==null)return[];let n=[],o=Xu(e,r),i=Xu(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=Uz(o,r),s++;return n}function Xu(e,t){let r=new Date(e);switch(t){case"hour":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),r.getUTCHours());case"day":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate());case"week":{let n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),i=(new Date(n).getUTCDay()+6)%7;return n-i*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function Uz(e,t){switch(t){case"hour":return e+36e5;case"day":return e+864e5;case"week":return e+6048e5;case"month":{let r=new Date(e);return Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,1)}}}function el(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let t=e.trim();if(t==="")return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)?n:null}let r=Date.parse(t);return Number.isNaN(r)?null:r}function Fz(e,t){return String(e??"").localeCompare(String(t??""))}var Vz=["validate","simple","complex","think"];var Kz={validate:1,simple:.85,complex:.65,think:.45};function Hz(){return{schemaVersion:1,buckets:{}}}function __(e,t={}){let r=Xz(t.initial??Hz());for(let n of e)Wz(r,n,t);return r}function Wz(e,t,r={}){let n=(r.tierForEvent??Gz)(t);if(!n)return e;let i=Qz(e,t.taskClass).arms[n],s=Jz(t,n);return i.posterior.alpha=y_(i.posterior.alpha+s),i.posterior.beta=y_(i.posterior.beta+(1-s)),i.observations+=1,t.outcome==="success"?(i.successes+=1,i.consecutiveFailures=0):(i.failures+=1,i.consecutiveFailures+=1),e}function Gz(e){let t=e.chosenOption.kind;if(eO(t))return t;let r=e.chosenOption.model?.toLowerCase()??"",n=e.chosenOption.effort?.toLowerCase()??"";if(r.includes("haiku"))return"validate";if(r.includes("sonnet"))return"simple";if(r.includes("opus")&&n==="high")return"think";if(r.includes("opus"))return"complex"}function Jz(e,t){return e.outcome!=="success"?0:Kz[t]}function Qz(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=Yz(),e.buckets[r]}function Yz(){return{arms:{validate:zi(),simple:zi(),complex:zi(),think:zi()}}}function zi(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function Xz(e){return JSON.parse(JSON.stringify(e))}function eO(e){return Vz.includes(e)}function y_(e){return Math.round(e*1e3)/1e3}var Oi=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],w_={contact:"person"},Ii=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Je={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var Ni=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;outcomeEventCache=null;modelTierBanditCache=null;static async open(t){let r=new e(t);return r.db=await f_(t.uri),await r.bootstrap(),r}get raw(){return this.db}async close(){await this.db.close()}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Je.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Je.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Je.outcomeEvents}`)}kv(){return this.db.kv(Je.kv)}async capture(t){let r=E_(t.kind??"note"),n=Date.now(),o=oO(t.tags??[]),i=m_([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),s=await this.findArtifactByHash(i);if(s!=null){let h=await this.getArtifact(s);if(h)return h}let a=await this.listArtifacts(),c=`${h_(t.title)}-${i.slice(0,8)}`,l={id:c,title:t.title,content:t.content,tags:o,source_agent:t.sourceAgent,source_runner:t.sourceRunner,source_session:t.sourceSession,source_path:t.sourcePath,created_at:n,updated_at:n,hash:i,metadata:t.metadata},u={label:c,kind:r,properties:l},f=(await this.db.query(`INSERT INTO ${Je.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,i,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let p=Number(f.red_entity_id??f.rid);await this.kv().put(v_(i),p),this.artifactCache=null;let m={...u,rid:p};return await this.autoLinkArtifact(m,a),await this.materializeTagConnections(m),m}async getArtifact(t){let r=await this.listArtifacts();return typeof t=="number"?r.find(n=>n.rid===t)??null:r.find(n=>n.properties.id===t||n.label===t)??null}async listArtifacts(){if(this.artifactCache==null){let t=await this.db.query(`SELECT * FROM ${Je.artifacts}`);this.artifactCache=t.rows.map(tO).filter(Ai)}return this.artifactCache}async search(t,r=10,n={}){let o=iO(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=P_(u,o),f=R_({...d,connections:sO(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:cO(u.properties.content,o)}}).filter(u=>u.score>0).sort((u,d)=>d.score-u.score||d.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,r)}async link(t){let r=await this.getArtifact(t.from),n=await this.getArtifact(t.to);if(!r)throw new Error(`Brain artifact not found: ${t.from}`);if(!n)throw new Error(`Brain artifact not found: ${t.to}`);let o=T_(t.kind??"related_to"),i=await this.findConnection(r.rid,n.rid,o);if(i!=null){let u=(await this.listConnections()).find(d=>d.rid===i);if(u)return u}let s={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${Je.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,s)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let l=Number(c.red_entity_id??c.rid);return await this.kv().put(x_(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:s}}async backlinks(t){let r=await this.getArtifact(t);if(!r)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(n=>n.to_rid===r.rid)}async listConnections(){if(this.connectionCache==null){let t=await this.db.query(`SELECT * FROM ${Je.connections}`);this.connectionCache=t.rows.map(rO).filter(Ai)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:hO(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new Ri(r).events(t)}async appendOutcomeEvent(t){if(!Wn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Je.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,r)).rows[0])throw new Error("INSERT outcome event returned no row");return this.outcomeEventCache=null,t}async replayOutcomeEvents(){if(this.outcomeEventCache==null){let t=await this.db.query(`SELECT * FROM ${Je.outcomeEvents}`);this.outcomeEventCache=t.rows.map(nO).filter(Ai).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(k_());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return $_(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!$_(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(k_(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=__(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!Or(i.artifact)).slice(0,r);return uO(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(v_(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(x_(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||Or(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=Zy(t),i=new Set([t.rid]);for(let d of r)Or(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!Or(d.artifact)).map(d=>({artifact:Cu(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Cu(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:Nu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!Du(d.kind))continue;let f=await this.getArtifact(d.from),p=await this.getArtifact(d.to);if(!f||!p)continue;let m=f.rid===t.rid||p.rid===t.rid,h=n.has(f.rid)||n.has(p.rid);if(!m||!h||f.rid===p.rid)continue;let _=await this.link({from:f.rid,to:p.rid,kind:d.kind,reason:d.reason,confidence:"derived",metadata:{...d.metadata??{},derived_by:"brain.autolink.afk-headless",source_artifact_rid:t.rid}});u.push({proposal:d,connection:_})}return u}catch(o){if(this.opts.autoLinkErrors==="throw")throw o;return[]}}};function E_(e){let r=w_[e]??e;if(Oi.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function T_(e){if(Ii.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function tO(e){let t=Number(e.red_entity_id??e.rid),r=tl(e.properties??e.PROPERTIES),n=String(e.node_type??e.NODE_TYPE??r.kind??"note");if(!Number.isFinite(t))return null;let o=String(r.id??e.label??e.LABEL??t),i=String(r.title??e.label??e.LABEL??o),s=String(r.content??""),a=Array.isArray(r.tags)?r.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??o),kind:E_(n),properties:{...r,id:o,title:i,content:s,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function rO(e){let t=Number(e.red_entity_id??e.rid),r=Number(e.from??e.FROM??e.from_rid??e.source),n=Number(e.to??e.TO??e.to_rid??e.target),o=String(e.label??e.LABEL??"related_to");return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)?null:{rid:t,kind:T_(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:tl(e.properties??e.PROPERTIES)}}function nO(e){let t=Number(e.red_entity_id??e.rid),r=tl(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Wn(r)?null:{rid:t,event:r}}function tl(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function Ai(e){return e!=null}function oO(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function iO(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function b_(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function P_(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(s=>s.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((s,a)=>s+b_(r,a)*3+b_(n,a),0),tags:t.reduce((s,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return s+c},0),kind:t.reduce((s,a)=>i===a?s+3:i.includes(a)||a.includes(i)?s+1:s,0)}}function sO(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||Or(a))continue;let c=R_({...P_(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*aO(i.kind))}return Yt(o*.35)}function aO(e){switch(e){case"supports":case"contradicts":case"depends_on":case"derived_from":case"part_of":return 1;case"related_to":case"authored":return .75;case"preceded_by":case"followed_by":return .5;case"tagged":return .2}}function R_(e){return{...e,lexical:Yt(e.lexical),tags:Yt(e.tags),kind:Yt(e.kind),connections:Yt(e.connections),vector:Yt(e.vector),total:Yt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Yt(e){return Math.round(e*1e3)/1e3}function cO(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(i=>r.indexOf(i)).filter(i=>i>=0).sort((i,s)=>i-s)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function uO(e,t){let r=t.map(lO),n=dO(t),o=fO(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:pO(e,r,n,o)}}function lO(e,t){let r=e.artifact,n={};return r.properties.source_path&&(n.path=r.properties.source_path),r.properties.source_session&&(n.session=r.properties.source_session),r.properties.source_agent&&(n.agent=r.properties.source_agent),r.properties.source_runner&&(n.runner=r.properties.source_runner),{ref:`B${t+1}`,rid:r.rid,id:r.properties.id,title:r.properties.title,kind:r.kind,score:e.score,score_breakdown:e.score_breakdown,excerpt:e.excerpt,source:Object.keys(n).length>0?n:void 0}}function dO(e){let t=e[0];if(!t)return"none";let r=Object.entries(t.score_breakdown).filter(([n,o])=>n!=="total"&&o>0).length;return t.score>=8||t.score>=5&&r>=2?"high":t.score>=3?"medium":"low"}function fO(e,t,r){if(t.length===0)return[`No Brain artifacts matched "${e}". Capture or ingest cited artifacts before relying on Brain for this answer.`];let n=[];return r==="low"&&n.push("Only low-scoring deterministic matches were found; open the cited artifacts before treating this as settled."),t.length===1&&n.push("Only one cited artifact matched; missing context or contradictions may not be visible yet."),t.every(o=>o.source==null)&&n.push("The matched artifacts do not carry source path, session, agent, or runner provenance."),n}function pO(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
73
- `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${mO(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
74
- `)}function mO(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(Ai);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function v_(e){return`artifact.hash.${e}`}function x_(e,t,r){return`connection.${e}.${r}.${t}`}function k_(){return`model-tier-bandit.v${1}`}function $_(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function hO(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function gO(e=process.cwd()){let t=await Ky(e);if(Wy(t))try{return{config:t,store:await Gy(t),project:z_(t.rootDir)}}catch(n){let o=xi(t.rootDir);if(await Bn(o.socketPath,50))throw n}let r=await Ni.open({uri:t.connectionString,autoLinker:Uy()});return{config:t,store:r,project:z_(t.rootDir)}}async function we(e,t=process.cwd()){let r=await gO(t);try{return await e(r)}finally{await r.store.close()}}function wO(e){return mt(e)}async function I_(e,t){if(e!=="SessionStart")return{};let r=await we(async({config:o,store:i})=>(await i.status(),o)),n=O_(r.rootDir,".red","brain","sessions");return await yO(n,{recursive:!0}),await _O(O_(n,"last-session.json"),wO({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()}),"utf8"),{}}var Ci=class{map({event:t,sourceAgent:r}){return{title:bO(t),content:vO(t),kind:"event",tags:xO(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:A_(t),metadata:kO(t)}}};function A_(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${Ju(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function bO(e){let t=[];e.platform&&t.push(e.platform),e.target&&t.push(e.target);let r=t.length>0?`[${t.join(":")}]`:"[channel-event]";if(e.message){let n=e.message.slice(0,60).replace(/\n/g," ");return`${r} ${n}`}return e.type?`${r} ${e.type}`:`${r} event`}function vO(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
75
- `)||JSON.stringify(e.raw)}function xO(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function kO(e){let t={event_key:A_(e)};return e.id!=null&&(t.event_id=e.id),e.cursor!=null&&(t.cursor=e.cursor),e.timestamp!=null&&(t.timestamp=e.timestamp),e.platform!=null&&(t.platform=e.platform),e.target!=null&&(t.target=e.target),e.sessionKey!=null&&(t.session_key=e.sessionKey),e.type!=null&&(t.event_type=e.type),t}async function Di(e){let t=new Ci,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Xt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function C_(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Xt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Xt("brain_act requires a non-empty message");let o=t.connect??(a=>Gt.connect(a)),i=t.process??$O(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Xt(`brain_act could not reach the channel bridge: ${N_(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Xt(`brain_act could not send to "${r}": ${N_(c)}`,{cause:c})}if(!a.ok)throw new Xt(`brain_act could not send to "${r}": ${SO(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function $O(e=process.env){let t=e.RED_BRAIN_HERMES_COMMAND?.trim()||void 0,r=e.RED_BRAIN_HERMES_ARGS?.trim(),n=r?r.split(/\s+/).filter(Boolean):void 0;return{command:t,args:n}}function SO(e){return EO(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function EO(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let r=e;for(let n of t){let o=r[n];if(typeof o=="string"&&o.trim())return o}}function N_(e){return e instanceof Error?e.message:String(e)}import{createServer as TO}from"node:http";async function M_(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),i=await e.eventKpis({interval:"day"}),s=await e.eventKpis({interval:"day",groupBy:"platform"}),a=await e.eventKpis({interval:"day",groupBy:"event_type"}),c=t.decisionLimit??8,l=t.connectionLimit??12;return{schema_version:"brain.dashboard.v1",generated_at:new Date(t.now??Date.now()).toISOString(),project:t.project,root:t.rootDir,stats:{artifacts:r.length,connections:n.length,decisions:r.filter(u=>u.kind==="decision").length,events:i.total,supports:rl(n,"supports"),contradicts:rl(n,"contradicts"),depends_on:rl(n,"depends_on")},kpis:{events_daily:i,events_by_platform:s,events_by_type:a},recent_decisions:r.filter(u=>u.kind==="decision").sort((u,d)=>d.properties.updated_at-u.properties.updated_at||d.rid-u.rid).slice(0,c).map(u=>PO(u,n)),recent_connections:n.filter(u=>o.has(u.from_rid)&&o.has(u.to_rid)).sort((u,d)=>d.properties.created_at-u.properties.created_at||d.rid-u.rid).slice(0,l).map(u=>RO(u,o)),attribution:{red_hermes:"Dashboard layout and command-center interaction model are adapted from the red-hermes web surface; NOTICE records the MIT attribution."}}}function q_(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:zO(e)}}async function L_(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=TO((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
76
- `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function PO(e,t){let r=t.filter(n=>n.from_rid===e.rid||n.to_rid===e.rid);return{rid:e.rid,id:e.properties.id,title:e.properties.title,updated_at:new Date(e.properties.updated_at).toISOString(),tags:e.properties.tags,connection_counts:{supports:r.filter(n=>n.kind==="supports").length,contradicts:r.filter(n=>n.kind==="contradicts").length,depends_on:r.filter(n=>n.kind==="depends_on").length,related_to:r.filter(n=>n.kind==="related_to").length},excerpt:AO(e.properties.content)}}function RO(e,t){let r=t.get(e.from_rid),n=t.get(e.to_rid);if(!r||!n)throw new Error(`connection ${e.rid} references missing artifacts`);return{rid:e.rid,kind:e.kind,from:{rid:r.rid,title:r.properties.title},to:{rid:n.rid,title:n.properties.title},created_at:new Date(e.properties.created_at).toISOString(),reason:e.properties.reason??null}}function zO(e){return`<!doctype html>
72
+ `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function Uu(e,t){return`${Fu(e)}.${cz(t)}`}function Fu(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new z("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function cz(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function uz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function o_(e){return`'${String(e).replace(/'/g,"''")}'`}var Un=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${ht(t)}`})}push(t,r,n={}){let o=fz(n);return this.client.call("query",{sql:`QUEUE PUSH ${ht(t)} ${pz(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${ht(t)}${Ku(r)}`});return Vu(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${ht(t)}${Ku(r)}`});return Vu(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${ht(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${ht(t)}`})}async readWait(t,r,n={}){let o=lz(t,r,n),i=await this.client.call("query",{sql:o});return Vu(i)}};function lz(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=ht(e),a=ht(t),c=o!=null?` GROUP ${ht(o)}`:"",l=i!=null?Ku(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function ht(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Ku(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new z("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function dz(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function fz(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new z("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${dz(e.priority)}`),e.key!=null&&(t+=` KEY ${Hu(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Hu(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function pz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Hu(e):JSON.stringify(e)}function Hu(e){return`'${String(e).replace(/'/g,"''")}'`}function Vu(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Fn=class{constructor(t){this.db=t}async insert(t,r){i_(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Ei(t)} DOCUMENT VALUES (${gz(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new z("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:n.affected??1,rid:o.rid,item:o}}async get(t,r){let n=await this.db.get(t,r);if(!n.entity)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=mz(r.limit),o=r.orderBy??r.order_by??"rid ASC",i=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${Ei(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){i_(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new z("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new z("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=o.map(([c,l])=>`${s_(c)} = ${yz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Ei(t)} SET ${i} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return a}async delete(t,r){let o=(await this.db.delete(t,r)).affected??0;return{affected:o,deleted:o>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${Ei(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function i_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function mz(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new z("INVALID_ARGUMENT","limit must be a positive integer");return e}function Ei(e){return String(e).split(".").map(s_).join(".")}function s_(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function hz(e){return a_(JSON.stringify(e))}function gz(e){return JSON.stringify(e)}function yz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?hz(e):a_(e)}function a_(e){return`'${String(e).replace(/'/g,"''")}'`}var Vn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){wz(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(c_).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${It(o)} ${It(t)} = ${_z(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${It(n)} ${It(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${It(n)} ${It(t)}`})}};function _z(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${It(r)}.${It(n)})`}return vz(e)}function wz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function It(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function vz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):c_(e)}function c_(e){return`'${String(e).replace(/'/g,"''")}'`}var Kn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){bz(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(u_).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Nr(o)}.${Nr(t)} = ${xz(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Nr(n)}.${Nr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Nr(n)}.${Nr(t)}`})}};function bz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Nr(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function xz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):u_(e)}function u_(e){return`'${String(e).replace(/'/g,"''")}'`}async function d_(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(kz)}async function f_(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${Sz(t)}`)).rows??[]).some(n=>n.name===String(t))}var Hn=class e{constructor(t,r,n=null,o=[],i=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=i}select(...t){let r=t.length===1&&Array.isArray(t[0])?t[0]:t,n=r.length===1&&r[0]==="*"?null:r;return new e(this.db,this.collection,n!=null&&n.length>0?n:null,this.whereClauses,this.params)}where(t,...r){if(typeof t!="string"||t.trim().length===0)throw new z("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...n])}async run(){let t=this.columns==null?"*":this.columns.map(l_).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${l_(this.collection)}${r}`,i=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?i:i.map(s=>{let a={};for(let c of this.columns)a[c]=s[c];return a})}};function kz(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function l_(e){return String(e).split(".").map($z).join(".")}function $z(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function Sz(e){return`'${String(e).replace(/'/g,"''")}'`}var Ez="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",Tz="1.0",h_="1.0.9",p_="NESTED_TX_NOT_SUPPORTED";async function g_(e,t={}){let r=Zu(e);if(Cz(r),r.kind==="embedded"){let n=Nz(r,t.auth);if(n.token||n.username)throw new z("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=Az(r),i=t.binary??r_(),s=await e_(i,o),a=new Si(s);return await a.call("version",{}),new Gu(a,{transport:"embedded"})}}function m_(e){return Rz(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:zz(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&Iz(e)?{$uuid:e}:e}function Rz(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new z("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new z("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new z("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function Pz(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(m_):e.map(m_)}function zz(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}function Oz(e){if(typeof Buffer<"u"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Iz(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Ti(e){if(Array.isArray(e))return e.map(Ti);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return Oz(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let n=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(n/1000000n))}}let r={};for(let[n,o]of Object.entries(e))r[n]=Ti(o);return r}return e}function Az(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function Nz(e,t){let r={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return r;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");r.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");r.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");r.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");r.password=t.password}return t.loginUrl!=null&&(r.loginUrl=t.loginUrl),r}function Cz(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",Ez)}var Ri=class{constructor(t){this.db=t}query(t,...r){return this.db.query(t,...r)}execute(t,...r){return this.db.execute(t,...r)}insert(t,r){return this.db.insert(t,r)}bulkInsert(t,r){return this.db.bulkInsert(t,r)}async transaction(){throw Ju()}},Wu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Ju();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new z("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new Ri(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){y_(r,n)}throw r}}},Gu=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=Tz,this.cache=new Zn(t,this.transport),this.queue=new Un(t),this.queues=this.queue,this.documents=new Fn(this);let n=new Ar(t);this.kv=Object.assign((o="kv_default")=>new Ar(t,o),{put:n.put.bind(n),invalidateTags:n.invalidateTags.bind(n),watch:n.watch.bind(n),watchPrefix:n.watchPrefix.bind(n)}),this.config=(o="red.config")=>new Vn(t,o),this.vault=(o="red.vault")=>new Kn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new z("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=Pz(r);return n==null?this.client.call("query",{sql:t}).then(Ti):this.client.call("query",{sql:t,params:n}).then(Ti)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return Dz(n,"insert")}async bulkInsert(t,r){if(Array.isArray(r)&&r.length===0)return{affected:0,rids:[],ids:[]};let n=await this.client.call("bulk_insert",{collection:t,payloads:r});return jz(n,r.length)}tx(){return new Wu(this)}async transaction(t){if(this.inTransaction)throw Ju();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let r=!1;try{await this.query("BEGIN"),r=!0;let n=await t(new Ri(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){y_(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return f_(this,t)}list(){return d_(this)}from(t){return new Hn(this,t)}get(t,r){return this.client.call("get",{collection:t,id:String(r)})}delete(t,r){return this.client.call("delete",{collection:t,id:String(r)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,r){return this.client.call("auth.login",{username:t,password:r})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,r){return this.client.call("auth.change_password",{current_password:t,new_password:r})}createApiKey({username:t,role:r}={}){return this.client.call("auth.create_api_key",{username:t,role:r})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}};function Ju(){return new z(p_,`${p_}: nested transactions are not supported on one connection`)}function y_(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function Dz(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${h_} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function jz(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new z("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${h_} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new z("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}function Wn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&Mz(t.chosenOption)&&qz(t.outcome)&&Lz(t.cost)}function Mz(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function qz(e){return e==="success"||e==="failure"||e==="escalated"}function Lz(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}import{createHash as Bz}from"node:crypto";function Qu(e){return Bz("sha256").update(e).digest("hex")}function __(e){return Qu(JSON.stringify(e))}function w_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Yu="unknown",Pi=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=tl(t.from),i=tl(t.to),s=this.artifacts.filter(p=>p.kind==="event").map(p=>Zz(p,n)).filter(p=>p!=null).filter(p=>Fz(p,t)).filter(p=>Vz(p.ts,o,i)).sort((p,m)=>p.ts-m.ts),a=s.length,c=o??(s.length>0?s[0].ts:null),l=i??(s.length>0?s[s.length-1].ts:null),u=Wz(c,l,r),f=[v_(null,s,u,r)];if(t.groupBy){let m=[...Kz(s,t.groupBy).entries()].map(([h,_])=>v_(h,_,u,r)).sort((h,_)=>_.total-h.total||Jz(h.group,_.group));f.push(...m)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:f}}};function Zz(e,t){let r=e.properties.metadata??{},n=Uz(e,r,t);return n==null?null:{ts:n,platform:Xu(r,"platform")??Yu,eventType:Xu(r,"event_type")??Yu,target:Xu(r,"target")??Yu}}function Uz(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:tl(t.timestamp)??n}function Xu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Fz(e,t){return!(t.platform!=null&&e.platform!==t.platform||t.eventType!=null&&e.eventType!==t.eventType||t.target!=null&&e.target!==t.target)}function Vz(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function Kz(e,t){let r=new Map;for(let n of e){let o=Hz(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function Hz(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function v_(e,t,r,n){let o=new Map;for(let s of t){let a=el(s.ts,n);o.set(a,(o.get(a)??0)+1)}let i=r.map(s=>({start:s,startIso:new Date(s).toISOString(),count:o.get(s)??0}));return{group:e,total:t.length,buckets:i}}function Wz(e,t,r){if(e==null||t==null)return[];let n=[],o=el(e,r),i=el(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=Gz(o,r),s++;return n}function el(e,t){let r=new Date(e);switch(t){case"hour":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),r.getUTCHours());case"day":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate());case"week":{let n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),i=(new Date(n).getUTCDay()+6)%7;return n-i*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function Gz(e,t){switch(t){case"hour":return e+36e5;case"day":return e+864e5;case"week":return e+6048e5;case"month":{let r=new Date(e);return Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,1)}}}function tl(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let t=e.trim();if(t==="")return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)?n:null}let r=Date.parse(t);return Number.isNaN(r)?null:r}function Jz(e,t){return String(e??"").localeCompare(String(t??""))}var Qz=["validate","simple","complex","think"];var Yz={validate:1,simple:.85,complex:.65,think:.45};function Xz(){return{schemaVersion:1,buckets:{}}}function x_(e,t={}){let r=iO(t.initial??Xz());for(let n of e)eO(r,n,t);return r}function eO(e,t,r={}){let n=(r.tierForEvent??tO)(t);if(!n)return e;let i=nO(e,t.taskClass).arms[n],s=rO(t,n);return i.posterior.alpha=b_(i.posterior.alpha+s),i.posterior.beta=b_(i.posterior.beta+(1-s)),i.observations+=1,t.outcome==="success"?(i.successes+=1,i.consecutiveFailures=0):(i.failures+=1,i.consecutiveFailures+=1),e}function tO(e){let t=e.chosenOption.kind;if(sO(t))return t;let r=e.chosenOption.model?.toLowerCase()??"",n=e.chosenOption.effort?.toLowerCase()??"";if(r.includes("haiku"))return"validate";if(r.includes("sonnet"))return"simple";if(r.includes("opus")&&n==="high")return"think";if(r.includes("opus"))return"complex"}function rO(e,t){return e.outcome!=="success"?0:Yz[t]}function nO(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=oO(),e.buckets[r]}function oO(){return{arms:{validate:zi(),simple:zi(),complex:zi(),think:zi()}}}function zi(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function iO(e){return JSON.parse(JSON.stringify(e))}function sO(e){return Qz.includes(e)}function b_(e){return Math.round(e*1e3)/1e3}var Oi=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],k_={contact:"person"},Ii=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Ge={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var Ni=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;outcomeEventCache=null;modelTierBanditCache=null;static async open(t){let r=new e(t);return r.db=await g_(t.uri),await r.bootstrap(),r}get raw(){return this.db}async close(){await this.db.close()}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ge.outcomeEvents}`)}kv(){return this.db.kv(Ge.kv)}async capture(t){let r=z_(t.kind??"note"),n=Date.now(),o=lO(t.tags??[]),i=__([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),s=await this.findArtifactByHash(i);if(s!=null){let h=await this.getArtifact(s);if(h)return h}let a=await this.listArtifacts(),c=`${w_(t.title)}-${i.slice(0,8)}`,l={id:c,title:t.title,content:t.content,tags:o,source_agent:t.sourceAgent,source_runner:t.sourceRunner,source_session:t.sourceSession,source_path:t.sourcePath,created_at:n,updated_at:n,hash:i,metadata:t.metadata},u={label:c,kind:r,properties:l},f=(await this.db.query(`INSERT INTO ${Ge.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,i,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let p=Number(f.red_entity_id??f.rid);await this.kv().put(S_(i),p),this.artifactCache=null;let m={...u,rid:p};return await this.autoLinkArtifact(m,a),await this.materializeTagConnections(m),m}async getArtifact(t){let r=await this.listArtifacts();return typeof t=="number"?r.find(n=>n.rid===t)??null:r.find(n=>n.properties.id===t||n.label===t)??null}async listArtifacts(){if(this.artifactCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.artifacts}`);this.artifactCache=t.rows.map(aO).filter(Ai)}return this.artifactCache}async search(t,r=10,n={}){let o=dO(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=I_(u,o),f=A_({...d,connections:fO(u,o,a,c),vector:0});return{artifact:u,score:f.total,score_breakdown:f,excerpt:mO(u.properties.content,o)}}).filter(u=>u.score>0).sort((u,d)=>d.score-u.score||d.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,r)}async link(t){let r=await this.getArtifact(t.from),n=await this.getArtifact(t.to);if(!r)throw new Error(`Brain artifact not found: ${t.from}`);if(!n)throw new Error(`Brain artifact not found: ${t.to}`);let o=O_(t.kind??"related_to"),i=await this.findConnection(r.rid,n.rid,o);if(i!=null){let u=(await this.listConnections()).find(d=>d.rid===i);if(u)return u}let s={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${Ge.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,s)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let l=Number(c.red_entity_id??c.rid);return await this.kv().put(E_(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:s}}async backlinks(t){let r=await this.getArtifact(t);if(!r)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(n=>n.to_rid===r.rid)}async listConnections(){if(this.connectionCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.connections}`);this.connectionCache=t.rows.map(cO).filter(Ai)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:bO(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new Pi(r).events(t)}async appendOutcomeEvent(t){if(!Wn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Ge.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,r)).rows[0])throw new Error("INSERT outcome event returned no row");return this.outcomeEventCache=null,t}async replayOutcomeEvents(){if(this.outcomeEventCache==null){let t=await this.db.query(`SELECT * FROM ${Ge.outcomeEvents}`);this.outcomeEventCache=t.rows.map(uO).filter(Ai).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(T_());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return R_(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!R_(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(T_(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=x_(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!Or(i.artifact)).slice(0,r);return hO(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(S_(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(E_(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||Or(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=Ky(t),i=new Set([t.rid]);for(let d of r)Or(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!Or(d.artifact)).map(d=>({artifact:Du(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Du(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:Cu},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!ju(d.kind))continue;let f=await this.getArtifact(d.from),p=await this.getArtifact(d.to);if(!f||!p)continue;let m=f.rid===t.rid||p.rid===t.rid,h=n.has(f.rid)||n.has(p.rid);if(!m||!h||f.rid===p.rid)continue;let _=await this.link({from:f.rid,to:p.rid,kind:d.kind,reason:d.reason,confidence:"derived",metadata:{...d.metadata??{},derived_by:"brain.autolink.afk-headless",source_artifact_rid:t.rid}});u.push({proposal:d,connection:_})}return u}catch(o){if(this.opts.autoLinkErrors==="throw")throw o;return[]}}};function z_(e){let r=k_[e]??e;if(Oi.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function O_(e){if(Ii.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function aO(e){let t=Number(e.red_entity_id??e.rid),r=rl(e.properties??e.PROPERTIES),n=String(e.node_type??e.NODE_TYPE??r.kind??"note");if(!Number.isFinite(t))return null;let o=String(r.id??e.label??e.LABEL??t),i=String(r.title??e.label??e.LABEL??o),s=String(r.content??""),a=Array.isArray(r.tags)?r.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??o),kind:z_(n),properties:{...r,id:o,title:i,content:s,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function cO(e){let t=Number(e.red_entity_id??e.rid),r=Number(e.from??e.FROM??e.from_rid??e.source),n=Number(e.to??e.TO??e.to_rid??e.target),o=String(e.label??e.LABEL??"related_to");return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)?null:{rid:t,kind:O_(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:rl(e.properties??e.PROPERTIES)}}function uO(e){let t=Number(e.red_entity_id??e.rid),r=rl(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Wn(r)?null:{rid:t,event:r}}function rl(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function Ai(e){return e!=null}function lO(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function dO(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function $_(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function I_(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(s=>s.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((s,a)=>s+$_(r,a)*3+$_(n,a),0),tags:t.reduce((s,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return s+c},0),kind:t.reduce((s,a)=>i===a?s+3:i.includes(a)||a.includes(i)?s+1:s,0)}}function fO(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||Or(a))continue;let c=A_({...I_(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*pO(i.kind))}return Yt(o*.35)}function pO(e){switch(e){case"supports":case"contradicts":case"depends_on":case"derived_from":case"part_of":return 1;case"related_to":case"authored":return .75;case"preceded_by":case"followed_by":return .5;case"tagged":return .2}}function A_(e){return{...e,lexical:Yt(e.lexical),tags:Yt(e.tags),kind:Yt(e.kind),connections:Yt(e.connections),vector:Yt(e.vector),total:Yt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Yt(e){return Math.round(e*1e3)/1e3}function mO(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(i=>r.indexOf(i)).filter(i=>i>=0).sort((i,s)=>i-s)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function hO(e,t){let r=t.map(gO),n=yO(t),o=_O(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:wO(e,r,n,o)}}function gO(e,t){let r=e.artifact,n={};return r.properties.source_path&&(n.path=r.properties.source_path),r.properties.source_session&&(n.session=r.properties.source_session),r.properties.source_agent&&(n.agent=r.properties.source_agent),r.properties.source_runner&&(n.runner=r.properties.source_runner),{ref:`B${t+1}`,rid:r.rid,id:r.properties.id,title:r.properties.title,kind:r.kind,score:e.score,score_breakdown:e.score_breakdown,excerpt:e.excerpt,source:Object.keys(n).length>0?n:void 0}}function yO(e){let t=e[0];if(!t)return"none";let r=Object.entries(t.score_breakdown).filter(([n,o])=>n!=="total"&&o>0).length;return t.score>=8||t.score>=5&&r>=2?"high":t.score>=3?"medium":"low"}function _O(e,t,r){if(t.length===0)return[`No Brain artifacts matched "${e}". Capture or ingest cited artifacts before relying on Brain for this answer.`];let n=[];return r==="low"&&n.push("Only low-scoring deterministic matches were found; open the cited artifacts before treating this as settled."),t.length===1&&n.push("Only one cited artifact matched; missing context or contradictions may not be visible yet."),t.every(o=>o.source==null)&&n.push("The matched artifacts do not carry source path, session, agent, or runner provenance."),n}function wO(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
73
+ `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${vO(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
74
+ `)}function vO(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(Ai);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function S_(e){return`artifact.hash.${e}`}function E_(e,t,r){return`connection.${e}.${r}.${t}`}function T_(){return`model-tier-bandit.v${1}`}function R_(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function bO(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function xO(e=process.cwd()){let t=await Jy(e);if(Yy(t))try{return{config:t,store:await Xy(t),project:N_(t.rootDir)}}catch(n){let o=xi(t.rootDir);if(await Bn(o.socketPath,50))throw n}let r=await Ni.open({uri:t.connectionString,autoLinker:Hy()});return{config:t,store:r,project:N_(t.rootDir)}}async function we(e,t=process.cwd()){let r=await xO(t);try{return await e(r)}finally{await r.store.close()}}function SO(e){return pt(e)}async function D_(e,t){if(e!=="SessionStart")return{};let r=await we(async({config:o,store:i})=>(await i.status(),o)),n=C_(r.rootDir,".red","brain","sessions");return await kO(n,{recursive:!0}),await $O(C_(n,"last-session.json"),SO({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()}),"utf8"),{}}var Ci=class{map({event:t,sourceAgent:r}){return{title:EO(t),content:TO(t),kind:"event",tags:RO(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:j_(t),metadata:PO(t)}}};function j_(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${Qu(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function EO(e){let t=[];e.platform&&t.push(e.platform),e.target&&t.push(e.target);let r=t.length>0?`[${t.join(":")}]`:"[channel-event]";if(e.message){let n=e.message.slice(0,60).replace(/\n/g," ");return`${r} ${n}`}return e.type?`${r} ${e.type}`:`${r} event`}function TO(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
75
+ `)||JSON.stringify(e.raw)}function RO(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function PO(e){let t={event_key:j_(e)};return e.id!=null&&(t.event_id=e.id),e.cursor!=null&&(t.cursor=e.cursor),e.timestamp!=null&&(t.timestamp=e.timestamp),e.platform!=null&&(t.platform=e.platform),e.target!=null&&(t.target=e.target),e.sessionKey!=null&&(t.session_key=e.sessionKey),e.type!=null&&(t.event_type=e.type),t}async function Di(e){let t=new Ci,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Xt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function q_(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Xt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Xt("brain_act requires a non-empty message");let o=t.connect??(a=>Gt.connect(a)),i=t.process??zO(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Xt(`brain_act could not reach the channel bridge: ${M_(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Xt(`brain_act could not send to "${r}": ${M_(c)}`,{cause:c})}if(!a.ok)throw new Xt(`brain_act could not send to "${r}": ${OO(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function zO(e=process.env){let t=e.RED_BRAIN_HERMES_COMMAND?.trim()||void 0,r=e.RED_BRAIN_HERMES_ARGS?.trim(),n=r?r.split(/\s+/).filter(Boolean):void 0;return{command:t,args:n}}function OO(e){return IO(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function IO(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let r=e;for(let n of t){let o=r[n];if(typeof o=="string"&&o.trim())return o}}function M_(e){return e instanceof Error?e.message:String(e)}import{createServer as AO}from"node:http";async function Z_(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),i=await e.eventKpis({interval:"day"}),s=await e.eventKpis({interval:"day",groupBy:"platform"}),a=await e.eventKpis({interval:"day",groupBy:"event_type"}),c=t.decisionLimit??8,l=t.connectionLimit??12;return{schema_version:"brain.dashboard.v1",generated_at:new Date(t.now??Date.now()).toISOString(),project:t.project,root:t.rootDir,stats:{artifacts:r.length,connections:n.length,decisions:r.filter(u=>u.kind==="decision").length,events:i.total,supports:nl(n,"supports"),contradicts:nl(n,"contradicts"),depends_on:nl(n,"depends_on")},kpis:{events_daily:i,events_by_platform:s,events_by_type:a},recent_decisions:r.filter(u=>u.kind==="decision").sort((u,d)=>d.properties.updated_at-u.properties.updated_at||d.rid-u.rid).slice(0,c).map(u=>NO(u,n)),recent_connections:n.filter(u=>o.has(u.from_rid)&&o.has(u.to_rid)).sort((u,d)=>d.properties.created_at-u.properties.created_at||d.rid-u.rid).slice(0,l).map(u=>CO(u,o)),attribution:{red_hermes:"Dashboard layout and command-center interaction model are adapted from the red-hermes web surface; NOTICE records the MIT attribution."}}}function U_(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:DO(e)}}async function F_(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=AO((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
76
+ `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function NO(e,t){let r=t.filter(n=>n.from_rid===e.rid||n.to_rid===e.rid);return{rid:e.rid,id:e.properties.id,title:e.properties.title,updated_at:new Date(e.properties.updated_at).toISOString(),tags:e.properties.tags,connection_counts:{supports:r.filter(n=>n.kind==="supports").length,contradicts:r.filter(n=>n.kind==="contradicts").length,depends_on:r.filter(n=>n.kind==="depends_on").length,related_to:r.filter(n=>n.kind==="related_to").length},excerpt:qO(e.properties.content)}}function CO(e,t){let r=t.get(e.from_rid),n=t.get(e.to_rid);if(!r||!n)throw new Error(`connection ${e.rid} references missing artifacts`);return{rid:e.rid,kind:e.kind,from:{rid:r.rid,title:r.properties.title},to:{rid:n.rid,title:n.properties.title},created_at:new Date(e.properties.created_at).toISOString(),reason:e.properties.reason??null}}function DO(e){return`<!doctype html>
77
77
  <html lang="en">
78
78
  <head>
79
79
  <meta charset="utf-8">
@@ -265,36 +265,36 @@ ${o}`),n.join(`
265
265
  <section>
266
266
  <h2>Event KPIs</h2>
267
267
  <div class="meta">Derived from kind:event artifacts through KpiQuery. No separate metrics store.</div>
268
- ${D_(e.kpis.events_by_platform,"Platform")}
269
- ${D_(e.kpis.events_by_type,"Event type")}
268
+ ${L_(e.kpis.events_by_platform,"Platform")}
269
+ ${L_(e.kpis.events_by_type,"Event type")}
270
270
  </section>
271
271
  <section>
272
272
  <h2>Recent Decisions</h2>
273
273
  <div class="feed">
274
- ${e.recent_decisions.length===0?j_("No decision artifacts captured yet."):e.recent_decisions.map(OO).join("")}
274
+ ${e.recent_decisions.length===0?B_("No decision artifacts captured yet."):e.recent_decisions.map(jO).join("")}
275
275
  </div>
276
276
  </section>
277
277
  </div>
278
278
  <section>
279
279
  <h2>Recent Connections</h2>
280
280
  <div class="feed">
281
- ${e.recent_connections.length===0?j_("No graph connections captured yet."):e.recent_connections.map(IO).join("")}
281
+ ${e.recent_connections.length===0?B_("No graph connections captured yet."):e.recent_connections.map(MO).join("")}
282
282
  </div>
283
283
  </section>
284
284
  </main>
285
285
  <footer class="meta">${se(e.attribution.red_hermes)}</footer>
286
- <script id="brain-dashboard-data" type="application/json">${NO(e)}</script>
286
+ <script id="brain-dashboard-data" type="application/json">${LO(e)}</script>
287
287
  </body>
288
- </html>`}function Cr(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function D_(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function OO(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
288
+ </html>`}function Cr(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function L_(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function jO(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
289
289
  <h3>${se(e.title)}</h3>
290
290
  <div class="meta">#${e.rid} - ${se(e.updated_at)} - supports ${t.supports}, contradicts ${t.contradicts}, depends_on ${t.depends_on}, related_to ${t.related_to}</div>
291
291
  <p class="meta">${se(e.excerpt)}</p>
292
292
  ${r}
293
- </article>`}function IO(e){return`<article class="item">
293
+ </article>`}function MO(e){return`<article class="item">
294
294
  <h3><span class="edge ${se(e.kind)}">${se(e.kind)}</span> ${se(e.from.title)} -> ${se(e.to.title)}</h3>
295
295
  <div class="meta">#${e.rid} - ${se(e.created_at)}${e.reason?` - ${se(e.reason)}`:""}</div>
296
- </article>`}function j_(e){return`<div class="empty">${se(e)}</div>`}function rl(e,t){return e.filter(r=>r.kind===t).length}function AO(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function NO(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as jO,readFile as MO,writeFile as qO}from"node:fs/promises";import{dirname as LO}from"node:path";function B_(e){return mt(e,{keyedMapCollapse:!0})}var CO=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],DO=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.json",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.json",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.json",kind:"toon"}],IB=[...CO,...DO];async function Z_(e){let t=await Di({bridge:e.bridge,store:e.store,afterCursor:e.state.cursor,sessionKey:e.sessionKey,limit:e.limit,sourceAgent:e.sourceAgent}),r={cursor:t.nextCursor??e.state.cursor,lastRunAt:new Date().toISOString()};return{polled:t.polled,captured:t.captured,skipped:t.skipped,state:r}}async function U_(e){try{let r=(await MO(e,"utf8")).trim();if(!r)return{};try{return JSON.parse(r)}catch{return pt(r)}}catch(t){if(t.code==="ENOENT")return{};throw t}}async function F_(e,t){await jO(LO(e),{recursive:!0}),await qO(e,`${B_(t)}
297
- `,"utf8")}async function VO(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":aI();return;case"init":await we(async({config:r,store:n})=>{let o=await n.status();$e({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await we(async({config:r,store:n})=>{$e({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await HO(t);return;case"search":await WO(t);return;case"think":case"query":await GO(t);return;case"get":await JO(t);return;case"link":await QO(t);return;case"backlinks":await YO(t);return;case"act":await nI(t);return;case"hook":await oI(t);return;case"ingest-events":await eI(t);return;case"schedule-ingest":await XO(t);return;case"kpi":case"kpis":await tI(t);return;case"dashboard":await rI(t);return;case"outcome-event":await KO(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function KO(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=Qe(r),o=await sI(),i=JSON.parse(o);if(!Wn(i))throw new Error("invalid brain outcome event");await we(async({store:s})=>{$e(await s.appendOutcomeEvent(i))},M(n,"root")??process.cwd())}async function HO(e){let t=Qe(e),r=(M(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=M(t,"content")??(M(t,"file")?await BO(String(M(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await we(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:M(t,"kind")??"note",tags:iI(t,"tag"),sourceAgent:M(t,"agent"),sourceRunner:M(t,"runner"),sourceSession:M(t,"session"),sourcePath:process.cwd()});$e(i)})}async function WO(e){let t=Qe(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=Gn(t,"limit")??10;await we(async({store:o})=>$e(await o.search(r,n)))}async function GO(e){let t=Qe(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=Gn(t,"limit")??8;await we(async({store:o})=>{let i=await o.think(r,n);t.json===!0?$e(i):console.log(i.answer)})}async function JO(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await we(async({store:r})=>{let n=await r.getArtifact(ji(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);$e(n)})}async function QO(e){let t=Qe(e),r=M(t,"from"),n=M(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await we(async({store:o})=>{$e(await o.link({from:ji(r),to:ji(n),kind:M(t,"kind")??"related_to",reason:M(t,"reason")}))})}async function YO(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await we(async({store:r})=>$e(await r.backlinks(ji(t))))}async function XO(e){let t=Qe(e),r=M(t,"session-key")??M(t,"session"),n=Gn(t,"limit"),o=await Gt.connect();try{await we(async({config:i,store:s})=>{let a=M(t,"state")??V_(i.rootDir,".red","brain","ingestion-state.json"),c=await U_(a),l=await Z_({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await F_(a,l.state),$e(l)})}finally{await o.close().catch(()=>{})}}async function eI(e){let t=Qe(e),r=M(t,"after-cursor")??M(t,"cursor"),n=M(t,"session-key")??M(t,"session"),o=Gn(t,"limit"),i=await Gt.connect();try{await we(async({store:s})=>{let a=await Di({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});$e(a)})}finally{await i.close().catch(()=>{})}}async function tI(e){let t=Qe(e),r=M(t,"interval"),n=M(t,"group-by"),o=M(t,"time-field");await we(async({store:i})=>{$e(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:M(t,"from"),to:M(t,"to"),platform:M(t,"platform"),eventType:M(t,"event-type"),target:M(t,"target")}))})}async function rI(e){let t=Qe(e),r=await we(async({config:o,store:i,project:s})=>{let a=await M_(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:q_(a),defaultOut:V_(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){$e(r.dashboard);return}if(t.serve===!0){let o=M(t,"host")??"127.0.0.1",i=Gn(t,"port")??4738,s=await L_(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=M(t,"out")??r.defaultOut;await ZO(FO(n),{recursive:!0}),await UO(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function nI(e){let t=Qe(e),r=M(t,"target")??t._[0],n=M(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");$e(await C_({target:r,message:n}))}async function oI(e){let[t="SessionStart",...r]=e,n=Qe(r),o=M(n,"runner")??"unknown";$e(await I_(t,o))}function ji(e){return/^\d+$/.test(e)?Number(e):e}function Qe(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function M(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function iI(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function Gn(e,t){let r=M(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function $e(e){console.log(JSON.stringify(e,null,2))}async function sI(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function aI(){console.log(`brain commands:
296
+ </article>`}function B_(e){return`<div class="empty">${se(e)}</div>`}function nl(e,t){return e.filter(r=>r.kind===t).length}function qO(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function LO(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as UO,readFile as FO,writeFile as VO}from"node:fs/promises";import{dirname as KO}from"node:path";function V_(e){return pt(e,{keyedMapCollapse:!0})}var BO=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],ZO=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.json",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.json",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.json",kind:"toon"}],FB=[...BO,...ZO];async function K_(e){let t=await Di({bridge:e.bridge,store:e.store,afterCursor:e.state.cursor,sessionKey:e.sessionKey,limit:e.limit,sourceAgent:e.sourceAgent}),r={cursor:t.nextCursor??e.state.cursor,lastRunAt:new Date().toISOString()};return{polled:t.polled,captured:t.captured,skipped:t.skipped,state:r}}async function H_(e){try{let r=(await FO(e,"utf8")).trim();if(!r)return{};try{return JSON.parse(r)}catch{return ft(r)}}catch(t){if(t.code==="ENOENT")return{};throw t}}async function W_(e,t){await UO(KO(e),{recursive:!0}),await VO(e,`${V_(t)}
297
+ `,"utf8")}async function QO(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":pI();return;case"init":await we(async({config:r,store:n})=>{let o=await n.status();$e({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await we(async({config:r,store:n})=>{$e({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await XO(t);return;case"search":await eI(t);return;case"think":case"query":await tI(t);return;case"get":await rI(t);return;case"link":await nI(t);return;case"backlinks":await oI(t);return;case"act":await uI(t);return;case"hook":await lI(t);return;case"ingest-events":await sI(t);return;case"schedule-ingest":await iI(t);return;case"kpi":case"kpis":await aI(t);return;case"dashboard":await cI(t);return;case"outcome-event":await YO(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function YO(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=Je(r),o=await fI(),i=JSON.parse(o);if(!Wn(i))throw new Error("invalid brain outcome event");await we(async({store:s})=>{$e(await s.appendOutcomeEvent(i))},M(n,"root")??process.cwd())}async function XO(e){let t=Je(e),r=(M(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=M(t,"content")??(M(t,"file")?await HO(String(M(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await we(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:M(t,"kind")??"note",tags:dI(t,"tag"),sourceAgent:M(t,"agent"),sourceRunner:M(t,"runner"),sourceSession:M(t,"session"),sourcePath:process.cwd()});$e(i)})}async function eI(e){let t=Je(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=Gn(t,"limit")??10;await we(async({store:o})=>$e(await o.search(r,n)))}async function tI(e){let t=Je(e),r=M(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=Gn(t,"limit")??8;await we(async({store:o})=>{let i=await o.think(r,n);t.json===!0?$e(i):console.log(i.answer)})}async function rI(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await we(async({store:r})=>{let n=await r.getArtifact(ji(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);$e(n)})}async function nI(e){let t=Je(e),r=M(t,"from"),n=M(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await we(async({store:o})=>{$e(await o.link({from:ji(r),to:ji(n),kind:M(t,"kind")??"related_to",reason:M(t,"reason")}))})}async function oI(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await we(async({store:r})=>$e(await r.backlinks(ji(t))))}async function iI(e){let t=Je(e),r=M(t,"session-key")??M(t,"session"),n=Gn(t,"limit"),o=await Gt.connect();try{await we(async({config:i,store:s})=>{let a=M(t,"state")??G_(i.rootDir,".red","brain","ingestion-state.json"),c=await H_(a),l=await K_({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await W_(a,l.state),$e(l)})}finally{await o.close().catch(()=>{})}}async function sI(e){let t=Je(e),r=M(t,"after-cursor")??M(t,"cursor"),n=M(t,"session-key")??M(t,"session"),o=Gn(t,"limit"),i=await Gt.connect();try{await we(async({store:s})=>{let a=await Di({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});$e(a)})}finally{await i.close().catch(()=>{})}}async function aI(e){let t=Je(e),r=M(t,"interval"),n=M(t,"group-by"),o=M(t,"time-field");await we(async({store:i})=>{$e(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:M(t,"from"),to:M(t,"to"),platform:M(t,"platform"),eventType:M(t,"event-type"),target:M(t,"target")}))})}async function cI(e){let t=Je(e),r=await we(async({config:o,store:i,project:s})=>{let a=await Z_(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:U_(a),defaultOut:G_(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){$e(r.dashboard);return}if(t.serve===!0){let o=M(t,"host")??"127.0.0.1",i=Gn(t,"port")??4738,s=await F_(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=M(t,"out")??r.defaultOut;await WO(JO(n),{recursive:!0}),await GO(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function uI(e){let t=Je(e),r=M(t,"target")??t._[0],n=M(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");$e(await q_({target:r,message:n}))}async function lI(e){let[t="SessionStart",...r]=e,n=Je(r),o=M(n,"runner")??"unknown";$e(await D_(t,o))}function ji(e){return/^\d+$/.test(e)?Number(e):e}function Je(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function M(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function dI(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function Gn(e,t){let r=M(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function $e(e){console.log(JSON.stringify(e,null,2))}async function fI(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function pI(){console.log(`brain commands:
298
298
  init
299
299
  status
300
300
  capture [text] --title <title> --kind <${Oi.join("|")}> --tag <tag>
@@ -309,4 +309,4 @@ ${o}`),n.join(`
309
309
  kpi [--interval hour|day|week|month] [--group-by platform|event_type|target] [--time-field event|ingested] [--from T] [--to T] [--platform P] [--event-type T] [--target T]
310
310
  dashboard [--out PATH] [--json] [--serve] [--host 127.0.0.1] [--port 4738]
311
311
  outcome-event record [--root PATH] < event.json
312
- `)}VO().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
312
+ `)}QO().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});