@aifight/aifight 0.1.0-alpha.2 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "module"; const require = createRequire(import.meta.url);
3
- var yp=Object.create;var $c=Object.defineProperty;var _p=Object.getOwnPropertyDescriptor;var wp=Object.getOwnPropertyNames;var vp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var Z=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Sp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wp(e))!bp.call(t,o)&&o!==n&&$c(t,o,{get:()=>e[o],enumerable:!(r=_p(e,o))||r.enumerable});return t};var Ae=(t,e,n)=>(n=t!=null?yp(vp(t)):{},Sp(e||!t||!t.__esModule?$c(n,"default",{value:t,enumerable:!0}):n,t));var ar=_(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var ir=class{};D._CodeOrName=ir;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ut=class extends ir{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=Ut;var xe=class extends ir{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Ut&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=xe;D.nil=new xe("");function Fc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)wi(n,e[r]),n.push(t[++r]);return new xe(n)}D._=Fc;var _i=new xe("+");function Bc(t,...e){let n=[sr(t[0])],r=0;for(;r<e.length;)n.push(_i),wi(n,e[r]),n.push(_i,sr(t[++r]));return Lp(n),new xe(n)}D.str=Bc;function wi(t,e){e instanceof xe?t.push(...e._items):e instanceof Ut?t.push(e):t.push(Fp(e))}D.addCodeArg=wi;function Lp(t){let e=1;for(;e<t.length-1;){if(t[e]===_i){let n=jp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function jp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ut||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ut))return`"${t}${e.slice(1)}`}function Dp(t,e){return e.emptyStr()?t:t.emptyStr()?e:Bc`${t}${e}`}D.strConcat=Dp;function Fp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:sr(Array.isArray(t)?t.join(","):t)}function Bp(t){return new xe(sr(t))}D.stringify=Bp;function sr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=sr;function qp(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new xe(`.${t}`):Fc`[${t}]`}D.getProperty=qp;function Up(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new xe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Up;function Hp(t){return new xe(t.toString())}D.regexpCode=Hp});var Si=_(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.ValueScope=we.ValueScopeName=we.Scope=we.varKinds=we.UsedValueState=void 0;var _e=ar(),vi=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},oo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(oo||(we.UsedValueState=oo={}));we.varKinds={const:new _e.Name("const"),let:new _e.Name("let"),var:new _e.Name("var")};var io=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof _e.Name?e:this.name(e)}name(e){return new _e.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};we.Scope=io;var so=class extends _e.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,_e._)`.${new _e.Name(n)}[${r}]`}};we.ValueScopeName=so;var Wp=(0,_e._)`\n`,bi=class extends io{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Wp:_e.nil}}get(){return this._scope}name(e){return new so(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:i,itemIndex:l}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,_e._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let i=_e.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,oo.Started);let u=n(l);if(u){let d=this.opts.es5?we.varKinds.var:we.varKinds.const;i=(0,_e._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,_e._)`${i}${u}${this.opts._n}`;else throw new vi(l);c.set(l,oo.Completed)})}return i}};we.ValueScope=bi});var A=_(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.or=C.and=C.not=C.CodeGen=C.operators=C.varKinds=C.ValueScopeName=C.ValueScope=C.Scope=C.Name=C.regexpCode=C.stringify=C.getProperty=C.nil=C.strConcat=C.str=C._=void 0;var N=ar(),je=Si(),St=ar();Object.defineProperty(C,"_",{enumerable:!0,get:function(){return St._}});Object.defineProperty(C,"str",{enumerable:!0,get:function(){return St.str}});Object.defineProperty(C,"strConcat",{enumerable:!0,get:function(){return St.strConcat}});Object.defineProperty(C,"nil",{enumerable:!0,get:function(){return St.nil}});Object.defineProperty(C,"getProperty",{enumerable:!0,get:function(){return St.getProperty}});Object.defineProperty(C,"stringify",{enumerable:!0,get:function(){return St.stringify}});Object.defineProperty(C,"regexpCode",{enumerable:!0,get:function(){return St.regexpCode}});Object.defineProperty(C,"Name",{enumerable:!0,get:function(){return St.Name}});var uo=Si();Object.defineProperty(C,"Scope",{enumerable:!0,get:function(){return uo.Scope}});Object.defineProperty(C,"ValueScope",{enumerable:!0,get:function(){return uo.ValueScope}});Object.defineProperty(C,"ValueScopeName",{enumerable:!0,get:function(){return uo.ValueScopeName}});Object.defineProperty(C,"varKinds",{enumerable:!0,get:function(){return uo.varKinds}});C.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var at=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Ei=class extends at{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?je.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=vn(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},ao=class extends at{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=vn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return lo(e,this.rhs)}},$i=class extends ao{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ki=class extends at{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ri=class extends at{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Pi=class extends at{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ti=class extends at{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=vn(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},cr=class extends at{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let i=r[o];i.optimizeNames(e,n)||(Vp(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Vt(e,n.names),{})}},ct=class extends cr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ai=class extends cr{},wn=class extends ct{};wn.kind="else";var Ht=class t extends ct{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new wn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(qc(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=vn(this.condition,e,n),this}get names(){let e=super.names;return lo(e,this.condition),this.else&&Vt(e,this.else.names),e}};Ht.kind="if";var Wt=class extends ct{};Wt.kind="for";var xi=class extends Wt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=vn(this.iteration,e,n),this}get names(){return Vt(super.names,this.iteration.names)}},Ci=class extends Wt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?je.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${n} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=lo(super.names,this.from);return lo(e,this.to)}},co=class extends Wt{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=vn(this.iterable,e,n),this}get names(){return Vt(super.names,this.iterable.names)}},lr=class extends ct{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};lr.kind="func";var ur=class extends cr{render(e){return"return "+super.render(e)}};ur.kind="return";var Ii=class extends ct{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Vt(e,this.catch.names),this.finally&&Vt(e,this.finally.names),e}},dr=class extends ct{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};dr.kind="catch";var fr=class extends ct{render(e){return"finally"+super.render(e)}};fr.kind="finally";var Oi=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
- `:""},this._extScope=e,this._scope=new je.Scope({parent:e}),this._nodes=[new Ai]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let i=this._scope.toName(n);return r!==void 0&&o&&(this._constants[i.str]=r),this._leafNode(new Ei(e,i,r)),i}const(e,n,r){return this._def(je.varKinds.const,e,n,r)}let(e,n,r){return this._def(je.varKinds.let,e,n,r)}var(e,n,r){return this._def(je.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ao(e,n,r))}add(e,n){return this._leafNode(new $i(e,C.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ti(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,o));return n.push("}"),new N._Code(n)}if(e,n,r){if(this._blockNode(new Ht(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ht(e))}else(){return this._elseNode(new wn)}endIf(){return this._endBlockNode(Ht,wn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new xi(e),n)}forRange(e,n,r,o,i=this.opts.es5?je.varKinds.var:je.varKinds.let){let s=this._scope.toName(e);return this._for(new Ci(i,s,n,r),()=>o(s))}forOf(e,n,r,o=je.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,a=>{this.var(i,(0,N._)`${s}[${a}]`),r(i)})}return this._for(new co("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?je.varKinds.var:je.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new co("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Wt)}label(e){return this._leafNode(new ki(e))}break(e){return this._leafNode(new Ri(e))}return(e){let n=new ur;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ur)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ii;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new dr(i),n(i)}return r&&(this._currNode=o.finally=new fr,this.code(r)),this._endBlockNode(dr,fr)}throw(e){return this._leafNode(new Pi(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,r,o){return this._blockNode(new lr(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(lr)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ht))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};C.CodeGen=Oi;function Vt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function lo(t,e){return e instanceof N._CodeOrName?Vt(t,e.names):t}function vn(t,e,n){if(t instanceof N.Name)return r(t);if(!o(t))return t;return new N._Code(t._items.reduce((i,s)=>(s instanceof N.Name&&(s=r(s)),s instanceof N._Code?i.push(...s._items):i.push(s),i),[]));function r(i){let s=n[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof N._Code&&i._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Vp(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function qc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${Ni(t)}`}C.not=qc;var Gp=Uc(C.operators.AND);function zp(...t){return t.reduce(Gp)}C.and=zp;var Kp=Uc(C.operators.OR);function Jp(...t){return t.reduce(Kp)}C.or=Jp;function Uc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${Ni(e)} ${t} ${Ni(n)}`}function Ni(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;var q=A(),Yp=ar();function Qp(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=Qp;function Xp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vc(t,e),!Gc(e,t.self.RULES.all))}I.alwaysValidSchema=Xp;function Vc(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let i in e)o[i]||Jc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Vc;function Gc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=Gc;function Zp(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}I.schemaHasRulesButRef=Zp;function eh({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,q._)`${n}`}return(0,q._)`${t}${e}${(0,q.getProperty)(r)}`}I.schemaRefOrVal=eh;function th(t){return zc(decodeURIComponent(t))}I.unescapeFragment=th;function nh(t){return encodeURIComponent(Li(t))}I.escapeFragment=nh;function Li(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=Li;function zc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=zc;function rh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=rh;function Hc({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof q.Name?(i instanceof q.Name?t(o,i,s):e(o,i,s),s):i instanceof q.Name?(e(o,s,i),i):n(i,s);return a===q.Name&&!(c instanceof q.Name)?r(o,c):c}}I.mergeEvaluated={props:Hc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,q._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,q._)`${n} || {}`).code((0,q._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,q._)`${n} || {}`),ji(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Kc}),items:Hc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,q._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,q._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Kc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&ji(t,n,e),n}I.evaluatedPropsToName=Kc;function ji(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=ji;var Wc={};function oh(t,e){return t.scopeValue("func",{ref:e,code:Wc[e.code]||(Wc[e.code]=new Yp._Code(e.code))})}I.useFunc=oh;var Mi;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Mi||(I.Type=Mi={}));function ih(t,e,n){if(t instanceof q.Name){let r=e===Mi.Num;return n?r?(0,q._)`"[" + ${t} + "]"`:(0,q._)`"['" + ${t} + "']"`:r?(0,q._)`"/" + ${t}`:(0,q._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,q.getProperty)(t).toString():"/"+Li(t)}I.getErrorPath=ih;function Jc(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Jc});var lt=_(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});var le=A(),sh={data:new le.Name("data"),valCxt:new le.Name("valCxt"),instancePath:new le.Name("instancePath"),parentData:new le.Name("parentData"),parentDataProperty:new le.Name("parentDataProperty"),rootData:new le.Name("rootData"),dynamicAnchors:new le.Name("dynamicAnchors"),vErrors:new le.Name("vErrors"),errors:new le.Name("errors"),this:new le.Name("this"),self:new le.Name("self"),scope:new le.Name("scope"),json:new le.Name("json"),jsonPos:new le.Name("jsonPos"),jsonLen:new le.Name("jsonLen"),jsonPart:new le.Name("jsonPart")};Di.default=sh});var mr=_(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.extendErrors=ue.resetErrorsCount=ue.reportExtraError=ue.reportError=ue.keyword$DataError=ue.keywordError=void 0;var L=A(),fo=M(),he=lt();ue.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function ah(t,e=ue.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=Xc(t,e,n);r??(s||a)?Yc(i,c):Qc(o,(0,L._)`[${c}]`)}ue.reportError=ah;function ch(t,e=ue.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=Xc(t,e,n);Yc(o,a),i||s||Qc(r,he.default.vErrors)}ue.reportExtraError=ch;function lh(t,e){t.assign(he.default.errors,e),t.if((0,L._)`${he.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${he.default.vErrors}.length`,e),()=>t.assign(he.default.vErrors,null)))}ue.resetErrorsCount=lh;function uh({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,he.default.errors,a=>{t.const(s,(0,L._)`${he.default.vErrors}[${a}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(he.default.instancePath,i.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,r))})}ue.extendErrors=uh;function Yc(t,e){let n=t.const("err",e);t.if((0,L._)`${he.default.vErrors} === null`,()=>t.assign(he.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${he.default.vErrors}.push(${n})`),t.code((0,L._)`${he.default.errors}++`)}function Qc(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${r}.errors`,e),n.return(!1))}var Gt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function Xc(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,L._)`{}`:dh(t,e,n)}function dh(t,e,n={}){let{gen:r,it:o}=t,i=[fh(o,n),mh(t,n)];return ph(t,e,i),r.object(...i)}function fh({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,fo.getErrorPath)(e,fo.Type.Str)}`:t;return[he.default.instancePath,(0,L.strConcat)(he.default.instancePath,n)]}function mh({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,L.str)`${e}/${t}`;return n&&(o=(0,L.str)`${o}${(0,fo.getErrorPath)(n,fo.Type.Str)}`),[Gt.schemaPath,o]}function ph(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;r.push([Gt.keyword,o],[Gt.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),c.messages&&r.push([Gt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Gt.schema,s],[Gt.parentSchema,(0,L._)`${u}${d}`],[he.default.data,i]),l&&r.push([Gt.propertyName,l])}});var el=_(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.boolOrEmptySchema=bn.topBoolOrEmptySchema=void 0;var hh=mr(),gh=A(),yh=lt(),_h={message:"boolean schema is false"};function wh(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Zc(t,!1):typeof n=="object"&&n.$async===!0?e.return(yh.default.data):(e.assign((0,gh._)`${r}.errors`,null),e.return(!0))}bn.topBoolOrEmptySchema=wh;function vh(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Zc(t)):n.var(e,!0)}bn.boolOrEmptySchema=vh;function Zc(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,hh.reportError)(o,_h,void 0,e)}});var Fi=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.getRules=Sn.isJSONType=void 0;var bh=["string","number","integer","boolean","null","object","array"],Sh=new Set(bh);function Eh(t){return typeof t=="string"&&Sh.has(t)}Sn.isJSONType=Eh;function $h(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Sn.getRules=$h});var Bi=_(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.shouldUseRule=Et.shouldUseGroup=Et.schemaHasRulesForType=void 0;function kh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&tl(t,r)}Et.schemaHasRulesForType=kh;function tl(t,e){return e.rules.some(n=>nl(t,n))}Et.shouldUseGroup=tl;function nl(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Et.shouldUseRule=nl});var pr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.reportTypeError=de.checkDataTypes=de.checkDataType=de.coerceAndCheckDataType=de.getJSONTypes=de.getSchemaTypes=de.DataType=void 0;var Rh=Fi(),Ph=Bi(),Th=mr(),T=A(),rl=M(),En;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(En||(de.DataType=En={}));function Ah(t){let e=ol(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}de.getSchemaTypes=Ah;function ol(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Rh.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}de.getJSONTypes=ol;function xh(t,e){let{gen:n,data:r,opts:o}=t,i=Ch(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Ph.schemaHasRulesForType)(t,e[0]));if(s){let a=Ui(e,r,o.strictNumbers,En.Wrong);n.if(a,()=>{i.length?Ih(t,e,i):Hi(t)})}return s}de.coerceAndCheckDataType=xh;var il=new Set(["string","number","integer","boolean","null"]);function Ch(t,e){return e?t.filter(n=>il.has(n)||e==="array"&&n==="array"):[]}function Ih(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,T._)`typeof ${o}`),a=r.let("coerced",(0,T._)`undefined`);i.coerceTypes==="array"&&r.if((0,T._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,T._)`${o}[0]`).assign(s,(0,T._)`typeof ${o}`).if(Ui(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,T._)`${a} !== undefined`);for(let l of n)(il.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),Hi(t),r.endIf(),r.if((0,T._)`${a} !== undefined`,()=>{r.assign(o,a),Oh(t,a)});function c(l){switch(l){case"string":r.elseIf((0,T._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,T._)`"" + ${o}`).elseIf((0,T._)`${o} === null`).assign(a,(0,T._)`""`);return;case"number":r.elseIf((0,T._)`${s} == "boolean" || ${o} === null
3
+ var _p=Object.create;var $c=Object.defineProperty;var wp=Object.getOwnPropertyDescriptor;var vp=Object.getOwnPropertyNames;var bp=Object.getPrototypeOf,Sp=Object.prototype.hasOwnProperty;var Z=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ep=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vp(e))!Sp.call(t,o)&&o!==n&&$c(t,o,{get:()=>e[o],enumerable:!(r=wp(e,o))||r.enumerable});return t};var Ce=(t,e,n)=>(n=t!=null?_p(bp(t)):{},Ep(e||!t||!t.__esModule?$c(n,"default",{value:t,enumerable:!0}):n,t));var cr=_(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var sr=class{};D._CodeOrName=sr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ut=class extends sr{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=Ut;var xe=class extends sr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Ut&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=xe;D.nil=new xe("");function Bc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)vi(n,e[r]),n.push(t[++r]);return new xe(n)}D._=Bc;var wi=new xe("+");function qc(t,...e){let n=[ar(t[0])],r=0;for(;r<e.length;)n.push(wi),vi(n,e[r]),n.push(wi,ar(t[++r]));return jp(n),new xe(n)}D.str=qc;function vi(t,e){e instanceof xe?t.push(...e._items):e instanceof Ut?t.push(e):t.push(Bp(e))}D.addCodeArg=vi;function jp(t){let e=1;for(;e<t.length-1;){if(t[e]===wi){let n=Dp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Dp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ut||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ut))return`"${t}${e.slice(1)}`}function Fp(t,e){return e.emptyStr()?t:t.emptyStr()?e:qc`${t}${e}`}D.strConcat=Fp;function Bp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ar(Array.isArray(t)?t.join(","):t)}function qp(t){return new xe(ar(t))}D.stringify=qp;function ar(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=ar;function Up(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new xe(`.${t}`):Bc`[${t}]`}D.getProperty=Up;function Hp(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new xe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Hp;function Gp(t){return new xe(t.toString())}D.regexpCode=Gp});var Ei=_(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.ValueScope=we.ValueScopeName=we.Scope=we.varKinds=we.UsedValueState=void 0;var _e=cr(),bi=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},oo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(oo||(we.UsedValueState=oo={}));we.varKinds={const:new _e.Name("const"),let:new _e.Name("let"),var:new _e.Name("var")};var io=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof _e.Name?e:this.name(e)}name(e){return new _e.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};we.Scope=io;var so=class extends _e.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,_e._)`.${new _e.Name(n)}[${r}]`}};we.ValueScopeName=so;var Wp=(0,_e._)`\n`,Si=class extends io{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Wp:_e.nil}}get(){return this._scope}name(e){return new so(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:i,itemIndex:l}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,_e._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let i=_e.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,oo.Started);let u=n(l);if(u){let d=this.opts.es5?we.varKinds.var:we.varKinds.const;i=(0,_e._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,_e._)`${i}${u}${this.opts._n}`;else throw new bi(l);c.set(l,oo.Completed)})}return i}};we.ValueScope=Si});var A=_(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.or=x.and=x.not=x.CodeGen=x.operators=x.varKinds=x.ValueScopeName=x.ValueScope=x.Scope=x.Name=x.regexpCode=x.stringify=x.getProperty=x.nil=x.strConcat=x.str=x._=void 0;var N=cr(),je=Ei(),St=cr();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return St._}});Object.defineProperty(x,"str",{enumerable:!0,get:function(){return St.str}});Object.defineProperty(x,"strConcat",{enumerable:!0,get:function(){return St.strConcat}});Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return St.nil}});Object.defineProperty(x,"getProperty",{enumerable:!0,get:function(){return St.getProperty}});Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return St.stringify}});Object.defineProperty(x,"regexpCode",{enumerable:!0,get:function(){return St.regexpCode}});Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return St.Name}});var uo=Ei();Object.defineProperty(x,"Scope",{enumerable:!0,get:function(){return uo.Scope}});Object.defineProperty(x,"ValueScope",{enumerable:!0,get:function(){return uo.ValueScope}});Object.defineProperty(x,"ValueScopeName",{enumerable:!0,get:function(){return uo.ValueScopeName}});Object.defineProperty(x,"varKinds",{enumerable:!0,get:function(){return uo.varKinds}});x.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var ct=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},ki=class extends ct{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?je.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=bn(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},ao=class extends ct{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=bn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return lo(e,this.rhs)}},$i=class extends ao{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ri=class extends ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Pi=class extends ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ti=class extends ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ai=class extends ct{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=bn(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},lr=class extends ct{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let i=r[o];i.optimizeNames(e,n)||(Vp(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Wt(e,n.names),{})}},lt=class extends lr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ci=class extends lr{},vn=class extends lt{};vn.kind="else";var Ht=class t extends lt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new vn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Uc(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=bn(this.condition,e,n),this}get names(){let e=super.names;return lo(e,this.condition),this.else&&Wt(e,this.else.names),e}};Ht.kind="if";var Gt=class extends lt{};Gt.kind="for";var xi=class extends Gt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=bn(this.iteration,e,n),this}get names(){return Wt(super.names,this.iteration.names)}},Ii=class extends Gt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?je.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${n} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=lo(super.names,this.from);return lo(e,this.to)}},co=class extends Gt{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=bn(this.iterable,e,n),this}get names(){return Wt(super.names,this.iterable.names)}},ur=class extends lt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ur.kind="func";var dr=class extends lr{render(e){return"return "+super.render(e)}};dr.kind="return";var Oi=class extends lt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Wt(e,this.catch.names),this.finally&&Wt(e,this.finally.names),e}},fr=class extends lt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fr.kind="catch";var mr=class extends lt{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Ni=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
+ `:""},this._extScope=e,this._scope=new je.Scope({parent:e}),this._nodes=[new Ci]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let i=this._scope.toName(n);return r!==void 0&&o&&(this._constants[i.str]=r),this._leafNode(new ki(e,i,r)),i}const(e,n,r){return this._def(je.varKinds.const,e,n,r)}let(e,n,r){return this._def(je.varKinds.let,e,n,r)}var(e,n,r){return this._def(je.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ao(e,n,r))}add(e,n){return this._leafNode(new $i(e,x.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ai(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,o));return n.push("}"),new N._Code(n)}if(e,n,r){if(this._blockNode(new Ht(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ht(e))}else(){return this._elseNode(new vn)}endIf(){return this._endBlockNode(Ht,vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new xi(e),n)}forRange(e,n,r,o,i=this.opts.es5?je.varKinds.var:je.varKinds.let){let s=this._scope.toName(e);return this._for(new Ii(i,s,n,r),()=>o(s))}forOf(e,n,r,o=je.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,a=>{this.var(i,(0,N._)`${s}[${a}]`),r(i)})}return this._for(new co("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?je.varKinds.var:je.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new co("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Gt)}label(e){return this._leafNode(new Ri(e))}break(e){return this._leafNode(new Pi(e))}return(e){let n=new dr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Oi;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new fr(i),n(i)}return r&&(this._currNode=o.finally=new mr,this.code(r)),this._endBlockNode(fr,mr)}throw(e){return this._leafNode(new Ti(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,r,o){return this._blockNode(new ur(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ur)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ht))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};x.CodeGen=Ni;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function lo(t,e){return e instanceof N._CodeOrName?Wt(t,e.names):t}function bn(t,e,n){if(t instanceof N.Name)return r(t);if(!o(t))return t;return new N._Code(t._items.reduce((i,s)=>(s instanceof N.Name&&(s=r(s)),s instanceof N._Code?i.push(...s._items):i.push(s),i),[]));function r(i){let s=n[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof N._Code&&i._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Vp(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Uc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${Mi(t)}`}x.not=Uc;var zp=Hc(x.operators.AND);function Kp(...t){return t.reduce(zp)}x.and=Kp;var Jp=Hc(x.operators.OR);function Yp(...t){return t.reduce(Jp)}x.or=Yp;function Hc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${Mi(e)} ${t} ${Mi(n)}`}function Mi(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;var q=A(),Qp=cr();function Xp(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=Xp;function Zp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vc(t,e),!zc(e,t.self.RULES.all))}I.alwaysValidSchema=Zp;function Vc(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let i in e)o[i]||Yc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Vc;function zc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=zc;function eh(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}I.schemaHasRulesButRef=eh;function th({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,q._)`${n}`}return(0,q._)`${t}${e}${(0,q.getProperty)(r)}`}I.schemaRefOrVal=th;function nh(t){return Kc(decodeURIComponent(t))}I.unescapeFragment=nh;function rh(t){return encodeURIComponent(ji(t))}I.escapeFragment=rh;function ji(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=ji;function Kc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Kc;function oh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=oh;function Gc({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof q.Name?(i instanceof q.Name?t(o,i,s):e(o,i,s),s):i instanceof q.Name?(e(o,s,i),i):n(i,s);return a===q.Name&&!(c instanceof q.Name)?r(o,c):c}}I.mergeEvaluated={props:Gc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,q._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,q._)`${n} || {}`).code((0,q._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,q._)`${n} || {}`),Di(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Jc}),items:Gc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,q._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,q._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Jc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Di(t,n,e),n}I.evaluatedPropsToName=Jc;function Di(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Di;var Wc={};function ih(t,e){return t.scopeValue("func",{ref:e,code:Wc[e.code]||(Wc[e.code]=new Qp._Code(e.code))})}I.useFunc=ih;var Li;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Li||(I.Type=Li={}));function sh(t,e,n){if(t instanceof q.Name){let r=e===Li.Num;return n?r?(0,q._)`"[" + ${t} + "]"`:(0,q._)`"['" + ${t} + "']"`:r?(0,q._)`"/" + ${t}`:(0,q._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,q.getProperty)(t).toString():"/"+ji(t)}I.getErrorPath=sh;function Yc(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Yc});var ut=_(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var le=A(),ah={data:new le.Name("data"),valCxt:new le.Name("valCxt"),instancePath:new le.Name("instancePath"),parentData:new le.Name("parentData"),parentDataProperty:new le.Name("parentDataProperty"),rootData:new le.Name("rootData"),dynamicAnchors:new le.Name("dynamicAnchors"),vErrors:new le.Name("vErrors"),errors:new le.Name("errors"),this:new le.Name("this"),self:new le.Name("self"),scope:new le.Name("scope"),json:new le.Name("json"),jsonPos:new le.Name("jsonPos"),jsonLen:new le.Name("jsonLen"),jsonPart:new le.Name("jsonPart")};Fi.default=ah});var pr=_(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.extendErrors=ue.resetErrorsCount=ue.reportExtraError=ue.reportError=ue.keyword$DataError=ue.keywordError=void 0;var L=A(),fo=M(),he=ut();ue.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function ch(t,e=ue.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=Zc(t,e,n);r??(s||a)?Qc(i,c):Xc(o,(0,L._)`[${c}]`)}ue.reportError=ch;function lh(t,e=ue.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=Zc(t,e,n);Qc(o,a),i||s||Xc(r,he.default.vErrors)}ue.reportExtraError=lh;function uh(t,e){t.assign(he.default.errors,e),t.if((0,L._)`${he.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${he.default.vErrors}.length`,e),()=>t.assign(he.default.vErrors,null)))}ue.resetErrorsCount=uh;function dh({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,he.default.errors,a=>{t.const(s,(0,L._)`${he.default.vErrors}[${a}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(he.default.instancePath,i.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,r))})}ue.extendErrors=dh;function Qc(t,e){let n=t.const("err",e);t.if((0,L._)`${he.default.vErrors} === null`,()=>t.assign(he.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${he.default.vErrors}.push(${n})`),t.code((0,L._)`${he.default.errors}++`)}function Xc(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${r}.errors`,e),n.return(!1))}var Vt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function Zc(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,L._)`{}`:fh(t,e,n)}function fh(t,e,n={}){let{gen:r,it:o}=t,i=[mh(o,n),ph(t,n)];return hh(t,e,i),r.object(...i)}function mh({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,fo.getErrorPath)(e,fo.Type.Str)}`:t;return[he.default.instancePath,(0,L.strConcat)(he.default.instancePath,n)]}function ph({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,L.str)`${e}/${t}`;return n&&(o=(0,L.str)`${o}${(0,fo.getErrorPath)(n,fo.Type.Str)}`),[Vt.schemaPath,o]}function hh(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;r.push([Vt.keyword,o],[Vt.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),c.messages&&r.push([Vt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Vt.schema,s],[Vt.parentSchema,(0,L._)`${u}${d}`],[he.default.data,i]),l&&r.push([Vt.propertyName,l])}});var tl=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.boolOrEmptySchema=Sn.topBoolOrEmptySchema=void 0;var gh=pr(),yh=A(),_h=ut(),wh={message:"boolean schema is false"};function vh(t){let{gen:e,schema:n,validateName:r}=t;n===!1?el(t,!1):typeof n=="object"&&n.$async===!0?e.return(_h.default.data):(e.assign((0,yh._)`${r}.errors`,null),e.return(!0))}Sn.topBoolOrEmptySchema=vh;function bh(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),el(t)):n.var(e,!0)}Sn.boolOrEmptySchema=bh;function el(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,gh.reportError)(o,wh,void 0,e)}});var Bi=_(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var Sh=["string","number","integer","boolean","null","object","array"],Eh=new Set(Sh);function kh(t){return typeof t=="string"&&Eh.has(t)}En.isJSONType=kh;function $h(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}En.getRules=$h});var qi=_(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.shouldUseRule=Et.shouldUseGroup=Et.schemaHasRulesForType=void 0;function Rh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&nl(t,r)}Et.schemaHasRulesForType=Rh;function nl(t,e){return e.rules.some(n=>rl(t,n))}Et.shouldUseGroup=nl;function rl(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Et.shouldUseRule=rl});var hr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.reportTypeError=de.checkDataTypes=de.checkDataType=de.coerceAndCheckDataType=de.getJSONTypes=de.getSchemaTypes=de.DataType=void 0;var Ph=Bi(),Th=qi(),Ah=pr(),T=A(),ol=M(),kn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(kn||(de.DataType=kn={}));function Ch(t){let e=il(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}de.getSchemaTypes=Ch;function il(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ph.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}de.getJSONTypes=il;function xh(t,e){let{gen:n,data:r,opts:o}=t,i=Ih(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Th.schemaHasRulesForType)(t,e[0]));if(s){let a=Hi(e,r,o.strictNumbers,kn.Wrong);n.if(a,()=>{i.length?Oh(t,e,i):Gi(t)})}return s}de.coerceAndCheckDataType=xh;var sl=new Set(["string","number","integer","boolean","null"]);function Ih(t,e){return e?t.filter(n=>sl.has(n)||e==="array"&&n==="array"):[]}function Oh(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,T._)`typeof ${o}`),a=r.let("coerced",(0,T._)`undefined`);i.coerceTypes==="array"&&r.if((0,T._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,T._)`${o}[0]`).assign(s,(0,T._)`typeof ${o}`).if(Hi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,T._)`${a} !== undefined`);for(let l of n)(sl.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),Gi(t),r.endIf(),r.if((0,T._)`${a} !== undefined`,()=>{r.assign(o,a),Nh(t,a)});function c(l){switch(l){case"string":r.elseIf((0,T._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,T._)`"" + ${o}`).elseIf((0,T._)`${o} === null`).assign(a,(0,T._)`""`);return;case"number":r.elseIf((0,T._)`${s} == "boolean" || ${o} === null
5
5
  || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,T._)`+${o}`);return;case"integer":r.elseIf((0,T._)`${s} === "boolean" || ${o} === null
6
6
  || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,T._)`+${o}`);return;case"boolean":r.elseIf((0,T._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,T._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,T._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,T._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,T._)`[${o}]`)}}}function Oh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,T._)`${e} !== undefined`,()=>t.assign((0,T._)`${e}[${n}]`,r))}function qi(t,e,n,r=En.Correct){let o=r===En.Correct?T.operators.EQ:T.operators.NEQ,i;switch(t){case"null":return(0,T._)`${e} ${o} null`;case"array":i=(0,T._)`Array.isArray(${e})`;break;case"object":i=(0,T._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,T._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,T._)`typeof ${e} ${o} ${t}`}return r===En.Correct?i:(0,T.not)(i);function s(a=T.nil){return(0,T.and)((0,T._)`typeof ${e} == "number"`,a,n?(0,T._)`isFinite(${e})`:T.nil)}}de.checkDataType=qi;function Ui(t,e,n,r){if(t.length===1)return qi(t[0],e,n,r);let o,i=(0,rl.toHash)(t);if(i.array&&i.object){let s=(0,T._)`typeof ${e} != "object"`;o=i.null?s:(0,T._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=T.nil;i.number&&delete i.integer;for(let s in i)o=(0,T.and)(o,qi(s,e,n,r));return o}de.checkDataTypes=Ui;var Nh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,T._)`{type: ${t}}`:(0,T._)`{type: ${e}}`};function Hi(t){let e=Mh(t);(0,Th.reportError)(e,Nh)}de.reportTypeError=Hi;function Mh(t){let{gen:e,data:n,schema:r}=t,o=(0,rl.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var al=_(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.assignDefaults=void 0;var $n=A(),Lh=M();function jh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)sl(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>sl(t,i,o.default))}mo.assignDefaults=jh;function sl(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,$n._)`${i}${(0,$n.getProperty)(e)}`;if(o){(0,Lh.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,$n._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,$n._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,$n._)`${a} = ${(0,$n.stringify)(n)}`)}});var Ce=_(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var H=A(),Wi=M(),$t=lt(),Dh=M();function Fh(t,e){let{gen:n,data:r,it:o}=t;n.if(Gi(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,H._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Fh;function Bh({gen:t,data:e,it:{opts:n}},r,o){return(0,H.or)(...r.map(i=>(0,H.and)(Gi(t,e,i,n.ownProperties),(0,H._)`${o} = ${i}`)))}F.checkMissingProp=Bh;function qh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=qh;function cl(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,H._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=cl;function Vi(t,e,n){return(0,H._)`${cl(t)}.call(${e}, ${n})`}F.isOwnProperty=Vi;function Uh(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} !== undefined`;return r?(0,H._)`${o} && ${Vi(t,e,n)}`:o}F.propertyInData=Uh;function Gi(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} === undefined`;return r?(0,H.or)(o,(0,H.not)(Vi(t,e,n))):o}F.noPropertyInData=Gi;function ll(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ll;function Hh(t,e){return ll(e).filter(n=>!(0,Wi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Hh;function Wh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,H._)`${t}, ${e}, ${r}${o}`:e,d=[[$t.default.instancePath,(0,H.strConcat)($t.default.instancePath,i)],[$t.default.parentData,s.parentData],[$t.default.parentDataProperty,s.parentDataProperty],[$t.default.rootData,$t.default.rootData]];s.opts.dynamicRef&&d.push([$t.default.dynamicAnchors,$t.default.dynamicAnchors]);let h=(0,H._)`${u}, ${n.object(...d)}`;return c!==H.nil?(0,H._)`${a}.call(${c}, ${h})`:(0,H._)`${a}(${h})`}F.callValidateCode=Wh;var Vh=(0,H._)`new RegExp`;function Gh({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(n,r);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,H._)`${o.code==="new RegExp"?Vh:(0,Dh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=Gh;function zh(t){let{gen:e,data:n,keyword:r,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,H._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:Wi.Type.Num},i),e.if((0,H.not)(i),a)})}}F.validateArray=zh;function Kh(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Wi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,l)=>{let u=t.subschema({keyword:r,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,H._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,H.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Kh});var fl=_(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var ge=A(),zt=lt(),Jh=Ce(),Yh=mr();function Qh(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=dl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Je.macroKeywordCode=Qh;function Xh(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;eg(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=dl(r,o,l),d=r.let("valid");t.block$data(d,h),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function h(){if(e.errors===!1)m(),e.modifying&&ul(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&ul(t),g(()=>Zh(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ge._)`await `),v=>r.assign(d,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ge._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ge._)`${u}.errors`;return r.assign(y,null),m(ge.nil),y}function m(y=e.async?(0,ge._)`await `:ge.nil){let v=c.opts.passContext?zt.default.this:zt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ge._)`${y}${(0,Jh.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ge.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Je.funcKeywordCode=Xh;function ul(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function Zh(t,e){let{gen:n}=t;n.if((0,ge._)`Array.isArray(${e})`,()=>{n.assign(zt.default.vErrors,(0,ge._)`${zt.default.vErrors} === null ? ${e} : ${zt.default.vErrors}.concat(${e})`).assign(zt.default.errors,(0,ge._)`${zt.default.vErrors}.length`),(0,Yh.extendErrors)(t)},()=>t.error())}function eg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function dl(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function tg(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Je.validSchemaType=tg;function ng({schema:t,opts:e,self:n,errSchemaPath:r},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(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Je.validateKeywordUsage=ng});var pl=_(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.extendSubschemaMode=kt.extendSubschemaData=kt.getSubschema=void 0;var Ye=A(),ml=M();function rg(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}${(0,Ye.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ml.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}kt.getSubschema=rg;function og(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,h=a.let("data",(0,Ye._)`${e.data}${(0,Ye.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Ye.str)`${l}${(0,ml.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ye._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Ye.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}kt.extendSubschemaData=og;function ig(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:i}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=n}kt.extendSubschemaMode=ig});var zi=_((Ok,hl)=>{"use strict";hl.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,i;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[o]))return!1;for(o=r;o--!==0;){var s=i[o];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var yl=_((Nk,gl)=>{"use strict";var Rt=gl.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};po(e,r,o,t,"",t)};Rt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Rt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Rt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Rt.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 po(t,e,n,r,o,i,s,a,c,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,l);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in Rt.arrayKeywords)for(var h=0;h<d.length;h++)po(t,e,n,d[h],o+"/"+u+"/"+h,i,o,u,r,h)}else if(u in Rt.propsKeywords){if(d&&typeof d=="object")for(var p in d)po(t,e,n,d[p],o+"/"+u+"/"+sg(p),i,o,u,r,p)}else(u in Rt.keywords||t.allKeys&&!(u in Rt.skipKeywords))&&po(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function sg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var hr=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var ag=M(),cg=zi(),lg=yl(),ug=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function dg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ki(t):e?_l(t)<=e:!1}ve.inlineRef=dg;var fg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ki(t){for(let e in t){if(fg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ki)||typeof n=="object"&&Ki(n))return!0}return!1}function _l(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!ug.has(n)&&(typeof t[n]=="object"&&(0,ag.eachItem)(t[n],r=>e+=_l(r)),e===1/0))return 1/0}return e}function wl(t,e="",n){n!==!1&&(e=kn(e));let r=t.parse(e);return vl(t,r)}ve.getFullPath=wl;function vl(t,e){return t.serialize(e).split("#")[0]+"#"}ve._getFullPath=vl;var mg=/#\/?$/;function kn(t){return t?t.replace(mg,""):""}ve.normalizeId=kn;function pg(t,e,n){return n=kn(n),t.resolve(e,n)}ve.resolveUrl=pg;var hg=/^[a-z_][-a-z0-9._]*$/i;function gg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=kn(t[n]||e),i={"":o},s=wl(r,o,!1),a={},c=new Set;return lg(t,{allKeys:!0},(d,h,p,f)=>{if(f===void 0)return;let m=s+h,g=i[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[h]=g;function y(S){let R=this.opts.uriResolver.resolve;if(S=kn(g?R(g,S):S),c.has(S))throw u(S);c.add(S);let k=this.refs[S];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?l(d,k.schema,S):S!==kn(m)&&(S[0]==="#"?(l(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!hg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,h,p){if(h!==void 0&&!cg(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ve.getSchemaRefs=gg});var _r=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getData=Pt.KeywordCxt=Pt.validateFunctionCode=void 0;var kl=el(),bl=pr(),Yi=Bi(),ho=pr(),yg=al(),yr=fl(),Ji=pl(),b=A(),P=lt(),_g=hr(),ut=M(),gr=mr();function wg(t){if(Tl(t)&&(Al(t),Pl(t))){Sg(t);return}Rl(t,()=>(0,kl.topBoolOrEmptySchema)(t))}Pt.validateFunctionCode=wg;function Rl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${P.default.data}, ${P.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${Sl(n,o)}`),bg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${vg(o)}`,r.$async,()=>t.code(Sl(n,o)).code(i))}function vg(t){return(0,b._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,b._)`, ${P.default.dynamicAnchors}={}`:b.nil}}={}`}function bg(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,b._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,b._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,b._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,b._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,b._)`""`),t.var(P.default.parentData,(0,b._)`undefined`),t.var(P.default.parentDataProperty,(0,b._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`{}`)})}function Sg(t){let{schema:e,opts:n,gen:r}=t;Rl(t,()=>{n.$comment&&e.$comment&&Cl(t),Pg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&Eg(t),xl(t),xg(t)})}function Eg(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,b._)`${n}.evaluated`),e.if((0,b._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,b._)`${t.evaluated}.props`,(0,b._)`undefined`)),e.if((0,b._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,b._)`${t.evaluated}.items`,(0,b._)`undefined`))}function Sl(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,b._)`/*# sourceURL=${n} */`:b.nil}function $g(t,e){if(Tl(t)&&(Al(t),Pl(t))){kg(t,e);return}(0,kl.boolOrEmptySchema)(t,e)}function Pl({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Tl(t){return typeof t.schema!="boolean"}function kg(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Cl(t),Tg(t),Ag(t);let i=r.const("_errs",P.default.errors);xl(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Al(t){(0,ut.checkUnknownRules)(t),Rg(t)}function xl(t,e){if(t.opts.jtd)return El(t,[],!1,e);let n=(0,bl.getSchemaTypes)(t.schema),r=(0,bl.coerceAndCheckDataType)(t,n);El(t,n,!r,e)}function Rg(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Pg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ut.checkStrictMode)(t,"default is ignored in the schema root")}function Tg(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,_g.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Ag(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cl({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${P.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,b.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,b._)`${P.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function xg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,b._)`new ${o}(${P.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,P.default.vErrors),i.unevaluated&&Cg(t),e.return((0,b._)`${P.default.errors} === 0`))}function Cg({gen:t,evaluated:e,props:n,items:r}){n instanceof b.Name&&t.assign((0,b._)`${e}.props`,n),r instanceof b.Name&&t.assign((0,b._)`${e}.items`,r)}function El(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(i,u))){o.block(()=>Ol(t,"$ref",u.all.$ref.definition));return}c.jtd||Ig(t,e),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Yi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,ho.checkDataType)(h.type,s,c.strictNumbers)),$l(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,ho.reportTypeError)(t)),o.endIf()):$l(t,h),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function $l(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,yg.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Yi.shouldUseRule)(r,i)&&Ol(t,i.keyword,i.definition,e.type)})}function Ig(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Og(t,e),t.opts.allowUnionTypes||Ng(t,e),Mg(t,t.dataTypes))}function Og(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Il(t.dataTypes,n)||Qi(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),jg(t,e)}}function Ng(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Qi(t,"use allowUnionTypes to allow union type keyword")}function Mg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Yi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Lg(e,s))&&Qi(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function Lg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Il(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function jg(t,e){let n=[];for(let r of t.dataTypes)Il(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Qi(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ut.checkStrictMode)(t,e,t.opts.strictTypes)}var go=class{constructor(e,n,r){if((0,yr.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ut.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Nl(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,yr.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,n,r){this.failResult((0,b.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,b.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,b._)`${n} !== undefined && (${(0,b.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?gr.reportExtraError:gr.reportError)(this,this.def.error,n)}$dataError(){(0,gr.reportError)(this,this.def.$dataError||gr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,gr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=b.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=b.nil,n=b.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,b.or)((0,b._)`${o} === undefined`,n)),e!==b.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==b.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,b.or)(s(),a());function s(){if(r.length){if(!(n instanceof b.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,b._)`${(0,ho.checkDataTypes)(c,n,i.opts.strictNumbers,ho.DataType.Wrong)}`}return b.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,b._)`!${c}(${n})`}return b.nil}}subschema(e,n){let r=(0,Ji.getSubschema)(this.it,e);(0,Ji.extendSubschemaData)(r,this.it,e),(0,Ji.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return $g(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ut.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ut.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,b.Name)),!0}};Pt.KeywordCxt=go;function Ol(t,e,n,r){let o=new go(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,yr.funcKeywordCode)(o,n):"macro"in n?(0,yr.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,yr.funcKeywordCode)(o,n)}var Dg=/^\/(?:[^~]|~0|~1)*$/,Fg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Nl(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Dg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=Fg.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return r[e-u]}if(u>e)throw new Error(c("data",u));if(i=n[e-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,b._)`${i}${(0,b.getProperty)((0,ut.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Pt.getData=Nl});var yo=_(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var Xi=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Zi.default=Xi});var wr=_(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var es=hr(),ts=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,es.resolveUrl)(e,n,r),this.missingSchema=(0,es.normalizeId)((0,es.getFullPath)(e,this.missingRef))}};ns.default=ts});var wo=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.resolveSchema=Ie.getCompilingSchema=Ie.resolveRef=Ie.compileSchema=Ie.SchemaEnv=void 0;var De=A(),Bg=yo(),Kt=lt(),Fe=hr(),Ml=M(),qg=_r(),Rn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Fe.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Ie.SchemaEnv=Rn;function os(t){let e=Ll.call(this,t);if(e)return e;let n=(0,Fe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new De.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:Bg.default,code:(0,De._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Kt.default.data,parentData:Kt.default.parentData,parentDataProperty:Kt.default.parentDataProperty,dataNames:[Kt.default.data],dataPathArr:[De.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,De.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:De.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,De._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,qg.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Kt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Kt.default.self}`,`${Kt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;p.evaluated={props:f instanceof De.Name?void 0:f,items:m instanceof De.Name?void 0:m,dynamicProps:f instanceof De.Name,dynamicItems:m instanceof De.Name},p.source&&(p.source.evaluated=(0,De.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Ie.compileSchema=os;function Ug(t,e,n){var r;n=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Vg.call(this,t,n);if(i===void 0){let s=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new Rn({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Hg.call(this,i)}Ie.resolveRef=Ug;function Hg(t){return(0,Fe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:os.call(this,t)}function Ll(t){for(let e of this._compilations)if(Wg(e,t))return e}Ie.getCompilingSchema=Ll;function Wg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Vg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||_o.call(this,t,e)}function _o(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Fe._getFullPath)(this.opts.uriResolver,n),o=(0,Fe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return rs.call(this,n,t);let i=(0,Fe.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=_o.call(this,t,s);return typeof a?.schema!="object"?void 0:rs.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||os.call(this,s),i===(0,Fe.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,l)),new Rn({schema:a,schemaId:c,root:t,baseId:o})}return rs.call(this,n,s)}}Ie.resolveSchema=_o;var Gg=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rs(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Ml.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!Gg.has(a)&&l&&(e=(0,Fe.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Ml.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=_o.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new Rn({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var jl=_((Bk,zg)=>{zg.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 ss=_((qk,ql)=>{"use strict";var Kg=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Fl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function is(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var Jg=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Dl(t){return t.length=0,!0}function Yg(t,e,n){if(t.length){let r=is(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Qg(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=Yg;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),r.push(":");continue}else if(l==="%"){if(!a(o,r,n))break;a=Dl}else{o.push(l);continue}}return o.length&&(a===Dl?n.zone=o.join(""):s?r.push(o.join("")):r.push(is(o))),n.address=r.join(""),n}function Bl(t){if(Xg(t,":")<2)return{host:t,isIPV6:!1};let e=Qg(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Xg(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function Zg(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function ey(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function ty(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Fl(n)){let r=Bl(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}ql.exports={nonSimpleDomain:Jg,recomposeAuthority:ty,normalizeComponentEncoding:ey,removeDotSegments:Zg,isIPv4:Fl,isUUID:Kg,normalizeIPv6:Bl,stringArrayToHexStripped:is}});var Gl=_((Uk,Vl)=>{"use strict";var{isUUID:ny}=ss(),ry=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,oy=["http","https","ws","wss","urn","urn:uuid"];function iy(t){return oy.indexOf(t)!==-1}function as(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Ul(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Hl(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function sy(t){return t.secure=as(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ay(t){if((t.port===(as(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function cy(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(ry);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,i=cs(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function ly(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,i=cs(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${r||e.nid}:${a}`,e.skipEscape=!0,s}function uy(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ny(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function dy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Wl={scheme:"http",domainHost:!0,parse:Ul,serialize:Hl},fy={scheme:"https",domainHost:Wl.domainHost,parse:Ul,serialize:Hl},vo={scheme:"ws",domainHost:!0,parse:sy,serialize:ay},my={scheme:"wss",domainHost:vo.domainHost,parse:vo.parse,serialize:vo.serialize},py={scheme:"urn",parse:cy,serialize:ly,skipNormalize:!0},hy={scheme:"urn:uuid",parse:uy,serialize:dy,skipNormalize:!0},bo={http:Wl,https:fy,ws:vo,wss:my,urn:py,"urn:uuid":hy};Object.setPrototypeOf(bo,null);function cs(t){return t&&(bo[t]||bo[t.toLowerCase()])||void 0}Vl.exports={wsIsSecure:as,SCHEMES:bo,isValidSchemeName:iy,getSchemeHandler:cs}});var Jl=_((Hk,Eo)=>{"use strict";var{normalizeIPv6:gy,removeDotSegments:vr,recomposeAuthority:yy,normalizeComponentEncoding:So,isIPv4:_y,nonSimpleDomain:wy}=ss(),{SCHEMES:vy,getSchemeHandler:zl}=Gl();function by(t,e){return typeof t=="string"?t=Qe(dt(t,e),e):typeof t=="object"&&(t=dt(Qe(t,e),e)),t}function Sy(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Kl(dt(t,r),dt(e,r),r,!0);return r.skipEscape=!0,Qe(o,r)}function Kl(t,e,n,r){let o={};return r||(t=dt(Qe(t,n),n),e=dt(Qe(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=vr(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=vr(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=vr(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=vr(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function Ey(t,e,n){return typeof t=="string"?(t=unescape(t),t=Qe(So(dt(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Qe(So(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Qe(So(dt(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Qe(So(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Qe(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],i=zl(r.scheme||n.scheme);i&&i.serialize&&i.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let s=yy(n);if(s!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(s),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!i||!i.absolutePath)&&(a=vr(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var $y=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function dt(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match($y);if(i){if(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]),r.host)if(_y(r.host)===!1){let c=gy(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let s=zl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&wy(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),s&&s.parse&&s.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var ls={SCHEMES:vy,normalize:by,resolve:Sy,resolveComponent:Kl,equal:Ey,serialize:Qe,parse:dt};Eo.exports=ls;Eo.exports.default=ls;Eo.exports.fastUri=ls});var Ql=_(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});var Yl=Jl();Yl.code='require("ajv/dist/runtime/uri").default';us.default=Yl});var iu=_(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var ky=_r();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return ky.KeywordCxt}});var Pn=A();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return Pn._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return Pn.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return Pn.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return Pn.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return Pn.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return Pn.CodeGen}});var Ry=yo(),nu=wr(),Py=Fi(),br=wo(),Ty=A(),Sr=hr(),$o=pr(),fs=M(),Xl=jl(),Ay=Ql(),ru=(t,e)=>new RegExp(t,e);ru.code="new RegExp";var xy=["removeAdditional","useDefaults","coerceTypes"],Cy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Iy={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."},Oy={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Zl=200;function Ny(t){var e,n,r,o,i,s,a,c,l,u,d,h,p,f,m,g,y,v,S,R,k,G,Q,oe,ze;let ot=t.strict,tr=(e=t.code)===null||e===void 0?void 0:e.optimize,Ke=tr===!0||tr===void 0?1:tr||0,te=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:ru,Bt=(o=t.uriResolver)!==null&&o!==void 0?o:Ay.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:ot)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ot)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:ot)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:ot)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:ot)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Ke,regExp:te}:{optimize:Ke,regExp:te},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Zl,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Zl,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(G=t.validateSchema)!==null&&G!==void 0?G:!0,validateFormats:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(oe=t.unicodeRegExp)!==null&&oe!==void 0?oe:!0,int32range:(ze=t.int32range)!==null&&ze!==void 0?ze:!0,uriResolver:Bt}}var Er=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Ny(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Ty.ValueScope({scope:{},prefixes:Cy,es5:n,lines:r}),this.logger=By(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Py.getRules)(),eu.call(this,Iy,e,"NOT SUPPORTED"),eu.call(this,Oy,e,"DEPRECATED","warn"),this._metaOpts=Dy.call(this),e.formats&&Ly.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&jy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),My.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=Xl;r==="id"&&(o={...Xl},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(u,d){await i.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||s.call(this,h)}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 nu.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,n)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return n=(0,Sr.normalizeId)(n||i),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let n;for(;typeof(n=tu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new br.SchemaEnv({schema:{},schemaId:r});if(n=br.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=tu.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Sr.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Uy.call(this,r,n),!n)return(0,fs.eachItem)(r,i=>ds.call(this,i)),this;Wy.call(this,n);let o={...n,type:(0,$o.getJSONTypes)(n.type),schemaType:(0,$o.getJSONTypes)(n.schemaType)};return(0,fs.eachItem)(r,o.type.length===0?i=>ds.call(this,i,o):i=>o.type.forEach(s=>ds.call(this,i,o,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(i=>i.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,i)=>o+n+i)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=ou(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,Sr.normalizeId)(s||r);let l=Sr.getSchemaRefs.call(this,e,r);return c=new br.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:l}),this._cache.set(c.schema,c),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):br.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{br.compileSchema.call(this,e)}finally{this.opts=n}}};Er.ValidationError=Ry.default;Er.MissingRefError=nu.default;ie.default=Er;function eu(t,e,n,r="error"){for(let o in t){let i=o;i in e&&this.logger[r](`${n}: option ${o}. ${t[i]}`)}}function tu(t){return t=(0,Sr.normalizeId)(t),this.schemas[t]||this.refs[t]}function My(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Ly(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function jy(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Dy(){let t={...this.opts};for(let e of xy)delete t[e];return t}var Fy={log(){},warn(){},error(){}};function By(t){if(t===!1)return Fy;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var qy=/^[a-z_$][a-z0-9_$:-]*$/i;function Uy(t,e){let{RULES:n}=this;if((0,fs.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!qy.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ds(t,e,n){var r;let o=e?.post;if(n&&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===n);if(s||(s={type:n,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,$o.getJSONTypes)(e.type),schemaType:(0,$o.getJSONTypes)(e.schemaType)}};e.before?Hy.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function Hy(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Wy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=ou(e)),t.validateSchema=this.compile(e,!0))}var Vy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ou(t){return{anyOf:[t,Vy]}}});var su=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var Gy={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ms.default=Gy});var uu=_(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.callRef=Jt.getValidate=void 0;var zy=wr(),au=Ce(),be=A(),Tn=lt(),cu=wo(),ko=M(),Ky={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=r,{root:l}=i;if((n==="#"||n==="#/")&&o===l.baseId)return d();let u=cu.resolveRef.call(c,l,o,n);if(u===void 0)throw new zy.default(r.opts.uriResolver,o,n);if(u instanceof cu.SchemaEnv)return h(u);return p(u);function d(){if(i===l)return Ro(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return Ro(t,(0,be._)`${f}.validate`,l,l.$async)}function h(f){let m=lu(t,f);Ro(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,be.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:be.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function lu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Jt.getValidate=lu;function Ro(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?Tn.default.this:be.nil;r?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,be._)`await ${(0,au.callValidateCode)(t,e,l)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,be._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,au.callValidateCode)(t,e,l),()=>p(e),()=>h(e))}function h(f){let m=(0,be._)`${f}.errors`;o.assign(Tn.default.vErrors,(0,be._)`${Tn.default.vErrors} === null ? ${m} : ${Tn.default.vErrors}.concat(${m})`),o.assign(Tn.default.errors,(0,be._)`${Tn.default.vErrors}.length`)}function p(f){var m;if(!i.opts.unevaluated)return;let g=(m=n?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=ko.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,be._)`${f}.evaluated.props`);i.props=ko.mergeEvaluated.props(o,y,i.props,be.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=ko.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,be._)`${f}.evaluated.items`);i.items=ko.mergeEvaluated.items(o,y,i.items,be.Name)}}}Jt.callRef=Ro;Jt.default=Ky});var du=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var Jy=su(),Yy=uu(),Qy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Jy.default,Yy.default];ps.default=Qy});var fu=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Po=A(),Tt=Po.operators,To={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}},Xy={message:({keyword:t,schemaCode:e})=>(0,Po.str)`must be ${To[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Po._)`{comparison: ${To[t].okStr}, limit: ${e}}`},Zy={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:Xy,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Po._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};hs.default=Zy});var mu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var $r=A(),e_={message:({schemaCode:t})=>(0,$r.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$r._)`{multipleOf: ${t}}`},t_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:e_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,$r._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,$r._)`${s} !== parseInt(${s})`;t.fail$data((0,$r._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};gs.default=t_});var hu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});function pu(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}ys.default=pu;pu.code='require("ajv/dist/runtime/ucs2length").default'});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var Yt=A(),n_=M(),r_=hu(),o_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Yt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Yt._)`{limit: ${t}}`},i_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:o_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Yt.operators.GT:Yt.operators.LT,s=o.opts.unicode===!1?(0,Yt._)`${n}.length`:(0,Yt._)`${(0,n_.useFunc)(t.gen,r_.default)}(${n})`;t.fail$data((0,Yt._)`${s} ${i} ${r}`)}};_s.default=i_});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var s_=Ce(),a_=M(),An=A(),c_={message:({schemaCode:t})=>(0,An.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,An._)`{pattern: ${t}}`},l_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:c_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,An._)`new RegExp`:(0,a_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,An._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,An._)`!${u}`)}else{let c=(0,s_.usePattern)(t,o);t.fail$data((0,An._)`!${c}.test(${n})`)}}};ws.default=l_});var _u=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var kr=A(),u_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,kr.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,kr._)`{limit: ${t}}`},d_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:u_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?kr.operators.GT:kr.operators.LT;t.fail$data((0,kr._)`Object.keys(${n}).length ${o} ${r}`)}};vs.default=d_});var wu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Rr=Ce(),Pr=A(),f_=M(),m_={message:({params:{missingProperty:t}})=>(0,Pr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Pr._)`{missingProperty: ${t}}`},p_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:m_,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&n.length===0)return;let c=n.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let m of n)if(p?.[m]===void 0&&!f.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,f_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(Pr.nil,d);else for(let p of n)(0,Rr.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||i){let f=e.let("valid",!0);t.block$data(f,()=>h(p,f)),t.ok(f)}else e.if((0,Rr.checkMissingProp)(t,n,p)),(0,Rr.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",r,p=>{t.setParams({missingProperty:p}),e.if((0,Rr.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function h(p,f){t.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(f,(0,Rr.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Pr.not)(f),()=>{t.error(),e.break()})},Pr.nil)}}};bs.default=p_});var vu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var Tr=A(),h_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Tr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Tr._)`{limit: ${t}}`},g_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:h_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Tr.operators.GT:Tr.operators.LT;t.fail$data((0,Tr._)`${n}.length ${o} ${r}`)}};Ss.default=g_});var Ao=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var bu=zi();bu.code='require("ajv/dist/runtime/equal").default';Es.default=bu});var Su=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var $s=pr(),se=A(),y_=M(),__=Ao(),w_={message:({params:{i:t,j:e}})=>(0,se.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,se._)`{i: ${t}, j: ${e}}`},v_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:w_,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),l=i.items?(0,$s.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,se._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,se._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,se._)`${f} > 1`,()=>(d()?h:p)(f,m))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function h(f,m){let g=e.name("item"),y=(0,$s.checkDataTypes)(l,g,a.opts.strictNumbers,$s.DataType.Wrong),v=e.const("indices",(0,se._)`{}`);e.for((0,se._)`;${f}--;`,()=>{e.let(g,(0,se._)`${n}[${f}]`),e.if(y,(0,se._)`continue`),l.length>1&&e.if((0,se._)`typeof ${g} == "string"`,(0,se._)`${g} += "_"`),e.if((0,se._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,se._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,se._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,y_.useFunc)(e,__.default),y=e.name("outer");e.label(y).for((0,se._)`;${f}--;`,()=>e.for((0,se._)`${m} = ${f}; ${m}--;`,()=>e.if((0,se._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};ks.default=v_});var Eu=_(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var Rs=A(),b_=M(),S_=Ao(),E_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Rs._)`{allowedValue: ${t}}`},$_={keyword:"const",$data:!0,error:E_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Rs._)`!${(0,b_.useFunc)(e,S_.default)}(${n}, ${o})`):t.fail((0,Rs._)`${i} !== ${n}`)}};Ps.default=$_});var $u=_(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var Ar=A(),k_=M(),R_=Ao(),P_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ar._)`{allowedValues: ${t}}`},T_={keyword:"enum",schemaType:"array",$data:!0,error:P_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,k_.useFunc)(e,R_.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,Ar.or)(...o.map((f,m)=>h(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,Ar._)`${l()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,Ar._)`${l()}(${n}, ${p}[${f}])`:(0,Ar._)`${n} === ${m}`}}};Ts.default=T_});var ku=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var A_=fu(),x_=mu(),C_=gu(),I_=yu(),O_=_u(),N_=wu(),M_=vu(),L_=Su(),j_=Eu(),D_=$u(),F_=[A_.default,x_.default,C_.default,I_.default,O_.default,N_.default,M_.default,L_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},j_.default,D_.default];As.default=F_});var Cs=_(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateAdditionalItems=void 0;var Qt=A(),xs=M(),B_={message:({params:{len:t}})=>(0,Qt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qt._)`{limit: ${t}}`},q_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:B_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,xs.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ru(t,r)}};function Ru(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Qt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Qt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,xs.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Qt._)`${a} <= ${e.length}`);n.if((0,Qt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:xs.Type.Num},l),s.allErrors||n.if((0,Qt.not)(l),()=>n.break())})}}xr.validateAdditionalItems=Ru;xr.default=q_});var Is=_(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.validateTuple=void 0;var Pu=A(),xo=M(),U_=Ce(),H_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Tu(t,"additionalItems",e);n.items=!0,!(0,xo.alwaysValidSchema)(n,e)&&t.ok((0,U_.validateArray)(t))}};function Tu(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=xo.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),l=r.const("len",(0,Pu._)`${i}.length`);n.forEach((d,h)=>{(0,xo.alwaysValidSchema)(a,d)||(r.if((0,Pu._)`${l} > ${h}`,()=>t.subschema({keyword:s,schemaProp:h,dataProp:h},c)),t.ok(c))});function u(d){let{opts:h,errSchemaPath:p}=a,f=n.length,m=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(h.strictTuples&&!m){let g=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,xo.checkStrictMode)(a,g,h.strictTuples)}}}Cr.validateTuple=Tu;Cr.default=H_});var Au=_(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var W_=Is(),V_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,W_.validateTuple)(t,"items")};Os.default=V_});var Cu=_(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var xu=A(),G_=M(),z_=Ce(),K_=Cs(),J_={message:({params:{len:t}})=>(0,xu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xu._)`{limit: ${t}}`},Y_={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:J_,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,G_.alwaysValidSchema)(r,e)&&(o?(0,K_.validateAdditionalItems)(t,o):t.ok((0,z_.validateArray)(t)))}};Ns.default=Y_});var Iu=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var Oe=A(),Co=M(),Q_={message:({params:{min:t,max:e}})=>e===void 0?(0,Oe.str)`must contain at least ${t} valid item(s)`:(0,Oe.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Oe._)`{minContains: ${t}}`:(0,Oe._)`{minContains: ${t}, maxContains: ${e}}`},X_={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Q_,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:l}=r;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Oe._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Co.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Co.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Co.alwaysValidSchema)(i,n)){let m=(0,Oe._)`${u} >= ${s}`;a!==void 0&&(m=(0,Oe._)`${m} && ${u} <= ${a}`),t.pass(m);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Oe._)`${o}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>f(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Co.Type.Num,compositeRule:!0},m),g()})}function f(m){e.code((0,Oe._)`${m}++`),a===void 0?e.if((0,Oe._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Oe._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Oe._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Ms.default=X_});var Mu=_(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateSchemaDeps=Xe.validatePropertyDeps=Xe.error=void 0;var Ls=A(),Z_=M(),Ir=Ce();Xe.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Ls.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Ls._)`{property: ${t},
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,T._)`[${o}]`)}}}function Nh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,T._)`${e} !== undefined`,()=>t.assign((0,T._)`${e}[${n}]`,r))}function Ui(t,e,n,r=kn.Correct){let o=r===kn.Correct?T.operators.EQ:T.operators.NEQ,i;switch(t){case"null":return(0,T._)`${e} ${o} null`;case"array":i=(0,T._)`Array.isArray(${e})`;break;case"object":i=(0,T._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,T._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,T._)`typeof ${e} ${o} ${t}`}return r===kn.Correct?i:(0,T.not)(i);function s(a=T.nil){return(0,T.and)((0,T._)`typeof ${e} == "number"`,a,n?(0,T._)`isFinite(${e})`:T.nil)}}de.checkDataType=Ui;function Hi(t,e,n,r){if(t.length===1)return Ui(t[0],e,n,r);let o,i=(0,ol.toHash)(t);if(i.array&&i.object){let s=(0,T._)`typeof ${e} != "object"`;o=i.null?s:(0,T._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=T.nil;i.number&&delete i.integer;for(let s in i)o=(0,T.and)(o,Ui(s,e,n,r));return o}de.checkDataTypes=Hi;var Mh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,T._)`{type: ${t}}`:(0,T._)`{type: ${e}}`};function Gi(t){let e=Lh(t);(0,Ah.reportError)(e,Mh)}de.reportTypeError=Gi;function Lh(t){let{gen:e,data:n,schema:r}=t,o=(0,ol.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var cl=_(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.assignDefaults=void 0;var $n=A(),jh=M();function Dh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)al(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>al(t,i,o.default))}mo.assignDefaults=Dh;function al(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,$n._)`${i}${(0,$n.getProperty)(e)}`;if(o){(0,jh.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,$n._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,$n._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,$n._)`${a} = ${(0,$n.stringify)(n)}`)}});var Ie=_(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var H=A(),Wi=M(),kt=ut(),Fh=M();function Bh(t,e){let{gen:n,data:r,it:o}=t;n.if(zi(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,H._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Bh;function qh({gen:t,data:e,it:{opts:n}},r,o){return(0,H.or)(...r.map(i=>(0,H.and)(zi(t,e,i,n.ownProperties),(0,H._)`${o} = ${i}`)))}F.checkMissingProp=qh;function Uh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Uh;function ll(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,H._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=ll;function Vi(t,e,n){return(0,H._)`${ll(t)}.call(${e}, ${n})`}F.isOwnProperty=Vi;function Hh(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} !== undefined`;return r?(0,H._)`${o} && ${Vi(t,e,n)}`:o}F.propertyInData=Hh;function zi(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} === undefined`;return r?(0,H.or)(o,(0,H.not)(Vi(t,e,n))):o}F.noPropertyInData=zi;function ul(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ul;function Gh(t,e){return ul(e).filter(n=>!(0,Wi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Gh;function Wh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,H._)`${t}, ${e}, ${r}${o}`:e,d=[[kt.default.instancePath,(0,H.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 h=(0,H._)`${u}, ${n.object(...d)}`;return c!==H.nil?(0,H._)`${a}.call(${c}, ${h})`:(0,H._)`${a}(${h})`}F.callValidateCode=Wh;var Vh=(0,H._)`new RegExp`;function zh({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(n,r);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,H._)`${o.code==="new RegExp"?Vh:(0,Fh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=zh;function Kh(t){let{gen:e,data:n,keyword:r,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,H._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:Wi.Type.Num},i),e.if((0,H.not)(i),a)})}}F.validateArray=Kh;function Jh(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Wi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,l)=>{let u=t.subschema({keyword:r,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,H._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,H.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Jh});var ml=_(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var ge=A(),zt=ut(),Yh=Ie(),Qh=pr();function Xh(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=fl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Je.macroKeywordCode=Xh;function Zh(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;tg(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=fl(r,o,l),d=r.let("valid");t.block$data(d,h),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function h(){if(e.errors===!1)m(),e.modifying&&dl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&dl(t),g(()=>eg(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ge._)`await `),v=>r.assign(d,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ge._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ge._)`${u}.errors`;return r.assign(y,null),m(ge.nil),y}function m(y=e.async?(0,ge._)`await `:ge.nil){let v=c.opts.passContext?zt.default.this:zt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ge._)`${y}${(0,Yh.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ge.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Je.funcKeywordCode=Zh;function dl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function eg(t,e){let{gen:n}=t;n.if((0,ge._)`Array.isArray(${e})`,()=>{n.assign(zt.default.vErrors,(0,ge._)`${zt.default.vErrors} === null ? ${e} : ${zt.default.vErrors}.concat(${e})`).assign(zt.default.errors,(0,ge._)`${zt.default.vErrors}.length`),(0,Qh.extendErrors)(t)},()=>t.error())}function tg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function fl(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function ng(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Je.validSchemaType=ng;function rg({schema:t,opts:e,self:n,errSchemaPath:r},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(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Je.validateKeywordUsage=rg});var hl=_($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.extendSubschemaMode=$t.extendSubschemaData=$t.getSubschema=void 0;var Ye=A(),pl=M();function og(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}${(0,Ye.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,pl.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}$t.getSubschema=og;function ig(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,h=a.let("data",(0,Ye._)`${e.data}${(0,Ye.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Ye.str)`${l}${(0,pl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ye._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Ye.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}$t.extendSubschemaData=ig;function sg(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:i}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=n}$t.extendSubschemaMode=sg});var Ki=_((B$,gl)=>{"use strict";gl.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,i;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[o]))return!1;for(o=r;o--!==0;){var s=i[o];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var _l=_((q$,yl)=>{"use strict";var Rt=yl.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};po(e,r,o,t,"",t)};Rt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Rt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Rt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Rt.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 po(t,e,n,r,o,i,s,a,c,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,l);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in Rt.arrayKeywords)for(var h=0;h<d.length;h++)po(t,e,n,d[h],o+"/"+u+"/"+h,i,o,u,r,h)}else if(u in Rt.propsKeywords){if(d&&typeof d=="object")for(var p in d)po(t,e,n,d[p],o+"/"+u+"/"+ag(p),i,o,u,r,p)}else(u in Rt.keywords||t.allKeys&&!(u in Rt.skipKeywords))&&po(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function ag(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gr=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var cg=M(),lg=Ki(),ug=_l(),dg=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function fg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ji(t):e?wl(t)<=e:!1}ve.inlineRef=fg;var mg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ji(t){for(let e in t){if(mg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ji)||typeof n=="object"&&Ji(n))return!0}return!1}function wl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!dg.has(n)&&(typeof t[n]=="object"&&(0,cg.eachItem)(t[n],r=>e+=wl(r)),e===1/0))return 1/0}return e}function vl(t,e="",n){n!==!1&&(e=Rn(e));let r=t.parse(e);return bl(t,r)}ve.getFullPath=vl;function bl(t,e){return t.serialize(e).split("#")[0]+"#"}ve._getFullPath=bl;var pg=/#\/?$/;function Rn(t){return t?t.replace(pg,""):""}ve.normalizeId=Rn;function hg(t,e,n){return n=Rn(n),t.resolve(e,n)}ve.resolveUrl=hg;var gg=/^[a-z_][-a-z0-9._]*$/i;function yg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Rn(t[n]||e),i={"":o},s=vl(r,o,!1),a={},c=new Set;return ug(t,{allKeys:!0},(d,h,p,f)=>{if(f===void 0)return;let m=s+h,g=i[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[h]=g;function y(S){let R=this.opts.uriResolver.resolve;if(S=Rn(g?R(g,S):S),c.has(S))throw u(S);c.add(S);let $=this.refs[S];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?l(d,$.schema,S):S!==Rn(m)&&(S[0]==="#"?(l(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!gg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,h,p){if(h!==void 0&&!lg(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ve.getSchemaRefs=yg});var wr=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getData=Pt.KeywordCxt=Pt.validateFunctionCode=void 0;var Rl=tl(),Sl=hr(),Qi=qi(),ho=hr(),_g=cl(),_r=ml(),Yi=hl(),b=A(),P=ut(),wg=gr(),dt=M(),yr=pr();function vg(t){if(Al(t)&&(Cl(t),Tl(t))){Eg(t);return}Pl(t,()=>(0,Rl.topBoolOrEmptySchema)(t))}Pt.validateFunctionCode=vg;function Pl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${P.default.data}, ${P.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${El(n,o)}`),Sg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${bg(o)}`,r.$async,()=>t.code(El(n,o)).code(i))}function bg(t){return(0,b._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,b._)`, ${P.default.dynamicAnchors}={}`:b.nil}}={}`}function Sg(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,b._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,b._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,b._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,b._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,b._)`""`),t.var(P.default.parentData,(0,b._)`undefined`),t.var(P.default.parentDataProperty,(0,b._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`{}`)})}function Eg(t){let{schema:e,opts:n,gen:r}=t;Pl(t,()=>{n.$comment&&e.$comment&&Il(t),Tg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&kg(t),xl(t),xg(t)})}function kg(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,b._)`${n}.evaluated`),e.if((0,b._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,b._)`${t.evaluated}.props`,(0,b._)`undefined`)),e.if((0,b._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,b._)`${t.evaluated}.items`,(0,b._)`undefined`))}function El(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,b._)`/*# sourceURL=${n} */`:b.nil}function $g(t,e){if(Al(t)&&(Cl(t),Tl(t))){Rg(t,e);return}(0,Rl.boolOrEmptySchema)(t,e)}function Tl({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Al(t){return typeof t.schema!="boolean"}function Rg(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Il(t),Ag(t),Cg(t);let i=r.const("_errs",P.default.errors);xl(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Cl(t){(0,dt.checkUnknownRules)(t),Pg(t)}function xl(t,e){if(t.opts.jtd)return kl(t,[],!1,e);let n=(0,Sl.getSchemaTypes)(t.schema),r=(0,Sl.coerceAndCheckDataType)(t,n);kl(t,n,!r,e)}function Pg(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,dt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Tg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,dt.checkStrictMode)(t,"default is ignored in the schema root")}function Ag(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,wg.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Cg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Il({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${P.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,b.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,b._)`${P.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function xg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,b._)`new ${o}(${P.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,P.default.vErrors),i.unevaluated&&Ig(t),e.return((0,b._)`${P.default.errors} === 0`))}function Ig({gen:t,evaluated:e,props:n,items:r}){n instanceof b.Name&&t.assign((0,b._)`${e}.props`,n),r instanceof b.Name&&t.assign((0,b._)`${e}.items`,r)}function kl(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,dt.schemaHasRulesButRef)(i,u))){o.block(()=>Nl(t,"$ref",u.all.$ref.definition));return}c.jtd||Og(t,e),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Qi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,ho.checkDataType)(h.type,s,c.strictNumbers)),$l(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,ho.reportTypeError)(t)),o.endIf()):$l(t,h),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function $l(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,_g.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Qi.shouldUseRule)(r,i)&&Nl(t,i.keyword,i.definition,e.type)})}function Og(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ng(t,e),t.opts.allowUnionTypes||Mg(t,e),Lg(t,t.dataTypes))}function Ng(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Ol(t.dataTypes,n)||Xi(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dg(t,e)}}function Mg(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Xi(t,"use allowUnionTypes to allow union type keyword")}function Lg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Qi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>jg(e,s))&&Xi(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function jg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ol(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dg(t,e){let n=[];for(let r of t.dataTypes)Ol(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Xi(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,dt.checkStrictMode)(t,e,t.opts.strictTypes)}var go=class{constructor(e,n,r){if((0,_r.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,dt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Ml(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,_r.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,n,r){this.failResult((0,b.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,b.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,b._)`${n} !== undefined && (${(0,b.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?yr.reportExtraError:yr.reportError)(this,this.def.error,n)}$dataError(){(0,yr.reportError)(this,this.def.$dataError||yr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=b.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=b.nil,n=b.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,b.or)((0,b._)`${o} === undefined`,n)),e!==b.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==b.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,b.or)(s(),a());function s(){if(r.length){if(!(n instanceof b.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,b._)`${(0,ho.checkDataTypes)(c,n,i.opts.strictNumbers,ho.DataType.Wrong)}`}return b.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,b._)`!${c}(${n})`}return b.nil}}subschema(e,n){let r=(0,Yi.getSubschema)(this.it,e);(0,Yi.extendSubschemaData)(r,this.it,e),(0,Yi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return $g(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=dt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=dt.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,b.Name)),!0}};Pt.KeywordCxt=go;function Nl(t,e,n,r){let o=new go(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,_r.funcKeywordCode)(o,n):"macro"in n?(0,_r.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,_r.funcKeywordCode)(o,n)}var Fg=/^\/(?:[^~]|~0|~1)*$/,Bg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ml(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Fg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=Bg.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return r[e-u]}if(u>e)throw new Error(c("data",u));if(i=n[e-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,b._)`${i}${(0,b.getProperty)((0,dt.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Pt.getData=Ml});var yo=_(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var Zi=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};es.default=Zi});var vr=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var ts=gr(),ns=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,ts.resolveUrl)(e,n,r),this.missingSchema=(0,ts.normalizeId)((0,ts.getFullPath)(e,this.missingRef))}};rs.default=ns});var wo=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var De=A(),qg=yo(),Kt=ut(),Fe=gr(),Ll=M(),Ug=wr(),Pn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Fe.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Oe.SchemaEnv=Pn;function is(t){let e=jl.call(this,t);if(e)return e;let n=(0,Fe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new De.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:qg.default,code:(0,De._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Kt.default.data,parentData:Kt.default.parentData,parentDataProperty:Kt.default.parentDataProperty,dataNames:[Kt.default.data],dataPathArr:[De.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,De.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:De.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,De._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Ug.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Kt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Kt.default.self}`,`${Kt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;p.evaluated={props:f instanceof De.Name?void 0:f,items:m instanceof De.Name?void 0:m,dynamicProps:f instanceof De.Name,dynamicItems:m instanceof De.Name},p.source&&(p.source.evaluated=(0,De.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Oe.compileSchema=is;function Hg(t,e,n){var r;n=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Vg.call(this,t,n);if(i===void 0){let s=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new Pn({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Gg.call(this,i)}Oe.resolveRef=Hg;function Gg(t){return(0,Fe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:is.call(this,t)}function jl(t){for(let e of this._compilations)if(Wg(e,t))return e}Oe.getCompilingSchema=jl;function Wg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Vg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||_o.call(this,t,e)}function _o(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Fe._getFullPath)(this.opts.uriResolver,n),o=(0,Fe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return os.call(this,n,t);let i=(0,Fe.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=_o.call(this,t,s);return typeof a?.schema!="object"?void 0:os.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||is.call(this,s),i===(0,Fe.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,l)),new Pn({schema:a,schemaId:c,root:t,baseId:o})}return os.call(this,n,s)}}Oe.resolveSchema=_o;var zg=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function os(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Ll.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!zg.has(a)&&l&&(e=(0,Fe.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Ll.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=_o.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new Pn({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Dl=_((z$,Kg)=>{Kg.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 as=_((K$,Ul)=>{"use strict";var Jg=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Bl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ss(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var Yg=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fl(t){return t.length=0,!0}function Qg(t,e,n){if(t.length){let r=ss(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Xg(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=Qg;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),r.push(":");continue}else if(l==="%"){if(!a(o,r,n))break;a=Fl}else{o.push(l);continue}}return o.length&&(a===Fl?n.zone=o.join(""):s?r.push(o.join("")):r.push(ss(o))),n.address=r.join(""),n}function ql(t){if(Zg(t,":")<2)return{host:t,isIPV6:!1};let e=Xg(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Zg(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function ey(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function ty(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function ny(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Bl(n)){let r=ql(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Ul.exports={nonSimpleDomain:Yg,recomposeAuthority:ny,normalizeComponentEncoding:ty,removeDotSegments:ey,isIPv4:Bl,isUUID:Jg,normalizeIPv6:ql,stringArrayToHexStripped:ss}});var zl=_((J$,Vl)=>{"use strict";var{isUUID:ry}=as(),oy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,iy=["http","https","ws","wss","urn","urn:uuid"];function sy(t){return iy.indexOf(t)!==-1}function cs(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Hl(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Gl(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ay(t){return t.secure=cs(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function cy(t){if((t.port===(cs(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function ly(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(oy);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,i=ls(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function uy(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,i=ls(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${r||e.nid}:${a}`,e.skipEscape=!0,s}function dy(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ry(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function fy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Wl={scheme:"http",domainHost:!0,parse:Hl,serialize:Gl},my={scheme:"https",domainHost:Wl.domainHost,parse:Hl,serialize:Gl},vo={scheme:"ws",domainHost:!0,parse:ay,serialize:cy},py={scheme:"wss",domainHost:vo.domainHost,parse:vo.parse,serialize:vo.serialize},hy={scheme:"urn",parse:ly,serialize:uy,skipNormalize:!0},gy={scheme:"urn:uuid",parse:dy,serialize:fy,skipNormalize:!0},bo={http:Wl,https:my,ws:vo,wss:py,urn:hy,"urn:uuid":gy};Object.setPrototypeOf(bo,null);function ls(t){return t&&(bo[t]||bo[t.toLowerCase()])||void 0}Vl.exports={wsIsSecure:cs,SCHEMES:bo,isValidSchemeName:sy,getSchemeHandler:ls}});var Yl=_((Y$,Eo)=>{"use strict";var{normalizeIPv6:yy,removeDotSegments:br,recomposeAuthority:_y,normalizeComponentEncoding:So,isIPv4:wy,nonSimpleDomain:vy}=as(),{SCHEMES:by,getSchemeHandler:Kl}=zl();function Sy(t,e){return typeof t=="string"?t=Qe(ft(t,e),e):typeof t=="object"&&(t=ft(Qe(t,e),e)),t}function Ey(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Jl(ft(t,r),ft(e,r),r,!0);return r.skipEscape=!0,Qe(o,r)}function Jl(t,e,n,r){let o={};return r||(t=ft(Qe(t,n),n),e=ft(Qe(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=br(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=br(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function ky(t,e,n){return typeof t=="string"?(t=unescape(t),t=Qe(So(ft(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Qe(So(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Qe(So(ft(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Qe(So(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Qe(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],i=Kl(r.scheme||n.scheme);i&&i.serialize&&i.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let s=_y(n);if(s!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(s),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!i||!i.absolutePath)&&(a=br(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var $y=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ft(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match($y);if(i){if(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]),r.host)if(wy(r.host)===!1){let c=yy(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let s=Kl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&vy(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),s&&s.parse&&s.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var us={SCHEMES:by,normalize:Sy,resolve:Ey,resolveComponent:Jl,equal:ky,serialize:Qe,parse:ft};Eo.exports=us;Eo.exports.default=us;Eo.exports.fastUri=us});var Xl=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var Ql=Yl();Ql.code='require("ajv/dist/runtime/uri").default';ds.default=Ql});var su=_(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.CodeGen=se.Name=se.nil=se.stringify=se.str=se._=se.KeywordCxt=void 0;var Ry=wr();Object.defineProperty(se,"KeywordCxt",{enumerable:!0,get:function(){return Ry.KeywordCxt}});var Tn=A();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Tn._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Tn.str}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Tn.stringify}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Tn.nil}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Tn.Name}});Object.defineProperty(se,"CodeGen",{enumerable:!0,get:function(){return Tn.CodeGen}});var Py=yo(),ru=vr(),Ty=Bi(),Sr=wo(),Ay=A(),Er=gr(),ko=hr(),ms=M(),Zl=Dl(),Cy=Xl(),ou=(t,e)=>new RegExp(t,e);ou.code="new RegExp";var xy=["removeAdditional","useDefaults","coerceTypes"],Iy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Oy={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."},Ny={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},eu=200;function My(t){var e,n,r,o,i,s,a,c,l,u,d,h,p,f,m,g,y,v,S,R,$,z,Q,ie,ze;let it=t.strict,nr=(e=t.code)===null||e===void 0?void 0:e.optimize,Ke=nr===!0||nr===void 0?1:nr||0,ne=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:ou,Bt=(o=t.uriResolver)!==null&&o!==void 0?o:Cy.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:it)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:it)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:it)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:it)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:it)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Ke,regExp:ne}:{optimize:Ke,regExp:ne},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:eu,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:eu,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(z=t.validateSchema)!==null&&z!==void 0?z:!0,validateFormats:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(ie=t.unicodeRegExp)!==null&&ie!==void 0?ie:!0,int32range:(ze=t.int32range)!==null&&ze!==void 0?ze:!0,uriResolver:Bt}}var kr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...My(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Ay.ValueScope({scope:{},prefixes:Iy,es5:n,lines:r}),this.logger=qy(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ty.getRules)(),tu.call(this,Oy,e,"NOT SUPPORTED"),tu.call(this,Ny,e,"DEPRECATED","warn"),this._metaOpts=Fy.call(this),e.formats&&jy.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Dy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ly.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=Zl;r==="id"&&(o={...Zl},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(u,d){await i.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||s.call(this,h)}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 ru.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,n)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return n=(0,Er.normalizeId)(n||i),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let n;for(;typeof(n=nu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Sr.SchemaEnv({schema:{},schemaId:r});if(n=Sr.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=nu.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Er.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Hy.call(this,r,n),!n)return(0,ms.eachItem)(r,i=>fs.call(this,i)),this;Wy.call(this,n);let o={...n,type:(0,ko.getJSONTypes)(n.type),schemaType:(0,ko.getJSONTypes)(n.schemaType)};return(0,ms.eachItem)(r,o.type.length===0?i=>fs.call(this,i,o):i=>o.type.forEach(s=>fs.call(this,i,o,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(i=>i.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,i)=>o+n+i)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=iu(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,Er.normalizeId)(s||r);let l=Er.getSchemaRefs.call(this,e,r);return c=new Sr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:l}),this._cache.set(c.schema,c),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Sr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Sr.compileSchema.call(this,e)}finally{this.opts=n}}};kr.ValidationError=Py.default;kr.MissingRefError=ru.default;se.default=kr;function tu(t,e,n,r="error"){for(let o in t){let i=o;i in e&&this.logger[r](`${n}: option ${o}. ${t[i]}`)}}function nu(t){return t=(0,Er.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ly(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function jy(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Dy(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Fy(){let t={...this.opts};for(let e of xy)delete t[e];return t}var By={log(){},warn(){},error(){}};function qy(t){if(t===!1)return By;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Uy=/^[a-z_$][a-z0-9_$:-]*$/i;function Hy(t,e){let{RULES:n}=this;if((0,ms.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Uy.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function fs(t,e,n){var r;let o=e?.post;if(n&&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===n);if(s||(s={type:n,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ko.getJSONTypes)(e.type),schemaType:(0,ko.getJSONTypes)(e.schemaType)}};e.before?Gy.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function Gy(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Wy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=iu(e)),t.validateSchema=this.compile(e,!0))}var Vy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function iu(t){return{anyOf:[t,Vy]}}});var au=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var zy={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ps.default=zy});var du=_(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.callRef=Jt.getValidate=void 0;var Ky=vr(),cu=Ie(),be=A(),An=ut(),lu=wo(),$o=M(),Jy={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=r,{root:l}=i;if((n==="#"||n==="#/")&&o===l.baseId)return d();let u=lu.resolveRef.call(c,l,o,n);if(u===void 0)throw new Ky.default(r.opts.uriResolver,o,n);if(u instanceof lu.SchemaEnv)return h(u);return p(u);function d(){if(i===l)return Ro(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return Ro(t,(0,be._)`${f}.validate`,l,l.$async)}function h(f){let m=uu(t,f);Ro(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,be.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:be.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function uu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Jt.getValidate=uu;function Ro(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?An.default.this:be.nil;r?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,be._)`await ${(0,cu.callValidateCode)(t,e,l)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,be._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,cu.callValidateCode)(t,e,l),()=>p(e),()=>h(e))}function h(f){let m=(0,be._)`${f}.errors`;o.assign(An.default.vErrors,(0,be._)`${An.default.vErrors} === null ? ${m} : ${An.default.vErrors}.concat(${m})`),o.assign(An.default.errors,(0,be._)`${An.default.vErrors}.length`)}function p(f){var m;if(!i.opts.unevaluated)return;let g=(m=n?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=$o.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,be._)`${f}.evaluated.props`);i.props=$o.mergeEvaluated.props(o,y,i.props,be.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=$o.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,be._)`${f}.evaluated.items`);i.items=$o.mergeEvaluated.items(o,y,i.items,be.Name)}}}Jt.callRef=Ro;Jt.default=Jy});var fu=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Yy=au(),Qy=du(),Xy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Yy.default,Qy.default];hs.default=Xy});var mu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var Po=A(),Tt=Po.operators,To={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}},Zy={message:({keyword:t,schemaCode:e})=>(0,Po.str)`must be ${To[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Po._)`{comparison: ${To[t].okStr}, limit: ${e}}`},e_={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:Zy,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Po._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};gs.default=e_});var pu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var $r=A(),t_={message:({schemaCode:t})=>(0,$r.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$r._)`{multipleOf: ${t}}`},n_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:t_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,$r._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,$r._)`${s} !== parseInt(${s})`;t.fail$data((0,$r._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};ys.default=n_});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});function hu(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}_s.default=hu;hu.code='require("ajv/dist/runtime/ucs2length").default'});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var Yt=A(),r_=M(),o_=gu(),i_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Yt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Yt._)`{limit: ${t}}`},s_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Yt.operators.GT:Yt.operators.LT,s=o.opts.unicode===!1?(0,Yt._)`${n}.length`:(0,Yt._)`${(0,r_.useFunc)(t.gen,o_.default)}(${n})`;t.fail$data((0,Yt._)`${s} ${i} ${r}`)}};ws.default=s_});var _u=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var a_=Ie(),c_=M(),Cn=A(),l_={message:({schemaCode:t})=>(0,Cn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Cn._)`{pattern: ${t}}`},u_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:l_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,Cn._)`new RegExp`:(0,c_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Cn._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,Cn._)`!${u}`)}else{let c=(0,a_.usePattern)(t,o);t.fail$data((0,Cn._)`!${c}.test(${n})`)}}};vs.default=u_});var wu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Rr=A(),d_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Rr.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Rr._)`{limit: ${t}}`},f_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:d_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Rr.operators.GT:Rr.operators.LT;t.fail$data((0,Rr._)`Object.keys(${n}).length ${o} ${r}`)}};bs.default=f_});var vu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var Pr=Ie(),Tr=A(),m_=M(),p_={message:({params:{missingProperty:t}})=>(0,Tr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Tr._)`{missingProperty: ${t}}`},h_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:p_,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&n.length===0)return;let c=n.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let m of n)if(p?.[m]===void 0&&!f.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,m_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(Tr.nil,d);else for(let p of n)(0,Pr.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||i){let f=e.let("valid",!0);t.block$data(f,()=>h(p,f)),t.ok(f)}else e.if((0,Pr.checkMissingProp)(t,n,p)),(0,Pr.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",r,p=>{t.setParams({missingProperty:p}),e.if((0,Pr.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function h(p,f){t.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(f,(0,Pr.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Tr.not)(f),()=>{t.error(),e.break()})},Tr.nil)}}};Ss.default=h_});var bu=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Ar=A(),g_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Ar.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Ar._)`{limit: ${t}}`},y_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:g_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Ar.operators.GT:Ar.operators.LT;t.fail$data((0,Ar._)`${n}.length ${o} ${r}`)}};Es.default=y_});var Ao=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Su=Ki();Su.code='require("ajv/dist/runtime/equal").default';ks.default=Su});var Eu=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var $s=hr(),ae=A(),__=M(),w_=Ao(),v_={message:({params:{i:t,j:e}})=>(0,ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ae._)`{i: ${t}, j: ${e}}`},b_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:v_,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),l=i.items?(0,$s.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,ae._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,ae._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,ae._)`${f} > 1`,()=>(d()?h:p)(f,m))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function h(f,m){let g=e.name("item"),y=(0,$s.checkDataTypes)(l,g,a.opts.strictNumbers,$s.DataType.Wrong),v=e.const("indices",(0,ae._)`{}`);e.for((0,ae._)`;${f}--;`,()=>{e.let(g,(0,ae._)`${n}[${f}]`),e.if(y,(0,ae._)`continue`),l.length>1&&e.if((0,ae._)`typeof ${g} == "string"`,(0,ae._)`${g} += "_"`),e.if((0,ae._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,ae._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,ae._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,__.useFunc)(e,w_.default),y=e.name("outer");e.label(y).for((0,ae._)`;${f}--;`,()=>e.for((0,ae._)`${m} = ${f}; ${m}--;`,()=>e.if((0,ae._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Rs.default=b_});var ku=_(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var Ps=A(),S_=M(),E_=Ao(),k_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ps._)`{allowedValue: ${t}}`},$_={keyword:"const",$data:!0,error:k_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Ps._)`!${(0,S_.useFunc)(e,E_.default)}(${n}, ${o})`):t.fail((0,Ps._)`${i} !== ${n}`)}};Ts.default=$_});var $u=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Cr=A(),R_=M(),P_=Ao(),T_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Cr._)`{allowedValues: ${t}}`},A_={keyword:"enum",schemaType:"array",$data:!0,error:T_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,R_.useFunc)(e,P_.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,Cr.or)(...o.map((f,m)=>h(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,Cr._)`${l()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,Cr._)`${l()}(${n}, ${p}[${f}])`:(0,Cr._)`${n} === ${m}`}}};As.default=A_});var Ru=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var C_=mu(),x_=pu(),I_=yu(),O_=_u(),N_=wu(),M_=vu(),L_=bu(),j_=Eu(),D_=ku(),F_=$u(),B_=[C_.default,x_.default,I_.default,O_.default,N_.default,M_.default,L_.default,j_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},D_.default,F_.default];Cs.default=B_});var Is=_(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateAdditionalItems=void 0;var Qt=A(),xs=M(),q_={message:({params:{len:t}})=>(0,Qt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qt._)`{limit: ${t}}`},U_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:q_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,xs.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Pu(t,r)}};function Pu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Qt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Qt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,xs.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Qt._)`${a} <= ${e.length}`);n.if((0,Qt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:xs.Type.Num},l),s.allErrors||n.if((0,Qt.not)(l),()=>n.break())})}}xr.validateAdditionalItems=Pu;xr.default=U_});var Os=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var Tu=A(),Co=M(),H_=Ie(),G_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Au(t,"additionalItems",e);n.items=!0,!(0,Co.alwaysValidSchema)(n,e)&&t.ok((0,H_.validateArray)(t))}};function Au(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Co.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),l=r.const("len",(0,Tu._)`${i}.length`);n.forEach((d,h)=>{(0,Co.alwaysValidSchema)(a,d)||(r.if((0,Tu._)`${l} > ${h}`,()=>t.subschema({keyword:s,schemaProp:h,dataProp:h},c)),t.ok(c))});function u(d){let{opts:h,errSchemaPath:p}=a,f=n.length,m=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(h.strictTuples&&!m){let g=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Co.checkStrictMode)(a,g,h.strictTuples)}}}Ir.validateTuple=Au;Ir.default=G_});var Cu=_(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var W_=Os(),V_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,W_.validateTuple)(t,"items")};Ns.default=V_});var Iu=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var xu=A(),z_=M(),K_=Ie(),J_=Is(),Y_={message:({params:{len:t}})=>(0,xu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xu._)`{limit: ${t}}`},Q_={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Y_,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,z_.alwaysValidSchema)(r,e)&&(o?(0,J_.validateAdditionalItems)(t,o):t.ok((0,K_.validateArray)(t)))}};Ms.default=Q_});var Ou=_(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Ne=A(),xo=M(),X_={message:({params:{min:t,max:e}})=>e===void 0?(0,Ne.str)`must contain at least ${t} valid item(s)`:(0,Ne.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ne._)`{minContains: ${t}}`:(0,Ne._)`{minContains: ${t}, maxContains: ${e}}`},Z_={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:X_,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:l}=r;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Ne._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,xo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,xo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xo.alwaysValidSchema)(i,n)){let m=(0,Ne._)`${u} >= ${s}`;a!==void 0&&(m=(0,Ne._)`${m} && ${u} <= ${a}`),t.pass(m);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Ne._)`${o}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>f(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:xo.Type.Num,compositeRule:!0},m),g()})}function f(m){e.code((0,Ne._)`${m}++`),a===void 0?e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Ne._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Ls.default=Z_});var Lu=_(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateSchemaDeps=Xe.validatePropertyDeps=Xe.error=void 0;var js=A(),ew=M(),Or=Ie();Xe.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,js.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,js._)`{property: ${t},
8
8
  missingProperty: ${r},
9
9
  depsCount: ${e},
10
- deps: ${n}}`};var ew={keyword:"dependencies",type:"object",schemaType:"object",error:Xe.error,code(t){let[e,n]=tw(t);Ou(t,e),Nu(t,n)}};function tw({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Ou(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let i=n.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Ir.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let l of a)(0,Ir.checkReportMissingProp)(t,l)}):(n.if((0,Ls._)`${c} && (${(0,Ir.checkMissingProp)(t,a,i)})`),(0,Ir.reportMissingProp)(t,i),n.else())}}Xe.validatePropertyDeps=Ou;function Nu(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,Z_.alwaysValidSchema)(i,e[a])||(n.if((0,Ir.propertyInData)(n,r,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),t.ok(s))}Xe.validateSchemaDeps=Nu;Xe.default=ew});var ju=_(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Lu=A(),nw=M(),rw={message:"property name must be valid",params:({params:t})=>(0,Lu._)`{propertyName: ${t.propertyName}}`},ow={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rw,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,nw.alwaysValidSchema)(o,n))return;let i=e.name("valid");e.forIn("key",r,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,Lu.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};js.default=ow});var Fs=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Io=Ce(),Be=A(),iw=lt(),Oo=M(),sw={message:"must NOT have additional properties",params:({params:t})=>(0,Be._)`{additionalProperty: ${t.additionalProperty}}`},aw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:sw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Oo.alwaysValidSchema)(s,n))return;let l=(0,Io.allSchemaProperties)(r.properties),u=(0,Io.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Be._)`${i} === ${iw.default.errors}`);function d(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(h(g),()=>f(g))})}function h(g){let y;if(l.length>8){let v=(0,Oo.schemaRefOrVal)(s,r.properties,"properties");y=(0,Io.isOwnProperty)(e,v,g)}else l.length?y=(0,Be.or)(...l.map(v=>(0,Be._)`${g} === ${v}`)):y=Be.nil;return u.length&&(y=(0,Be.or)(y,...u.map(v=>(0,Be._)`${(0,Io.usePattern)(t,v)}.test(${g})`))),(0,Be.not)(y)}function p(g){e.code((0,Be._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){p(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Oo.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Be.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Be.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Oo.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Ds.default=aw});var Bu=_(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var cw=_r(),Du=Ce(),Bs=M(),Fu=Fs(),lw={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t;i.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Fu.default.code(new cw.KeywordCxt(i,Fu.default,"additionalProperties"));let s=(0,Du.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Bs.mergeEvaluated.props(e,(0,Bs.toHash)(s),i.props));let a=s.filter(d=>!(0,Bs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Du.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};qs.default=lw});var Wu=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var qu=Ce(),No=A(),Uu=M(),Hu=M(),uw={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,qu.allSchemaProperties)(n),c=a.filter(m=>(0,Uu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof No.Name)&&(i.props=(0,Hu.evaluatedPropsToName)(e,i.props));let{props:d}=i;h();function h(){for(let m of a)l&&p(m),i.allErrors?f(m):(e.var(u,!0),f(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,Uu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,No._)`${(0,qu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:Hu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,No._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,No.not)(u),()=>e.break())})})}}};Us.default=uw});var Vu=_(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var dw=M(),fw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,dw.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Hs.default=fw});var Gu=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var mw=Ce(),pw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mw.validateUnion,error:{message:"must match a schema in anyOf"}};Ws.default=pw});var zu=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Mo=A(),hw=M(),gw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},yw={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gw,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let i=n,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((u,d)=>{let h;(0,hw.alwaysValidSchema)(o,u)?e.var(c,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Mo.Name)})})}}};Vs.default=yw});var Ku=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var _w=M(),ww={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((i,s)=>{if((0,_w.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};Gs.default=ww});var Qu=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var Lo=A(),Yu=M(),vw={message:({params:t})=>(0,Lo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Lo._)`{failingKeyword: ${t.ifClause}}`},bw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Yu.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Ju(r,"then"),i=Ju(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,Lo.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(h,s),d?e.assign(d,(0,Lo._)`${u}`):t.setParams({ifClause:u})}}}};function Ju(t,e){let n=t.schema[e];return n!==void 0&&!(0,Yu.alwaysValidSchema)(t,n)}zs.default=bw});var Xu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Sw=M(),Ew={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,Sw.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Ks.default=Ew});var Zu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var $w=Cs(),kw=Au(),Rw=Is(),Pw=Cu(),Tw=Iu(),Aw=Mu(),xw=ju(),Cw=Fs(),Iw=Bu(),Ow=Wu(),Nw=Vu(),Mw=Gu(),Lw=zu(),jw=Ku(),Dw=Qu(),Fw=Xu();function Bw(t=!1){let e=[Nw.default,Mw.default,Lw.default,jw.default,Dw.default,Fw.default,xw.default,Cw.default,Aw.default,Iw.default,Ow.default];return t?e.push(kw.default,Pw.default):e.push($w.default,Rw.default),e.push(Tw.default),e}Js.default=Bw});var ed=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var Y=A(),qw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Uw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?h():p();function h(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=n.const("fDef",(0,Y._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Y._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Y._)`${m}.type || "string"`).assign(y,(0,Y._)`${m}.validate`),()=>n.assign(g,(0,Y._)`"string"`).assign(y,m)),t.fail$data((0,Y.or)(v(),S()));function v(){return c.strictSchema===!1?Y.nil:(0,Y._)`${s} && !${y}`}function S(){let R=u.$async?(0,Y._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Y._)`${y}(${r})`,k=(0,Y._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Y._)`${y} && ${y} !== true && ${g} === ${e} && !${k}`}}function p(){let f=d.formats[i];if(!f){v();return}if(f===!0)return;let[m,g,y]=S(f);m===e&&t.pass(R());function v(){if(c.strictSchema===!1){d.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function S(k){let G=k instanceof RegExp?(0,Y.regexpCode)(k):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,Q=n.scopeValue("formats",{key:i,ref:k,code:G});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,Y._)`${Q}.validate`]:["string",k,Q]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${y}(${r})`}return typeof g=="function"?(0,Y._)`${y}(${r})`:(0,Y._)`${y}.test(${r})`}}}};Ys.default=Uw});var td=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Hw=ed(),Ww=[Hw.default];Qs.default=Ww});var nd=_(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var od=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Vw=du(),Gw=ku(),zw=Zu(),Kw=td(),rd=nd(),Jw=[Vw.default,Gw.default,(0,zw.default)(),Kw.default,rd.metadataVocabulary,rd.contentVocabulary];Xs.default=Jw});var sd=_(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.DiscrError=void 0;var id;(function(t){t.Tag="tag",t.Mapping="mapping"})(id||(jo.DiscrError=id={}))});var cd=_(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var Cn=A(),Zs=sd(),ad=wo(),Yw=wr(),Qw=M(),Xw={message:({params:{discrError:t,tagName:e}})=>t===Zs.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Cn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},Zw={keyword:"discriminator",type:"object",schemaType:"object",error:Xw,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Cn._)`${n}${(0,Cn.getProperty)(a)}`);e.if((0,Cn._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Zs.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=h();e.if(!1);for(let f in p)e.elseIf((0,Cn._)`${l} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:Zs.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(m,Cn.Name),f}function h(){var p;let f={},m=y(o),g=!0;for(let R=0;R<s.length;R++){let k=s[R];if(k?.$ref&&!(0,Qw.schemaHasRulesButRef)(k,i.self.RULES)){let Q=k.$ref;if(k=ad.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Q),k instanceof ad.SchemaEnv&&(k=k.schema),k===void 0)throw new Yw.default(i.opts.uriResolver,i.baseId,Q)}let G=(p=k?.properties)===null||p===void 0?void 0:p[a];if(typeof G!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(k)),v(G,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function v(R,k){if(R.const)S(R.const,k);else if(R.enum)for(let G of R.enum)S(G,k);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(R,k){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=k}}}};ea.default=Zw});var ld=_((CR,ev)=>{ev.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 Fo=_((W,ta)=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var tv=iu(),nv=od(),rv=cd(),ud=ld(),ov=["/properties"],Do="http://json-schema.org/draft-07/schema",In=class extends tv.default{_addVocabularies(){super._addVocabularies(),nv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rv.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ud,ov):ud;this.addMetaSchema(e,Do,!1),this.refs["http://json-schema.org/schema"]=Do}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Do)?Do:void 0)}};W.Ajv=In;ta.exports=W=In;ta.exports.Ajv=In;Object.defineProperty(W,"__esModule",{value:!0});W.default=In;var iv=_r();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return iv.KeywordCxt}});var On=A();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return On._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return On.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return On.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return On.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return On.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return On.CodeGen}});var sv=yo();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return sv.default}});var av=wr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return av.default}})});var _d=_(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Ze(t,e){return{validate:t,compare:e}}et.fullFormats={date:Ze(pd,ia),time:Ze(ra(!0),sa),"date-time":Ze(dd(!0),gd),"iso-time":Ze(ra(),hd),"iso-date-time":Ze(dd(),yd),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:mv,"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:vv,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:pv,int32:{type:"number",validate:yv},int64:{type:"number",validate:_v},float:{type:"number",validate:md},double:{type:"number",validate:md},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Ze(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ia),time:Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,sa),"date-time":Ze(/^\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,gd),"iso-time":Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,hd),"iso-date-time":Ze(/^\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,yd),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};et.formatNames=Object.keys(et.fullFormats);function cv(t){return t%4===0&&(t%100!==0||t%400===0)}var lv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uv=[0,31,28,31,30,31,30,31,31,30,31,30,31];function pd(t){let e=lv.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&cv(n)?29:uv[r])}function ia(t,e){if(t&&e)return t>e?1:t<e?-1:0}var na=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ra(t){return function(n){let r=na.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,l=+(r[6]||0),u=+(r[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,h=o-l*c-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function sa(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function hd(t,e){if(!(t&&e))return;let n=na.exec(t),r=na.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var oa=/t|\s/i;function dd(t){let e=ra(t);return function(r){let o=r.split(oa);return o.length===2&&pd(o[0])&&e(o[1])}}function gd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function yd(t,e){if(!(t&&e))return;let[n,r]=t.split(oa),[o,i]=e.split(oa),s=ia(n,o);if(s!==void 0)return s||sa(r,i)}var dv=/\/|:/,fv=/^(?:[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 mv(t){return dv.test(t)&&fv.test(t)}var fd=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function pv(t){return fd.lastIndex=0,fd.test(t)}var hv=-(2**31),gv=2**31-1;function yv(t){return Number.isInteger(t)&&t<=gv&&t>=hv}function _v(t){return Number.isInteger(t)}function md(){return!0}var wv=/[^\\]\\Z/;function vv(t){if(wv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var wd=_(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.formatLimitDefinition=void 0;var bv=Fo(),qe=A(),At=qe.operators,Bo={formatMaximum:{okStr:"<=",ok:At.LTE,fail:At.GT},formatMinimum:{okStr:">=",ok:At.GTE,fail:At.LT},formatExclusiveMaximum:{okStr:"<",ok:At.LT,fail:At.GTE},formatExclusiveMinimum:{okStr:">",ok:At.GT,fail:At.LTE}},Sv={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Bo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Bo[t].okStr}, limit: ${e}}`};Nn.formatLimitDefinition={keyword:Object.keys(Bo),type:"string",schemaType:"string",$data:!0,error:Sv,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new bv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let h=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,qe._)`${h}[${c.schemaCode}]`);t.fail$data((0,qe.or)((0,qe._)`typeof ${p} != "object"`,(0,qe._)`${p} instanceof RegExp`,(0,qe._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=c.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${h}" does not define "compare" function`);let f=e.scopeValue("formats",{key:h,ref:p,code:s.code.formats?(0,qe._)`${s.code.formats}${(0,qe.getProperty)(h)}`:void 0});t.fail$data(d(f))}function d(h){return(0,qe._)`${h}.compare(${n}, ${r}) ${Bo[o].fail} 0`}},dependencies:["format"]};var Ev=t=>(t.addKeyword(Nn.formatLimitDefinition),t);Nn.default=Ev});var la=_((Or,Sd)=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});var Mn=_d(),$v=wd(),aa=A(),vd=new aa.Name("fullFormats"),kv=new aa.Name("fastFormats"),ca=(t,e={keywords:!0})=>{if(Array.isArray(e))return bd(t,e,Mn.fullFormats,vd),t;let[n,r]=e.mode==="fast"?[Mn.fastFormats,kv]:[Mn.fullFormats,vd],o=e.formats||Mn.formatNames;return bd(t,o,n,r),e.keywords&&(0,$v.default)(t),t};ca.get=(t,e="full")=>{let r=(e==="fast"?Mn.fastFormats:Mn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function bd(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,aa._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Sd.exports=Or=ca;Object.defineProperty(Or,"__esModule",{value:!0});Or.default=ca});var mt=_((eP,Cd)=>{"use strict";var Ad=["nodebuffer","arraybuffer","fragments"],xd=typeof Blob<"u";xd&&Ad.push("blob");Cd.exports={BINARY_TYPES:Ad,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:xd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Nr=_((tP,qo)=>{"use strict";var{EMPTY_BUFFER:jv}=mt(),da=Buffer[Symbol.species];function Dv(t,e){if(t.length===0)return jv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let o=0;o<t.length;o++){let i=t[o];n.set(i,r),r+=i.length}return r<e?new da(n.buffer,n.byteOffset,r):n}function Id(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function Od(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Fv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function fa(t){if(fa.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new da(t):ArrayBuffer.isView(t)?e=new da(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),fa.readOnly=!1),e}qo.exports={concat:Dv,mask:Id,toArrayBuffer:Fv,toBuffer:fa,unmask:Od};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Z("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Id(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?Od(e,n):t.unmask(e,n)}}catch{}});var Ld=_((nP,Md)=>{"use strict";var Nd=Symbol("kDone"),ma=Symbol("kRun"),pa=class{constructor(e){this[Nd]=()=>{this.pending--,this[ma]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ma]()}[ma](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Nd])}}};Md.exports=pa});var Bn=_((rP,Bd)=>{"use strict";var Mr=Z("zlib"),jd=Nr(),Bv=Ld(),{kStatusCode:Dd}=mt(),qv=Buffer[Symbol.species],Uv=Buffer.from([0,0,255,255]),Ho=Symbol("permessage-deflate"),pt=Symbol("total-length"),Dn=Symbol("callback"),xt=Symbol("buffers"),Fn=Symbol("error"),Uo,ha=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Uo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Uo=new Bv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Dn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),e}decompress(e,n,r){Uo.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Uo.add(o=>{this._compress(e,n,(i,s)=>{o(),r(i,s)})})}_decompress(e,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Mr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Mr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ho]=this,this._inflate[pt]=0,this._inflate[xt]=[],this._inflate.on("error",Wv),this._inflate.on("data",Fd)}this._inflate[Dn]=r,this._inflate.write(e),n&&this._inflate.write(Uv),this._inflate.flush(()=>{let i=this._inflate[Fn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=jd.concat(this._inflate[xt],this._inflate[pt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pt]=0,this._inflate[xt]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Mr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Mr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[pt]=0,this._deflate[xt]=[],this._deflate.on("data",Hv)}this._deflate[Dn]=r,this._deflate.write(e),this._deflate.flush(Mr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=jd.concat(this._deflate[xt],this._deflate[pt]);n&&(i=new qv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Dn]=null,this._deflate[pt]=0,this._deflate[xt]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Bd.exports=ha;function Hv(t){this[xt].push(t),this[pt]+=t.length}function Fd(t){if(this[pt]+=t.length,this[Ho]._maxPayload<1||this[pt]<=this[Ho]._maxPayload){this[xt].push(t);return}this[Fn]=new RangeError("Max payload size exceeded"),this[Fn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fn][Dd]=1009,this.removeListener("data",Fd),this.reset()}function Wv(t){if(this[Ho]._inflate=null,this[Fn]){this[Dn](this[Fn]);return}t[Dd]=1007,this[Dn](t)}});var qn=_((oP,Wo)=>{"use strict";var{isUtf8:qd}=Z("buffer"),{hasBlob:Vv}=mt(),Gv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function zv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ga(t){let e=t.length,n=0;for(;n<e;)if(!(t[n]&128))n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Kv(t){return Vv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Wo.exports={isBlob:Kv,isValidStatusCode:zv,isValidUTF8:ga,tokenChars:Gv};if(qd)Wo.exports.isValidUTF8=function(t){return t.length<24?ga(t):qd(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Z("utf-8-validate");Wo.exports.isValidUTF8=function(e){return e.length<32?ga(e):t(e)}}catch{}});var ba=_((iP,Kd)=>{"use strict";var{Writable:Jv}=Z("stream"),Ud=Bn(),{BINARY_TYPES:Yv,EMPTY_BUFFER:Hd,kStatusCode:Qv,kWebSocket:Xv}=mt(),{concat:ya,toArrayBuffer:Zv,unmask:eb}=Nr(),{isValidStatusCode:tb,isValidUTF8:Wd}=qn(),Vo=Buffer[Symbol.species],Ne=0,Vd=1,Gd=2,zd=3,_a=4,wa=5,Go=6,va=class extends Jv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Yv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Xv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ne}_write(e,n,r){if(this._opcode===8&&this._state==Ne)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Vo(r.buffer,r.byteOffset+e,r.length-e),new Vo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],o=n.length-e;e>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),o),this._buffers[0]=new Vo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case Vd:this.getPayloadLength16(e);break;case Gd:this.getPayloadLength64(e);break;case zd:this.getMask();break;case _a:this.getData(e);break;case wa:case Go:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if(n[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Ud.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Vd:this._payloadLength===127?this._state=Gd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=zd:this._state=_a}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=_a}getData(e){let n=Hd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&eb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=wa,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Ud.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return n(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===Ne&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=ya(r,n):this._binaryType==="arraybuffer"?o=Zv(ya(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Ne):(this._state=Go,setImmediate(()=>{this.emit("message",o,!0),this._state=Ne,this.startLoop(e)}))}else{let o=ya(r,n);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===wa||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Ne):(this._state=Go,setImmediate(()=>{this.emit("message",o,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Hd),this.end();else{let r=e.readUInt16BE(0);if(!tb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Vo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Go,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(n)}))}createError(e,n,r,o,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[Qv]=o,s}};Kd.exports=va});var $a=_((aP,Qd)=>{"use strict";var{Duplex:sP}=Z("stream"),{randomFillSync:nb}=Z("crypto"),Jd=Bn(),{EMPTY_BUFFER:rb,kWebSocket:ob,NOOP:ib}=mt(),{isBlob:Un,isValidStatusCode:sb}=qn(),{mask:Yd,toBuffer:tn}=Nr(),Me=Symbol("kByteLength"),ab=Buffer.alloc(4),zo=8*1024,nn,Hn=zo,Ue=0,cb=1,lb=2,Sa=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ue,this.onerror=ib,this[ob]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||ab,n.generateMask?n.generateMask(r):(Hn===zo&&(nn===void 0&&(nn=Buffer.alloc(zo)),nb(nn,0,zo),Hn=0),r[0]=nn[Hn++],r[1]=nn[Hn++],r[2]=nn[Hn++],r[3]=nn[Hn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[Me]!==void 0?a=n[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,o=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(o?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],s?[l,e]:o?(Yd(e,r,l,i,a),[l]):(Yd(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=rb;else{if(typeof e!="number"||!sb(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let s={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ue?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Un(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Me]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Un(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Un(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Me]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Un(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Jd.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Un(e)?(a=e.size,c=!1):(e=tn(e),a=e.length,c=tn.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Un(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ue?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Me],this._state=lb,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ea,this,a,o);return}this._bufferedBytes-=r[Me];let s=tn(i);n?this.dispatch(s,n,r,o):(this._state=Ue,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(ub,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Jd.extensionName];this._bufferedBytes+=r[Me],this._state=cb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ea(this,c,o);return}this._bufferedBytes-=r[Me],this._state=Ue,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===Ue&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Qd.exports=Sa;function Ea(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let o=t._queue[r],i=o[o.length-1];typeof i=="function"&&i(e)}}function ub(t,e,n){Ea(t,e,n),t.onerror(e)}});var af=_((cP,sf)=>{"use strict";var{kForOnEventAttribute:Lr,kListener:ka}=mt(),Xd=Symbol("kCode"),Zd=Symbol("kData"),ef=Symbol("kError"),tf=Symbol("kMessage"),nf=Symbol("kReason"),Wn=Symbol("kTarget"),rf=Symbol("kType"),of=Symbol("kWasClean"),ht=class{constructor(e){this[Wn]=null,this[rf]=e}get target(){return this[Wn]}get type(){return this[rf]}};Object.defineProperty(ht.prototype,"target",{enumerable:!0});Object.defineProperty(ht.prototype,"type",{enumerable:!0});var rn=class extends ht{constructor(e,n={}){super(e),this[Xd]=n.code===void 0?0:n.code,this[nf]=n.reason===void 0?"":n.reason,this[of]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Xd]}get reason(){return this[nf]}get wasClean(){return this[of]}};Object.defineProperty(rn.prototype,"code",{enumerable:!0});Object.defineProperty(rn.prototype,"reason",{enumerable:!0});Object.defineProperty(rn.prototype,"wasClean",{enumerable:!0});var Vn=class extends ht{constructor(e,n={}){super(e),this[ef]=n.error===void 0?null:n.error,this[tf]=n.message===void 0?"":n.message}get error(){return this[ef]}get message(){return this[tf]}};Object.defineProperty(Vn.prototype,"error",{enumerable:!0});Object.defineProperty(Vn.prototype,"message",{enumerable:!0});var jr=class extends ht{constructor(e,n={}){super(e),this[Zd]=n.data===void 0?null:n.data}get data(){return this[Zd]}};Object.defineProperty(jr.prototype,"data",{enumerable:!0});var db={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[Lr]&&o[ka]===e&&!o[Lr])return;let r;if(t==="message")r=function(i,s){let a=new jr("message",{data:s?i:i.toString()});a[Wn]=this,Ko(e,this,a)};else if(t==="close")r=function(i,s){let a=new rn("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Wn]=this,Ko(e,this,a)};else if(t==="error")r=function(i){let s=new Vn("error",{error:i,message:i.message});s[Wn]=this,Ko(e,this,s)};else if(t==="open")r=function(){let i=new ht("open");i[Wn]=this,Ko(e,this,i)};else return;r[Lr]=!!n[Lr],r[ka]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ka]===e&&!n[Lr]){this.removeListener(t,n);break}}};sf.exports={CloseEvent:rn,ErrorEvent:Vn,Event:ht,EventTarget:db,MessageEvent:jr};function Ko(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jo=_((lP,cf)=>{"use strict";var{tokenChars:Dr}=qn();function tt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function fb(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Dr[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);l===44?(tt(e,p,n),n=Object.create(null)):s=p,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Dr[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),tt(n,t.slice(c,u),!0),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Dr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Dr[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Dr[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);r&&(p=p.replace(/\\/g,""),r=!1),tt(n,a,p),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let h=t.slice(c,u);return s===void 0?tt(e,h,n):(a===void 0?tt(n,h,!0):r?tt(n,a,h.replace(/\\/g,"")):tt(n,a,h),tt(e,s,n)),e}function mb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}cf.exports={format:mb,parse:fb}});var Zo=_((fP,vf)=>{"use strict";var pb=Z("events"),hb=Z("https"),gb=Z("http"),df=Z("net"),yb=Z("tls"),{randomBytes:_b,createHash:wb}=Z("crypto"),{Duplex:uP,Readable:dP}=Z("stream"),{URL:Ra}=Z("url"),Ct=Bn(),vb=ba(),bb=$a(),{isBlob:Sb}=qn(),{BINARY_TYPES:lf,CLOSE_TIMEOUT:Eb,EMPTY_BUFFER:Yo,GUID:$b,kForOnEventAttribute:Pa,kListener:kb,kStatusCode:Rb,kWebSocket:re,NOOP:ff}=mt(),{EventTarget:{addEventListener:Pb,removeEventListener:Tb}}=af(),{format:Ab,parse:xb}=Jo(),{toBuffer:Cb}=Nr(),mf=Symbol("kAborted"),Ta=[8,13],gt=["CONNECTING","OPEN","CLOSING","CLOSED"],Ib=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends pb{constructor(e,n,r){super(),this._binaryType=lf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),pf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){lf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let o=new vb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new bb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[re]=this,i[re]=this,e[re]=this,o.on("conclude",Mb),o.on("drain",Lb),o.on("error",jb),o.on("message",Db),o.on("ping",Fb),o.on("pong",Bb),i.onerror=qb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",yf),e.on("data",Xo),e.on("end",_f),e.on("error",wf),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ct.extensionName]&&this._extensions[Ct.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ke(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),gf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Aa(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Aa(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Aa(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ct.extensionName]||(o.compress=!1),this._sender.send(e||Yo,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ke(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(V.prototype,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(V,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Pa])return e[kb];return null},set(e){for(let n of this.listeners(t))if(n[Pa]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Pa]:!0})}})});V.prototype.addEventListener=Pb;V.prototype.removeEventListener=Tb;vf.exports=V;function pf(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Eb,protocolVersion:Ta[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Ta.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ta.join(", ")})`);let i;if(e instanceof Ra)i=e;else try{i=new Ra(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Qo(t,m);return}let l=s?443:80,u=_b(16).toString("base64"),d=s?hb.request:gb.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?Nb:Ob),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new Ct({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Ab({[Ct.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Ib.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let m=o.path.split(":");o.socketPath=m[0],o.path=m[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,y]of Object.entries(m))r.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,m||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=d(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(o);o.timeout&&f.on("timeout",()=>{ke(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[mf]||(f=t._req=null,Qo(t,m))}),f.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&o.followRedirects&&y>=300&&y<400){if(++t._redirects>o.maxRedirects){ke(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new Ra(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Qo(t,R);return}pf(t,v,n,r)}else t.emit("unexpected-response",f,m)||ke(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==V.CONNECTING)return;f=t._req=null;let v=m.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){ke(t,g,"Invalid Upgrade header");return}let S=wb("sha1").update(u+$b).digest("base64");if(m.headers["sec-websocket-accept"]!==S){ke(t,g,"Invalid Sec-WebSocket-Accept header");return}let R=m.headers["sec-websocket-protocol"],k;if(R!==void 0?h.size?h.has(R)||(k="Server sent an invalid subprotocol"):k="Server sent a subprotocol but none was requested":h.size&&(k="Server sent no subprotocol"),k){ke(t,g,k);return}R&&(t._protocol=R);let G=m.headers["sec-websocket-extensions"];if(G!==void 0){if(!p){ke(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Q;try{Q=xb(G)}catch{ke(t,g,"Invalid Sec-WebSocket-Extensions header");return}let oe=Object.keys(Q);if(oe.length!==1||oe[0]!==Ct.extensionName){ke(t,g,"Server indicated an extension that was not requested");return}try{p.accept(Q[Ct.extensionName])}catch{ke(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ct.extensionName]=p}t.setSocket(g,y,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Qo(t,e){t._readyState=V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ob(t){return t.path=t.socketPath,df.connect(t)}function Nb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=df.isIP(t.host)?"":t.host),yb.connect(t)}function ke(t,e,n){t._readyState=V.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ke),e.setHeader?(e[mf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Aa(t,e,n){if(e){let r=Sb(e)?e.size:Cb(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${gt[t.readyState]})`);process.nextTick(n,r)}}function Mb(t,e){let n=this[re];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[re]!==void 0&&(n._socket.removeListener("data",Xo),process.nextTick(hf,n._socket),t===1005?n.close():n.close(t,e))}function Lb(){let t=this[re];t.isPaused||t._socket.resume()}function jb(t){let e=this[re];e._socket[re]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(hf,e._socket),e.close(t[Rb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function uf(){this[re].emitClose()}function Db(t,e){this[re].emit("message",t,e)}function Fb(t){let e=this[re];e._autoPong&&e.pong(t,!this._isServer,ff),e.emit("ping",t)}function Bb(t){this[re].emit("pong",t)}function hf(t){t.resume()}function qb(t){let e=this[re];e.readyState!==V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,gf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function gf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function yf(){let t=this[re];if(this.removeListener("close",yf),this.removeListener("data",Xo),this.removeListener("end",_f),t._readyState=V.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[re]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",uf),t._receiver.on("finish",uf))}function Xo(t){this[re]._receiver.write(t)||this.pause()}function _f(){let t=this[re];t._readyState=V.CLOSING,t._receiver.end(),this.end()}function wf(){let t=this[re];this.removeListener("error",wf),this.on("error",ff),t&&(t._readyState=V.CLOSING,this.destroy())}});var $f=_((pP,Ef)=>{"use strict";var mP=Zo(),{Duplex:Ub}=Z("stream");function bf(t){t.emit("close")}function Hb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Sf(t){this.removeListener("error",Sf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wb(t,e){let n=!0,r=new Ub({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(bf,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick(bf,r)}),n&&t.terminate()},r._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(o,i,s)});return}t.send(o,s)},r.on("end",Hb),r.on("error",Sf),r}Ef.exports=Wb});var xa=_((hP,kf)=>{"use strict";var{tokenChars:Vb}=qn();function Gb(t){let e=new Set,n=-1,r=-1,o=0;for(o;o<t.length;o++){let s=t.charCodeAt(o);if(r===-1&&Vb[s]===1)n===-1&&(n=o);else if(o!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=o);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}kf.exports={parse:Gb}});var If=_((yP,Cf)=>{"use strict";var zb=Z("events"),ei=Z("http"),{Duplex:gP}=Z("stream"),{createHash:Kb}=Z("crypto"),Rf=Jo(),on=Bn(),Jb=xa(),Yb=Zo(),{CLOSE_TIMEOUT:Qb,GUID:Xb,kWebSocket:Zb}=mt(),eS=/^[+/0-9A-Za-z]{22}==$/,Pf=0,Tf=1,xf=2,Ca=class extends zb{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Qb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Yb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ei.createServer((r,o)=>{let i=ei.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=tS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Pf}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===xf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Fr,this);return}if(e&&this.once("close",e),this._state!==Tf)if(this._state=Tf,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Fr,this):process.nextTick(Fr,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Fr(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,o){n.on("error",Af);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sn(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){sn(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!eS.test(i)){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Br(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Jb.parse(c)}catch{sn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let h=new on({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Rf.parse(u);p[on.extensionName]&&(h.accept(p[on.extensionName]),d[on.extensionName]=h)}catch{sn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,f,m,g)=>{if(!p)return Br(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(h))return Br(n,401)}this.completeUpgrade(d,i,l,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[Zb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Pf)return Br(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Kb("sha1").update(n+Xb).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[on.extensionName]){let d=e[on.extensionName].params,h=Rf.format({[on.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
10
+ deps: ${n}}`};var tw={keyword:"dependencies",type:"object",schemaType:"object",error:Xe.error,code(t){let[e,n]=nw(t);Nu(t,e),Mu(t,n)}};function nw({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Nu(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let i=n.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Or.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let l of a)(0,Or.checkReportMissingProp)(t,l)}):(n.if((0,js._)`${c} && (${(0,Or.checkMissingProp)(t,a,i)})`),(0,Or.reportMissingProp)(t,i),n.else())}}Xe.validatePropertyDeps=Nu;function Mu(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,ew.alwaysValidSchema)(i,e[a])||(n.if((0,Or.propertyInData)(n,r,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),t.ok(s))}Xe.validateSchemaDeps=Mu;Xe.default=tw});var Du=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var ju=A(),rw=M(),ow={message:"property name must be valid",params:({params:t})=>(0,ju._)`{propertyName: ${t.propertyName}}`},iw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ow,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,rw.alwaysValidSchema)(o,n))return;let i=e.name("valid");e.forIn("key",r,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,ju.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Ds.default=iw});var Bs=_(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Io=Ie(),Be=A(),sw=ut(),Oo=M(),aw={message:"must NOT have additional properties",params:({params:t})=>(0,Be._)`{additionalProperty: ${t.additionalProperty}}`},cw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Oo.alwaysValidSchema)(s,n))return;let l=(0,Io.allSchemaProperties)(r.properties),u=(0,Io.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Be._)`${i} === ${sw.default.errors}`);function d(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(h(g),()=>f(g))})}function h(g){let y;if(l.length>8){let v=(0,Oo.schemaRefOrVal)(s,r.properties,"properties");y=(0,Io.isOwnProperty)(e,v,g)}else l.length?y=(0,Be.or)(...l.map(v=>(0,Be._)`${g} === ${v}`)):y=Be.nil;return u.length&&(y=(0,Be.or)(y,...u.map(v=>(0,Be._)`${(0,Io.usePattern)(t,v)}.test(${g})`))),(0,Be.not)(y)}function p(g){e.code((0,Be._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){p(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Oo.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Be.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Be.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Oo.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Fs.default=cw});var qu=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var lw=wr(),Fu=Ie(),qs=M(),Bu=Bs(),uw={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t;i.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Bu.default.code(new lw.KeywordCxt(i,Bu.default,"additionalProperties"));let s=(0,Fu.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=qs.mergeEvaluated.props(e,(0,qs.toHash)(s),i.props));let a=s.filter(d=>!(0,qs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Fu.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Us.default=uw});var Wu=_(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var Uu=Ie(),No=A(),Hu=M(),Gu=M(),dw={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,Uu.allSchemaProperties)(n),c=a.filter(m=>(0,Hu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof No.Name)&&(i.props=(0,Gu.evaluatedPropsToName)(e,i.props));let{props:d}=i;h();function h(){for(let m of a)l&&p(m),i.allErrors?f(m):(e.var(u,!0),f(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,Hu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,No._)`${(0,Uu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:Gu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,No._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,No.not)(u),()=>e.break())})})}}};Hs.default=dw});var Vu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var fw=M(),mw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,fw.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Gs.default=mw});var zu=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var pw=Ie(),hw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:pw.validateUnion,error:{message:"must match a schema in anyOf"}};Ws.default=hw});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Mo=A(),gw=M(),yw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},_w={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yw,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let i=n,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((u,d)=>{let h;(0,gw.alwaysValidSchema)(o,u)?e.var(c,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Mo.Name)})})}}};Vs.default=_w});var Ju=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var ww=M(),vw={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((i,s)=>{if((0,ww.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};zs.default=vw});var Xu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Lo=A(),Qu=M(),bw={message:({params:t})=>(0,Lo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Lo._)`{failingKeyword: ${t.ifClause}}`},Sw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:bw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Qu.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Yu(r,"then"),i=Yu(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,Lo.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(h,s),d?e.assign(d,(0,Lo._)`${u}`):t.setParams({ifClause:u})}}}};function Yu(t,e){let n=t.schema[e];return n!==void 0&&!(0,Qu.alwaysValidSchema)(t,n)}Ks.default=Sw});var Zu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Ew=M(),kw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,Ew.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Js.default=kw});var ed=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var $w=Is(),Rw=Cu(),Pw=Os(),Tw=Iu(),Aw=Ou(),Cw=Lu(),xw=Du(),Iw=Bs(),Ow=qu(),Nw=Wu(),Mw=Vu(),Lw=zu(),jw=Ku(),Dw=Ju(),Fw=Xu(),Bw=Zu();function qw(t=!1){let e=[Mw.default,Lw.default,jw.default,Dw.default,Fw.default,Bw.default,xw.default,Iw.default,Cw.default,Ow.default,Nw.default];return t?e.push(Rw.default,Tw.default):e.push($w.default,Pw.default),e.push(Aw.default),e}Ys.default=qw});var td=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Y=A(),Uw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Hw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Uw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?h():p();function h(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=n.const("fDef",(0,Y._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Y._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Y._)`${m}.type || "string"`).assign(y,(0,Y._)`${m}.validate`),()=>n.assign(g,(0,Y._)`"string"`).assign(y,m)),t.fail$data((0,Y.or)(v(),S()));function v(){return c.strictSchema===!1?Y.nil:(0,Y._)`${s} && !${y}`}function S(){let R=u.$async?(0,Y._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Y._)`${y}(${r})`,$=(0,Y._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Y._)`${y} && ${y} !== true && ${g} === ${e} && !${$}`}}function p(){let f=d.formats[i];if(!f){v();return}if(f===!0)return;let[m,g,y]=S(f);m===e&&t.pass(R());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function S($){let z=$ instanceof RegExp?(0,Y.regexpCode)($):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,Q=n.scopeValue("formats",{key:i,ref:$,code:z});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Y._)`${Q}.validate`]:["string",$,Q]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${y}(${r})`}return typeof g=="function"?(0,Y._)`${y}(${r})`:(0,Y._)`${y}.test(${r})`}}}};Qs.default=Hw});var nd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Gw=td(),Ww=[Gw.default];Xs.default=Ww});var rd=_(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var id=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Vw=fu(),zw=Ru(),Kw=ed(),Jw=nd(),od=rd(),Yw=[Vw.default,zw.default,(0,Kw.default)(),Jw.default,od.metadataVocabulary,od.contentVocabulary];Zs.default=Yw});var ad=_(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.DiscrError=void 0;var sd;(function(t){t.Tag="tag",t.Mapping="mapping"})(sd||(jo.DiscrError=sd={}))});var ld=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var In=A(),ea=ad(),cd=wo(),Qw=vr(),Xw=M(),Zw={message:({params:{discrError:t,tagName:e}})=>t===ea.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,In._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},ev={keyword:"discriminator",type:"object",schemaType:"object",error:Zw,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,In._)`${n}${(0,In.getProperty)(a)}`);e.if((0,In._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:ea.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=h();e.if(!1);for(let f in p)e.elseIf((0,In._)`${l} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:ea.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(m,In.Name),f}function h(){var p;let f={},m=y(o),g=!0;for(let R=0;R<s.length;R++){let $=s[R];if($?.$ref&&!(0,Xw.schemaHasRulesButRef)($,i.self.RULES)){let Q=$.$ref;if($=cd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Q),$ instanceof cd.SchemaEnv&&($=$.schema),$===void 0)throw new Qw.default(i.opts.uriResolver,i.baseId,Q)}let z=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y($)),v(z,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function v(R,$){if(R.const)S(R.const,$);else if(R.enum)for(let z of R.enum)S(z,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(R,$){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=$}}}};ta.default=ev});var ud=_((DR,tv)=>{tv.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 Fo=_((G,na)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.MissingRefError=G.ValidationError=G.CodeGen=G.Name=G.nil=G.stringify=G.str=G._=G.KeywordCxt=G.Ajv=void 0;var nv=su(),rv=id(),ov=ld(),dd=ud(),iv=["/properties"],Do="http://json-schema.org/draft-07/schema",On=class extends nv.default{_addVocabularies(){super._addVocabularies(),rv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ov.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(dd,iv):dd;this.addMetaSchema(e,Do,!1),this.refs["http://json-schema.org/schema"]=Do}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Do)?Do:void 0)}};G.Ajv=On;na.exports=G=On;na.exports.Ajv=On;Object.defineProperty(G,"__esModule",{value:!0});G.default=On;var sv=wr();Object.defineProperty(G,"KeywordCxt",{enumerable:!0,get:function(){return sv.KeywordCxt}});var Nn=A();Object.defineProperty(G,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(G,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(G,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(G,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(G,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(G,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var av=yo();Object.defineProperty(G,"ValidationError",{enumerable:!0,get:function(){return av.default}});var cv=vr();Object.defineProperty(G,"MissingRefError",{enumerable:!0,get:function(){return cv.default}})});var wd=_(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Ze(t,e){return{validate:t,compare:e}}et.fullFormats={date:Ze(hd,sa),time:Ze(oa(!0),aa),"date-time":Ze(fd(!0),yd),"iso-time":Ze(oa(),gd),"iso-date-time":Ze(fd(),_d),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pv,"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:bv,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:hv,int32:{type:"number",validate:_v},int64:{type:"number",validate:wv},float:{type:"number",validate:pd},double:{type:"number",validate:pd},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Ze(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sa),time:Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aa),"date-time":Ze(/^\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,yd),"iso-time":Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gd),"iso-date-time":Ze(/^\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,_d),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};et.formatNames=Object.keys(et.fullFormats);function lv(t){return t%4===0&&(t%100!==0||t%400===0)}var uv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dv=[0,31,28,31,30,31,30,31,31,30,31,30,31];function hd(t){let e=uv.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&lv(n)?29:dv[r])}function sa(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ra=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function oa(t){return function(n){let r=ra.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,l=+(r[6]||0),u=+(r[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,h=o-l*c-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function aa(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function gd(t,e){if(!(t&&e))return;let n=ra.exec(t),r=ra.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var ia=/t|\s/i;function fd(t){let e=oa(t);return function(r){let o=r.split(ia);return o.length===2&&hd(o[0])&&e(o[1])}}function yd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function _d(t,e){if(!(t&&e))return;let[n,r]=t.split(ia),[o,i]=e.split(ia),s=sa(n,o);if(s!==void 0)return s||aa(r,i)}var fv=/\/|:/,mv=/^(?:[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 pv(t){return fv.test(t)&&mv.test(t)}var md=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hv(t){return md.lastIndex=0,md.test(t)}var gv=-(2**31),yv=2**31-1;function _v(t){return Number.isInteger(t)&&t<=yv&&t>=gv}function wv(t){return Number.isInteger(t)}function pd(){return!0}var vv=/[^\\]\\Z/;function bv(t){if(vv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var vd=_(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.formatLimitDefinition=void 0;var Sv=Fo(),qe=A(),At=qe.operators,Bo={formatMaximum:{okStr:"<=",ok:At.LTE,fail:At.GT},formatMinimum:{okStr:">=",ok:At.GTE,fail:At.LT},formatExclusiveMaximum:{okStr:"<",ok:At.LT,fail:At.GTE},formatExclusiveMinimum:{okStr:">",ok:At.GT,fail:At.LTE}},Ev={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Bo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Bo[t].okStr}, limit: ${e}}`};Mn.formatLimitDefinition={keyword:Object.keys(Bo),type:"string",schemaType:"string",$data:!0,error:Ev,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Sv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let h=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,qe._)`${h}[${c.schemaCode}]`);t.fail$data((0,qe.or)((0,qe._)`typeof ${p} != "object"`,(0,qe._)`${p} instanceof RegExp`,(0,qe._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=c.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${h}" does not define "compare" function`);let f=e.scopeValue("formats",{key:h,ref:p,code:s.code.formats?(0,qe._)`${s.code.formats}${(0,qe.getProperty)(h)}`:void 0});t.fail$data(d(f))}function d(h){return(0,qe._)`${h}.compare(${n}, ${r}) ${Bo[o].fail} 0`}},dependencies:["format"]};var kv=t=>(t.addKeyword(Mn.formatLimitDefinition),t);Mn.default=kv});var ua=_((Nr,Ed)=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});var Ln=wd(),$v=vd(),ca=A(),bd=new ca.Name("fullFormats"),Rv=new ca.Name("fastFormats"),la=(t,e={keywords:!0})=>{if(Array.isArray(e))return Sd(t,e,Ln.fullFormats,bd),t;let[n,r]=e.mode==="fast"?[Ln.fastFormats,Rv]:[Ln.fullFormats,bd],o=e.formats||Ln.formatNames;return Sd(t,o,n,r),e.keywords&&(0,$v.default)(t),t};la.get=(t,e="full")=>{let r=(e==="fast"?Ln.fastFormats:Ln.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Sd(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ca._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Ed.exports=Nr=la;Object.defineProperty(Nr,"__esModule",{value:!0});Nr.default=la});var pt=_((aP,Id)=>{"use strict";var Cd=["nodebuffer","arraybuffer","fragments"],xd=typeof Blob<"u";xd&&Cd.push("blob");Id.exports={BINARY_TYPES:Cd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:xd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Mr=_((cP,qo)=>{"use strict";var{EMPTY_BUFFER:Dv}=pt(),fa=Buffer[Symbol.species];function Fv(t,e){if(t.length===0)return Dv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let o=0;o<t.length;o++){let i=t[o];n.set(i,r),r+=i.length}return r<e?new fa(n.buffer,n.byteOffset,r):n}function Od(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function Nd(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Bv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ma(t){if(ma.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new fa(t):ArrayBuffer.isView(t)?e=new fa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ma.readOnly=!1),e}qo.exports={concat:Fv,mask:Od,toArrayBuffer:Bv,toBuffer:ma,unmask:Nd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Z("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Od(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?Nd(e,n):t.unmask(e,n)}}catch{}});var jd=_((lP,Ld)=>{"use strict";var Md=Symbol("kDone"),pa=Symbol("kRun"),ha=class{constructor(e){this[Md]=()=>{this.pending--,this[pa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[pa]()}[pa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Md])}}};Ld.exports=ha});var qn=_((uP,qd)=>{"use strict";var Lr=Z("zlib"),Dd=Mr(),qv=jd(),{kStatusCode:Fd}=pt(),Uv=Buffer[Symbol.species],Hv=Buffer.from([0,0,255,255]),Ho=Symbol("permessage-deflate"),ht=Symbol("total-length"),Fn=Symbol("callback"),Ct=Symbol("buffers"),Bn=Symbol("error"),Uo,ga=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Uo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Uo=new qv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Fn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),e}decompress(e,n,r){Uo.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Uo.add(o=>{this._compress(e,n,(i,s)=>{o(),r(i,s)})})}_decompress(e,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Lr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Lr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ho]=this,this._inflate[ht]=0,this._inflate[Ct]=[],this._inflate.on("error",Wv),this._inflate.on("data",Bd)}this._inflate[Fn]=r,this._inflate.write(e),n&&this._inflate.write(Hv),this._inflate.flush(()=>{let i=this._inflate[Bn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Dd.concat(this._inflate[Ct],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[Ct]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Lr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Lr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[ht]=0,this._deflate[Ct]=[],this._deflate.on("data",Gv)}this._deflate[Fn]=r,this._deflate.write(e),this._deflate.flush(Lr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Dd.concat(this._deflate[Ct],this._deflate[ht]);n&&(i=new Uv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Fn]=null,this._deflate[ht]=0,this._deflate[Ct]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};qd.exports=ga;function Gv(t){this[Ct].push(t),this[ht]+=t.length}function Bd(t){if(this[ht]+=t.length,this[Ho]._maxPayload<1||this[ht]<=this[Ho]._maxPayload){this[Ct].push(t);return}this[Bn]=new RangeError("Max payload size exceeded"),this[Bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Bn][Fd]=1009,this.removeListener("data",Bd),this.reset()}function Wv(t){if(this[Ho]._inflate=null,this[Bn]){this[Fn](this[Bn]);return}t[Fd]=1007,this[Fn](t)}});var Un=_((dP,Go)=>{"use strict";var{isUtf8:Ud}=Z("buffer"),{hasBlob:Vv}=pt(),zv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Kv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ya(t){let e=t.length,n=0;for(;n<e;)if(!(t[n]&128))n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Jv(t){return Vv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Go.exports={isBlob:Jv,isValidStatusCode:Kv,isValidUTF8:ya,tokenChars:zv};if(Ud)Go.exports.isValidUTF8=function(t){return t.length<24?ya(t):Ud(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Z("utf-8-validate");Go.exports.isValidUTF8=function(e){return e.length<32?ya(e):t(e)}}catch{}});var Sa=_((fP,Jd)=>{"use strict";var{Writable:Yv}=Z("stream"),Hd=qn(),{BINARY_TYPES:Qv,EMPTY_BUFFER:Gd,kStatusCode:Xv,kWebSocket:Zv}=pt(),{concat:_a,toArrayBuffer:eb,unmask:tb}=Mr(),{isValidStatusCode:nb,isValidUTF8:Wd}=Un(),Wo=Buffer[Symbol.species],Me=0,Vd=1,zd=2,Kd=3,wa=4,va=5,Vo=6,ba=class extends Yv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Qv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Zv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Me}_write(e,n,r){if(this._opcode===8&&this._state==Me)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e),new Wo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],o=n.length-e;e>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),o),this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Me:this.getInfo(e);break;case Vd:this.getPayloadLength16(e);break;case zd:this.getPayloadLength64(e);break;case Kd:this.getMask();break;case wa:this.getData(e);break;case va:case Vo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if(n[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Hd.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Vd:this._payloadLength===127?this._state=zd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Kd:this._state=wa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wa}getData(e){let n=Gd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&tb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=va,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hd.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return n(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===Me&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Me;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=_a(r,n):this._binaryType==="arraybuffer"?o=eb(_a(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!0),this._state=Me,this.startLoop(e)}))}else{let o=_a(r,n);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===va||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!1),this._state=Me,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gd),this.end();else{let r=e.readUInt16BE(0);if(!nb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Me;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Me,this.startLoop(n)}))}createError(e,n,r,o,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[Xv]=o,s}};Jd.exports=ba});var $a=_((pP,Xd)=>{"use strict";var{Duplex:mP}=Z("stream"),{randomFillSync:rb}=Z("crypto"),Yd=qn(),{EMPTY_BUFFER:ob,kWebSocket:ib,NOOP:sb}=pt(),{isBlob:Hn,isValidStatusCode:ab}=Un(),{mask:Qd,toBuffer:tn}=Mr(),Le=Symbol("kByteLength"),cb=Buffer.alloc(4),zo=8*1024,nn,Gn=zo,Ue=0,lb=1,ub=2,Ea=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ue,this.onerror=sb,this[ib]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||cb,n.generateMask?n.generateMask(r):(Gn===zo&&(nn===void 0&&(nn=Buffer.alloc(zo)),rb(nn,0,zo),Gn=0),r[0]=nn[Gn++],r[1]=nn[Gn++],r[2]=nn[Gn++],r[3]=nn[Gn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[Le]!==void 0?a=n[Le]:(e=Buffer.from(e),a=e.length):(a=e.length,o=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(o?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],s?[l,e]:o?(Qd(e,r,l,i,a),[l]):(Qd(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=ob;else{if(typeof e!="number"||!ab(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let s={[Le]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ue?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Le]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Le]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Yd.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Hn(e)?(a=e.size,c=!1):(e=tn(e),a=e.length,c=tn.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[Le]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ue?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Le],this._state=ub,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ka,this,a,o);return}this._bufferedBytes-=r[Le];let s=tn(i);n?this.dispatch(s,n,r,o):(this._state=Ue,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(db,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Yd.extensionName];this._bufferedBytes+=r[Le],this._state=lb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ka(this,c,o);return}this._bufferedBytes-=r[Le],this._state=Ue,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===Ue&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Le],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Xd.exports=Ea;function ka(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let o=t._queue[r],i=o[o.length-1];typeof i=="function"&&i(e)}}function db(t,e,n){ka(t,e,n),t.onerror(e)}});var cf=_((hP,af)=>{"use strict";var{kForOnEventAttribute:jr,kListener:Ra}=pt(),Zd=Symbol("kCode"),ef=Symbol("kData"),tf=Symbol("kError"),nf=Symbol("kMessage"),rf=Symbol("kReason"),Wn=Symbol("kTarget"),of=Symbol("kType"),sf=Symbol("kWasClean"),gt=class{constructor(e){this[Wn]=null,this[of]=e}get target(){return this[Wn]}get type(){return this[of]}};Object.defineProperty(gt.prototype,"target",{enumerable:!0});Object.defineProperty(gt.prototype,"type",{enumerable:!0});var rn=class extends gt{constructor(e,n={}){super(e),this[Zd]=n.code===void 0?0:n.code,this[rf]=n.reason===void 0?"":n.reason,this[sf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Zd]}get reason(){return this[rf]}get wasClean(){return this[sf]}};Object.defineProperty(rn.prototype,"code",{enumerable:!0});Object.defineProperty(rn.prototype,"reason",{enumerable:!0});Object.defineProperty(rn.prototype,"wasClean",{enumerable:!0});var Vn=class extends gt{constructor(e,n={}){super(e),this[tf]=n.error===void 0?null:n.error,this[nf]=n.message===void 0?"":n.message}get error(){return this[tf]}get message(){return this[nf]}};Object.defineProperty(Vn.prototype,"error",{enumerable:!0});Object.defineProperty(Vn.prototype,"message",{enumerable:!0});var Dr=class extends gt{constructor(e,n={}){super(e),this[ef]=n.data===void 0?null:n.data}get data(){return this[ef]}};Object.defineProperty(Dr.prototype,"data",{enumerable:!0});var fb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[jr]&&o[Ra]===e&&!o[jr])return;let r;if(t==="message")r=function(i,s){let a=new Dr("message",{data:s?i:i.toString()});a[Wn]=this,Ko(e,this,a)};else if(t==="close")r=function(i,s){let a=new rn("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Wn]=this,Ko(e,this,a)};else if(t==="error")r=function(i){let s=new Vn("error",{error:i,message:i.message});s[Wn]=this,Ko(e,this,s)};else if(t==="open")r=function(){let i=new gt("open");i[Wn]=this,Ko(e,this,i)};else return;r[jr]=!!n[jr],r[Ra]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Ra]===e&&!n[jr]){this.removeListener(t,n);break}}};af.exports={CloseEvent:rn,ErrorEvent:Vn,Event:gt,EventTarget:fb,MessageEvent:Dr};function Ko(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jo=_((gP,lf)=>{"use strict";var{tokenChars:Fr}=Un();function tt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function mb(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);l===44?(tt(e,p,n),n=Object.create(null)):s=p,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),tt(n,t.slice(c,u),!0),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Fr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Fr[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);r&&(p=p.replace(/\\/g,""),r=!1),tt(n,a,p),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let h=t.slice(c,u);return s===void 0?tt(e,h,n):(a===void 0?tt(n,h,!0):r?tt(n,a,h.replace(/\\/g,"")):tt(n,a,h),tt(e,s,n)),e}function pb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lf.exports={format:pb,parse:mb}});var Zo=_((wP,bf)=>{"use strict";var hb=Z("events"),gb=Z("https"),yb=Z("http"),ff=Z("net"),_b=Z("tls"),{randomBytes:wb,createHash:vb}=Z("crypto"),{Duplex:yP,Readable:_P}=Z("stream"),{URL:Pa}=Z("url"),xt=qn(),bb=Sa(),Sb=$a(),{isBlob:Eb}=Un(),{BINARY_TYPES:uf,CLOSE_TIMEOUT:kb,EMPTY_BUFFER:Yo,GUID:$b,kForOnEventAttribute:Ta,kListener:Rb,kStatusCode:Pb,kWebSocket:oe,NOOP:mf}=pt(),{EventTarget:{addEventListener:Tb,removeEventListener:Ab}}=cf(),{format:Cb,parse:xb}=Jo(),{toBuffer:Ib}=Mr(),pf=Symbol("kAborted"),Aa=[8,13],yt=["CONNECTING","OPEN","CLOSING","CLOSED"],Ob=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends hb{constructor(e,n,r){super(),this._binaryType=uf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),hf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let o=new bb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Sb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[oe]=this,i[oe]=this,e[oe]=this,o.on("conclude",Lb),o.on("drain",jb),o.on("error",Db),o.on("message",Fb),o.on("ping",Bb),o.on("pong",qb),i.onerror=Ub,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",_f),e.on("data",Xo),e.on("end",wf),e.on("error",vf),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[xt.extensionName]&&this._extensions[xt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),yf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xt.extensionName]||(o.compress=!1),this._sender.send(e||Yo,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(V.prototype,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(V,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ta])return e[Rb];return null},set(e){for(let n of this.listeners(t))if(n[Ta]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ta]:!0})}})});V.prototype.addEventListener=Tb;V.prototype.removeEventListener=Ab;bf.exports=V;function hf(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kb,protocolVersion:Aa[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Aa.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Aa.join(", ")})`);let i;if(e instanceof Pa)i=e;else try{i=new Pa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Qo(t,m);return}let l=s?443:80,u=wb(16).toString("base64"),d=s?gb.request:yb.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?Mb:Nb),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new xt({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Cb({[xt.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Ob.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let m=o.path.split(":");o.socketPath=m[0],o.path=m[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,y]of Object.entries(m))r.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,m||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=d(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(o);o.timeout&&f.on("timeout",()=>{$e(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[pf]||(f=t._req=null,Qo(t,m))}),f.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&o.followRedirects&&y>=300&&y<400){if(++t._redirects>o.maxRedirects){$e(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new Pa(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Qo(t,R);return}hf(t,v,n,r)}else t.emit("unexpected-response",f,m)||$e(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==V.CONNECTING)return;f=t._req=null;let v=m.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){$e(t,g,"Invalid Upgrade header");return}let S=vb("sha1").update(u+$b).digest("base64");if(m.headers["sec-websocket-accept"]!==S){$e(t,g,"Invalid Sec-WebSocket-Accept header");return}let R=m.headers["sec-websocket-protocol"],$;if(R!==void 0?h.size?h.has(R)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":h.size&&($="Server sent no subprotocol"),$){$e(t,g,$);return}R&&(t._protocol=R);let z=m.headers["sec-websocket-extensions"];if(z!==void 0){if(!p){$e(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Q;try{Q=xb(z)}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ie=Object.keys(Q);if(ie.length!==1||ie[0]!==xt.extensionName){$e(t,g,"Server indicated an extension that was not requested");return}try{p.accept(Q[xt.extensionName])}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xt.extensionName]=p}t.setSocket(g,y,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Qo(t,e){t._readyState=V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Nb(t){return t.path=t.socketPath,ff.connect(t)}function Mb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ff.isIP(t.host)?"":t.host),_b.connect(t)}function $e(t,e,n){t._readyState=V.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[pf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ca(t,e,n){if(e){let r=Eb(e)?e.size:Ib(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${yt[t.readyState]})`);process.nextTick(n,r)}}function Lb(t,e){let n=this[oe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[oe]!==void 0&&(n._socket.removeListener("data",Xo),process.nextTick(gf,n._socket),t===1005?n.close():n.close(t,e))}function jb(){let t=this[oe];t.isPaused||t._socket.resume()}function Db(t){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(gf,e._socket),e.close(t[Pb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function df(){this[oe].emitClose()}function Fb(t,e){this[oe].emit("message",t,e)}function Bb(t){let e=this[oe];e._autoPong&&e.pong(t,!this._isServer,mf),e.emit("ping",t)}function qb(t){this[oe].emit("pong",t)}function gf(t){t.resume()}function Ub(t){let e=this[oe];e.readyState!==V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,yf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function _f(){let t=this[oe];if(this.removeListener("close",_f),this.removeListener("data",Xo),this.removeListener("end",wf),t._readyState=V.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[oe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",df),t._receiver.on("finish",df))}function Xo(t){this[oe]._receiver.write(t)||this.pause()}function wf(){let t=this[oe];t._readyState=V.CLOSING,t._receiver.end(),this.end()}function vf(){let t=this[oe];this.removeListener("error",vf),this.on("error",mf),t&&(t._readyState=V.CLOSING,this.destroy())}});var $f=_((bP,kf)=>{"use strict";var vP=Zo(),{Duplex:Hb}=Z("stream");function Sf(t){t.emit("close")}function Gb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ef(t){this.removeListener("error",Ef),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wb(t,e){let n=!0,r=new Hb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(Sf,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick(Sf,r)}),n&&t.terminate()},r._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(o,i,s)});return}t.send(o,s)},r.on("end",Gb),r.on("error",Ef),r}kf.exports=Wb});var xa=_((SP,Rf)=>{"use strict";var{tokenChars:Vb}=Un();function zb(t){let e=new Set,n=-1,r=-1,o=0;for(o;o<t.length;o++){let s=t.charCodeAt(o);if(r===-1&&Vb[s]===1)n===-1&&(n=o);else if(o!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=o);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Rf.exports={parse:zb}});var Of=_((kP,If)=>{"use strict";var Kb=Z("events"),ei=Z("http"),{Duplex:EP}=Z("stream"),{createHash:Jb}=Z("crypto"),Pf=Jo(),on=qn(),Yb=xa(),Qb=Zo(),{CLOSE_TIMEOUT:Xb,GUID:Zb,kWebSocket:eS}=pt(),tS=/^[+/0-9A-Za-z]{22}==$/,Tf=0,Af=1,xf=2,Ia=class extends Kb{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Xb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Qb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ei.createServer((r,o)=>{let i=ei.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=nS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Tf}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===xf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Br,this);return}if(e&&this.once("close",e),this._state!==Af)if(this._state=Af,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Br,this):process.nextTick(Br,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Br(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,o){n.on("error",Cf);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sn(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){sn(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!tS.test(i)){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qr(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Yb.parse(c)}catch{sn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let h=new on({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Pf.parse(u);p[on.extensionName]&&(h.accept(p[on.extensionName]),d[on.extensionName]=h)}catch{sn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,f,m,g)=>{if(!p)return qr(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(h))return qr(n,401)}this.completeUpgrade(d,i,l,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[eS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Tf)return qr(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Jb("sha1").update(n+Zb).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[on.extensionName]){let d=e[on.extensionName].params,h=Pf.format({[on.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
11
11
  `).join(`\r
12
- `)),i.removeListener("error",Af),u.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Fr,this)})),a(u,o)}};Cf.exports=Ca;function tS(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Fr(t){t._state=xf,t.emit("close")}function Af(){this.destroy()}function Br(t,e,n,r){n=n||ei.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ei.STATUS_CODES[e]}\r
12
+ `)),i.removeListener("error",Cf),u.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Br,this)})),a(u,o)}};If.exports=Ia;function nS(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Br(t){t._state=xf,t.emit("close")}function Cf(){this.destroy()}function qr(t,e,n,r){n=n||ei.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ei.STATUS_CODES[e]}\r
13
13
  `+Object.keys(r).map(o=>`${o}: ${r[o]}`).join(`\r
14
14
  `)+`\r
15
15
  \r
16
- `+n)}function sn(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,sn),t.emit("wsClientError",s,n,e)}else Br(n,r,o,i)}});var kc={"-v":"version","-h":"help"};function Ep(t){return t.startsWith("--")?!0:kc[t]!==void 0}function Rc(t,e){let n=[],r={},o=[],i=new Map;for(let c of e)i.set(c.name,c);let s=!1,a=0;for(;a<t.length;){let c=t[a];if(s){n.push(c),a+=1;continue}if(c==="--"){s=!0,a+=1;continue}if(c.startsWith("--")){let l=c.indexOf("="),u=l>=0?c.slice(2,l):c.slice(2),d=l>=0?c.slice(l+1):void 0,h=i.get(u);if(!h){o.push(`unknown flag: --${u}`),a+=1;continue}if(h.type==="boolean"){d===void 0||d==="true"?r[u]=!0:d==="false"?r[u]=!1:o.push(`flag --${u} expects no value (got "${d}")`),a+=1;continue}let p;if(d!==void 0)p=d,a+=1;else{let f=t[a+1];if(f===void 0||Ep(f)){o.push(`flag --${u} requires a value`),a+=1;continue}p=f,a+=2}if(h.type==="number"){if(!/^-?\d+(\.\d+)?$/.test(p)){o.push(`flag --${u} requires a number (got "${p}")`);continue}r[u]=Number(p);continue}r[u]=p;continue}if(c.startsWith("-")&&c.length>1){let l=kc[c];if(!l){o.push(`unknown flag: ${c}`),a+=1;continue}let u=i.get(l);if(!u||u.type!=="boolean"){o.push(`unknown flag: ${c}`),a+=1;continue}r[l]=!0,a+=1;continue}n.push(c),a+=1}for(let c of e)c.default!==void 0&&r[c.name]===void 0&&(r[c.name]=c.default);for(let c of e)c.required&&r[c.name]===void 0&&o.push(`missing required flag: --${c.name}`);return{positional:n,flags:r,errors:o}}import Ac from"node:path";import xc from"node:fs";import Pc from"node:fs";import $p from"node:os";import Tc from"node:path";var kp=Tc.join(".aifight","runtime");function ne(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Tc.join($p.homedir(),kp)}function it(){let t=ne();if(Pc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{Pc.chmodSync(t,448)}catch{}}var $e=class extends Error{name="RuntimeFilesError";kind;filePath;constructor(e,n,r){super(r),this.kind=e,this.filePath=n}};function Rp(){return Ac.join(ne(),"token")}function Pp(){return Ac.join(ne(),"port")}function Cc(){let t=Rp(),e;try{e=xc.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new $e("token_missing",t,`token file not found at ${t}; AIFight Bridge must be running`):new $e("token_corrupt",t,`failed to read token file at ${t}: ${r.message}`)}let n=e.trim();if(n.length===0)throw new $e("token_corrupt",t,`token file at ${t} is empty`);return n}function Ic(){let t=Pp(),e;try{e=xc.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new $e("port_missing",t,`port file not found at ${t}; AIFight Bridge must be running`):new $e("port_corrupt",t,`failed to read port file at ${t}: ${o.message}`)}let n=e.trim();if(n.length===0)throw new $e("port_corrupt",t,`port file at ${t} is empty`);if(!/^-?\d+$/.test(n))throw new $e("port_corrupt",t,`port file at ${t} is not a number: "${n}"`);let r=Number.parseInt(n,10);if(r<1||r>65535)throw new $e("port_corrupt",t,`port file at ${t} is out of range [1, 65535]: ${r}`);return r}var Tp=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function Ap(t){return typeof t=="string"&&Tp.has(t)}function xp(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let n=e;return Ap(n.code)&&typeof n.message=="string"}var me=class extends Error{name="ControlClientError";kind;serverCode;status;body;cause;constructor(e,n,r){super(n),this.kind=e,this.serverCode=r?.serverCode,this.status=r?.status??0,this.body=r?.body,this.cause=r?.cause}},Cp="127.0.0.1",Ip=1e4;function Oc(t){let e=t.host??Cp,n=t.baseTimeoutMs??Ip,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new me("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new me("runtime_files_corrupt",`corrupt runtime files: ${f.message}`,{cause:f})}function a(){if(o!==void 0&&i!==void 0)return{token:o,port:i};try{let f=t.tokenSource(),m=t.portSource();return o=f,i=m,{token:f,port:m}}catch(f){throw f instanceof $e?s(f):f}}function c(){let f=o,m=i;try{let g=t.tokenSource(),y=t.portSource();return o=g,i=y,{token:g,port:y,changed:g!==f||y!==m}}catch(g){throw g instanceof $e?s(g):g}}function l(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function u(f,m,g,y){let v={Authorization:`Bearer ${g}`},S;return m===void 0?S=void 0:(v["Content-Type"]="application/json",S=JSON.stringify(m)),{method:f,headers:v,body:S,signal:y}}async function d(f,m,g,y,v){let S=`http://${e}:${v}${m}`,R=new AbortController,k=setTimeout(()=>{R.abort()},n);try{let G;try{G=await r(S,u(f,g,y,R.signal))}catch(oe){throw l(oe)?new me("request_timeout",`request timed out after ${n}ms`,{cause:oe}):new me("daemon_unreachable",`AIFight Bridge not running: ${oe.message}`,{cause:oe})}let Q;try{Q=await G.text()}catch(oe){throw l(oe)?new me("request_timeout",`request timed out after ${n}ms`,{cause:oe}):new me("transport_unparseable",`failed to read response body (status ${G.status})`,{status:G.status,cause:oe})}if(Q.length===0)return{status:G.status,parsedBody:void 0,parseFailed:!1};try{return{status:G.status,parsedBody:JSON.parse(Q),parseFailed:!1}}catch{return{status:G.status,parsedBody:Q,parseFailed:!0}}}finally{clearTimeout(k)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new me("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!xp(f.parsedBody))throw new me("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new me("server_error",m.error.message,{serverCode:m.error.code,status:f.status,body:m})}async function p(f,m,g){let y=a(),v=await d(f,m,g,y.token,y.port);if(v.status!==401)return h(v);let S=c();if(!S.changed)throw new me("auth_failed","token mismatch \u2014 daemon rejected the cached credentials and the token / port files have not been rotated",{status:401});t.onLog&&t.onLog({code:"rebootstrap",message:"rebootstrap reason=401"});let R=await d(f,m,g,S.token,S.port);if(R.status===401)throw new me("auth_failed","token mismatch \u2014 daemon still rejected after reread + retry",{status:401});return h(R)}return{get(f){return p("GET",f,void 0)},post(f,m){return p("POST",f,m)},delete(f){return p("DELETE",f,void 0)}}}function Nc(t,e={}){return Oc({tokenSource:Cc,portSource:Ic,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var pe=["texas_holdem","liars_dice","coup"];function st(t){return pe.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},z=class extends Error{name="CommandError";code;exitCode;hint;constructor(e,n,r={}){super(n),this.code=e,this.exitCode=r.exitCode??1,r.hint!==void 0&&(this.hint=r.hint)}};function J(t,e,n,r){let o=t.positional.length;if(o<e)throw new O(`missing required positional argument${e===1?"":"s"}`,r);if(o>n){let i=t.positional.slice(n).join(" ");throw new O(`unexpected extra positional argument${o-n===1?"":"s"}: ${i}`,r)}}function to(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
- `}import ro from"node:fs";import rr from"node:path";import{fileURLToPath as Op}from"node:url";var Mc=["./schemas","../../../protocol/schema","../../protocol/schema"],no=null;function or(t=Np()){if(no)return no;for(let e of Mc){let n=rr.resolve(t,e);if(Lc(n)&&Lc(rr.join(n,"messages")))return no=n,no}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Mc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function Np(){return rr.dirname(Op(import.meta.url))}function Lc(t){try{return ro.statSync(t).isDirectory()}catch{return!1}}var Mp={welcome:"messages/server_welcome.schema.json",queue_joined:"messages/server_queue_joined.schema.json",queue_left:"messages/server_queue_left.schema.json",match_confirm_request:"messages/server_match_confirm_request.schema.json",match_cancelled:"messages/server_match_cancelled.schema.json",game_start:"messages/server_game_start.schema.json",readiness_check:"messages/server_readiness_check.schema.json",action_request:"messages/server_action_request.schema.json",event:"messages/server_event.schema.json",game_state:"messages/server_game_state.schema.json",game_over:"messages/server_game_over.schema.json",error:"messages/server_error.schema.json",join_queue:"messages/client_join_queue.schema.json",leave_queue:"messages/client_leave_queue.schema.json",match_confirm:"messages/client_match_confirm.schema.json",action:"messages/client_action.schema.json",runtime_status:"messages/client_runtime_status.schema.json"};function gi(){return Object.keys(Mp)}function qt(){let t=or(),e=new Map;return Dc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=ro.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function Dc(t,e){for(let n of ro.readdirSync(t,{withFileTypes:!0})){let r=rr.join(t,n.name);n.isDirectory()?Dc(r,e):n.isFile()&&e(r)}}var jc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function yi(t){let e=jc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(jc).join(", ")}`);let n=or(),r=rr.join(n,e),o=ro.readFileSync(r,"utf8");return JSON.parse(o)}var Ed=Ae(Fo(),1),$d=Ae(la(),1);var Ln=class extends Error{},ft=class extends Ln{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Xt=class extends Ln{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},Zt=class extends Ln{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var Rv=3e4,en="/api/agents/register",Pv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",jn=null;function Tv(){if(jn)return jn;let t=new Ed.default({strict:!1,allErrors:!0});(0,$d.default)(t);let e=qt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(Pv);if(n)return jn=n,jn;let r=yi("register_response");return jn=t.compile(r),jn}async function ua(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??Rv,r=t.baseUrl.replace(/\/+$/,"")+en,o=AbortSignal.timeout(n),i=t.signal?AbortSignal.any([o,t.signal]):o,s;try{s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.request),signal:i})}catch(p){if(o.aborted)throw new ft(`POST ${en} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new ft(`POST ${en} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new ft(`POST ${en} failed: ${f}`,p)}let a=await s.text(),c,l=null;if(a.length>0)try{c=JSON.parse(a)}catch(p){l=p instanceof Error?p:new Error(String(p))}if(s.status!==201){let p=c&&typeof c=="object"&&c!==null&&"error"in c?c:a;throw new Xt(s.status,p,`POST ${en} returned HTTP ${s.status}`)}if(l!==null)throw new Zt([],`POST ${en} returned 201 with non-JSON body: ${l.message}`);if(typeof c!="object"||c===null)throw new Zt([],`POST ${en} returned 201 with non-object body`);let u=Tv();if(!u(c)){let p=(u.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new Zt(p,"register_response schema validation failed")}let h=c;return{response:h,apiKey:h.agent.api_key,claimToken:h.claim_token,agentId:h.agent.id,claimUrl:h.claim_url}}import qR from"better-sqlite3";var kd=`-- runtime/src/store/schema.sql
16
+ `+n)}function sn(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,sn),t.emit("wsClientError",s,n,e)}else qr(n,r,o,i)}});var Rc={"-v":"version","-h":"help"};function kp(t){return t.startsWith("--")?!0:Rc[t]!==void 0}function Pc(t,e){let n=[],r={},o=[],i=new Map;for(let c of e)i.set(c.name,c);let s=!1,a=0;for(;a<t.length;){let c=t[a];if(s){n.push(c),a+=1;continue}if(c==="--"){s=!0,a+=1;continue}if(c.startsWith("--")){let l=c.indexOf("="),u=l>=0?c.slice(2,l):c.slice(2),d=l>=0?c.slice(l+1):void 0,h=i.get(u);if(!h){o.push(`unknown flag: --${u}`),a+=1;continue}if(h.type==="boolean"){d===void 0||d==="true"?r[u]=!0:d==="false"?r[u]=!1:o.push(`flag --${u} expects no value (got "${d}")`),a+=1;continue}let p;if(d!==void 0)p=d,a+=1;else{let f=t[a+1];if(f===void 0||kp(f)){o.push(`flag --${u} requires a value`),a+=1;continue}p=f,a+=2}if(h.type==="number"){if(!/^-?\d+(\.\d+)?$/.test(p)){o.push(`flag --${u} requires a number (got "${p}")`);continue}r[u]=Number(p);continue}r[u]=p;continue}if(c.startsWith("-")&&c.length>1){let l=Rc[c];if(!l){o.push(`unknown flag: ${c}`),a+=1;continue}let u=i.get(l);if(!u||u.type!=="boolean"){o.push(`unknown flag: ${c}`),a+=1;continue}r[l]=!0,a+=1;continue}n.push(c),a+=1}for(let c of e)c.default!==void 0&&r[c.name]===void 0&&(r[c.name]=c.default);for(let c of e)c.required&&r[c.name]===void 0&&o.push(`missing required flag: --${c.name}`);return{positional:n,flags:r,errors:o}}import Cc from"node:path";import xc from"node:fs";import Tc from"node:fs";import $p from"node:os";import Ac from"node:path";var Rp=Ac.join(".aifight","runtime");function re(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Ac.join($p.homedir(),Rp)}function st(){let t=re();if(Tc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{Tc.chmodSync(t,448)}catch{}}var ke=class extends Error{name="RuntimeFilesError";kind;filePath;constructor(e,n,r){super(r),this.kind=e,this.filePath=n}};function Pp(){return Cc.join(re(),"token")}function Tp(){return Cc.join(re(),"port")}function Ic(){let t=Pp(),e;try{e=xc.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new ke("token_missing",t,`token file not found at ${t}; AIFight Bridge must be running`):new ke("token_corrupt",t,`failed to read token file at ${t}: ${r.message}`)}let n=e.trim();if(n.length===0)throw new ke("token_corrupt",t,`token file at ${t} is empty`);return n}function Oc(){let t=Tp(),e;try{e=xc.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new ke("port_missing",t,`port file not found at ${t}; AIFight Bridge must be running`):new ke("port_corrupt",t,`failed to read port file at ${t}: ${o.message}`)}let n=e.trim();if(n.length===0)throw new ke("port_corrupt",t,`port file at ${t} is empty`);if(!/^-?\d+$/.test(n))throw new ke("port_corrupt",t,`port file at ${t} is not a number: "${n}"`);let r=Number.parseInt(n,10);if(r<1||r>65535)throw new ke("port_corrupt",t,`port file at ${t} is out of range [1, 65535]: ${r}`);return r}var Ap=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function Cp(t){return typeof t=="string"&&Ap.has(t)}function xp(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let n=e;return Cp(n.code)&&typeof n.message=="string"}var me=class extends Error{name="ControlClientError";kind;serverCode;status;body;cause;constructor(e,n,r){super(n),this.kind=e,this.serverCode=r?.serverCode,this.status=r?.status??0,this.body=r?.body,this.cause=r?.cause}},Ip="127.0.0.1",Op=1e4;function Nc(t){let e=t.host??Ip,n=t.baseTimeoutMs??Op,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new me("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new me("runtime_files_corrupt",`corrupt runtime files: ${f.message}`,{cause:f})}function a(){if(o!==void 0&&i!==void 0)return{token:o,port:i};try{let f=t.tokenSource(),m=t.portSource();return o=f,i=m,{token:f,port:m}}catch(f){throw f instanceof ke?s(f):f}}function c(){let f=o,m=i;try{let g=t.tokenSource(),y=t.portSource();return o=g,i=y,{token:g,port:y,changed:g!==f||y!==m}}catch(g){throw g instanceof ke?s(g):g}}function l(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function u(f,m,g,y){let v={Authorization:`Bearer ${g}`},S;return m===void 0?S=void 0:(v["Content-Type"]="application/json",S=JSON.stringify(m)),{method:f,headers:v,body:S,signal:y}}async function d(f,m,g,y,v){let S=`http://${e}:${v}${m}`,R=new AbortController,$=setTimeout(()=>{R.abort()},n);try{let z;try{z=await r(S,u(f,g,y,R.signal))}catch(ie){throw l(ie)?new me("request_timeout",`request timed out after ${n}ms`,{cause:ie}):new me("daemon_unreachable",`AIFight Bridge not running: ${ie.message}`,{cause:ie})}let Q;try{Q=await z.text()}catch(ie){throw l(ie)?new me("request_timeout",`request timed out after ${n}ms`,{cause:ie}):new me("transport_unparseable",`failed to read response body (status ${z.status})`,{status:z.status,cause:ie})}if(Q.length===0)return{status:z.status,parsedBody:void 0,parseFailed:!1};try{return{status:z.status,parsedBody:JSON.parse(Q),parseFailed:!1}}catch{return{status:z.status,parsedBody:Q,parseFailed:!0}}}finally{clearTimeout($)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new me("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!xp(f.parsedBody))throw new me("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new me("server_error",m.error.message,{serverCode:m.error.code,status:f.status,body:m})}async function p(f,m,g){let y=a(),v=await d(f,m,g,y.token,y.port);if(v.status!==401)return h(v);let S=c();if(!S.changed)throw new me("auth_failed","token mismatch \u2014 daemon rejected the cached credentials and the token / port files have not been rotated",{status:401});t.onLog&&t.onLog({code:"rebootstrap",message:"rebootstrap reason=401"});let R=await d(f,m,g,S.token,S.port);if(R.status===401)throw new me("auth_failed","token mismatch \u2014 daemon still rejected after reread + retry",{status:401});return h(R)}return{get(f){return p("GET",f,void 0)},post(f,m){return p("POST",f,m)},delete(f){return p("DELETE",f,void 0)}}}function Mc(t,e={}){return Nc({tokenSource:Ic,portSource:Oc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var pe=["texas_holdem","liars_dice","coup"];function at(t){return pe.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},W=class extends Error{name="CommandError";code;exitCode;hint;constructor(e,n,r={}){super(n),this.code=e,this.exitCode=r.exitCode??1,r.hint!==void 0&&(this.hint=r.hint)}};function J(t,e,n,r){let o=t.positional.length;if(o<e)throw new O(`missing required positional argument${e===1?"":"s"}`,r);if(o>n){let i=t.positional.slice(n).join(" ");throw new O(`unexpected extra positional argument${o-n===1?"":"s"}: ${i}`,r)}}function to(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
+ `}import ro from"node:fs";import or from"node:path";import{fileURLToPath as Np}from"node:url";var Lc=["./schemas","../../../protocol/schema","../../protocol/schema"],no=null;function ir(t=Mp()){if(no)return no;for(let e of Lc){let n=or.resolve(t,e);if(jc(n)&&jc(or.join(n,"messages")))return no=n,no}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Lc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function Mp(){return or.dirname(Np(import.meta.url))}function jc(t){try{return ro.statSync(t).isDirectory()}catch{return!1}}var Lp={welcome:"messages/server_welcome.schema.json",queue_joined:"messages/server_queue_joined.schema.json",queue_left:"messages/server_queue_left.schema.json",match_confirm_request:"messages/server_match_confirm_request.schema.json",match_cancelled:"messages/server_match_cancelled.schema.json",game_start:"messages/server_game_start.schema.json",readiness_check:"messages/server_readiness_check.schema.json",action_request:"messages/server_action_request.schema.json",event:"messages/server_event.schema.json",game_state:"messages/server_game_state.schema.json",game_over:"messages/server_game_over.schema.json",error:"messages/server_error.schema.json",join_queue:"messages/client_join_queue.schema.json",leave_queue:"messages/client_leave_queue.schema.json",match_confirm:"messages/client_match_confirm.schema.json",action:"messages/client_action.schema.json",runtime_status:"messages/client_runtime_status.schema.json"};function yi(){return Object.keys(Lp)}function qt(){let t=ir(),e=new Map;return Fc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=ro.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function Fc(t,e){for(let n of ro.readdirSync(t,{withFileTypes:!0})){let r=or.join(t,n.name);n.isDirectory()?Fc(r,e):n.isFile()&&e(r)}}var Dc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function _i(t){let e=Dc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Dc).join(", ")}`);let n=ir(),r=or.join(n,e),o=ro.readFileSync(r,"utf8");return JSON.parse(o)}var kd=Ce(Fo(),1),$d=Ce(ua(),1);var jn=class extends Error{},mt=class extends jn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Xt=class extends jn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},Zt=class extends jn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var Pv=3e4,en="/api/agents/register",Tv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Dn=null;function Av(){if(Dn)return Dn;let t=new kd.default({strict:!1,allErrors:!0});(0,$d.default)(t);let e=qt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(Tv);if(n)return Dn=n,Dn;let r=_i("register_response");return Dn=t.compile(r),Dn}async function da(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??Pv,r=t.baseUrl.replace(/\/+$/,"")+en,o=AbortSignal.timeout(n),i=t.signal?AbortSignal.any([o,t.signal]):o,s;try{s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.request),signal:i})}catch(p){if(o.aborted)throw new mt(`POST ${en} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new mt(`POST ${en} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new mt(`POST ${en} failed: ${f}`,p)}let a=await s.text(),c,l=null;if(a.length>0)try{c=JSON.parse(a)}catch(p){l=p instanceof Error?p:new Error(String(p))}if(s.status!==201){let p=c&&typeof c=="object"&&c!==null&&"error"in c?c:a;throw new Xt(s.status,p,`POST ${en} returned HTTP ${s.status}`)}if(l!==null)throw new Zt([],`POST ${en} returned 201 with non-JSON body: ${l.message}`);if(typeof c!="object"||c===null)throw new Zt([],`POST ${en} returned 201 with non-object body`);let u=Av();if(!u(c)){let p=(u.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new Zt(p,"register_response schema validation failed")}let h=c;return{response:h,apiKey:h.agent.api_key,claimToken:h.claim_token,agentId:h.agent.id,claimUrl:h.claim_url}}import KR from"better-sqlite3";var Rd=`-- runtime/src/store/schema.sql
18
18
  -- AUTO-APPLIED by src/store/sqlite.ts as the v1 migration step.
19
19
  -- DO NOT edit this file by hand \u2014 this is v1's BYTE SOURCE (bundled
20
20
  -- into SCHEMA_SQL_V1 by bundle-schema.mjs). M1-05 appended a v2
@@ -49,7 +49,7 @@ CREATE TABLE IF NOT EXISTS agents (
49
49
  );
50
50
 
51
51
  CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
52
- `;var Rd=[{version:1,up:t=>{t.exec(kd)}},{version:2,up:t=>{let e=t.prepare("SELECT COUNT(*) AS n FROM agents").get().n;if(e>0)throw new Error(`M1-05 migration refuses to upgrade a populated agents table (${e} rows). These rows were written in schema v1 with TEXT plaintext columns and cannot be silently reinterpreted as encrypted BLOBs. Remediation: back up the DB file, then DELETE FROM agents, then re-open to trigger migration. For a real re-encrypt migration, open a new TED.`);t.exec(`
52
+ `;var Pd=[{version:1,up:t=>{t.exec(Rd)}},{version:2,up:t=>{let e=t.prepare("SELECT COUNT(*) AS n FROM agents").get().n;if(e>0)throw new Error(`M1-05 migration refuses to upgrade a populated agents table (${e} rows). These rows were written in schema v1 with TEXT plaintext columns and cannot be silently reinterpreted as encrypted BLOBs. Remediation: back up the DB file, then DELETE FROM agents, then re-open to trigger migration. For a real re-encrypt migration, open a new TED.`);t.exec(`
53
53
  CREATE TABLE agents_new (
54
54
  id TEXT NOT NULL PRIMARY KEY,
55
55
  name TEXT NOT NULL UNIQUE,
@@ -64,103 +64,116 @@ CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
64
64
  ALTER TABLE agents_new RENAME TO agents;
65
65
  DROP INDEX IF EXISTS idx_agents_name;
66
66
  CREATE INDEX idx_agents_name ON agents(name);
67
- `)}}],VR=Rd[Rd.length-1].version;import{Entry as KR}from"@napi-rs/keyring";var Pd="AIFIGHT_KEYCHAIN_V1:",Td="AIFIGHT_CRYPTO_V1:";var QR=Buffer.byteLength(Pd,"ascii"),XR=Buffer.byteLength(Td,"ascii");var nS=Ae($f(),1),rS=Ae(Jo(),1),oS=Ae(Bn(),1),iS=Ae(ba(),1),sS=Ae($a(),1),aS=Ae(xa(),1),Ia=Ae(Zo(),1),cS=Ae(If(),1);var fe=class extends Error{},It=class extends fe{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Ot=class extends fe{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},an=class extends fe{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Nt=class extends fe{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},cn=class extends fe{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},ln=class extends fe{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends fe{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},nt=class extends fe{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},yt=class extends fe{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},_t=class extends fe{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var Of=Ae(Fo(),1),Nf=Ae(la(),1);var Na=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),Ma=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Mf="https://aifight.ai/protocol/v1/messages/";function lS(t){return`${Mf}client_${t}.schema.json`}function uS(t){return`${Mf}server_${t}.schema.json`}var Oa=null;function Lf(){if(Oa)return Oa;let t=new Of.default({strict:!1,allErrors:!0});(0,Nf.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Oa=t,t}function jf(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function Df(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ff(t){if(!Df(t))throw new nt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new nt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(Ma.has(e))throw new nt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!Na.has(e))throw new nt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...Na].join(", ")})`);let n=Lf(),r=lS(e),o=n.getSchema(r);if(!o)throw new nt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new nt(e,jf(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function La(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${l}`)}if(!Df(n))throw new Re("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Re("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!Ma.has(r))throw Na.has(r)?new yt(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new yt(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...Ma].join(", ")})`);let o=Lf(),i=uS(r),s=o.getSchema(i);if(!s)throw new Re(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Re(r,jf(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var dS=1e4,fS=25e3;function Bf(t){if(t===void 0)return"(no reason)";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return String(t)}catch{return"(unstringifiable reason)"}}var ja=class{#e;#t="connected";#n=null;#r=null;#o=null;#a=new Set;#c=new Set;#u=new Set;#g=!1;#d=null;#l=null;#i=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#s(i)}),this.#e.on("error",()=>{}),this.#e.once("close",(i,s)=>{let a=s?.toString("utf8")??"",c=this.#d??"server";this.#y({code:i,reason:a,initiator:c}),this.#t="closed",this.#_(),this.#i&&(this.#i(),this.#i=null)});let o=r.pingIntervalMs??fS;o>0&&(this.#n=setInterval(()=>{try{this.#e.ping()}catch{this.#n&&(clearInterval(this.#n),this.#n=null)}},o)),r.signal&&(this.#r=r.signal,this.#o=()=>{if(this.#t!=="closed"){this.#d="abort",this.#y({code:0,reason:"aborted",initiator:"abort"}),this.#t="closed",this.#_();try{this.#e.terminate()}catch{}}},r.signal.addEventListener("abort",this.#o,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#c.add(e),()=>{this.#c.delete(e)}}onClose(e){return this.#u.add(e),()=>{this.#u.delete(e)}}#s(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=La(n)}catch(o){if(o instanceof Re||o instanceof yt)this.#m(o);else{let i=o instanceof Error?o.message:String(o);this.#m(new Re("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#h(r)}#h(e){let n=[...this.#a];for(let r of n)this.#p(()=>r(e))}#m(e){let n=[...this.#c];for(let r of n)this.#p(()=>r(e))}#y(e){if(this.#g)return;this.#g=!0;let n=[...this.#u];for(let r of n)this.#p(()=>r(e))}#p(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new ln(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Ff(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#o&&(this.#r.removeEventListener("abort",this.#o),this.#r=null,this.#o=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#l&&await this.#l;return}this.#d="client",this.#t="closing",this.#_(),this.#l=new Promise(r=>{this.#i=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#i&&(this.#i(),this.#i=null)}await this.#l}}};async function Da(t){let e=t.welcomeTimeoutMs??dS;return t.signal?.aborted?Promise.reject(new _t(`createWSClient aborted before start: ${Bf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new Ia.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new It(`failed to construct WebSocket for ${t.url}: ${d}`,u));return}let i=!1,s=null,a=null,c=()=>{s&&(clearTimeout(s),s=null),t.signal&&a&&(t.signal.removeEventListener("abort",a),a=null),o.removeAllListeners(),o.on("error",()=>{})},l=u=>{i||(i=!0,c(),u())};t.signal&&(a=()=>{l(()=>{try{o.terminate()}catch{}r(new _t(`createWSClient aborted during handshake: ${Bf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new It(`WebSocket connect failed for ${t.url}: ${u.message}`,u))})}),o.once("unexpected-response",(u,d)=>{let h="";d.setEncoding("utf8"),d.on("data",p=>{h+=p}),d.on("end",()=>{let p=d.statusCode??0,f=d.statusMessage??"";try{u.destroy()}catch{}l(()=>r(new Ot(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;l(()=>r(new Ot(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new an(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",u=>{let d=typeof u=="string"||Buffer.isBuffer(u)?u:Buffer.from(u),h;try{h=La(d)}catch(v){let S=[],R="first frame failed to parse";v instanceof Re?(S=v.ajvErrors,R=v.messageType==="welcome"?`welcome failed schema validation: ${v.message}`:`first frame parse failure (${v.messageType}): ${v.message}`):v instanceof yt?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),l(()=>{try{o.terminate()}catch{}r(new Nt(S,R))});return}if(h.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Nt([],`expected first frame to be 'welcome', got '${h.type}'`))});return}let p=h,f=p.data.server_protocol_version,m=v=>v.startsWith("v")?v.slice(1):v,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){l(()=>{try{o.terminate()}catch{}r(new cn(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new ja(o,p,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(v)})})})}var Gn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},mS=1e3,pS=2,hS=3e4,gS="full",yS=5*60*1e3,_S=15*60*1e3,wS=new Set([1001,1006,1011,1012]);function vS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function bS(t,e){switch(e){case"none":return t;case"full":return Math.floor(Math.random()*t);case"equal":return Math.floor(t/2+Math.random()*t/2)}}function SS(t){return t.code>=4e3&&t.code<5e3?!1:wS.has(t.code)}function ES(t){if(t instanceof _t||t instanceof Nt||t instanceof cn)return!1;if(t instanceof It||t instanceof an)return!0;if(t instanceof Ot){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function $S(t){return t>=_S?"error":t>=yS?"warning":"info"}var Fa=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#o=new Set;#a=new Set;#c=0;#u=0;#g=null;#d=null;#l=!1;#i=null;#s=!1;#h=null;#m=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new ln(`cannot send while ReconnectingWSClient.state="${this.state}"`);this.#t.send(e)}onMessage(e){this.#n.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onMessage(e)),()=>{this.#n.delete(e),n&&n()}}onError(e){this.#r.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onError(e)),()=>{this.#r.delete(e),n&&n()}}onClose(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#i={code:e,reason:n},this.#h&&this.#h("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#s||this.#f({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#g=e,this.#d=n,this.#y()}async#y(){if(this.#c=Date.now(),this.#e.signal?.aborted){this.#S("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#b("attempt-start",this.attempt);let e,n=!1;try{let a=await Da({url:this.#e.url,apiKey:this.#e.apiKey,expectedProtocolVersion:this.#e.expectedProtocolVersion,welcomeTimeoutMs:this.#e.welcomeTimeoutMs,pingIntervalMs:this.#e.pingIntervalMs,signal:this.#e.signal});n=!0,this.#t=a,this.welcome=a.welcome,this.#E(a),this.state="connected";let c=this.attempt;this.attempt=0,this.#u=0,this.#b("attempt-success",c),this.#l||(this.#l=!0,this.#g?.());let l=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??l.code,closeReason:this.#i.reason??l.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!SS(l)){let u=new Gn("fatal-close",void 0,`close code ${l.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:l.code,closeReason:l.reason,cause:u});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof fe&&(e=a),!ES(a)){let c=a instanceof fe?a:void 0,l=a instanceof _t?"signal":"fatal-error",u=a instanceof Error?a.message:"non-retriable error";this.#S(l,c,u);return}this.#u++,this.state="backoff"}let r=vS(this.#u,this.#e.initialBackoffMs??mS,this.#e.backoffFactor??pS,this.#e.maxBackoffMs??hS),o=bS(r,this.#e.jitter??gS),i=this.attempt===0?1:this.attempt;if(this.#b("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#u>=this.#e.maxAttempts){this.#S("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#p(o);if(s==="abort"){this.#f({kind:"signal",cause:void 0}),this.#l||(this.#l=!0,this.#d?.(new Gn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#f({kind:"caller-close",code:this.#i?.code??1e3,closeReason:this.#i?.reason,cause:void 0});return}}}#p(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#h=null,n(c))},i=setTimeout(()=>o("timeout"),e),s=this.#e.signal,a=null;if(s){if(s.aborted){o("abort");return}a=()=>o("abort"),s.addEventListener("abort",a)}this.#h=c=>o(c)})}#_(e){return new Promise(n=>{let r=e.onClose(o=>{try{r()}catch{}n(o)})})}#E(e){this.#w();for(let n of this.#n)this.#m.push(e.onMessage(n));for(let n of this.#r)this.#m.push(e.onError(n))}#w(){for(let e of this.#m)try{e()}catch{}this.#m.length=0}#b(e,n,r,o){let i=Date.now()-this.#c,s=e==="give-up"?"error":e==="attempt-failure"?$S(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let l of c)try{l(a)}catch{}}#S(e,n,r){let o=new Gn(e,n,r);this.#f({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#l||(this.#l=!0,this.#d?.(o))}#f(e){if(this.#s)return;this.#s=!0,this.state="closed",this.#w(),this.#t=null,this.#b("give-up",this.attempt,void 0,e.cause);let n=[...this.#o];for(let r of n)try{r(e)}catch{}}};async function Ba(t){let e=new Fa(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var kS=["check","call","fold","raise","allin"];function qa(t){let{legalActions:e}=t;if(e.length===0)throw new Error("Texas Hold'em fallback requires at least one legal action");for(let n of kS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Ha(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Liar's Dice fallback requires at least one legal action");let r=n.find(i=>i.type==="bid"),o=n.find(i=>i.type==="challenge");if(r){let i=RS(r.data);if(i)return i.maxQuantity!==void 0&&i.minQuantity>i.maxQuantity?o??n[0]:{type:"bid",data:{quantity:i.minQuantity,face:i.minFace}};let s=PS(e);if(s)return typeof e.total_dice=="number"&&s.quantity>e.total_dice?o??n[0]:{type:"bid",data:s}}return o||n[0]}function RS(t){let e=TS(t);if(!e)return;let n=Ua(e,"min_quantity"),r=Ua(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Ua(e,"max_quantity")}}function PS(t){let e=t.current_bid;if(!e)return typeof t.total_dice!="number"?void 0:{quantity:1,face:1};if(!(typeof e.quantity!="number"||typeof e.face!="number"))return e.face<6?{quantity:e.quantity,face:e.face+1}:{quantity:e.quantity+1,face:1}}function TS(t){return t!==null&&typeof t=="object"?t:void 0}function Ua(t,e){let n=t[e];return typeof n=="number"?n:void 0}var AS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],xS=["pass","challenge"],CS=["pass","block"],IS=["lose_card"],OS=["return_cards"];function Wa(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Coup fallback requires at least one legal action");switch(e.phase){case"action":return qr(n,AS);case"challenge_action":case"challenge_block":return qr(n,xS);case"block":return qr(n,CS);case"lose_influence":return qr(n,IS);case"exchange_return":return qr(n,OS);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function qr(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var NS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ga(t,e,n=500){let r=t.trim(),o=jS(r),i;try{i=JSON.parse(o)}catch{return un("json_parse",r,n)}if(!ti(i))return un("missing_fields",r,n);let s=i.action;if(typeof s!="string")return un("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ti(c))return un("missing_fields",r,n);let l=ti(c)?c:void 0;if(!MS.has(s))return un("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return un("action_not_legal",r,n);if(s==="raise"){let d=LS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:un("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var MS=new Set(["fold","check","call","raise","allin"]);function LS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ti(t.data)?t.data:void 0,o=Va(r,"amount"),i=Va(r,"min")??o,s=Va(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function jS(t){let e=t.match(NS);return e?e[1].trim():t}function ti(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Va(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function un(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var DS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ka(t,e,n=500){let r=t.trim(),o=qS(r),i;try{i=JSON.parse(o)}catch{return dn("json_parse",r,n)}if(!ni(i))return dn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return dn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ni(c))return dn("missing_fields",r,n);let l=ni(c)?c:void 0;if(!FS.has(s))return dn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return dn("action_not_legal",r,n);if(s==="bid"){let d=BS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:dn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var FS=new Set(["bid","challenge"]);function BS(t,e){if(!e)return;let n=e.quantity,r=e.face;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n)||typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>6||n<1)return;let o=ni(t.data)?t.data:void 0,i=za(o,"min_quantity"),s=za(o,"min_face"),a=za(o,"max_quantity");if(!(i!==void 0&&n<i)&&!(a!==void 0&&n>a)&&!(i!==void 0&&s!==void 0&&n===i&&r<s))return{type:"bid",data:{quantity:n,face:r}}}function qS(t){let e=t.match(DS);return e?e[1].trim():t}function ni(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function za(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function dn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var US=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,HS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Ja(t,e,n=500){let r=t.trim(),o=VS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!zn(i))return fn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return fn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!zn(c))return fn("missing_fields",r,n);let l=zn(c)?c:void 0;if(!HS.has(s))return fn("unknown_action_type",r,n);let u=e.filter(h=>h.type===s);if(u.length===0)return fn("action_not_legal",r,n);let d=WS(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}function WS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>qf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>qf(o.data,"role")===r)}case"lose_card":{let r=n?.card_index;return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?void 0:e.find(o=>GS(o.data,"card_index")===r)}case"return_cards":{let r=n?.return_indices;return!Array.isArray(r)||!r.every(o=>typeof o=="number"&&Number.isFinite(o)&&Number.isInteger(o))?void 0:e.find(o=>{let i=zS(o.data,"return_indices");return i!==void 0&&KS(i,r)})}default:return e[0]}}function VS(t){let e=t.match(US);return e?e[1].trim():t}function zn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qf(t,e){if(!zn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function GS(t,e){if(!zn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function zS(t,e){if(!zn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function KS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var Se="0.1.0-alpha.2",Kf="v1.0.0";function Jf(){let t=or(),e=qt(),n=gi();return{ok:!0,runtimeVersion:Se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Ya(t,e){return J(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:Se})+`
67
+ `)}}],XR=Pd[Pd.length-1].version;import{Entry as tP}from"@napi-rs/keyring";var Td="AIFIGHT_KEYCHAIN_V1:",Ad="AIFIGHT_CRYPTO_V1:";var oP=Buffer.byteLength(Td,"ascii"),iP=Buffer.byteLength(Ad,"ascii");var rS=Ce($f(),1),oS=Ce(Jo(),1),iS=Ce(qn(),1),sS=Ce(Sa(),1),aS=Ce($a(),1),cS=Ce(xa(),1),Oa=Ce(Zo(),1),lS=Ce(Of(),1);var fe=class extends Error{},It=class extends fe{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Ot=class extends fe{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},an=class extends fe{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Nt=class extends fe{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},cn=class extends fe{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},ln=class extends fe{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends fe{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},nt=class extends fe{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},_t=class extends fe{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},wt=class extends fe{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var Nf=Ce(Fo(),1),Mf=Ce(ua(),1);var Ma=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),La=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Lf="https://aifight.ai/protocol/v1/messages/";function uS(t){return`${Lf}client_${t}.schema.json`}function dS(t){return`${Lf}server_${t}.schema.json`}var Na=null;function jf(){if(Na)return Na;let t=new Nf.default({strict:!1,allErrors:!0});(0,Mf.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Na=t,t}function Df(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function Ff(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Bf(t){if(!Ff(t))throw new nt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new nt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(La.has(e))throw new nt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!Ma.has(e))throw new nt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...Ma].join(", ")})`);let n=jf(),r=uS(e),o=n.getSchema(r);if(!o)throw new nt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new nt(e,Df(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function ja(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${l}`)}if(!Ff(n))throw new Re("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Re("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!La.has(r))throw Ma.has(r)?new _t(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new _t(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...La].join(", ")})`);let o=jf(),i=dS(r),s=o.getSchema(i);if(!s)throw new Re(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Re(r,Df(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var fS=1e4,mS=25e3;function qf(t){if(t===void 0)return"(no reason)";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return String(t)}catch{return"(unstringifiable reason)"}}var Da=class{#e;#t="connected";#n=null;#r=null;#o=null;#a=new Set;#c=new Set;#u=new Set;#g=!1;#d=null;#l=null;#i=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#s(i)}),this.#e.on("error",()=>{}),this.#e.once("close",(i,s)=>{let a=s?.toString("utf8")??"",c=this.#d??"server";this.#y({code:i,reason:a,initiator:c}),this.#t="closed",this.#_(),this.#i&&(this.#i(),this.#i=null)});let o=r.pingIntervalMs??mS;o>0&&(this.#n=setInterval(()=>{try{this.#e.ping()}catch{this.#n&&(clearInterval(this.#n),this.#n=null)}},o)),r.signal&&(this.#r=r.signal,this.#o=()=>{if(this.#t!=="closed"){this.#d="abort",this.#y({code:0,reason:"aborted",initiator:"abort"}),this.#t="closed",this.#_();try{this.#e.terminate()}catch{}}},r.signal.addEventListener("abort",this.#o,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#c.add(e),()=>{this.#c.delete(e)}}onClose(e){return this.#u.add(e),()=>{this.#u.delete(e)}}#s(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=ja(n)}catch(o){if(o instanceof Re||o instanceof _t)this.#m(o);else{let i=o instanceof Error?o.message:String(o);this.#m(new Re("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#h(r)}#h(e){let n=[...this.#a];for(let r of n)this.#p(()=>r(e))}#m(e){let n=[...this.#c];for(let r of n)this.#p(()=>r(e))}#y(e){if(this.#g)return;this.#g=!0;let n=[...this.#u];for(let r of n)this.#p(()=>r(e))}#p(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new ln(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Bf(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#o&&(this.#r.removeEventListener("abort",this.#o),this.#r=null,this.#o=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#l&&await this.#l;return}this.#d="client",this.#t="closing",this.#_(),this.#l=new Promise(r=>{this.#i=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#i&&(this.#i(),this.#i=null)}await this.#l}}};async function Fa(t){let e=t.welcomeTimeoutMs??fS;return t.signal?.aborted?Promise.reject(new wt(`createWSClient aborted before start: ${qf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new Oa.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new It(`failed to construct WebSocket for ${t.url}: ${d}`,u));return}let i=!1,s=null,a=null,c=()=>{s&&(clearTimeout(s),s=null),t.signal&&a&&(t.signal.removeEventListener("abort",a),a=null),o.removeAllListeners(),o.on("error",()=>{})},l=u=>{i||(i=!0,c(),u())};t.signal&&(a=()=>{l(()=>{try{o.terminate()}catch{}r(new wt(`createWSClient aborted during handshake: ${qf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new It(`WebSocket connect failed for ${t.url}: ${u.message}`,u))})}),o.once("unexpected-response",(u,d)=>{let h="";d.setEncoding("utf8"),d.on("data",p=>{h+=p}),d.on("end",()=>{let p=d.statusCode??0,f=d.statusMessage??"";try{u.destroy()}catch{}l(()=>r(new Ot(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;l(()=>r(new Ot(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new an(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",u=>{let d=typeof u=="string"||Buffer.isBuffer(u)?u:Buffer.from(u),h;try{h=ja(d)}catch(v){let S=[],R="first frame failed to parse";v instanceof Re?(S=v.ajvErrors,R=v.messageType==="welcome"?`welcome failed schema validation: ${v.message}`:`first frame parse failure (${v.messageType}): ${v.message}`):v instanceof _t?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),l(()=>{try{o.terminate()}catch{}r(new Nt(S,R))});return}if(h.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Nt([],`expected first frame to be 'welcome', got '${h.type}'`))});return}let p=h,f=p.data.server_protocol_version,m=v=>v.startsWith("v")?v.slice(1):v,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){l(()=>{try{o.terminate()}catch{}r(new cn(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new Da(o,p,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(v)})})})}var zn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},pS=1e3,hS=2,gS=3e4,yS="full",_S=5*60*1e3,wS=15*60*1e3,vS=new Set([1001,1006,1011,1012]);function bS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function SS(t,e){switch(e){case"none":return t;case"full":return Math.floor(Math.random()*t);case"equal":return Math.floor(t/2+Math.random()*t/2)}}function ES(t){return t.code>=4e3&&t.code<5e3?!1:vS.has(t.code)}function kS(t){if(t instanceof wt||t instanceof Nt||t instanceof cn)return!1;if(t instanceof It||t instanceof an)return!0;if(t instanceof Ot){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function $S(t){return t>=wS?"error":t>=_S?"warning":"info"}var Ba=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#o=new Set;#a=new Set;#c=0;#u=0;#g=null;#d=null;#l=!1;#i=null;#s=!1;#h=null;#m=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new ln(`cannot send while ReconnectingWSClient.state="${this.state}"`);this.#t.send(e)}onMessage(e){this.#n.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onMessage(e)),()=>{this.#n.delete(e),n&&n()}}onError(e){this.#r.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onError(e)),()=>{this.#r.delete(e),n&&n()}}onClose(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#i={code:e,reason:n},this.#h&&this.#h("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#s||this.#f({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#g=e,this.#d=n,this.#y()}async#y(){if(this.#c=Date.now(),this.#e.signal?.aborted){this.#S("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#b("attempt-start",this.attempt);let e,n=!1;try{let a=await Fa({url:this.#e.url,apiKey:this.#e.apiKey,expectedProtocolVersion:this.#e.expectedProtocolVersion,welcomeTimeoutMs:this.#e.welcomeTimeoutMs,pingIntervalMs:this.#e.pingIntervalMs,signal:this.#e.signal});n=!0,this.#t=a,this.welcome=a.welcome,this.#E(a),this.state="connected";let c=this.attempt;this.attempt=0,this.#u=0,this.#b("attempt-success",c),this.#l||(this.#l=!0,this.#g?.());let l=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??l.code,closeReason:this.#i.reason??l.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!ES(l)){let u=new zn("fatal-close",void 0,`close code ${l.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:l.code,closeReason:l.reason,cause:u});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof fe&&(e=a),!kS(a)){let c=a instanceof fe?a:void 0,l=a instanceof wt?"signal":"fatal-error",u=a instanceof Error?a.message:"non-retriable error";this.#S(l,c,u);return}this.#u++,this.state="backoff"}let r=bS(this.#u,this.#e.initialBackoffMs??pS,this.#e.backoffFactor??hS,this.#e.maxBackoffMs??gS),o=SS(r,this.#e.jitter??yS),i=this.attempt===0?1:this.attempt;if(this.#b("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#u>=this.#e.maxAttempts){this.#S("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#p(o);if(s==="abort"){this.#f({kind:"signal",cause:void 0}),this.#l||(this.#l=!0,this.#d?.(new zn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#f({kind:"caller-close",code:this.#i?.code??1e3,closeReason:this.#i?.reason,cause:void 0});return}}}#p(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#h=null,n(c))},i=setTimeout(()=>o("timeout"),e),s=this.#e.signal,a=null;if(s){if(s.aborted){o("abort");return}a=()=>o("abort"),s.addEventListener("abort",a)}this.#h=c=>o(c)})}#_(e){return new Promise(n=>{let r=e.onClose(o=>{try{r()}catch{}n(o)})})}#E(e){this.#w();for(let n of this.#n)this.#m.push(e.onMessage(n));for(let n of this.#r)this.#m.push(e.onError(n))}#w(){for(let e of this.#m)try{e()}catch{}this.#m.length=0}#b(e,n,r,o){let i=Date.now()-this.#c,s=e==="give-up"?"error":e==="attempt-failure"?$S(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let l of c)try{l(a)}catch{}}#S(e,n,r){let o=new zn(e,n,r);this.#f({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#l||(this.#l=!0,this.#d?.(o))}#f(e){if(this.#s)return;this.#s=!0,this.state="closed",this.#w(),this.#t=null,this.#b("give-up",this.attempt,void 0,e.cause);let n=[...this.#o];for(let r of n)try{r(e)}catch{}}};async function qa(t){let e=new Ba(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var RS=["check","call","fold","raise","allin"];function Ua(t){let{legalActions:e}=t;if(e.length===0)throw new Error("Texas Hold'em fallback requires at least one legal action");for(let n of RS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Ga(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Liar's Dice fallback requires at least one legal action");let r=n.find(i=>i.type==="bid"),o=n.find(i=>i.type==="challenge");if(r){let i=PS(r.data);if(i)return i.maxQuantity!==void 0&&i.minQuantity>i.maxQuantity?o??n[0]:{type:"bid",data:{quantity:i.minQuantity,face:i.minFace}};let s=TS(e);if(s)return typeof e.total_dice=="number"&&s.quantity>e.total_dice?o??n[0]:{type:"bid",data:s}}return o||n[0]}function PS(t){let e=AS(t);if(!e)return;let n=Ha(e,"min_quantity"),r=Ha(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Ha(e,"max_quantity")}}function TS(t){let e=t.current_bid;if(!e)return typeof t.total_dice!="number"?void 0:{quantity:1,face:1};if(!(typeof e.quantity!="number"||typeof e.face!="number"))return e.face<6?{quantity:e.quantity,face:e.face+1}:{quantity:e.quantity+1,face:1}}function AS(t){return t!==null&&typeof t=="object"?t:void 0}function Ha(t,e){let n=t[e];return typeof n=="number"?n:void 0}var CS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],xS=["pass","challenge"],IS=["pass","block"],OS=["lose_card"],NS=["return_cards"];function Wa(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Coup fallback requires at least one legal action");switch(e.phase){case"action":return Ur(n,CS);case"challenge_action":case"challenge_block":return Ur(n,xS);case"block":return Ur(n,IS);case"lose_influence":return Ur(n,OS);case"exchange_return":return Ur(n,NS);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function Ur(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var MS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function za(t,e,n=500){let r=t.trim(),o=DS(r),i;try{i=JSON.parse(o)}catch{return un("json_parse",r,n)}if(!ti(i))return un("missing_fields",r,n);let s=i.action;if(typeof s!="string")return un("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ti(c))return un("missing_fields",r,n);let l=ti(c)?c:void 0;if(!LS.has(s))return un("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return un("action_not_legal",r,n);if(s==="raise"){let d=jS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:un("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var LS=new Set(["fold","check","call","raise","allin"]);function jS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ti(t.data)?t.data:void 0,o=Va(r,"amount"),i=Va(r,"min")??o,s=Va(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function DS(t){let e=t.match(MS);return e?e[1].trim():t}function ti(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Va(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function un(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var FS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ja(t,e,n=500){let r=t.trim(),o=US(r),i;try{i=JSON.parse(o)}catch{return dn("json_parse",r,n)}if(!ni(i))return dn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return dn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ni(c))return dn("missing_fields",r,n);let l=ni(c)?c:void 0;if(!BS.has(s))return dn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return dn("action_not_legal",r,n);if(s==="bid"){let d=qS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:dn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var BS=new Set(["bid","challenge"]);function qS(t,e){if(!e)return;let n=e.quantity,r=e.face;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n)||typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>6||n<1)return;let o=ni(t.data)?t.data:void 0,i=Ka(o,"min_quantity"),s=Ka(o,"min_face"),a=Ka(o,"max_quantity");if(!(i!==void 0&&n<i)&&!(a!==void 0&&n>a)&&!(i!==void 0&&s!==void 0&&n===i&&r<s))return{type:"bid",data:{quantity:n,face:r}}}function US(t){let e=t.match(FS);return e?e[1].trim():t}function ni(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ka(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function dn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var HS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,GS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Ya(t,e,n=500){let r=t.trim(),o=VS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!Kn(i))return fn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return fn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Kn(c))return fn("missing_fields",r,n);let l=Kn(c)?c:void 0;if(!GS.has(s))return fn("unknown_action_type",r,n);let u=e.filter(h=>h.type===s);if(u.length===0)return fn("action_not_legal",r,n);let d=WS(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}function WS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Uf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Uf(o.data,"role")===r)}case"lose_card":{let r=n?.card_index;return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?void 0:e.find(o=>zS(o.data,"card_index")===r)}case"return_cards":{let r=n?.return_indices;return!Array.isArray(r)||!r.every(o=>typeof o=="number"&&Number.isFinite(o)&&Number.isInteger(o))?void 0:e.find(o=>{let i=KS(o.data,"return_indices");return i!==void 0&&JS(i,r)})}default:return e[0]}}function VS(t){let e=t.match(HS);return e?e[1].trim():t}function Kn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Uf(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function zS(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function KS(t,e){if(!Kn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function JS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var Se="0.1.0-alpha.3",Jf="v1.0.0";function Yf(){let t=ir(),e=qt(),n=yi();return{ok:!0,runtimeVersion:Se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Qa(t,e){return J(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:Se})+`
68
68
  `):e.stdout(`${Se}
69
- `),0}import Ur from"node:fs";import QS from"node:path";var He=class extends Error{name="RuntimeLocalUrlError"};function Kn(t){switch(t){case"openclaw":return"http://127.0.0.1:18789";case"hermes":return"http://127.0.0.1:8642";case"mock":return"mock://local"}}function Hr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new He("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new He("runtime URL must use http:// or https://");if(!t0(r.hostname))throw new He("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new He("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new He("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Mt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function Xa(){return QS.join(ne(),"bridge.json")}function Yf(){Ur.rmSync(Xa(),{force:!0})}function mn(t){it();let e=Xa(),n=`${e}.tmp`;if(Ur.writeFileSync(n,JSON.stringify(t,null,2)+`
70
- `,{mode:384}),Ur.renameSync(n,e),process.platform!=="win32")try{Ur.chmodSync(e,384)}catch{}}function ae(){let t=Xa(),e;try{e=Ur.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new Error("bridge is not configured; run `aifight register` for a new agent or `aifight connect <PAIRING_CODE>` for an existing agent"):r}let n=JSON.parse(e);if(!ZS(n))throw new Error("bridge config is invalid; run connect again");return n}function Lt(t){return{...t,apiKey:Qa(t.apiKey),...t.claimUrl!==void 0?{claimUrl:XS(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:Qa(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:Qa(t.runtimeLocalToken)}:{}}}function Qa(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function XS(t){try{let e=new URL(t),n=e.pathname.split("/"),r=n.at(-1);return r&&r.length>0&&(n[n.length-1]="<redacted>",e.pathname=n.join("/")),e.toString()}catch{return"<redacted>"}}function ZS(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.baseUrl=="string"&&typeof e.wsUrl=="string"&&typeof e.agentId=="string"&&typeof e.agentName=="string"&&(e.suggestedName===void 0||typeof e.suggestedName=="string")&&typeof e.apiKey=="string"&&(e.claimUrl===void 0||typeof e.claimUrl=="string")&&(e.claimToken===void 0||typeof e.claimToken=="string")&&(e.runtimeType==="openclaw"||e.runtimeType==="hermes"||e.runtimeType==="mock")&&typeof e.runtimeLocalUrl=="string"&&e0(e.runtimeLocalUrl,e.runtimeType)&&typeof e.updatedAt=="string"&&(e.runtimeLocalToken===void 0||typeof e.runtimeLocalToken=="string")&&(e.runtimeModel===void 0||typeof e.runtimeModel=="string")&&(e.autoDailyLimit===void 0||typeof e.autoDailyLimit=="number"&&Number.isInteger(e.autoDailyLimit)&&e.autoDailyLimit>=0)&&(e.autoGames===void 0||Array.isArray(e.autoGames)&&e.autoGames.every(n=>typeof n=="string"))}function e0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Hr(t,e),!0}catch{return!1}}function t0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var n0="npm install -g @aifight/aifight@alpha";async function jt(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${o0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return Za(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=i0(s);return a===null?Za(t.currentVersion,"version check returned invalid policy"):r0(t.currentVersion,a)}catch(i){let s=i?.name;return Za(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function r0(t,e){let n=Qf(t,e.minimumSupportedVersion);if(n!==null&&n<0)return{status:"unsupported",currentVersion:t,policy:e,message:`Bridge ${t} is below the minimum supported version ${e.minimumSupportedVersion}. Update before joining matches.`};let r=Qf(t,e.recommendedVersion);return r!==null&&r<0?{status:"update_recommended",currentVersion:t,policy:e,message:`Bridge ${t} works, but ${e.recommendedVersion} is recommended.`}:n===null||r===null?{status:"unknown",currentVersion:t,policy:e,message:"Bridge version could not be compared with the platform policy."}:{status:"current",currentVersion:t,policy:e,message:`Bridge ${t} is current enough for AIFight.`}}function Za(t,e){return{status:"unknown",currentVersion:t,message:e}}function o0(t){return t.replace(/\/+$/,"")}function i0(t){if(!t||typeof t!="object")return null;let e=t,n=e.minimum_supported_version,r=e.recommended_version,o=e.latest_version;return typeof n!="string"||typeof r!="string"||typeof o!="string"?null:{minimumSupportedVersion:n,recommendedVersion:r,latestVersion:o,updateCommand:typeof e.update_command=="string"&&e.update_command.trim()!==""?e.update_command:n0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function Qf(t,e){let n=Xf(t),r=Xf(e);if(n===null||r===null)return null;for(let o of["major","minor","patch"])if(n[o]!==r[o])return n[o]>r[o]?1:-1;return s0(n.prerelease,r.prerelease)}function Xf(t){let e=t.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);return e===null?null:{major:Number.parseInt(e[1],10),minor:Number.parseInt(e[2],10),patch:Number.parseInt(e[3],10),prerelease:e[4]===void 0?[]:e[4].split(".")}}function s0(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;let n=Math.max(t.length,e.length);for(let r=0;r<n;r++){let o=t[r],i=e[r];if(o===void 0)return-1;if(i===void 0)return 1;if(o===i)continue;let s=/^\d+$/.test(o)?Number.parseInt(o,10):null,a=/^\d+$/.test(i)?Number.parseInt(i,10):null;return s!==null&&a!==null?s>a?1:-1:s!==null?-1:a!==null||o>i?1:-1}return 0}var a0=1500;async function Zf(t,e){J(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Jf)()}catch(i){return t.jsonMode?e.stderr(JSON.stringify({error:{code:"client_doctor_schema",message:i.message}})+`
69
+ `),0}import Hr from"node:fs";import XS from"node:path";var He=class extends Error{name="RuntimeLocalUrlError"};function Jn(t){switch(t){case"openclaw":return"http://127.0.0.1:18789";case"hermes":return"http://127.0.0.1:8642";case"mock":return"mock://local"}}function Gr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new He("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new He("runtime URL must use http:// or https://");if(!n0(r.hostname))throw new He("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new He("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new He("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Mt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function Za(){return XS.join(re(),"bridge.json")}function Qf(){Hr.rmSync(Za(),{force:!0})}function mn(t){st();let e=Za(),n=`${e}.tmp`;if(Hr.writeFileSync(n,JSON.stringify(t,null,2)+`
70
+ `,{mode:384}),Hr.renameSync(n,e),process.platform!=="win32")try{Hr.chmodSync(e,384)}catch{}}function ce(){let t=Za(),e;try{e=Hr.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new Error("bridge is not configured; run `aifight register` for a new agent or `aifight connect <PAIRING_CODE>` for an existing agent"):r}let n=JSON.parse(e);if(!e0(n))throw new Error("bridge config is invalid; run connect again");return n}function Lt(t){return{...t,apiKey:Xa(t.apiKey),...t.claimUrl!==void 0?{claimUrl:ZS(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:Xa(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:Xa(t.runtimeLocalToken)}:{}}}function Xa(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function ZS(t){try{let e=new URL(t),n=e.pathname.split("/"),r=n.at(-1);return r&&r.length>0&&(n[n.length-1]="<redacted>",e.pathname=n.join("/")),e.toString()}catch{return"<redacted>"}}function e0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.baseUrl=="string"&&typeof e.wsUrl=="string"&&typeof e.agentId=="string"&&typeof e.agentName=="string"&&(e.suggestedName===void 0||typeof e.suggestedName=="string")&&typeof e.apiKey=="string"&&(e.claimUrl===void 0||typeof e.claimUrl=="string")&&(e.claimToken===void 0||typeof e.claimToken=="string")&&(e.runtimeType==="openclaw"||e.runtimeType==="hermes"||e.runtimeType==="mock")&&typeof e.runtimeLocalUrl=="string"&&t0(e.runtimeLocalUrl,e.runtimeType)&&typeof e.updatedAt=="string"&&(e.runtimeLocalToken===void 0||typeof e.runtimeLocalToken=="string")&&(e.runtimeModel===void 0||typeof e.runtimeModel=="string")&&(e.autoDailyLimit===void 0||typeof e.autoDailyLimit=="number"&&Number.isInteger(e.autoDailyLimit)&&e.autoDailyLimit>=0)&&(e.autoGames===void 0||Array.isArray(e.autoGames)&&e.autoGames.every(n=>typeof n=="string"))}function t0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Gr(t,e),!0}catch{return!1}}function n0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var r0="npm install -g @aifight/aifight@alpha";async function jt(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${i0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return ec(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=s0(s);return a===null?ec(t.currentVersion,"version check returned invalid policy"):o0(t.currentVersion,a)}catch(i){let s=i?.name;return ec(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function o0(t,e){let n=Xf(t,e.minimumSupportedVersion);if(n!==null&&n<0)return{status:"unsupported",currentVersion:t,policy:e,message:`Bridge ${t} is below the minimum supported version ${e.minimumSupportedVersion}. Update before joining matches.`};let r=Xf(t,e.recommendedVersion);return r!==null&&r<0?{status:"update_recommended",currentVersion:t,policy:e,message:`Bridge ${t} works, but ${e.recommendedVersion} is recommended.`}:n===null||r===null?{status:"unknown",currentVersion:t,policy:e,message:"Bridge version could not be compared with the platform policy."}:{status:"current",currentVersion:t,policy:e,message:`Bridge ${t} is current enough for AIFight.`}}function ec(t,e){return{status:"unknown",currentVersion:t,message:e}}function i0(t){return t.replace(/\/+$/,"")}function s0(t){if(!t||typeof t!="object")return null;let e=t,n=e.minimum_supported_version,r=e.recommended_version,o=e.latest_version;return typeof n!="string"||typeof r!="string"||typeof o!="string"?null:{minimumSupportedVersion:n,recommendedVersion:r,latestVersion:o,updateCommand:typeof e.update_command=="string"&&e.update_command.trim()!==""?e.update_command:r0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function Xf(t,e){let n=Zf(t),r=Zf(e);if(n===null||r===null)return null;for(let o of["major","minor","patch"])if(n[o]!==r[o])return n[o]>r[o]?1:-1;return a0(n.prerelease,r.prerelease)}function Zf(t){let e=t.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);return e===null?null:{major:Number.parseInt(e[1],10),minor:Number.parseInt(e[2],10),patch:Number.parseInt(e[3],10),prerelease:e[4]===void 0?[]:e[4].split(".")}}function a0(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;let n=Math.max(t.length,e.length);for(let r=0;r<n;r++){let o=t[r],i=e[r];if(o===void 0)return-1;if(i===void 0)return 1;if(o===i)continue;let s=/^\d+$/.test(o)?Number.parseInt(o,10):null,a=/^\d+$/.test(i)?Number.parseInt(i,10):null;return s!==null&&a!==null?s>a?1:-1:s!==null?-1:a!==null||o>i?1:-1}return 0}var c0=1500;async function em(t,e){J(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Yf)()}catch(i){return t.jsonMode?e.stderr(JSON.stringify({error:{code:"client_doctor_schema",message:i.message}})+`
71
71
  `):e.stderr(`aifight doctor FAILED: ${i.message}
72
- `),1}let r=await c0(n.runtimeVersion,e.fetchImpl??globalThis.fetch);if(t.jsonMode)return e.stdout(JSON.stringify({runtimeVersion:n.runtimeVersion,messageTypeCount:n.messageTypeCount,schemaCount:n.schemaCount,schemasRoot:n.schemasRoot,node:process.versions.node,platform:`${process.platform}-${process.arch}`,bridge:r})+`
72
+ `),1}let r=await l0(n.runtimeVersion,e.fetchImpl??globalThis.fetch);if(t.jsonMode)return e.stdout(JSON.stringify({runtimeVersion:n.runtimeVersion,messageTypeCount:n.messageTypeCount,schemaCount:n.schemaCount,schemasRoot:n.schemasRoot,node:process.versions.node,platform:`${process.platform}-${process.arch}`,bridge:r})+`
73
73
  `),0;let o=[];return o.push("aifight doctor:"),o.push(` version : ${n.runtimeVersion}`),o.push(` node : ${process.versions.node}`),o.push(` platform : ${process.platform}-${process.arch}`),o.push(` bridge config : ${r.config}`),r.runtime!==void 0&&o.push(` runtime probe : ${r.runtime.status}${r.runtime.detail?` (${r.runtime.detail})`:""}`),r.update!==void 0&&(o.push(` version policy : ${r.update.message}`),(r.update.status==="update_recommended"||r.update.status==="unsupported")&&o.push(` update command : ${r.update.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}`)),o.push(""),e.stdout(o.join(`
74
- `)),0}async function c0(t,e){try{let n=ae(),r=await jt({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Lt(n),runtime:await l0(n,e),update:r}}catch(n){let r=n.message;return r.includes("bridge is not configured")?{config:"not configured"}:{config:`invalid (${r})`}}}async function l0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??Mt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),a0);try{let s=await e(`${n}/v1/responses`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",...t.runtimeLocalToken?{Authorization:`Bearer ${t.runtimeLocalToken}`}:{}},body:JSON.stringify({model:r,input:'AIFight doctor health check. Return only JSON: {"action":"pass"}'})}),a=u0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${d0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function u0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function d0(t,e){return t==="openclaw"?e===404?"enable OpenClaw responses endpoint: openclaw config set gateway.http.endpoints.responses.enabled true --strict-json, then let Gateway restart or run openclaw gateway restart --safe":e===401||e===403?"check the local OpenClaw Gateway token passed with --runtime-token":"check OpenClaw Gateway logs and local model/provider config":t==="hermes"?e===401||e===403?"check Hermes API_SERVER_KEY and the local --runtime-token value":e===404?"confirm Hermes API Server is enabled in ~/.hermes/.env and restart Hermes; it does not hot-reload API_SERVER_*":"check Hermes API Server logs and local model/provider config":"check local runtime config"}import V0 from"node:os";import{randomBytes as G0}from"node:crypto";import{execFile as f0}from"node:child_process";import Pe from"node:fs";import ec from"node:os";import wt from"node:path";import{promisify as m0}from"node:util";var Dt="aifight.service",ri="ai.aifight.service",ce=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},p0=m0(f0),We=async(t,e)=>{try{let{stdout:n,stderr:r}=await p0(t,[...e],{timeout:5e3,maxBuffer:131072});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}}catch(n){throw n}};async function tc(t={}){let e=await Qn(t),n=t.execFile??We;h0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",rt(t),e.unitPath]);let o=await nc(t);return{...e,linger:"not_needed",...o?{warning:o}:{}}}let r=pn(e.platform);if(await n("systemctl",[...r,"daemon-reload"]),await n("systemctl",[...r,"enable","--now",Dt]),e.platform==="linux-systemd-user"){let o=await _0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await w0(e,t),new ce("service_install_failed",`failed to install ${Dt}: ${Jn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function oi(t={}){let e=await Qn(t),n=t.execFile??We;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),e;let r=pn(e.platform);return await n("systemctl",[...r,"disable","--now",Dt]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function rm(t={}){let e=await Qn(t),n=t.execFile??We;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",rt(t),e.unitPath]).catch(()=>{}),await nc(t),e):(await n("systemctl",[...pn(e.platform),"start",Dt]),e)}async function om(t={}){let e=await Qn(t),n=t.execFile??We;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...pn(e.platform),"stop",Dt]),e)}async function im(t={}){let e=await Qn(t),n=t.execFile??We;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",rt(t),e.unitPath]),await nc(t),e):(await n("systemctl",[...pn(e.platform),"restart",Dt]),e)}async function Yn(t={}){let e=await Qn(t),n=t.execFile??We;if(!Pe.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${rt(t)}/${ri}`]),{...e,installed:!0,running:!0,detail:"running"}}catch(o){return{...e,installed:!0,running:!1,detail:Jn(o)}}try{let i=(await n("systemctl",[...pn(e.platform),"is-active",Dt])).stdout.trim()||"active";return{...e,installed:!0,running:i==="active",detail:i}}catch(o){return{...e,installed:!0,running:!1,detail:Jn(o)}}}async function Qn(t={}){let e=t.platform??process.platform,n=t.uid??process.getuid?.()??0,r=t.homeDir??ec.homedir(),o=t.runtimeHome??ne(),i=await v0(t),s=b0(t);if(e==="linux")return await em("systemctl",["--version"],t),n===0?{platform:"linux-systemd-system",unitPath:t.systemdSystemUnitPath??"/etc/systemd/system/aifight.service",nodeExec:s,aifightExec:i,runtimeHome:o}:{platform:"linux-systemd-user",unitPath:t.systemdUserUnitPath??wt.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await em("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??wt.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new ce("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function h0(t){Pe.mkdirSync(wt.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?y0(t):g0(t);E0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function g0(t){let e=t.platform==="linux-systemd-system"?"multi-user.target":"default.target";return["# Auto-generated by AIFight. Re-run `aifight service install` to refresh.","","[Unit]","Description=AIFight Agent Service","Documentation=https://aifight.ai/skill.md","Wants=network-online.target","After=network-online.target","","[Service]","Type=simple",`ExecStart=${tm(t.nodeExec)} ${tm(t.aifightExec)} run`,nm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),nm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
- `)}function y0(t){let e=wt.dirname(t.unitPath).includes("LaunchAgents")?wt.join(ec.homedir(),"Library","Logs","aifight"):wt.join(wt.dirname(t.unitPath),"logs");return Pe.mkdirSync(e,{recursive:!0}),['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${ri}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Wr(t.nodeExec)}</string>`,` <string>${Wr(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Wr(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Wr(wt.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Wr(wt.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
- `)}function pn(t){return t==="linux-systemd-user"?["--user"]:[]}function rt(t){return`gui/${t.uid??process.getuid?.()??0}`}async function nc(t){let e=t.execFile??We,n=`${rt(t)}/${ri}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${ri} is loaded: ${Jn(r)}`}catch{throw r}}}async function _0(t){let e=t.username??ec.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??We;try{return await n("loginctl",["enable-linger",e]),{status:"enabled"}}catch(r){return{status:"failed",warning:`loginctl enable-linger ${e} failed: ${Jn(r)}`}}}async function w0(t,e){let n=e.execFile??We;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",rt(e),t.unitPath]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0});return}let r=pn(t.platform);await n("systemctl",[...r,"disable","--now",Dt]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function v0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Vr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!S0(n))try{return Vr(n)}catch{}let r=t.execFile??We;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
- `)[0];if(i)return Vr(i)}catch{}throw new ce("service_exec_unresolved","could not resolve a stable `aifight` executable for the background service","Install with `npm install -g @aifight/aifight@alpha`, then run `aifight service install` again.")}function b0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Vr(e);try{return Vr(process.execPath)}catch{throw new ce("service_exec_unresolved","could not resolve a stable Node.js executable for the background service","Install Node.js >=20.19 and rerun `aifight service install`.")}}function Vr(t){let e=Pe.realpathSync(t);return Pe.accessSync(e,Pe.constants.X_OK),e}function S0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function em(t,e,n){let r=n.execFile??We;try{await r(t,e)}catch(o){throw new ce("service_manager_unavailable",`${t} is not available or not usable on this system: ${Jn(o)}`,"AIFight will keep running in the foreground; use your own process manager if needed.")}}function tm(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function nm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function E0(t,e,n){let r=`${t}.${process.pid}.tmp`;Pe.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Pe.chmodSync(r,n),Pe.renameSync(r,t)}function Jn(t){let e=t,n=typeof e.stderr=="string"&&e.stderr.trim()!==""?e.stderr:e.message;return String(n).trim().split(`
78
- `)[0]??"unknown error"}function Wr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var rc=["usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
79
- `);async function sm(t,e){J(t,1,1,rc);let n=t.positional[0],r=$0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",rc);try{switch(n){case"install":{ae();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await tc(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
74
+ `)),0}async function l0(t,e){try{let n=ce(),r=await jt({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Lt(n),runtime:await u0(n,e),update:r}}catch(n){let r=n.message;return r.includes("bridge is not configured")?{config:"not configured"}:{config:`invalid (${r})`}}}async function u0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??Mt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),c0);try{let s=await e(`${n}/v1/responses`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",...t.runtimeLocalToken?{Authorization:`Bearer ${t.runtimeLocalToken}`}:{}},body:JSON.stringify({model:r,input:'AIFight doctor health check. Return only JSON: {"action":"pass"}'})}),a=d0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${f0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function d0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function f0(t,e){return t==="openclaw"?e===404?"enable OpenClaw responses endpoint: openclaw config set gateway.http.endpoints.responses.enabled true --strict-json, then let Gateway restart or run openclaw gateway restart --safe":e===401||e===403?"check the local OpenClaw Gateway token passed with --runtime-token":"check OpenClaw Gateway logs and local model/provider config":t==="hermes"?e===401||e===403?"check Hermes API_SERVER_KEY and the local --runtime-token value":e===404?"confirm Hermes API Server is enabled in ~/.hermes/.env and restart Hermes; it does not hot-reload API_SERVER_*":"check Hermes API Server logs and local model/provider config":"check local runtime config"}import K0 from"node:os";import{randomBytes as J0}from"node:crypto";import{execFile as m0}from"node:child_process";import Pe from"node:fs";import tc from"node:os";import vt from"node:path";import{promisify as p0}from"node:util";var Dt="aifight.service",ri="ai.aifight.service",te=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},h0=p0(m0),Ge=async(t,e)=>{try{let{stdout:n,stderr:r}=await h0(t,[...e],{timeout:5e3,maxBuffer:131072});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}}catch(n){throw n}};async function nc(t={}){let e=await Qn(t),n=t.execFile??Ge;g0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",rt(t),e.unitPath]);let o=await oc(t);return{...e,linger:"not_needed",...o?{warning:o}:{}}}let r=hn(e.platform);if(await n("systemctl",[...r,"daemon-reload"]),await n("systemctl",[...r,"enable","--now",Dt]),e.platform==="linux-systemd-user"){let o=await w0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await v0(e,t),new te("service_install_failed",`failed to install ${Dt}: ${Yn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function oi(t={}){let e=await Qn(t),n=t.execFile??Ge;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),e;let r=hn(e.platform);return await n("systemctl",[...r,"disable","--now",Dt]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function om(t={}){let e=await Qn(t),n=t.execFile??Ge;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",rt(t),e.unitPath]).catch(()=>{}),await oc(t),e):(await n("systemctl",[...hn(e.platform),"start",Dt]),e)}async function im(t={}){let e=await Qn(t),n=t.execFile??Ge;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...hn(e.platform),"stop",Dt]),e)}async function rc(t={}){let e=await Qn(t),n=t.execFile??Ge;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",rt(t),e.unitPath]),await oc(t),e):(await n("systemctl",[...hn(e.platform),"restart",Dt]),e)}async function pn(t={}){let e=await Qn(t),n=t.execFile??Ge;if(!Pe.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${rt(t)}/${ri}`]),{...e,installed:!0,running:!0,detail:"running"}}catch(o){return{...e,installed:!0,running:!1,detail:Yn(o)}}try{let i=(await n("systemctl",[...hn(e.platform),"is-active",Dt])).stdout.trim()||"active";return{...e,installed:!0,running:i==="active",detail:i}}catch(o){return{...e,installed:!0,running:!1,detail:Yn(o)}}}async function Qn(t={}){let e=t.platform??process.platform,n=t.uid??process.getuid?.()??0,r=t.homeDir??tc.homedir(),o=t.runtimeHome??re(),i=await b0(t),s=S0(t);if(e==="linux")return await tm("systemctl",["--version"],t),n===0?{platform:"linux-systemd-system",unitPath:t.systemdSystemUnitPath??"/etc/systemd/system/aifight.service",nodeExec:s,aifightExec:i,runtimeHome:o}:{platform:"linux-systemd-user",unitPath:t.systemdUserUnitPath??vt.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await tm("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??vt.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new te("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function g0(t){Pe.mkdirSync(vt.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?_0(t):y0(t);k0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function y0(t){let e=t.platform==="linux-systemd-system"?"multi-user.target":"default.target";return["# Auto-generated by AIFight. Re-run `aifight service install` to refresh.","","[Unit]","Description=AIFight Agent Service","Documentation=https://aifight.ai/skill.md","Wants=network-online.target","After=network-online.target","","[Service]","Type=simple",`ExecStart=${nm(t.nodeExec)} ${nm(t.aifightExec)} run`,rm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),rm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
+ `)}function _0(t){let e=vt.dirname(t.unitPath).includes("LaunchAgents")?vt.join(tc.homedir(),"Library","Logs","aifight"):vt.join(vt.dirname(t.unitPath),"logs");return Pe.mkdirSync(e,{recursive:!0}),['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${ri}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Wr(t.nodeExec)}</string>`,` <string>${Wr(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Wr(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Wr(vt.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Wr(vt.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
+ `)}function hn(t){return t==="linux-systemd-user"?["--user"]:[]}function rt(t){return`gui/${t.uid??process.getuid?.()??0}`}async function oc(t){let e=t.execFile??Ge,n=`${rt(t)}/${ri}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${ri} is loaded: ${Yn(r)}`}catch{throw r}}}async function w0(t){let e=t.username??tc.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??Ge;try{return await n("loginctl",["enable-linger",e]),{status:"enabled"}}catch(r){return{status:"failed",warning:`loginctl enable-linger ${e} failed: ${Yn(r)}`}}}async function v0(t,e){let n=e.execFile??Ge;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",rt(e),t.unitPath]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0});return}let r=hn(t.platform);await n("systemctl",[...r,"disable","--now",Dt]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function b0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Vr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!E0(n))try{return Vr(n)}catch{}let r=t.execFile??Ge;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
+ `)[0];if(i)return Vr(i)}catch{}throw new te("service_exec_unresolved","could not resolve a stable `aifight` executable for the background service","Install with `npm install -g @aifight/aifight@alpha`, then run `aifight service install` again.")}function S0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Vr(e);try{return Vr(process.execPath)}catch{throw new te("service_exec_unresolved","could not resolve a stable Node.js executable for the background service","Install Node.js >=20.19 and rerun `aifight service install`.")}}function Vr(t){let e=Pe.realpathSync(t);return Pe.accessSync(e,Pe.constants.X_OK),e}function E0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function tm(t,e,n){let r=n.execFile??Ge;try{await r(t,e)}catch(o){throw new te("service_manager_unavailable",`${t} is not available or not usable on this system: ${Yn(o)}`,"AIFight will keep running in the foreground; use your own process manager if needed.")}}function nm(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function rm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function k0(t,e,n){let r=`${t}.${process.pid}.tmp`;Pe.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Pe.chmodSync(r,n),Pe.renameSync(r,t)}function Yn(t){let e=t,n=typeof e.stderr=="string"&&e.stderr.trim()!==""?e.stderr:e.message;return String(n).trim().split(`
78
+ `)[0]??"unknown error"}function Wr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var ic=["usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
79
+ `);async function am(t,e){J(t,1,1,ic);let n=t.positional[0],r=$0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",ic);try{switch(n){case"install":{ce();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await nc(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
80
80
  `):(e.stdout(`aifight.service installed and started (${i.platform}).
81
81
  `),e.stdout(`unit: ${i.unitPath}
82
82
  `),i.warning&&e.stderr(`warning: ${i.warning}
83
- `)),0}case"status":{let o=await Yn(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
83
+ `)),0}case"status":{let o=await pn(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
84
84
  `):o.installed?(e.stdout(`aifight.service: ${o.running?"running":"stopped"} (${o.detail})
85
85
  `),e.stdout(`unit: ${o.unitPath}
86
86
  `)):(e.stdout(`aifight.service: not installed
87
87
  `),e.stdout(`run: aifight service install
88
- `)),0}case"start":{let o=await rm(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
89
- `),0}case"stop":{let o=await om(e.bridgeService);return e.stdout(`aifight.service stopped (${o.platform}).
90
- `),0}case"restart":{let o=await im(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
88
+ `)),0}case"start":{let o=await om(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
89
+ `),0}case"stop":{let o=await im(e.bridgeService);return e.stdout(`aifight.service stopped (${o.platform}).
90
+ `),0}case"restart":{let o=await rc(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
91
91
  `),0}case"uninstall":{let o=await oi(e.bridgeService);return e.stdout(`aifight.service uninstalled (${o.platform}).
92
- `),0}default:throw new O(`unknown service command '${n}'`,rc)}}catch(o){if(o instanceof O)throw o;if(o instanceof ce)return t.jsonMode?e.stderr(JSON.stringify({error:{code:o.code,message:o.message,...o.hint?{hint:o.hint}:{}}})+`
92
+ `),0}default:throw new O(`unknown service command '${n}'`,ic)}}catch(o){if(o instanceof O)throw o;if(o instanceof te)return t.jsonMode?e.stderr(JSON.stringify({error:{code:o.code,message:o.message,...o.hint?{hint:o.hint}:{}}})+`
93
93
  `):(e.stderr(`aifight: ${o.message}
94
94
  `),o.hint&&e.stderr(`${o.hint}
95
95
  `)),o.code==="service_platform_unsupported"||o.code==="service_manager_unavailable"?2:1;let i=o instanceof Error?o.message:String(o);return t.jsonMode?e.stderr(JSON.stringify({error:{code:"service_command_failed",message:i}})+`
96
96
  `):e.stderr(`aifight: service command failed: ${i}
97
- `),1}}function $0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function am(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";if(t.stdout(["AIFight needs a long-running local Bridge before your Agent can play scheduled matches and challenges.","","I can install a local background service named aifight.service.","It runs `aifight run` after reboot and keeps the outbound Bridge online for normal use.","","This does not expose your machine to the public internet.","AIFight Bridge only opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","","If you do not install it now, finish setup later with `aifight service install` or manage `aifight run` yourself.",""].join(`
98
- `)),!(e.approvedLocalSetup===!0?!0:await k0(t,"Install and start aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; installing aifight.service now.
99
- `);try{let r=await tc(t.bridgeService);return t.stdout(`aifight.service installed and started (${r.platform}).
100
- `),t.stdout(`unit: ${r.unitPath}
101
- `),r.warning&&t.stderr(`warning: ${r.warning}
102
- `),"installed"}catch(r){let o=(r instanceof ce,r.message),i=r instanceof ce?r.hint:void 0;return t.stderr(`aifight.service could not be installed: ${o}
103
- `),i&&t.stderr(`${i}
104
- `),"unavailable"}}async function k0(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}import{execFile as R0}from"node:child_process";import cm from"node:fs";import lm from"node:path";var P0=3e4;function Le(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(lm.delimiter))if(r)for(let o of n){let i=lm.join(r,`${t}${o}`);try{return cm.accessSync(i,cm.constants.X_OK),i}catch{}}}async function vt(t,e){let n=Le(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};R0(n,e,{timeout:P0},(a,c,l)=>{let u=a?.code;i({code:typeof u=="number"?u:a?1:0,stdout:String(c??""),stderr:String(l??"")})}).on("error",a=>{i({code:1,stdout:"",stderr:a.message})})})}function hn(t,e,n){n.stdout.trim()&&t.stdout(`${e}: ${n.stdout.trim()}
97
+ `),1}}function $0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function cm(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";let n=await R0(t);if(n?.installed&&n.running===!0){if(t.stdout(["aifight.service is already running.","AIFight just saved bridge credentials, so the service must reload them before the Dashboard can show the new Agent online.",""].join(`
98
+ `)),!(e.approvedLocalSetup===!0?!0:await sm(t,"Restart aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting aifight.service now.
99
+ `);try{let i=await rc(t.bridgeService);return t.stdout(`aifight.service restarted (${i.platform}).
100
+ `),t.stdout(`unit: ${i.unitPath}
101
+ `),"installed"}catch(i){let s=(i instanceof te,i.message),a=i instanceof te?i.hint:void 0;return t.stderr(`aifight.service could not be restarted: ${s}
102
+ `),a&&t.stderr(`${a}
103
+ `),"unavailable"}}if(t.stdout(["AIFight needs a long-running local Bridge before your Agent can play scheduled matches and challenges.","","I can install a local background service named aifight.service.","It runs `aifight run` after reboot and keeps the outbound Bridge online for normal use.","","This does not expose your machine to the public internet.","AIFight Bridge only opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","","If you do not install it now, finish setup later with `aifight service install` or manage `aifight run` yourself.",""].join(`
104
+ `)),!(e.approvedLocalSetup===!0?!0:await sm(t,"Install and start aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; installing aifight.service now.
105
+ `);try{let o=await nc(t.bridgeService);return t.stdout(`aifight.service installed and started (${o.platform}).
106
+ `),t.stdout(`unit: ${o.unitPath}
107
+ `),o.warning&&t.stderr(`warning: ${o.warning}
108
+ `),"installed"}catch(o){let i=(o instanceof te,o.message),s=o instanceof te?o.hint:void 0;return t.stderr(`aifight.service could not be installed: ${i}
109
+ `),s&&t.stderr(`${s}
110
+ `),"unavailable"}}async function R0(t){try{return await pn(t.bridgeService)}catch{return}}async function sm(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}import{execFile as P0}from"node:child_process";import lm from"node:fs";import um from"node:path";var T0=3e4;function Te(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(um.delimiter))if(r)for(let o of n){let i=um.join(r,`${t}${o}`);try{return lm.accessSync(i,lm.constants.X_OK),i}catch{}}}async function ot(t,e){let n=Te(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};P0(n,e,{timeout:T0},(a,c,l)=>{let u=a?.code;i({code:typeof u=="number"?u:a?1:0,stdout:String(c??""),stderr:String(l??"")})}).on("error",a=>{i({code:1,stdout:"",stderr:a.message})})})}function gn(t,e,n){n.stdout.trim()&&t.stdout(`${e}: ${n.stdout.trim()}
105
111
  `),n.stderr.trim()&&t.stderr(`${e}: ${n.stderr.trim()}
106
- `)}async function oc(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}async function Gr(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}async function Xn(t,e,n,r={}){let o=await T0(e),i=e==="openclaw"?"OpenClaw Gateway":"Hermes Gateway";if(o===void 0)return t.stdout([`${i} needs a restart for this change to apply.`,"I could not safely detect how it is managed, so I will not restart it automatically.",`Manual restart options: ${I0(e)}`,""].join(`
112
+ `)}async function ii(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}async function zr(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}async function Xn(t,e,n,r={}){let o=await A0(e),i=e==="openclaw"?"OpenClaw Gateway":"Hermes Gateway";if(o===void 0)return t.stdout([`${i} needs a restart for this change to apply.`,"I could not safely detect how it is managed, so I will not restart it automatically.",`Manual restart options: ${O0(e)}`,""].join(`
107
113
  `)),!1;if(t.stdout([`${i} needs a restart for this change to apply.`,`Detected restart method: ${o.label}.`,`Reason: ${n}`,"Restarting may interrupt any current OpenClaw/Hermes tasks using this Gateway.",o.note??"",`Command I would run: ${o.manualCommand}`,""].filter(c=>c!=="").join(`
108
114
  `)+`
109
- `),!(r.approvedLocalSetup===!0?!0:await Gr(t,"Restart now? [y/N] ")))return t.stdout(`Skipped restart. Run when ready: ${o.manualCommand}
115
+ `),!(r.approvedLocalSetup===!0?!0:await zr(t,"Restart now? [y/N] ")))return t.stdout(`Skipped restart. Run when ready: ${o.manualCommand}
110
116
 
111
117
  `),!1;r.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting now.
112
- `);let a=await vt(o.command,o.args);return hn(t,o.manualCommand,a),e==="hermes"&&C0(a)?(t.stdout("Hermes reported that no restartable service is available. Start it manually with `hermes gateway run` when ready.\n\n"),!1):a.code!==0?(t.stderr(`Restart command did not complete successfully. Run manually when ready: ${o.manualCommand}
118
+ `);let a=await ot(o.command,o.args);return gn(t,o.manualCommand,a),e==="hermes"&&I0(a)?(t.stdout("Hermes reported that no restartable service is available. Start it manually with `hermes gateway run` when ready.\n\n"),!1):a.code!==0?(t.stderr(`Restart command did not complete successfully. Run manually when ready: ${o.manualCommand}
113
119
 
114
120
  `),!1):(t.stdout(`${i} restart requested.
115
121
 
116
- `),!0)}async function T0(t){let e=await A0(t);if(e)return e;if(t==="openclaw"&&Le("openclaw"))return{label:"OpenClaw CLI",command:"openclaw",args:["gateway","restart","--safe"],manualCommand:"openclaw gateway restart --safe",note:"This uses OpenClaw's own safe restart command instead of killing a process."};if(t==="hermes"&&Le("hermes"))return{label:"Hermes CLI",command:"hermes",args:["gateway","restart"],manualCommand:"hermes gateway restart",note:"If Hermes is running in a foreground terminal, stop that process and run `hermes gateway run` when ready."}}async function A0(t){if(process.platform!=="linux"||!Le("systemctl"))return;let e=t==="openclaw"?["openclaw-gateway.service","openclaw.gateway.service","openclaw.service"]:["hermes-gateway.service","hermes.gateway.service","hermes.service"];for(let n of[[],["--user"]])for(let r of e){let o=await vt("systemctl",[...n,"is-active",r]);if(x0(o)){let i=n.length>0?`${n.join(" ")} `:"";return{label:`systemd ${i}${r}`.trim(),command:"systemctl",args:[...n,"restart",r],manualCommand:`systemctl ${i}restart ${r}`}}}}function x0(t){return t.code===0&&t.stdout.trim()==="active"}function C0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
117
- ${t.stderr}`)}function I0(t){return t==="openclaw"?"`openclaw gateway restart --safe`, or restart your own OpenClaw service manager":"`hermes gateway restart`, or restart the terminal running `hermes gateway run`"}import{randomBytes as M0}from"node:crypto";import Zn from"node:fs";import L0 from"node:os";import dm from"node:path";import zr from"node:fs";import O0 from"node:path";function ic(){return O0.join(ne(),"runtime-setup.json")}function sc(){try{let t=zr.readFileSync(ic(),"utf8"),e=JSON.parse(t);return N0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function ac(t){it();let e=sc(),n={version:1,updatedAt:new Date().toISOString(),...e?.openclaw?{openclaw:e.openclaw}:{},...e?.hermes?{hermes:e.hermes}:{},...t.openclaw?{openclaw:t.openclaw}:{},...t.hermes?{hermes:t.hermes}:{}},r=ic(),o=`${r}.tmp`;if(zr.writeFileSync(o,JSON.stringify(n,null,2)+`
118
- `,{mode:384}),zr.renameSync(o,r),process.platform!=="win32")try{zr.chmodSync(r,384)}catch{}}function um(){zr.rmSync(ic(),{force:!0})}function N0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var lc="gateway.http.endpoints.responses.enabled",fm=4e3,j0=6e3,mm=1e4;async function pm(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return await D0(t),{};case"hermes":return F0(t);case"mock":return{}}}async function D0(t){let e=await Kr(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable"){t.env.stdout(`OpenClaw local /v1/responses is reachable (${e.detail}).
122
+ `),!0)}async function A0(t){let e=await C0(t);if(e)return e;if(t==="openclaw"&&Te("openclaw"))return{label:"OpenClaw CLI",command:"openclaw",args:["gateway","restart","--safe"],manualCommand:"openclaw gateway restart --safe",note:"This uses OpenClaw's own safe restart command instead of killing a process."};if(t==="hermes"&&Te("hermes"))return{label:"Hermes CLI",command:"hermes",args:["gateway","restart"],manualCommand:"hermes gateway restart",note:"If Hermes is running in a foreground terminal, stop that process and run `hermes gateway run` when ready."}}async function C0(t){if(process.platform!=="linux"||!Te("systemctl"))return;let e=t==="openclaw"?["openclaw-gateway.service","openclaw.gateway.service","openclaw.service"]:["hermes-gateway.service","hermes.gateway.service","hermes.service"];for(let n of[[],["--user"]])for(let r of e){let o=await ot("systemctl",[...n,"is-active",r]);if(x0(o)){let i=n.length>0?`${n.join(" ")} `:"";return{label:`systemd ${i}${r}`.trim(),command:"systemctl",args:[...n,"restart",r],manualCommand:`systemctl ${i}restart ${r}`}}}}function x0(t){return t.code===0&&t.stdout.trim()==="active"}function I0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
123
+ ${t.stderr}`)}function O0(t){return t==="openclaw"?"`openclaw gateway restart --safe`, or restart your own OpenClaw service manager":"`hermes gateway restart`, or restart the terminal running `hermes gateway run`"}import{randomBytes as L0}from"node:crypto";import Zn from"node:fs";import j0 from"node:os";import fm from"node:path";import Kr from"node:fs";import N0 from"node:path";function sc(){return N0.join(re(),"runtime-setup.json")}function ac(){try{let t=Kr.readFileSync(sc(),"utf8"),e=JSON.parse(t);return M0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function cc(t){st();let e=ac(),n={version:1,updatedAt:new Date().toISOString(),...e?.openclaw?{openclaw:e.openclaw}:{},...e?.hermes?{hermes:e.hermes}:{},...t.openclaw?{openclaw:t.openclaw}:{},...t.hermes?{hermes:t.hermes}:{}},r=sc(),o=`${r}.tmp`;if(Kr.writeFileSync(o,JSON.stringify(n,null,2)+`
124
+ `,{mode:384}),Kr.renameSync(o,r),process.platform!=="win32")try{Kr.chmodSync(r,384)}catch{}}function dm(){Kr.rmSync(sc(),{force:!0})}function M0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var uc="gateway.http.endpoints.responses.enabled",mm=4e3,D0=6e3,pm=1e4;async function hm(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return F0(t);case"hermes":return B0(t);case"mock":return{}}}async function F0(t){let e=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`OpenClaw local /v1/responses is reachable (${e.detail}).
119
125
 
120
- `);return}if(e.status==="auth_failed"){t.env.stdout([`OpenClaw local /v1/responses is enabled but returned an auth error (${e.detail}).`,"If your Gateway requires a local token, rerun register with:"," aifight register --runtime-token <OPENCLAW_GATEWAY_TOKEN>",""].join(`
121
- `));return}if(t.env.stdout(["OpenClaw needs its local /v1/responses endpoint enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call OpenClaw only on localhost / 127.0.0.1.","Your model/provider keys stay inside OpenClaw.","If Gateway is already running, it may need a safe restart for this change to apply.","","I can run:",` openclaw config set ${lc} true --strict-json`," openclaw config validate",""].join(`
122
- `)),!Le("openclaw")){t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
126
+ `),{};if(e.status==="auth_failed"){if(t.runtimeLocalToken!==void 0)return t.env.stdout(`OpenClaw local /v1/responses rejected the provided runtime token (${e.detail}).
123
127
 
124
- `);return}if(!(t.approvedLocalSetup===!0?!0:await oc(t.env,"Allow this local OpenClaw config change now? [Y/n] "))){t.env.stdout(`Skipped OpenClaw config change. You can run the command above later.
128
+ `),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."};if(t.env.stdout([`OpenClaw local /v1/responses is enabled but requires a local Gateway token (${e.detail}).`,"AIFight can store that token only in the local bridge credentials so the bridge can call localhost.","The token is not uploaded to AIFight and will not be printed.",""].join(`
129
+ `)),!(t.approvedLocalSetup===!0?!0:await ii(t.env,"Allow AIFight to read and store the local OpenClaw Gateway token now? [Y/n] ")))return{blockedReason:"OpenClaw requires a local Gateway token before AIFight registration can finish."};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; reading the local OpenClaw Gateway token now.
130
+ `);let u=await W0();if(u.length===0)return t.env.stdout("Could not find an OpenClaw Gateway token from OPENCLAW_GATEWAY_TOKEN or `openclaw config get gateway.auth.token`.\n\n"),{blockedReason:"OpenClaw requires a local Gateway token before AIFight registration can finish."};for(let d of u){let h=await er(t.env,t.runtimeLocalUrl,d,t.runtimeModel);if(h.status==="ready"||h.status==="endpoint_reachable")return t.env.stdout(`OpenClaw accepted a local Gateway token (${h.detail}).
125
131
 
126
- `);return}t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; applying OpenClaw config now.
127
- `);let r=await W0(),o=await vt("openclaw",["config","set",lc,"true","--strict-json"]);if(hn(t.env,"openclaw config set",o),o.code!==0){t.env.stderr(`OpenClaw config update failed. Continue only after enabling /v1/responses manually.
132
+ `),{runtimeLocalToken:d}}return t.env.stdout(`OpenClaw did not accept any discovered local Gateway token.
128
133
 
129
- `);return}let i=await vt("openclaw",["config","validate"]);hn(t.env,"openclaw config validate",i),ac({openclaw:{responsesEnabledByAIFight:r!==!0,updatedAt:new Date().toISOString()}}),t.env.stdout(`OpenClaw config updated. Gateway may need a restart before the endpoint is available.
130
- `),await uc(j0);let s=await Kr(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(s.status==="ready"||s.status==="endpoint_reachable"){t.env.stdout(`OpenClaw endpoint check: ${s.detail}
134
+ `),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."}}if(t.env.stdout(["OpenClaw needs its local /v1/responses endpoint enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call OpenClaw only on localhost / 127.0.0.1.","Your model/provider keys stay inside OpenClaw.","If Gateway is already running, it may need a safe restart for this change to apply.","","I can run:",` openclaw config set ${uc} true --strict-json`," openclaw config validate",""].join(`
135
+ `)),!Te("openclaw"))return t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
131
136
 
132
- `);return}if(t.env.stdout(`OpenClaw endpoint is still not ready (${s.detail}).
133
- `),!await Xn(t.env,"openclaw","OpenClaw /v1/responses was enabled for AIFight.",{approvedLocalSetup:t.approvedLocalSetup})){t.env.stdout(`OpenClaw endpoint will be available after you restart Gateway when ready.
137
+ `),{};if(!(t.approvedLocalSetup===!0?!0:await ii(t.env,"Allow this local OpenClaw config change now? [Y/n] ")))return t.env.stdout(`Skipped OpenClaw config change. You can run the command above later.
134
138
 
135
- `);return}t.env.stdout(`Waiting 10 seconds before checking OpenClaw /v1/responses again...
136
- `),await uc(mm);let c=await Kr(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
139
+ `),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; applying OpenClaw config now.
140
+ `);let r=await z0(),o=await ot("openclaw",["config","set",uc,"true","--strict-json"]);if(gn(t.env,"openclaw config set",o),o.code!==0)return t.env.stderr(`OpenClaw config update failed. Continue only after enabling /v1/responses manually.
137
141
 
138
- `)}async function F0(t){let e=await ii(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`Hermes local API Server is reachable (${e.detail}).
142
+ `),{};let i=await ot("openclaw",["config","validate"]);gn(t.env,"openclaw config validate",i),cc({openclaw:{responsesEnabledByAIFight:r!==!0,updatedAt:new Date().toISOString()}}),t.env.stdout(`OpenClaw config updated. Gateway may need a restart before the endpoint is available.
143
+ `),await dc(D0);let s=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(s.status==="ready"||s.status==="endpoint_reachable")return t.env.stdout(`OpenClaw endpoint check: ${s.detail}
139
144
 
140
- `),{};if(t.env.stdout(["Hermes needs its local API Server enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call Hermes only on localhost / 127.0.0.1.","Your Hermes provider keys, tools, and strategy prompts stay local.","Hermes may need a Gateway restart for API_SERVER_* changes to apply.","","I can update ~/.hermes/.env with:"," API_SERVER_ENABLED=true"," API_SERVER_HOST=127.0.0.1",` API_SERVER_PORT=${gm(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
141
- `)),!Le("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
145
+ `),{};if(t.env.stdout(`OpenClaw endpoint is still not ready (${s.detail}).
146
+ `),!await Xn(t.env,"openclaw","OpenClaw /v1/responses was enabled for AIFight.",{approvedLocalSetup:t.approvedLocalSetup}))return t.env.stdout(`OpenClaw endpoint will be available after you restart Gateway when ready.
142
147
 
143
- `),{};if(!(t.approvedLocalSetup===!0?!0:await oc(t.env,"Allow this local Hermes .env update now? [Y/n] ")))return t.env.stdout(`Skipped Hermes .env update. You can add the API_SERVER_* values later.
148
+ `),{};t.env.stdout(`Waiting 10 seconds before checking OpenClaw /v1/responses again...
149
+ `),await dc(pm);let c=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);return t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
150
+
151
+ `),{}}async function B0(t){let e=await si(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`Hermes local API Server is reachable (${e.detail}).
152
+
153
+ `),{};if(t.env.stdout(["Hermes needs its local API Server enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call Hermes only on localhost / 127.0.0.1.","Your Hermes provider keys, tools, and strategy prompts stay local.","Hermes may need a Gateway restart for API_SERVER_* changes to apply.","","I can update ~/.hermes/.env with:"," API_SERVER_ENABLED=true"," API_SERVER_HOST=127.0.0.1",` API_SERVER_PORT=${ym(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
154
+ `)),!Te("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
155
+
156
+ `),{};if(!(t.approvedLocalSetup===!0?!0:await ii(t.env,"Allow this local Hermes .env update now? [Y/n] ")))return t.env.stdout(`Skipped Hermes .env update. You can add the API_SERVER_* values later.
144
157
 
145
158
  `),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; updating Hermes .env now.
146
- `);let r=B0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(ac({hermes:{envPath:r.envPath,previous:r.previous,updatedAt:new Date().toISOString()}}),t.env.stdout(`Hermes .env updated and backed up if it already existed.
159
+ `);let r=q0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(cc({hermes:{envPath:r.envPath,previous:r.previous,updatedAt:new Date().toISOString()}}),t.env.stdout(`Hermes .env updated and backed up if it already existed.
147
160
  `),t.env.stdout(`Hermes does not hot-reload API_SERVER_* settings.
148
161
  `),!await Xn(t.env,"hermes","Hermes API Server settings were updated for AIFight.",{approvedLocalSetup:t.approvedLocalSetup}))return t.env.stdout(`Hermes API Server will be available after you start or restart Gateway when ready.
149
162
 
150
163
  `),{runtimeLocalToken:o};t.env.stdout(`Waiting 10 seconds before checking Hermes /v1/responses again...
151
- `),await uc(mm);let s=await ii(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
164
+ `),await dc(pm);let s=await si(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
152
165
 
153
- `),{runtimeLocalToken:o}}async function Kr(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),fm);try{let a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let c=await o(`${e.replace(/\/+$/,"")}/v1/responses`,{method:"POST",headers:a,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'}),signal:i.signal});return c.status===404?{status:"disabled",detail:"OpenClaw /v1/responses returned HTTP 404"}:c.status===401||c.status===403?{status:"auth_failed",detail:`OpenClaw /v1/responses returned HTTP ${c.status}`}:c.ok?{status:"ready",detail:`OpenClaw /v1/responses HTTP ${c.status}`}:{status:"endpoint_reachable",detail:`OpenClaw /v1/responses HTTP ${c.status}`}}catch(a){let c=a instanceof Error&&a.name==="AbortError"?"OpenClaw /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config":`OpenClaw /v1/responses is not reachable (${a instanceof Error?a.message:String(a)})`;return{status:a instanceof Error&&a.name==="AbortError"?"endpoint_reachable":"unreachable",detail:c}}finally{clearTimeout(s)}}async function ii(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await cc(o,`${i}/health`,{});if(!s.ok)return{status:"unreachable",detail:`Hermes /health HTTP ${s.status}`};let a={};n&&(a.Authorization=`Bearer ${n}`);let c=await cc(o,`${i}/v1/models`,{headers:a});if(c.status===401||c.status===403)return{status:"auth_failed",detail:`Hermes /v1/models HTTP ${c.status}; check API_SERVER_KEY and --runtime-token`};if(!c.ok)return{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}`};let l={"Content-Type":"application/json",...a},u;try{u=await cc(o,`${i}/v1/responses`,{method:"POST",headers:l,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'})})}catch(d){return d instanceof Error&&d.name==="AbortError"?{status:"endpoint_reachable",detail:"Hermes /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config"}:{status:"unreachable",detail:`Hermes /v1/responses is not reachable (${d instanceof Error?d.message:String(d)})`}}return u.status===404?{status:"disabled",detail:"Hermes /v1/responses returned HTTP 404"}:u.status===401||u.status===403?{status:"auth_failed",detail:`Hermes /v1/responses HTTP ${u.status}; check API_SERVER_KEY and --runtime-token`}:u.ok?{status:"ready",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}:{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}}catch(s){return{status:"unreachable",detail:`Hermes API Server is not reachable (${s instanceof Error?s.message:String(s)})`}}}async function cc(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),fm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function B0(t){let e=process.env.HERMES_HOME??dm.join(L0.homedir(),".hermes");Zn.mkdirSync(e,{recursive:!0,mode:448});let n=dm.join(e,".env"),r=Zn.existsSync(n)?Zn.readFileSync(n,"utf8"):"";if(r!==""){let l=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");Zn.copyFileSync(n,`${n}.aifight-backup-${l}`)}let o=hm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${M0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:U0(t.runtimeLocalUrl),API_SERVER_PORT:String(gm(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=H0(r,Object.keys(s)),c=q0(r,s);if(Zn.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{Zn.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function q0(t,e){let n=new Set(Object.keys(e)),r=new Set,i=t.split(/\r?\n/).map(s=>{let a=s.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!a)return s;let c=a[3];return n.has(c)?(r.add(c),`${c}=${e[c]}`):s});if(i.length>0&&i[i.length-1]!==""&&i.push(""),[...n].some(s=>!r.has(s))){i.push("# AIFight local API Server settings");for(let s of Object.keys(e))r.has(s)||i.push(`${s}=${e[s]}`)}return i.join(`
166
+ `),{runtimeLocalToken:o}}async function er(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),mm);try{let a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let c=await o(`${e.replace(/\/+$/,"")}/v1/responses`,{method:"POST",headers:a,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'}),signal:i.signal});return c.status===404?{status:"disabled",detail:"OpenClaw /v1/responses returned HTTP 404"}:c.status===401||c.status===403?{status:"auth_failed",detail:`OpenClaw /v1/responses returned HTTP ${c.status}`}:c.ok?{status:"ready",detail:`OpenClaw /v1/responses HTTP ${c.status}`}:{status:"endpoint_reachable",detail:`OpenClaw /v1/responses HTTP ${c.status}`}}catch(a){let c=a instanceof Error&&a.name==="AbortError"?"OpenClaw /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config":`OpenClaw /v1/responses is not reachable (${a instanceof Error?a.message:String(a)})`;return{status:a instanceof Error&&a.name==="AbortError"?"endpoint_reachable":"unreachable",detail:c}}finally{clearTimeout(s)}}async function si(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await lc(o,`${i}/health`,{});if(!s.ok)return{status:"unreachable",detail:`Hermes /health HTTP ${s.status}`};let a={};n&&(a.Authorization=`Bearer ${n}`);let c=await lc(o,`${i}/v1/models`,{headers:a});if(c.status===401||c.status===403)return{status:"auth_failed",detail:`Hermes /v1/models HTTP ${c.status}; check API_SERVER_KEY and --runtime-token`};if(!c.ok)return{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}`};let l={"Content-Type":"application/json",...a},u;try{u=await lc(o,`${i}/v1/responses`,{method:"POST",headers:l,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'})})}catch(d){return d instanceof Error&&d.name==="AbortError"?{status:"endpoint_reachable",detail:"Hermes /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config"}:{status:"unreachable",detail:`Hermes /v1/responses is not reachable (${d instanceof Error?d.message:String(d)})`}}return u.status===404?{status:"disabled",detail:"Hermes /v1/responses returned HTTP 404"}:u.status===401||u.status===403?{status:"auth_failed",detail:`Hermes /v1/responses HTTP ${u.status}; check API_SERVER_KEY and --runtime-token`}:u.ok?{status:"ready",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}:{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}}catch(s){return{status:"unreachable",detail:`Hermes API Server is not reachable (${s instanceof Error?s.message:String(s)})`}}}async function lc(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),mm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function q0(t){let e=process.env.HERMES_HOME??fm.join(j0.homedir(),".hermes");Zn.mkdirSync(e,{recursive:!0,mode:448});let n=fm.join(e,".env"),r=Zn.existsSync(n)?Zn.readFileSync(n,"utf8"):"";if(r!==""){let l=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");Zn.copyFileSync(n,`${n}.aifight-backup-${l}`)}let o=gm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${L0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:H0(t.runtimeLocalUrl),API_SERVER_PORT:String(ym(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=G0(r,Object.keys(s)),c=U0(r,s);if(Zn.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{Zn.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function U0(t,e){let n=new Set(Object.keys(e)),r=new Set,i=t.split(/\r?\n/).map(s=>{let a=s.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!a)return s;let c=a[3];return n.has(c)?(r.add(c),`${c}=${e[c]}`):s});if(i.length>0&&i[i.length-1]!==""&&i.push(""),[...n].some(s=>!r.has(s))){i.push("# AIFight local API Server settings");for(let s of Object.keys(e))r.has(s)||i.push(`${s}=${e[s]}`)}return i.join(`
154
167
  `).replace(/\n*$/,`
155
- `)}function hm(t,e){for(let n of t.split(/\r?\n/)){if(n.trimStart().startsWith("#"))continue;let r=n.match(new RegExp(`^\\s*${e}\\s*=\\s*(.*)\\s*$`));if(!r)continue;return r[1].trim().replace(/^['"]|['"]$/g,"")}}function U0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function gm(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function H0(t,e){let n={};for(let r of e){let o=hm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function W0(){let t=await vt("openclaw",["config","get",lc]);if(t.code!==0)return;let e=t.stdout.trim().toLowerCase();if(e==="true"||e.endsWith(" true"))return!0;if(e==="false"||e.endsWith(" false"))return!1}function uc(t){return new Promise(e=>setTimeout(e,t))}var z0="https://aifight.ai",ym=2,K0="approved-local-setup",gn=["usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Creates a private bootstrap AIFight identity, saves local match credentials, and offers aifight.service."," In human interactive mode, asks which local runtime to use when none is specified."," --approved-local-setup is for Agent-assisted setup after the human already approved local runtime/service changes."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Claim the agent and choose its official Dashboard name before it can play matches or challenges."].join(`
156
- `);async function wm(t,e){J(t,0,1,gn);let n=t.flags[K0]===!0;if(t.jsonMode&&n)throw new O("--approved-local-setup cannot be combined with --json",gn);let r=await J0(t,e,n),o=X0(t,r),i=Z0(process.env.AIFIGHT_BASE_URL??z0),s=Jr(t.flags,"runtime-model")??Mt(r),a=tE(Jr(t.flags,"runtime-url")??Kn(r),r),c=Jr(t.flags,"runtime-token");try{let l=await pm({env:e,runtimeType:r,runtimeLocalUrl:a,runtimeLocalToken:c,runtimeModel:s,jsonMode:t.jsonMode,approvedLocalSetup:n});c=c??l.runtimeLocalToken;let u=await ua({baseUrl:i,request:{name:o,model:s,description:`AIFight Bridge agent (${r})`},fetchImpl:e.fetchImpl}),d={version:1,baseUrl:i,wsUrl:eE(i),agentId:u.agentId,agentName:u.response.agent.name,suggestedName:u.response.agent.suggested_name??o,apiKey:u.apiKey,claimUrl:u.claimUrl,claimToken:u.claimToken,runtimeType:r,runtimeLocalUrl:a,...c!==void 0?{runtimeLocalToken:c}:{},runtimeModel:s,autoDailyLimit:ym,updatedAt:new Date().toISOString()};return mn(d),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:u.claimUrl,config:Lt(d)})+`
168
+ `)}function gm(t,e){for(let n of t.split(/\r?\n/)){if(n.trimStart().startsWith("#"))continue;let r=n.match(new RegExp(`^\\s*${e}\\s*=\\s*(.*)\\s*$`));if(!r)continue;return r[1].trim().replace(/^['"]|['"]$/g,"")}}function H0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function ym(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function G0(t,e){let n={};for(let r of e){let o=gm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function W0(){let t=[],e=o=>{o&&!t.includes(o)&&t.push(o)},n=process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e(n),!Te("openclaw"))return t;let r=await ot("openclaw",["config","get","gateway.auth.token"]);return r.code===0&&e(V0(r.stdout)),t}function V0(t){let e=t.trim();if(e===""||e.toLowerCase()==="null"||e.toLowerCase()==="undefined")return;try{let i=JSON.parse(e);if(typeof i=="string"&&i.trim()!=="")return i.trim();if(i&&typeof i=="object"){let s=i.value??i.token??i["gateway.auth.token"];if(typeof s=="string"&&s.trim()!=="")return s.trim()}}catch{}let n=e.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0);if(!n)return;let o=(n.match(/(?:gateway\.auth\.token|token)\s*[:=]\s*(.+)$/i)?.[1]??n).trim().replace(/^['"]|['"]$/g,"");return o.length>0?o:void 0}async function z0(){let t=await ot("openclaw",["config","get",uc]);if(t.code!==0)return;let e=t.stdout.trim().toLowerCase();if(e==="true"||e.endsWith(" true"))return!0;if(e==="false"||e.endsWith(" false"))return!1}function dc(t){return new Promise(e=>setTimeout(e,t))}var Y0="https://aifight.ai",_m=2,Q0="approved-local-setup",yn=["usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Creates a private bootstrap AIFight identity, saves local match credentials, and offers aifight.service."," In human interactive mode, asks which local runtime to use when none is specified."," --approved-local-setup is for Agent-assisted setup after the human already approved local runtime/service changes."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Claim the agent and choose its official Dashboard name before it can play matches or challenges."].join(`
169
+ `);async function vm(t,e){J(t,0,1,yn);let n=t.flags[Q0]===!0;if(t.jsonMode&&n)throw new O("--approved-local-setup cannot be combined with --json",yn);let r=await X0(t,e,n),o=tE(t,r),i=nE(process.env.AIFIGHT_BASE_URL??Y0),s=Jr(t.flags,"runtime-model")??Mt(r),a=oE(Jr(t.flags,"runtime-url")??Jn(r),r),c=Jr(t.flags,"runtime-token");try{let l=await hm({env:e,runtimeType:r,runtimeLocalUrl:a,runtimeLocalToken:c,runtimeModel:s,jsonMode:t.jsonMode,approvedLocalSetup:n});if(l.blockedReason!==void 0)throw new W("runtime_setup_incomplete",l.blockedReason);c=c??l.runtimeLocalToken;let u=await da({baseUrl:i,request:{name:o,model:s,description:`AIFight Bridge agent (${r})`},fetchImpl:e.fetchImpl}),d={version:1,baseUrl:i,wsUrl:rE(i),agentId:u.agentId,agentName:u.response.agent.name,suggestedName:u.response.agent.suggested_name??o,apiKey:u.apiKey,claimUrl:u.claimUrl,claimToken:u.claimToken,runtimeType:r,runtimeLocalUrl:a,...c!==void 0?{runtimeLocalToken:c}:{},runtimeModel:s,autoDailyLimit:_m,updatedAt:new Date().toISOString()};return mn(d),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:u.claimUrl,config:Lt(d)})+`
157
170
  `),0):(e.stdout(`AIFight Agent registered.
158
171
 
159
172
  `),e.stdout(`Bootstrap ID: ${d.agentName}
160
173
  `),e.stdout(`Suggested name: ${d.suggestedName??o}
161
174
  `),e.stdout(`Status: unclaimed, official name pending
162
- `),e.stdout(`Runtime: ${vm(d.runtimeType)} at ${d.runtimeLocalUrl}
163
- `),e.stdout(`Automatic ranked matches: ${ym} per day
175
+ `),e.stdout(`Runtime: ${bm(d.runtimeType)} at ${d.runtimeLocalUrl}
176
+ `),e.stdout(`Automatic ranked matches: ${_m} per day
164
177
  `),e.stdout(`Local credentials saved on this machine.
165
178
 
166
179
  `),e.stdout(`Claim URL:
@@ -168,77 +181,78 @@ ${t.stderr}`)}function I0(t){return t==="openclaw"?"`openclaw gateway restart --
168
181
 
169
182
  `),e.stdout(`Claim this agent, then confirm its official public name in Dashboard before starting matches, challenges, or Grand Prix events. Claiming also enables dashboard management, profile settings, and recovery.
170
183
 
171
- `),await am(e,{approvedLocalSetup:n})==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
184
+ `),await cm(e,{approvedLocalSetup:n})==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
172
185
 
173
186
  `),e.stdout(`Normal use requires a long-running local Bridge.
174
187
  `),e.stdout(`Finish setup with:
175
188
  `),e.stdout(` aifight service install
176
189
 
177
190
  `),e.stdout(`Advanced alternatives:
178
- `),e.stdout(" - Manage `aifight run` with your own process manager.\n"),e.stdout(" - For developer debugging only, run `aifight run` in a terminal.\n")),0)}catch(l){if(l instanceof Xt){let u=typeof l.body=="object"?l.body.error:void 0;throw new z("registration_failed",u??`registration failed with HTTP ${l.status}`)}throw l instanceof ft?new z("registration_failed",l.message):l}}function vm(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function J0(t,e,n){let r=t.positional[0],o=Jr(t.flags,"runtime"),i=process.env.AIFIGHT_RUNTIME_TYPE,s=o??r??i;if(o!==void 0&&r!==void 0&&o!==r)throw new O("runtime argument and --runtime disagree",gn);if(s==="openclaw"||s==="hermes")return s;if(s===void 0){if(n){let a=await Y0(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${vm(a.runtimeType)} (${a.detail}).
191
+ `),e.stdout(" - Manage `aifight run` with your own process manager.\n"),e.stdout(" - For developer debugging only, run `aifight run` in a terminal.\n")),0)}catch(l){if(l instanceof Xt){let u=typeof l.body=="object"?l.body.error:void 0;throw new W("registration_failed",u??`registration failed with HTTP ${l.status}`)}throw l instanceof mt?new W("registration_failed",l.message):l}}function bm(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function X0(t,e,n){let r=t.positional[0],o=Jr(t.flags,"runtime"),i=process.env.AIFIGHT_RUNTIME_TYPE,s=o??r??i;if(o!==void 0&&r!==void 0&&o!==r)throw new O("runtime argument and --runtime disagree",yn);if(s==="openclaw"||s==="hermes")return s;if(s===void 0){if(n){let a=await Z0(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${bm(a.runtimeType)} (${a.detail}).
179
192
 
180
193
  `),a.runtimeType;throw new O(["Could not safely auto-detect whether this machine is running OpenClaw or Hermes.",a.detail,"Rerun with an explicit runtime:"," aifight register openclaw --approved-local-setup"," aifight register hermes --approved-local-setup"].join(`
181
- `),gn)}return!t.jsonMode&&process.stdin.isTTY?Q0(e):"openclaw"}throw new O(`runtime must be openclaw or hermes (got '${s}')`,gn)}async function Y0(t){let[e,n]=await Promise.all([Kr(t,Kn("openclaw"),void 0,Mt("openclaw")),ii(t,Kn("hermes"),void 0,Mt("hermes"))]),r=_m(e),o=_m(n);if(r>o)return{runtimeType:"openclaw",detail:e.detail};if(o>r)return{runtimeType:"hermes",detail:n.detail};if(r>0&&o>0)return{detail:`OpenClaw and Hermes both looked reachable: ${e.detail}; ${n.detail}`};let i=Le("openclaw")!==void 0,s=Le("hermes")!==void 0;if(i&&!s)return{runtimeType:"openclaw",detail:"OpenClaw CLI found on PATH; Hermes CLI not found"};if(s&&!i)return{runtimeType:"hermes",detail:"Hermes CLI found on PATH; OpenClaw CLI not found"};let a=i&&s?"both OpenClaw and Hermes CLIs are installed":"neither OpenClaw nor Hermes CLI was found on PATH";return{detail:`OpenClaw probe: ${e.detail}; Hermes probe: ${n.detail}; ${a}.`}}function _m(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function Q0(t){t.stdout(["Which local Agent runtime should this Bridge use?"," 1) OpenClaw (default)"," 2) Hermes","","Runtime [OpenClaw]: "].join(`
182
- `)),process.stdin.resume(),process.stdin.setEncoding("utf8");let e=await new Promise(r=>{process.stdin.once("data",o=>r(String(o)))});process.stdin.pause();let n=e.trim().toLowerCase();if(n===""||n==="1"||n==="openclaw"||n==="o")return"openclaw";if(n==="2"||n==="hermes"||n==="h")return"hermes";throw new O(`runtime must be openclaw or hermes (got '${e.trim()}')`,gn)}function X0(t,e){let n=Jr(t.flags,"name");if(n!==void 0)return n;let r=V0.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${G0(3).toString("hex")}`.slice(0,50)}function Z0(t){return t.replace(/\/+$/,"")}function eE(t){let e=new URL(t);if(e.protocol==="https:")e.protocol="wss:";else if(e.protocol==="http:")e.protocol="ws:";else throw new Error(`unsupported AIFight base URL protocol: ${e.protocol}`);return e.pathname="/api/ws",e.search="",e.hash="",e.toString()}function Jr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function tE(t,e){try{return Hr(t,e)}catch(n){throw n instanceof He?new O(n.message,gn):n}}var nE="https://aifight.ai";async function bm(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=rE(t.baseUrl??process.env.AIFIGHT_BASE_URL??nE),o=await(t.fetchImpl??globalThis.fetch)(`${n}/api/bridge/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_code:e})});if(!o.ok){let l=await oE(o);throw new Error(l)}let i=await o.json(),s=iE(i),a=s.agent.runtime_type,c=t.now??(()=>new Date);return{version:1,baseUrl:n,wsUrl:s.ws_url,agentId:s.agent.id,agentName:s.agent.name,apiKey:s.agent.api_key,runtimeType:a,runtimeLocalUrl:Kn(a),runtimeModel:Mt(a),updatedAt:c().toISOString()}}function rE(t){return t.replace(/\/+$/,"")}async function oE(t){let e=await t.json().catch(()=>{});if(e&&typeof e=="object"){let n=e.error;if(typeof n=="string"&&n.length>0)return n}return`pairing failed with HTTP ${t.status}`}function iE(t){if(!t||typeof t!="object")throw new Error("pairing response was not an object");let e=t,n=e.agent;if(!n||typeof n!="object")throw new Error("pairing response missing agent");let r=n;if(typeof r.id!="string"||typeof r.name!="string"||typeof r.api_key!="string"||r.runtime_type!=="openclaw"&&r.runtime_type!=="hermes"&&r.runtime_type!=="mock"||typeof e.ws_url!="string")throw new Error("pairing response had invalid fields");return{agent:{id:r.id,name:r.name,api_key:r.api_key,runtime_type:r.runtime_type},ws_url:e.ws_url,...typeof e.message=="string"?{message:e.message}:{}}}var Em=["usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," --runtime-token is local only; it is never sent to AIFight."].join(`
183
- `);async function $m(t,e){J(t,1,1,Em);let n=t.positional[0],r;try{r=await bm({pairingCode:n,fetchImpl:e.fetchImpl})}catch(l){let u=l instanceof Error?l.message:String(l);throw new z("pairing_failed",u)}let o={...r,...Sm(t.flags,"runtime-token","runtimeLocalToken"),...Sm(t.flags,"runtime-model","runtimeModel")},i=t.flags["runtime-url"],s=typeof i=="string"&&i.trim()!==""?i.trim():void 0,a=sE(s??o.runtimeLocalUrl,o.runtimeType),c={...o,runtimeLocalUrl:a};return mn(c),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Lt(c)})+`
194
+ `),yn)}return!t.jsonMode&&process.stdin.isTTY?eE(e):"openclaw"}throw new O(`runtime must be openclaw or hermes (got '${s}')`,yn)}async function Z0(t){let[e,n]=await Promise.all([er(t,Jn("openclaw"),void 0,Mt("openclaw")),si(t,Jn("hermes"),void 0,Mt("hermes"))]),r=wm(e),o=wm(n);if(r>o)return{runtimeType:"openclaw",detail:e.detail};if(o>r)return{runtimeType:"hermes",detail:n.detail};if(r>0&&o>0)return{detail:`OpenClaw and Hermes both looked reachable: ${e.detail}; ${n.detail}`};let i=Te("openclaw")!==void 0,s=Te("hermes")!==void 0;if(i&&!s)return{runtimeType:"openclaw",detail:"OpenClaw CLI found on PATH; Hermes CLI not found"};if(s&&!i)return{runtimeType:"hermes",detail:"Hermes CLI found on PATH; OpenClaw CLI not found"};let a=i&&s?"both OpenClaw and Hermes CLIs are installed":"neither OpenClaw nor Hermes CLI was found on PATH";return{detail:`OpenClaw probe: ${e.detail}; Hermes probe: ${n.detail}; ${a}.`}}function wm(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function eE(t){t.stdout(["Which local Agent runtime should this Bridge use?"," 1) OpenClaw (default)"," 2) Hermes","","Runtime [OpenClaw]: "].join(`
195
+ `)),process.stdin.resume(),process.stdin.setEncoding("utf8");let e=await new Promise(r=>{process.stdin.once("data",o=>r(String(o)))});process.stdin.pause();let n=e.trim().toLowerCase();if(n===""||n==="1"||n==="openclaw"||n==="o")return"openclaw";if(n==="2"||n==="hermes"||n==="h")return"hermes";throw new O(`runtime must be openclaw or hermes (got '${e.trim()}')`,yn)}function tE(t,e){let n=Jr(t.flags,"name");if(n!==void 0)return n;let r=K0.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${J0(3).toString("hex")}`.slice(0,50)}function nE(t){return t.replace(/\/+$/,"")}function rE(t){let e=new URL(t);if(e.protocol==="https:")e.protocol="wss:";else if(e.protocol==="http:")e.protocol="ws:";else throw new Error(`unsupported AIFight base URL protocol: ${e.protocol}`);return e.pathname="/api/ws",e.search="",e.hash="",e.toString()}function Jr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function oE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof He?new O(n.message,yn):n}}var iE="https://aifight.ai";async function Sm(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=sE(t.baseUrl??process.env.AIFIGHT_BASE_URL??iE),o=await(t.fetchImpl??globalThis.fetch)(`${n}/api/bridge/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_code:e})});if(!o.ok){let l=await aE(o);throw new Error(l)}let i=await o.json(),s=cE(i),a=s.agent.runtime_type,c=t.now??(()=>new Date);return{version:1,baseUrl:n,wsUrl:s.ws_url,agentId:s.agent.id,agentName:s.agent.name,apiKey:s.agent.api_key,runtimeType:a,runtimeLocalUrl:Jn(a),runtimeModel:Mt(a),updatedAt:c().toISOString()}}function sE(t){return t.replace(/\/+$/,"")}async function aE(t){let e=await t.json().catch(()=>{});if(e&&typeof e=="object"){let n=e.error;if(typeof n=="string"&&n.length>0)return n}return`pairing failed with HTTP ${t.status}`}function cE(t){if(!t||typeof t!="object")throw new Error("pairing response was not an object");let e=t,n=e.agent;if(!n||typeof n!="object")throw new Error("pairing response missing agent");let r=n;if(typeof r.id!="string"||typeof r.name!="string"||typeof r.api_key!="string"||r.runtime_type!=="openclaw"&&r.runtime_type!=="hermes"&&r.runtime_type!=="mock"||typeof e.ws_url!="string")throw new Error("pairing response had invalid fields");return{agent:{id:r.id,name:r.name,api_key:r.api_key,runtime_type:r.runtime_type},ws_url:e.ws_url,...typeof e.message=="string"?{message:e.message}:{}}}var km=["usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," --runtime-token is local only; it is never sent to AIFight."].join(`
196
+ `);async function $m(t,e){J(t,1,1,km);let n=t.positional[0],r;try{r=await Sm({pairingCode:n,fetchImpl:e.fetchImpl})}catch(l){let u=l instanceof Error?l.message:String(l);throw new W("pairing_failed",u)}let o={...r,...Em(t.flags,"runtime-token","runtimeLocalToken"),...Em(t.flags,"runtime-model","runtimeModel")},i=t.flags["runtime-url"],s=typeof i=="string"&&i.trim()!==""?i.trim():void 0,a=lE(s??o.runtimeLocalUrl,o.runtimeType),c={...o,runtimeLocalUrl:a};return mn(c),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Lt(c)})+`
184
197
  `),0):(e.stdout(`Bridge configured for ${c.agentName} (${c.runtimeType}).
185
198
  `),e.stdout(`Runtime local URL: ${c.runtimeLocalUrl}
186
199
  `),c.runtimeLocalToken&&e.stdout(`Runtime local token: configured locally (redacted)
187
200
  `),e.stdout(`Next: aifight service install
188
- `),0)}function Sm(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function sE(t,e){try{return Hr(t,e)}catch(n){throw n instanceof He?new O(n.message,Em):n}}var dc=20,si=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${dc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${pe.join(", ")}`].join(`
189
- `);async function Pm(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,si)}let n=aE(),r=cE(t.positional,n),o=await jt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
201
+ `),0)}function Em(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function lE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof He?new O(n.message,km):n}}var fc=20,ai=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${fc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${pe.join(", ")}`].join(`
202
+ `);async function Tm(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,ai)}let n=uE(),r=dE(t.positional,n),o=await jt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
190
203
  `),e.stderr(`Update command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
191
204
  `),1;o.status==="update_recommended"&&(e.stdout(`[warn] bridge.update: ${o.message}
192
205
  `),e.stdout(`[warn] update command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
193
- `));try{await Nc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof me?new z(lE(i),uE(i),{hint:await dE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
194
- `);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${fE(r.game)} ${i} for ${n.agentName}.
206
+ `));try{await Mc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof me?new W(fE(i),mE(i),{hint:await pE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
207
+ `);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${hE(r.game)} ${i} for ${n.agentName}.
195
208
  `),e.stdout(`The running Bridge will keep your Agent online and handle the match when AIFight pairs it.
196
- `)}return 0}function aE(){try{return ae()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new z("bridge_not_configured","AIFight Bridge is not configured.",{hint:"Run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent. Then install `aifight.service` before requesting manual matches."}):t}}function cE(t,e){if(t.length===0)return{game:Rm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=km(n);if(i!==null)return{game:Rm(e.autoGames),count:i};if(st(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,si)}let r=t[1];if(!st(n))throw new O(`unsupported game '${n}'`,si);let o=km(r);if(o===null)throw new O(`N must be an integer between 1 and ${dc}`,si);return{game:n,count:o}}function km(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>dc?null:e}function Rm(t){let e=(t??pe).filter(st),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}function lE(t){return t.kind==="daemon_unreachable"?"bridge_not_running":t.kind==="runtime_files_corrupt"?"bridge_runtime_files_invalid":t.kind==="auth_failed"?"bridge_control_auth_failed":t.kind==="request_timeout"?"bridge_control_timeout":"bridge_control_failed"}function uE(t){return t.kind==="daemon_unreachable"?"AIFight Bridge is not running.":t.kind==="runtime_files_corrupt"?"AIFight Bridge runtime files are invalid.":t.kind==="auth_failed"?"AIFight Bridge rejected the local control token.":t.kind==="request_timeout"?"AIFight Bridge did not answer the local control request in time.":t.message}async function dE(t){try{let e=await Yn(t.bridgeService);if(e.installed&&e.running===!1)return"Start it with `aifight service start`, then run this command again.";if(e.installed&&e.running===!0)return"The service appears to be running, but its local control API did not answer. Try `aifight service restart` when no match is in progress."}catch(e){if(!(e instanceof ce))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function fE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Ft from"node:path";import ee from"node:fs";import mE from"node:crypto";var ye=class extends Error{name="RuntimeFilesWriteError";kind;filePath;heldByPid;cause;constructor(e,n,r,o){super(r),this.kind=e,this.filePath=n,o?.heldByPid!==void 0&&(this.heldByPid=o.heldByPid),o?.cause!==void 0&&(this.cause=o.cause)}};function Am(){return Ft.join(ne(),"token")}function xm(){return Ft.join(ne(),"port")}function mc(){return Ft.join(ne(),"pid")}function pE(){return Ft.join(ne(),"lock")}var Tm=0,hE=/^[0-9a-f]{64}$/;function pc(t,e,n){let r=Ft.dirname(t),o=Ft.basename(t);Tm+=1;let i=Ft.join(r,`${o}.${process.pid}.${Tm}.tmp`),s;try{if(s=ee.openSync(i,"w",n),ee.writeSync(s,e),ee.closeSync(s),s=void 0,process.platform!=="win32")try{ee.chmodSync(i,n)}catch{}ee.renameSync(i,t)}catch(a){if(s!==void 0)try{ee.closeSync(s)}catch{}try{ee.unlinkSync(i)}catch{}throw new ye("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Cm(){return mE.randomBytes(32).toString("hex")}function Im(t){let e=Am();if(!hE.test(t))throw new ye("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);pc(e,t,384)}function Om(t){let e=xm();if(!Number.isInteger(t)||t<1||t>65535)throw new ye("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);pc(e,String(t),420)}function Nm(t){let e=mc();if(!Number.isInteger(t)||t<1)throw new ye("write_failed",e,`pid must be a positive integer but received ${t}`);pc(e,String(t),420)}function hc(t){for(let e of[Am(),xm(),mc()])try{ee.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Mm(){let t=ne(),e;try{e=ee.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{ee.unlinkSync(Ft.join(t,n))}catch{}}var fc=new Set;function gE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function yE(t){let e;try{e=ee.readFileSync(t,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"missing"}:{kind:"read_error",cause:o}}let n=e.trim();if(n.length===0)return{kind:"invalid",raw:n};if(!/^\d+$/.test(n))return{kind:"invalid",raw:n};let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<1?{kind:"invalid",raw:n}:{kind:"valid",pid:r}}function Lm(t){let e=pE(),n=mc(),r=t?.processIsAlive??gE;if(fc.has(e))throw new ye("lock_acquire_failed",e,`lock at ${e} already held by this process; release the existing handle first (reentrancy guard)`);for(let o=0;o<2;o+=1)try{let i=ee.openSync(e,ee.constants.O_WRONLY|ee.constants.O_CREAT|ee.constants.O_EXCL,384);if(ee.closeSync(i),process.platform!=="win32")try{ee.chmodSync(e,384)}catch{}return fc.add(e),_E(e)}catch(i){if(i.code!=="EEXIST")throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=yE(n);if(a.kind==="missing")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} is missing \u2014 ambiguous (possibly a racing daemon between acquireDaemonLock and writePid); refusing to steal lock. If the previous daemon truly crashed, manually remove ${e}.`);if(a.kind==="invalid")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} content is invalid (raw="${a.raw}") \u2014 ambiguous; refusing to steal lock. Manually remove both files if you confirm no daemon is running.`);if(a.kind==="read_error")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} could not be read (${a.cause.code??"unknown"}: ${a.cause.message}) \u2014 ambiguous; refusing to steal lock.`,{cause:a.cause});if(r(a.pid))throw new ye("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{ee.unlinkSync(e)}catch{}try{ee.unlinkSync(n)}catch{}}throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function _E(t){let e=!1;return{release(){if(!e){e=!0,fc.delete(t);try{ee.unlinkSync(t)}catch{}}}}}import*as Um from"node:http";import{Buffer as _c}from"node:buffer";import*as Hm from"node:crypto";var yn=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var Wm="0.1.0-alpha.2",jm=`aifight-runtime/${Wm}`,wE="127.0.0.1",vE=0,bE=1048576,SE=5e3,B=class extends Error{name="HttpError";status;code;details;constructor(e,n,r,o){super(r),this.status=e,this.code=n,this.details=o}};function Vm(t){return t.split("/").filter(e=>e.length>0)}function Te(t){let e=Vm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function EE(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let o=t.segments[r],i=e[r];if(o.literal!==void 0){if(o.literal!==i)return null}else if(o.param!==void 0)try{n[o.param]=decodeURIComponent(i)}catch{return null}}return n}async function Dm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new B(415,"unsupported_media_type","Content-Type must be application/json");let o=[],i=0,s=!1;for await(let c of t){if(s)continue;let l=c;if(i+=l.length,i>e)throw s=!0,new B(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(l)}let a=_c.concat(o).toString("utf8");if(a.length===0)throw new B(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new B(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function Fm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new B(400,"bad_request",`${n} body must be a JSON object`,{missing_fields:[...e]});let r=t,o=e.filter(i=>!Object.prototype.hasOwnProperty.call(r,i));if(o.length>0)throw new B(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function gc(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function Bm(t){if(typeof t!="object"||t===null||!("kind"in t))return null;let e=t.kind,n=t instanceof Error?t.message:"schedule operation failed";return e==="invalid_timezone"||e==="invalid_count"||e==="invalid_min_interval"?new B(400,"bad_request",n,{validation:e}):e==="invalid_state"?new B(503,"service_unavailable","scheduler stopped"):null}function qm(t){if(t.state===null)return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:null};let e=t.state,n={phase:e.phase,agentId:e.agentId,agentName:e.agentName,availableGames:e.availableGames,autoConfirmMatches:e.autoConfirmMatches,...e.queue!==void 0?{queue:e.queue}:{},...e.activeMatch!==void 0?{activeMatch:e.activeMatch}:{}};return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:n}}function $E(t){let e=t.lastAttempt===null?null:{atMs:t.lastAttempt.atMs,game:t.lastAttempt.game,outcome:t.lastAttempt.outcome};return{running:t.running,today:t.today,remaining:t.remaining,nextFireInMs:t.nextFireInMs,lastAttempt:e}}function Gm(t){let e=t.host??wE,n=t.port??vE,r=t.bodyLimitBytes??bE,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:Te("/v1/health"),handler:h},{method:"GET",pattern:Te("/v1/agents"),handler:y},{method:"GET",pattern:Te("/v1/agents/:name/status"),handler:v},{method:"POST",pattern:Te("/v1/agents/:name/join"),handler:S},{method:"POST",pattern:Te("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:Te("/v1/agents/:name/schedule"),handler:k},{method:"POST",pattern:Te("/v1/agents/:name/schedule"),handler:G},{method:"POST",pattern:Te("/v1/agents/:name/schedule/pause"),handler:Q},{method:"POST",pattern:Te("/v1/agents/:name/schedule/resume"),handler:oe},{method:"POST",pattern:Te("/v1/shutdown"),handler:ot},{method:"POST",pattern:Te("/v1/agents"),handler:p("M1-18")},{method:"DELETE",pattern:Te("/v1/agents/:name"),handler:p("M1-18")},{method:"POST",pattern:Te("/v1/agents/:name/setup"),handler:p("M1-18")}],a=new Map;function c(w){if(t.onLog)try{t.onLog(w)}catch{}}function l(w){let E=w.headers.authorization;if(!E)return{ok:!1,reason:"missing_header"};if(!E.startsWith("Bearer "))return{ok:!1,reason:"invalid_format"};let x=E.slice(7),$=t.tokenSource();if($===null)return{ok:!1,reason:"token_unset"};let j=_c.from(x,"utf8"),X=_c.from($,"utf8");return j.length!==X.length?{ok:!1,reason:"token_mismatch"}:Hm.timingSafeEqual(j,X)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function u(w,E,x){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",jm),w.statusCode=E,w.end(JSON.stringify(x)))}function d(w,E,x,$,j){u(w,E,j===void 0?{error:{code:x,message:$}}:{error:{code:x,message:$,details:j}})}function h(w){u(w.res,200,{status:"ok",version:Wm,uptimeMs:o.now()-i})}function p(w){return E=>{let x=E.url.pathname;throw new B(501,"not_implemented",`${x} deferred to ${w} daemon lifecycle wiring`,{retry_after_milestone:w})}}function f(w){let E=t.schedulerLookup?.(w)??null;if(!E)throw new B(404,"not_found",`agent '${w}' has no scheduler`);return E}function m(w){return a.has(w)?a.get(w)??null:t.scheduleConfigLookup?.(w)??null}function g(w){w.headersSent||(w.setHeader("Server",jm),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(qm);u(w.res,200,{agents:E})}function v(w){let E=w.params.name,x;try{x=t.router.getAgent({name:E})}catch(j){throw gc(j)?new B(404,"not_found",`agent '${E}' not found`):j}let $=x.snapshot();u(w.res,200,{agent:qm($)})}async function S(w){let E=w.params.name,x=await Dm(w.req,r);Fm(x,["game"],"/v1/agents/:name/join");let $=x;if(typeof $.game!="string"||$.game.length===0)throw new B(400,"bad_request","field 'game' must be a non-empty string",{invalid_field:"game"});if($.mode!==void 0&&typeof $.mode!="string")throw new B(400,"bad_request","field 'mode' must be a string when present",{invalid_field:"mode"});if($.one_shot!==void 0&&typeof $.one_shot!="boolean")throw new B(400,"bad_request","field 'one_shot' must be a boolean when present",{invalid_field:"one_shot"});if($.oneShot!==void 0&&typeof $.oneShot!="boolean")throw new B(400,"bad_request","field 'oneShot' must be a boolean when present",{invalid_field:"oneShot"});let j=$.count;if(j!==void 0&&(typeof j!="number"||!Number.isInteger(j)||j<1||j>20))throw new B(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let X=$.one_shot??$.oneShot;try{t.router.joinQueue({name:E},$.game,$.mode,{...X!==void 0?{oneShot:X}:{},...typeof j=="number"?{count:j}:{}})}catch(K){throw gc(K)?new B(404,"not_found",`agent '${E}' not found`):K}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(x){throw gc(x)?new B(404,"not_found",`agent '${E}' not found`):x}g(w.res)}function k(w){let E=w.params.name,x=f(E),$=m(E),j=$E(x.snapshot());u(w.res,200,{schedule:$,snapshot:j})}async function G(w){let E=w.params.name,x=f(E),$=await Dm(w.req,r),j;if($===null)j=null;else{Fm($,["enabled","timezone","days"],"/v1/agents/:name/schedule");let X=$;if(typeof X.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof X.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof X.days!="object"||X.days===null||Array.isArray(X.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=$}try{x.setSchedule(j)}catch(X){let K=Bm(X);throw K||X}a.set(E,j),g(w.res)}function Q(w){ze(w,!1)}function oe(w){ze(w,!0)}function ze(w,E){let x=w.params.name,$=f(x),j=m(x);if(j===null){let K=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${K}; POST /schedule first or configure initial schedule`)}let X={...j,enabled:E};try{$.setSchedule(X)}catch(K){let eo=Bm(K);throw eo||K}a.set(x,X),g(w.res)}function ot(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),u(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${yc(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function tr(w,E){let x=o.now(),$=w.method??"GET",j=w.url??"/",X=`http://${w.headers.host??"localhost"}`,K;try{K=new URL(j,X)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${$} ${j} -> 400 (${o.now()-x}ms)`,method:$,path:j,status:400,durationMs:o.now()-x});return}let eo=Vm(K.pathname),nr=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${$} ${K.pathname}: auth failed (${Ee.reason})`,method:$,path:K.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let mi=s.map(bt=>({route:bt,params:EE(bt.pattern,eo)})).filter(bt=>bt.params!==null);if(mi.length===0)throw new B(404,"not_found","path not found");let pi=mi.find(bt=>bt.route.method===$);if(!pi){let bt=mi.map(hi=>hi.route.method).filter((hi,hp,gp)=>gp.indexOf(hi)===hp).join(", ");throw E.headersSent||E.setHeader("Allow",bt),new B(405,"method_not_allowed",`method ${$} not allowed`)}c({level:"info",code:"request_received",message:`${$} ${K.pathname}`,method:$,path:K.pathname}),await pi.route.handler({req:w,res:E,url:K,params:pi.params}),nr=E.statusCode}catch(Ee){Ee instanceof B?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),nr=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${$} ${K.pathname}: ${yc(Ee)}`,method:$,path:K.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),nr=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${$} ${K.pathname} -> ${nr} (${o.now()-x}ms)`,method:$,path:K.pathname,status:nr,durationMs:o.now()-x})}}let Ke=Um.createServer((w,E)=>{tr(w,E).catch(x=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${yc(x)}`,method:w.method,path:w.url,cause:x}),!E.headersSent)try{d(E,500,"internal_error","internal server error")}catch{try{E.end()}catch{}}})}),te="pre-listen",Bt=null,_n=null,Zr=null;function fp(){return te==="listening"?Promise.reject(new yn("invalid_state","server already listening")):te==="closing"||te==="closed"||te==="bind-failed"?Promise.reject(new yn("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let x=$=>{te="bind-failed",E(new yn("bind_failed",`failed to bind ${e}:${n}: ${$.message}`,$))};Ke.once("error",x),Ke.listen({host:e,port:n},()=>{Ke.off("error",x);let $=Ke.address();if(typeof $=="string"||$===null){te="bind-failed",E(new yn("bind_failed","unexpected listen address shape from server.address()"));return}Bt=$.address,_n=$.port,te="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Bt}:${_n}`,host:Bt,port:_n}),w(_n)})})}function mp(){return te!=="listening"||Bt===null||_n===null?null:{host:Bt,port:_n}}function pp(){return te==="pre-listen"||te==="bind-failed"?(te="closed",Promise.resolve()):te==="closed"?Promise.resolve():(te==="closing"&&Zr||(te="closing",Zr=new Promise(w=>{let E=!1,x=()=>{E||(E=!0,clearTimeout(j),te="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},$=Ke.closeAllConnections,j=setTimeout(()=>{if(typeof $=="function")try{$.call(Ke)}catch{}x()},SE);j.unref(),Ke.close(()=>x())})),Zr)}return{listen:fp,address:mp,close:pp}}function yc(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function wc(t){return{phase:"connected",transport:"connected",agentId:t.welcome.data.agent_id,agentName:t.welcome.data.agent_name,availableGames:[...t.welcome.data.games],autoConfirmMatches:t.autoConfirmMatches??!0}}function zm(t,e){if(e.type==="start")return U(wc(e));if(t.phase==="closed")return e.type==="stop"?U(t):Ge(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return kE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return RE(t);case"command.confirm_match":return PE(t,e.confirmId);case"ws.message":return TE(t,e.message,e.now);case"decision.ready":return ME(t,e.action);case"decision.failed":return LE(t,e.reason);case"reconnect.event":return BE(t,e.event);case"reconnect.close":return qE(t,e.info);case"stop":return U({...t,phase:"closed",transport:"closed"})}}function kE(t,e,n,r){if(!t.availableGames.includes(e))return Ge(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Yr(n),...r===!0?{one_shot:!0}:{}};return U({...t,phase:"queuing",queue:o,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:void 0},[{type:"send",message:{type:"join_queue",data:o}}])}function RE(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?Ge(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function PE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?Ge(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):U({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function TE(t,e,n){switch(e.type){case"queue_joined":return AE(t,e);case"queue_left":return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return xE(t,e);case"match_cancelled":return CE(t,e);case"game_start":return IE(t,e,n);case"game_state":return OE(t,e);case"action_request":return NE(t,e);case"game_over":return jE(t,e);case"error":return DE(t,e);case"event":return FE(t,e);default:return Ge(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function AE(t,e){return U({...t,phase:"queuing",queue:{game:e.data.game,mode:Yr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function xE(t,e){let n={game:e.data.game,mode:Yr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?U({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):U({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[Ve("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function CE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Yr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Yr(e.data.mode)}:n;return U({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[Ve("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[Ve("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function IE(t,e,n){return U({...t,phase:"in_match",queue:void 0,pendingConfirm:void 0,pendingAction:void 0,activeMatch:{sessionId:e.data.match_id,game:e.data.game,startedAt:n??0}})}function OE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ge(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:t.activeMatch?"in_match":t.phase},[Ve("info","fsm.game_state","Received game state update")])}function NE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?Ge(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ge(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function ME(t,e){return t.phase!=="deciding"||!t.pendingAction?Ge(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):U({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function LE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ge(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):U(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function jE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?Ge(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:e},[{type:"record_result",gameOver:e,...t.activeMatch?.game!==void 0?{game:t.activeMatch.game}:{}}])}function DE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return U({...t,lastError:n},[Ve("error","server.error",n)])}function FE(t,e){return U(t,[Ve("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function BE(t,e){return e.type==="attempt-success"?U({...t,transport:"connected"}):e.type==="attempt-start"?U({...t,transport:"backoff"},[Ve("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?U({...t,transport:"backoff"},[Ve(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):U({...t,phase:"closed",transport:"closed"},[Ve(e.severity,"reconnect.give_up","Reconnect gave up")])}function qE(t,e){return U({...t,phase:"closed",transport:"closed"},[Ve("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function U(t,e=[]){return{state:t,effects:e}}function Ge(t,e,n){return U(t,[Ve("warning",e,n)])}function Ve(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Yr(t){return t&&t.length>0?t:"ranked"}var er=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Qr=class extends er{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Xr=class extends er{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},ci=class extends er{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},vc=class extends er{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},li=class{#e;#t=null;#n=null;#r=!1;#o=!1;#a=[];#c=new Set;#u=Promise.resolve();#g=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#o)throw new ci(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Qr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??Ba,n;try{n=await e(this.#e.ws)}catch(r){throw new Qr(`failed to start agent '${this.#e.name}': ${ai(r)}`,r)}if(n.welcome===null)throw new Qr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=wc({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#$()}),this.#r=!0,this.#l(n),this.#f(),this.snapshot()}async stop(e="agent stop"){if(this.#o)return;this.#o=!0,this.#k();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#s({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#s({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#s({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#s({type:"command.confirm_match",confirmId:e})}snapshot(){return{name:this.#e.name,state:this.#n,transport:this.#t?.state??"idle",started:this.#r,stopped:this.#o}}onState(e){return this.#c.add(e),()=>{this.#c.delete(e)}}#l(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#i(n.data);return}this.#s({type:"ws.message",message:n,now:this.#$()})}),e.onReconnect(n=>{this.#s({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#s({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#i(e){let n=UE(e);try{let r=this.#e.onReadinessCheck?await this.#e.onReadinessCheck(e):{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:"readiness check handler is not configured"};this.#p({type:"runtime_status",data:HE(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Km(`readiness check failed: ${ai(r)}`)}})}}#s(e){let n=this.#S(),r=zm(n,e);this.#n=r.state,this.#f(),this.#h(r.effects)}#h(e){e.length!==0&&(this.#u=this.#u.then(()=>this.#m(e)).catch(n=>{this.#v({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${ai(n)}`,cause:n})}))}async#m(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#p(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#v({level:"warning",code:"agent.fallback_required",message:`Decision failed for match ${e.actionRequest.data.match_id}; fallback required`,cause:e.reason});return;case"record_result":this.#e.onResult?.(e.gameOver,e.game!==void 0?{game:e.game}:{});return;case"notify":this.#v(e);return}}#p(e){let n=this.#b();try{n.send(e)}catch(r){this.#v({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${ai(r)}`,cause:new vc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#g;this.#d={token:n,matchId:e.matchId};let r=this.#S();try{let o=await this.#e.decisionProvider.decide({actionRequest:e.actionRequest,matchId:e.matchId,game:e.game,state:r});if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#s({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#s({type:"decision.failed",reason:o})}}#E(e,n){let r=this.#n;return this.#d?.token===e&&this.#d.matchId===n&&r?.phase==="deciding"&&r.pendingAction?.data.match_id===n}#w(){if(!this.#r||this.#n===null||this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new ci(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#n}#f(){let e=this.snapshot();for(let n of[...this.#c])n(e)}#k(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#v({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#v(e){this.#e.onNotify?.(e)}#$(){return this.#e.now?.()??Date.now()}};function ai(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function UE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function HE(t,e){let n=t&&typeof t=="object"?{...t}:{};return typeof n.request_id!="string"&&(n.request_id=e),typeof n.ready!="boolean"&&(n.ready=!1),n.runtime_type!=="openclaw"&&n.runtime_type!=="hermes"&&n.runtime_type!=="mock"&&(n.runtime_type="mock"),typeof n.checked_at!="string"&&(n.checked_at=new Date().toISOString()),typeof n.detail=="string"&&(n.detail=Km(n.detail)),n}function Km(t){return t.length>240?t.slice(0,240):t}function Jm(t){return{async decide(e){let n=KE(e.game),r=e.actionRequest.data,o=r.legal_actions??[];if(o.length===0)throw new Error("action_request had no legal actions");let i={game:n,matchId:e.matchId,playerId:JE(r.state),legalActions:o,publicState:r.state,timeoutMs:typeof r.timeout_ms=="number"?r.timeout_ms:0},s;try{s=await t.decide(i)}catch{try{s=await t.decide(i)}catch{return ui(n,o,r.state)}}return WE({game:n,raw:s,legalActions:o,publicState:r.state})}}}function Ym(){return{name:"mock",async decide(t){return ui(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function WE(t){if(typeof t.raw!="string")return zE(t.raw,t.legalActions)??ui(t.game,t.legalActions,t.publicState);let e=VE(t.game,t.raw,t.legalActions);return e!==null?e:ui(t.game,t.legalActions,t.publicState)}function VE(t,e,n){let r=GE(e),o=t==="texas_holdem"?Ga(r,n):t==="liars_dice"?Ka(r,n):Ja(r,n);return o.kind==="ok"?o.action:null}function GE(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function zE(t,e){let n=e.find(o=>YE(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function ui(t,e,n){return t==="texas_holdem"?qa({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Ha({publicState:n,legalActions:e,yourPlayerId:"p0"}):Wa({publicState:n,legalActions:e,yourPlayerId:"p0"})}function KE(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function JE(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function YE(t,e){return JSON.stringify(t)===JSON.stringify(e)}var QE="http://127.0.0.1:18789",XE="openclaw/default";function Qm(t){let e=(t.baseUrl??QE).replace(/\/+$/,""),n=t.model??XE,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:ZE(t,o),body:JSON.stringify({model:n,input:e$(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=t$(s);return n$(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function ZE(t,e){return{"Content-Type":"application/json","x-openclaw-session-key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function e$(t){return["You are an AIFight game-playing agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
197
- `)}function t$(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function n$(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("OpenClaw response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;let n=e.output,r=r$(n);if(r)return r;let o=e.choices,i=o$(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function r$(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
198
- `):null}function o$(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var i$="http://127.0.0.1:8642",s$="hermes-agent";function Xm(t){let e=(t.baseUrl??i$).replace(/\/+$/,""),n=t.model??s$,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:a$(t,o),body:JSON.stringify({model:n,input:c$(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=l$(s);return u$(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function a$(t,e){return{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`,"X-Hermes-Session-Key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`}:{}}}function c$(t){return["You are an AIFight game-playing Hermes Agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
199
- `)}function l$(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function u$(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("Hermes response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;let n=e.output,r=d$(n);if(r)return r;let o=e.choices,i=f$(o);if(i)return i;throw new Error("Hermes response did not contain text")}function d$(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(typeof r=="string"){e.push(r);continue}if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
200
- `):null}function f$(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var di=class{#e;#t=null;#n=null;constructor(e){this.#e=e}async start(){if(this.#t!==null)return this.#t.snapshot();let e=this.#e.runtimeProvider??w$(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:Kf},r=new li({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:Jm(e),...this.#e.connect!==void 0?{connect:this.#e.connect}:{},onReadinessCheck:async i=>this.#c(e,i),onNotify:i=>{this.#r(i.level,i.code,i.message)},onResult:(i,s)=>{this.#r("info","bridge.match_complete",p$(this.#e.config,i,s.game)),this.#a()},onFallbackRequired:i=>{this.#r("warning","bridge.fallback_required",`No action sent for match ${i.actionRequest.data.match_id}; runtime decision failed`)}});this.#t=r;let o=await r.start();if(this.#r("info","bridge.connected",`Connected ${this.#e.config.agentName}`),this.#e.autoJoinGame){let i=this.#e.autoJoinOneShot===!0;r.joinQueue(this.#e.autoJoinGame,this.#e.autoJoinMode,{oneShot:i}),this.#r("info","bridge.queue_joined",i?`Joined ${this.#e.autoJoinGame} for one manual match`:`Joined ${this.#e.autoJoinGame} for daily automatic matching`)}return o}async stop(){this.#t!==null&&(await this.#t.stop("bridge stop"),this.#t=null,this.#n=null)}snapshot(){return this.#t?.snapshot()??null}joinQueue(e,n,r={}){if(r.oneShot===!0||(r.count??1)>1){this.requestManualMatches(e,n,r.count??1);return}this.#o().joinQueue(e,n),this.#r("info","bridge.queue_joined",`Joined ${e} for ${n??"default"} matching`)}leaveQueue(){let e=this.#o();this.#n=null,e.leaveQueue()}requestManualMatches(e,n="ranked",r=1){if(!Number.isInteger(r)||r<1||r>20)throw new Error("manual match count must be an integer between 1 and 20");let o=this.#o(),i=o.snapshot().state?.phase;if(i==="confirming"||i==="matching"||i==="in_match"||i==="deciding"||i==="reporting")throw new Error("agent is already in or entering a match; try again after the current match completes");this.#n=r>1?{game:e,mode:n,remainingAfterCurrent:r-1}:null,o.joinQueue(e,n,{oneShot:!0}),this.#r("info","bridge.queue_joined",r===1?`Joined ${e} for one manual match`:`Joined ${e} for ${r} manual matches`)}#r(e,n,r){this.#e.onLog?.({level:e,code:n,message:r})}#o(){if(this.#t===null)throw new Error("bridge runner is not started");return this.#t}#a(){let e=this.#n,n=this.#t;if(!(e===null||n===null)){if(e.remainingAfterCurrent<=0){this.#n=null;return}try{n.joinQueue(e.game,e.mode,{oneShot:!0}),e.remainingAfterCurrent-=1,this.#r("info","bridge.queue_joined",e.remainingAfterCurrent===0?`Joined ${e.game} for the final manual match in this request`:`Joined ${e.game} for the next manual match; ${e.remainingAfterCurrent} remaining after this one`)}catch(r){this.#n=null,this.#r("error","bridge.manual_requeue_failed",`Could not request the next manual match: ${r instanceof Error?r.message:String(r)}`)}}}async#c(e,n){let r=m$(n),o=new Date().toISOString();if(!e.healthCheck)return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:"runtime provider does not expose a health check"};try{let i=await e.healthCheck();return{request_id:r,ready:i,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:i?"ready":"local runtime health check returned false"}}catch(i){return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:`local runtime health check failed: ${i instanceof Error?i.message:String(i)}`}}}};function m$(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function p$(t,e,n){let r=[`Match complete: ${_$(n)}`,`Result: ${h$(t.agentId,e)}`],o=y$(t.baseUrl,e.data.replay_url);return o!==void 0?r.push(`Replay: ${o}`):e.data.forfeit_reason!==void 0&&r.push(`Forfeit reason: ${e.data.forfeit_reason}`),(t.autoDailyLimit??0)===2&&r.push("","Your Agent is set to 2 automatic ranked matches per day.","To compete more often:"," aifight set daily 4"),r.join(`
201
- `)}function h$(t,e){let n=e.data.players.find(i=>i.agent_id===t);if(n===void 0)return"completed";if(e.data.forfeited_by===n.player_id)return"forfeit";if(e.data.forfeit_reason!==void 0)return"opponent forfeit";if(e.data.result.is_draw)return"draw";let r=e.data.result.payoffs[n.player_id];if(typeof r!="number")return e.data.result.winner===n.player_id?"1st place":"completed";let o=Object.values(e.data.result.payoffs).filter(i=>i>r).length;return`${g$(o+1)} place`}function g$(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function y$(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function _$(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup";default:return"AIFight match"}}function w$(t){return t.runtimeType==="mock"?Ym():t.runtimeType==="openclaw"?Qm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):Xm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}var v$=["usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," If aifight.service is already running, this command refuses unless --force is set."].join(`
202
- `);async function Zm(t,e){J(t,0,0,v$);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await T$(e))throw new z("bridge_already_running","aifight.service is already running.",{hint:"Use `aifight start` to request matches through the running service. Use `aifight run --force` only for advanced debugging."});if(n&&process.stdin.isTTY&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&(e.stdout(["AIFight service may already be running.","Starting a second foreground Bridge can duplicate match handling.",""].join(`
203
- `)),!await x$(e,"Continue anyway? [y/N] ")))return 0;let r=ae();return b$({config:r,env:e})}async function b$(t){let{config:e,env:n}=t,r=await jt({baseUrl:e.baseUrl,currentVersion:Se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
209
+ `)}return 0}function uE(){try{return ce()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new W("bridge_not_configured","AIFight Bridge is not configured.",{hint:"Run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent. Then install `aifight.service` before requesting manual matches."}):t}}function dE(t,e){if(t.length===0)return{game:Pm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Rm(n);if(i!==null)return{game:Pm(e.autoGames),count:i};if(at(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,ai)}let r=t[1];if(!at(n))throw new O(`unsupported game '${n}'`,ai);let o=Rm(r);if(o===null)throw new O(`N must be an integer between 1 and ${fc}`,ai);return{game:n,count:o}}function Rm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>fc?null:e}function Pm(t){let e=(t??pe).filter(at),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}function fE(t){return t.kind==="daemon_unreachable"?"bridge_not_running":t.kind==="runtime_files_corrupt"?"bridge_runtime_files_invalid":t.kind==="auth_failed"?"bridge_control_auth_failed":t.kind==="request_timeout"?"bridge_control_timeout":"bridge_control_failed"}function mE(t){return t.kind==="daemon_unreachable"?"AIFight Bridge is not running.":t.kind==="runtime_files_corrupt"?"AIFight Bridge runtime files are invalid.":t.kind==="auth_failed"?"AIFight Bridge rejected the local control token.":t.kind==="request_timeout"?"AIFight Bridge did not answer the local control request in time.":t.message}async function pE(t){try{let e=await pn(t.bridgeService);if(e.installed&&e.running===!1)return"Start it with `aifight service start`, then run this command again.";if(e.installed&&e.running===!0)return"The service appears to be running, but its local control API did not answer. Try `aifight service restart` when no match is in progress."}catch(e){if(!(e instanceof te))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function hE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Ft from"node:path";import ee from"node:fs";import gE from"node:crypto";var ye=class extends Error{name="RuntimeFilesWriteError";kind;filePath;heldByPid;cause;constructor(e,n,r,o){super(r),this.kind=e,this.filePath=n,o?.heldByPid!==void 0&&(this.heldByPid=o.heldByPid),o?.cause!==void 0&&(this.cause=o.cause)}};function Cm(){return Ft.join(re(),"token")}function xm(){return Ft.join(re(),"port")}function pc(){return Ft.join(re(),"pid")}function yE(){return Ft.join(re(),"lock")}var Am=0,_E=/^[0-9a-f]{64}$/;function hc(t,e,n){let r=Ft.dirname(t),o=Ft.basename(t);Am+=1;let i=Ft.join(r,`${o}.${process.pid}.${Am}.tmp`),s;try{if(s=ee.openSync(i,"w",n),ee.writeSync(s,e),ee.closeSync(s),s=void 0,process.platform!=="win32")try{ee.chmodSync(i,n)}catch{}ee.renameSync(i,t)}catch(a){if(s!==void 0)try{ee.closeSync(s)}catch{}try{ee.unlinkSync(i)}catch{}throw new ye("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Im(){return gE.randomBytes(32).toString("hex")}function Om(t){let e=Cm();if(!_E.test(t))throw new ye("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);hc(e,t,384)}function Nm(t){let e=xm();if(!Number.isInteger(t)||t<1||t>65535)throw new ye("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);hc(e,String(t),420)}function Mm(t){let e=pc();if(!Number.isInteger(t)||t<1)throw new ye("write_failed",e,`pid must be a positive integer but received ${t}`);hc(e,String(t),420)}function gc(t){for(let e of[Cm(),xm(),pc()])try{ee.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Lm(){let t=re(),e;try{e=ee.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{ee.unlinkSync(Ft.join(t,n))}catch{}}var mc=new Set;function wE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function vE(t){let e;try{e=ee.readFileSync(t,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"missing"}:{kind:"read_error",cause:o}}let n=e.trim();if(n.length===0)return{kind:"invalid",raw:n};if(!/^\d+$/.test(n))return{kind:"invalid",raw:n};let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<1?{kind:"invalid",raw:n}:{kind:"valid",pid:r}}function jm(t){let e=yE(),n=pc(),r=t?.processIsAlive??wE;if(mc.has(e))throw new ye("lock_acquire_failed",e,`lock at ${e} already held by this process; release the existing handle first (reentrancy guard)`);for(let o=0;o<2;o+=1)try{let i=ee.openSync(e,ee.constants.O_WRONLY|ee.constants.O_CREAT|ee.constants.O_EXCL,384);if(ee.closeSync(i),process.platform!=="win32")try{ee.chmodSync(e,384)}catch{}return mc.add(e),bE(e)}catch(i){if(i.code!=="EEXIST")throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=vE(n);if(a.kind==="missing")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} is missing \u2014 ambiguous (possibly a racing daemon between acquireDaemonLock and writePid); refusing to steal lock. If the previous daemon truly crashed, manually remove ${e}.`);if(a.kind==="invalid")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} content is invalid (raw="${a.raw}") \u2014 ambiguous; refusing to steal lock. Manually remove both files if you confirm no daemon is running.`);if(a.kind==="read_error")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} could not be read (${a.cause.code??"unknown"}: ${a.cause.message}) \u2014 ambiguous; refusing to steal lock.`,{cause:a.cause});if(r(a.pid))throw new ye("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{ee.unlinkSync(e)}catch{}try{ee.unlinkSync(n)}catch{}}throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function bE(t){let e=!1;return{release(){if(!e){e=!0,mc.delete(t);try{ee.unlinkSync(t)}catch{}}}}}import*as Hm from"node:http";import{Buffer as wc}from"node:buffer";import*as Gm from"node:crypto";var _n=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var Wm="0.1.0-alpha.3",Dm=`aifight-runtime/${Wm}`,SE="127.0.0.1",EE=0,kE=1048576,$E=5e3,B=class extends Error{name="HttpError";status;code;details;constructor(e,n,r,o){super(r),this.status=e,this.code=n,this.details=o}};function Vm(t){return t.split("/").filter(e=>e.length>0)}function Ae(t){let e=Vm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function RE(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let o=t.segments[r],i=e[r];if(o.literal!==void 0){if(o.literal!==i)return null}else if(o.param!==void 0)try{n[o.param]=decodeURIComponent(i)}catch{return null}}return n}async function Fm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new B(415,"unsupported_media_type","Content-Type must be application/json");let o=[],i=0,s=!1;for await(let c of t){if(s)continue;let l=c;if(i+=l.length,i>e)throw s=!0,new B(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(l)}let a=wc.concat(o).toString("utf8");if(a.length===0)throw new B(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new B(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function Bm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new B(400,"bad_request",`${n} body must be a JSON object`,{missing_fields:[...e]});let r=t,o=e.filter(i=>!Object.prototype.hasOwnProperty.call(r,i));if(o.length>0)throw new B(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function yc(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function qm(t){if(typeof t!="object"||t===null||!("kind"in t))return null;let e=t.kind,n=t instanceof Error?t.message:"schedule operation failed";return e==="invalid_timezone"||e==="invalid_count"||e==="invalid_min_interval"?new B(400,"bad_request",n,{validation:e}):e==="invalid_state"?new B(503,"service_unavailable","scheduler stopped"):null}function Um(t){if(t.state===null)return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:null};let e=t.state,n={phase:e.phase,agentId:e.agentId,agentName:e.agentName,availableGames:e.availableGames,autoConfirmMatches:e.autoConfirmMatches,...e.queue!==void 0?{queue:e.queue}:{},...e.activeMatch!==void 0?{activeMatch:e.activeMatch}:{}};return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:n}}function PE(t){let e=t.lastAttempt===null?null:{atMs:t.lastAttempt.atMs,game:t.lastAttempt.game,outcome:t.lastAttempt.outcome};return{running:t.running,today:t.today,remaining:t.remaining,nextFireInMs:t.nextFireInMs,lastAttempt:e}}function zm(t){let e=t.host??SE,n=t.port??EE,r=t.bodyLimitBytes??kE,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:Ae("/v1/health"),handler:h},{method:"GET",pattern:Ae("/v1/agents"),handler:y},{method:"GET",pattern:Ae("/v1/agents/:name/status"),handler:v},{method:"POST",pattern:Ae("/v1/agents/:name/join"),handler:S},{method:"POST",pattern:Ae("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:Ae("/v1/agents/:name/schedule"),handler:$},{method:"POST",pattern:Ae("/v1/agents/:name/schedule"),handler:z},{method:"POST",pattern:Ae("/v1/agents/:name/schedule/pause"),handler:Q},{method:"POST",pattern:Ae("/v1/agents/:name/schedule/resume"),handler:ie},{method:"POST",pattern:Ae("/v1/shutdown"),handler:it},{method:"POST",pattern:Ae("/v1/agents"),handler:p("M1-18")},{method:"DELETE",pattern:Ae("/v1/agents/:name"),handler:p("M1-18")},{method:"POST",pattern:Ae("/v1/agents/:name/setup"),handler:p("M1-18")}],a=new Map;function c(w){if(t.onLog)try{t.onLog(w)}catch{}}function l(w){let E=w.headers.authorization;if(!E)return{ok:!1,reason:"missing_header"};if(!E.startsWith("Bearer "))return{ok:!1,reason:"invalid_format"};let C=E.slice(7),k=t.tokenSource();if(k===null)return{ok:!1,reason:"token_unset"};let j=wc.from(C,"utf8"),X=wc.from(k,"utf8");return j.length!==X.length?{ok:!1,reason:"token_mismatch"}:Gm.timingSafeEqual(j,X)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function u(w,E,C){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",Dm),w.statusCode=E,w.end(JSON.stringify(C)))}function d(w,E,C,k,j){u(w,E,j===void 0?{error:{code:C,message:k}}:{error:{code:C,message:k,details:j}})}function h(w){u(w.res,200,{status:"ok",version:Wm,uptimeMs:o.now()-i})}function p(w){return E=>{let C=E.url.pathname;throw new B(501,"not_implemented",`${C} deferred to ${w} daemon lifecycle wiring`,{retry_after_milestone:w})}}function f(w){let E=t.schedulerLookup?.(w)??null;if(!E)throw new B(404,"not_found",`agent '${w}' has no scheduler`);return E}function m(w){return a.has(w)?a.get(w)??null:t.scheduleConfigLookup?.(w)??null}function g(w){w.headersSent||(w.setHeader("Server",Dm),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Um);u(w.res,200,{agents:E})}function v(w){let E=w.params.name,C;try{C=t.router.getAgent({name:E})}catch(j){throw yc(j)?new B(404,"not_found",`agent '${E}' not found`):j}let k=C.snapshot();u(w.res,200,{agent:Um(k)})}async function S(w){let E=w.params.name,C=await Fm(w.req,r);Bm(C,["game"],"/v1/agents/:name/join");let k=C;if(typeof k.game!="string"||k.game.length===0)throw new B(400,"bad_request","field 'game' must be a non-empty string",{invalid_field:"game"});if(k.mode!==void 0&&typeof k.mode!="string")throw new B(400,"bad_request","field 'mode' must be a string when present",{invalid_field:"mode"});if(k.one_shot!==void 0&&typeof k.one_shot!="boolean")throw new B(400,"bad_request","field 'one_shot' must be a boolean when present",{invalid_field:"one_shot"});if(k.oneShot!==void 0&&typeof k.oneShot!="boolean")throw new B(400,"bad_request","field 'oneShot' must be a boolean when present",{invalid_field:"oneShot"});let j=k.count;if(j!==void 0&&(typeof j!="number"||!Number.isInteger(j)||j<1||j>20))throw new B(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let X=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...X!==void 0?{oneShot:X}:{},...typeof j=="number"?{count:j}:{}})}catch(K){throw yc(K)?new B(404,"not_found",`agent '${E}' not found`):K}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(C){throw yc(C)?new B(404,"not_found",`agent '${E}' not found`):C}g(w.res)}function $(w){let E=w.params.name,C=f(E),k=m(E),j=PE(C.snapshot());u(w.res,200,{schedule:k,snapshot:j})}async function z(w){let E=w.params.name,C=f(E),k=await Fm(w.req,r),j;if(k===null)j=null;else{Bm(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let X=k;if(typeof X.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof X.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof X.days!="object"||X.days===null||Array.isArray(X.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{C.setSchedule(j)}catch(X){let K=qm(X);throw K||X}a.set(E,j),g(w.res)}function Q(w){ze(w,!1)}function ie(w){ze(w,!0)}function ze(w,E){let C=w.params.name,k=f(C),j=m(C);if(j===null){let K=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${K}; POST /schedule first or configure initial schedule`)}let X={...j,enabled:E};try{k.setSchedule(X)}catch(K){let eo=qm(K);throw eo||K}a.set(C,X),g(w.res)}function it(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),u(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${_c(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function nr(w,E){let C=o.now(),k=w.method??"GET",j=w.url??"/",X=`http://${w.headers.host??"localhost"}`,K;try{K=new URL(j,X)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${k} ${j} -> 400 (${o.now()-C}ms)`,method:k,path:j,status:400,durationMs:o.now()-C});return}let eo=Vm(K.pathname),rr=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${K.pathname}: auth failed (${Ee.reason})`,method:k,path:K.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let pi=s.map(bt=>({route:bt,params:RE(bt.pattern,eo)})).filter(bt=>bt.params!==null);if(pi.length===0)throw new B(404,"not_found","path not found");let hi=pi.find(bt=>bt.route.method===k);if(!hi){let bt=pi.map(gi=>gi.route.method).filter((gi,gp,yp)=>yp.indexOf(gi)===gp).join(", ");throw E.headersSent||E.setHeader("Allow",bt),new B(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${K.pathname}`,method:k,path:K.pathname}),await hi.route.handler({req:w,res:E,url:K,params:hi.params}),rr=E.statusCode}catch(Ee){Ee instanceof B?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),rr=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${k} ${K.pathname}: ${_c(Ee)}`,method:k,path:K.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),rr=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${k} ${K.pathname} -> ${rr} (${o.now()-C}ms)`,method:k,path:K.pathname,status:rr,durationMs:o.now()-C})}}let Ke=Hm.createServer((w,E)=>{nr(w,E).catch(C=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${_c(C)}`,method:w.method,path:w.url,cause:C}),!E.headersSent)try{d(E,500,"internal_error","internal server error")}catch{try{E.end()}catch{}}})}),ne="pre-listen",Bt=null,wn=null,Zr=null;function mp(){return ne==="listening"?Promise.reject(new _n("invalid_state","server already listening")):ne==="closing"||ne==="closed"||ne==="bind-failed"?Promise.reject(new _n("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let C=k=>{ne="bind-failed",E(new _n("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Ke.once("error",C),Ke.listen({host:e,port:n},()=>{Ke.off("error",C);let k=Ke.address();if(typeof k=="string"||k===null){ne="bind-failed",E(new _n("bind_failed","unexpected listen address shape from server.address()"));return}Bt=k.address,wn=k.port,ne="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Bt}:${wn}`,host:Bt,port:wn}),w(wn)})})}function pp(){return ne!=="listening"||Bt===null||wn===null?null:{host:Bt,port:wn}}function hp(){return ne==="pre-listen"||ne==="bind-failed"?(ne="closed",Promise.resolve()):ne==="closed"?Promise.resolve():(ne==="closing"&&Zr||(ne="closing",Zr=new Promise(w=>{let E=!1,C=()=>{E||(E=!0,clearTimeout(j),ne="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Ke.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Ke)}catch{}C()},$E);j.unref(),Ke.close(()=>C())})),Zr)}return{listen:mp,address:pp,close:hp}}function _c(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function vc(t){return{phase:"connected",transport:"connected",agentId:t.welcome.data.agent_id,agentName:t.welcome.data.agent_name,availableGames:[...t.welcome.data.games],autoConfirmMatches:t.autoConfirmMatches??!0}}function Km(t,e){if(e.type==="start")return U(vc(e));if(t.phase==="closed")return e.type==="stop"?U(t):Ve(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return TE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return AE(t);case"command.confirm_match":return CE(t,e.confirmId);case"ws.message":return xE(t,e.message,e.now);case"decision.ready":return DE(t,e.action);case"decision.failed":return FE(t,e.reason);case"reconnect.event":return HE(t,e.event);case"reconnect.close":return GE(t,e.info);case"stop":return U({...t,phase:"closed",transport:"closed"})}}function TE(t,e,n,r){if(!t.availableGames.includes(e))return Ve(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Yr(n),...r===!0?{one_shot:!0}:{}};return U({...t,phase:"queuing",queue:o,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:void 0},[{type:"send",message:{type:"join_queue",data:o}}])}function AE(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?Ve(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function CE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?Ve(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):U({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function xE(t,e,n){switch(e.type){case"queue_joined":return IE(t,e);case"queue_left":return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return OE(t,e);case"match_cancelled":return NE(t,e);case"game_start":return ME(t,e,n);case"game_state":return LE(t,e);case"action_request":return jE(t,e);case"game_over":return BE(t,e);case"error":return qE(t,e);case"event":return UE(t,e);default:return Ve(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function IE(t,e){return U({...t,phase:"queuing",queue:{game:e.data.game,mode:Yr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function OE(t,e){let n={game:e.data.game,mode:Yr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?U({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):U({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[We("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function NE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Yr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Yr(e.data.mode)}:n;return U({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function ME(t,e,n){return U({...t,phase:"in_match",queue:void 0,pendingConfirm:void 0,pendingAction:void 0,activeMatch:{sessionId:e.data.match_id,game:e.data.game,startedAt:n??0}})}function LE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function jE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?Ve(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function DE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):U({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function FE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):U(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function BE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?Ve(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:e},[{type:"record_result",gameOver:e,...t.activeMatch?.game!==void 0?{game:t.activeMatch.game}:{}}])}function qE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return U({...t,lastError:n},[We("error","server.error",n)])}function UE(t,e){return U(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function HE(t,e){return e.type==="attempt-success"?U({...t,transport:"connected"}):e.type==="attempt-start"?U({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?U({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):U({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function GE(t,e){return U({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function U(t,e=[]){return{state:t,effects:e}}function Ve(t,e,n){return U(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Yr(t){return t&&t.length>0?t:"ranked"}var tr=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Qr=class extends tr{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Xr=class extends tr{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},li=class extends tr{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},bc=class extends tr{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},ui=class{#e;#t=null;#n=null;#r=!1;#o=!1;#a=[];#c=new Set;#u=Promise.resolve();#g=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#o)throw new li(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Qr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??qa,n;try{n=await e(this.#e.ws)}catch(r){throw new Qr(`failed to start agent '${this.#e.name}': ${ci(r)}`,r)}if(n.welcome===null)throw new Qr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=vc({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#k()}),this.#r=!0,this.#l(n),this.#f(),this.snapshot()}async stop(e="agent stop"){if(this.#o)return;this.#o=!0,this.#$();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#s({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#s({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#s({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#s({type:"command.confirm_match",confirmId:e})}snapshot(){return{name:this.#e.name,state:this.#n,transport:this.#t?.state??"idle",started:this.#r,stopped:this.#o}}onState(e){return this.#c.add(e),()=>{this.#c.delete(e)}}#l(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#i(n.data);return}this.#s({type:"ws.message",message:n,now:this.#k()})}),e.onReconnect(n=>{this.#s({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#s({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#i(e){let n=WE(e);try{let r=this.#e.onReadinessCheck?await this.#e.onReadinessCheck(e):{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:"readiness check handler is not configured"};this.#p({type:"runtime_status",data:VE(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Jm(`readiness check failed: ${ci(r)}`)}})}}#s(e){let n=this.#S(),r=Km(n,e);this.#n=r.state,this.#f(),this.#h(r.effects)}#h(e){e.length!==0&&(this.#u=this.#u.then(()=>this.#m(e)).catch(n=>{this.#v({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${ci(n)}`,cause:n})}))}async#m(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#p(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#v({level:"warning",code:"agent.fallback_required",message:`Decision failed for match ${e.actionRequest.data.match_id}; fallback required`,cause:e.reason});return;case"record_result":this.#e.onResult?.(e.gameOver,e.game!==void 0?{game:e.game}:{});return;case"notify":this.#v(e);return}}#p(e){let n=this.#b();try{n.send(e)}catch(r){this.#v({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${ci(r)}`,cause:new bc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#g;this.#d={token:n,matchId:e.matchId};let r=this.#S();try{let o=await this.#e.decisionProvider.decide({actionRequest:e.actionRequest,matchId:e.matchId,game:e.game,state:r});if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#s({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#s({type:"decision.failed",reason:o})}}#E(e,n){let r=this.#n;return this.#d?.token===e&&this.#d.matchId===n&&r?.phase==="deciding"&&r.pendingAction?.data.match_id===n}#w(){if(!this.#r||this.#n===null||this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new li(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#n}#f(){let e=this.snapshot();for(let n of[...this.#c])n(e)}#$(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#v({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#v(e){this.#e.onNotify?.(e)}#k(){return this.#e.now?.()??Date.now()}};function ci(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function WE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function VE(t,e){let n=t&&typeof t=="object"?{...t}:{};return typeof n.request_id!="string"&&(n.request_id=e),typeof n.ready!="boolean"&&(n.ready=!1),n.runtime_type!=="openclaw"&&n.runtime_type!=="hermes"&&n.runtime_type!=="mock"&&(n.runtime_type="mock"),typeof n.checked_at!="string"&&(n.checked_at=new Date().toISOString()),typeof n.detail=="string"&&(n.detail=Jm(n.detail)),n}function Jm(t){return t.length>240?t.slice(0,240):t}function Ym(t){return{async decide(e){let n=QE(e.game),r=e.actionRequest.data,o=r.legal_actions??[];if(o.length===0)throw new Error("action_request had no legal actions");let i={game:n,matchId:e.matchId,playerId:XE(r.state),legalActions:o,publicState:r.state,timeoutMs:typeof r.timeout_ms=="number"?r.timeout_ms:0},s;try{s=await t.decide(i)}catch{try{s=await t.decide(i)}catch{return di(n,o,r.state)}}return zE({game:n,raw:s,legalActions:o,publicState:r.state})}}}function Qm(){return{name:"mock",async decide(t){return di(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function zE(t){if(typeof t.raw!="string")return YE(t.raw,t.legalActions)??di(t.game,t.legalActions,t.publicState);let e=KE(t.game,t.raw,t.legalActions);return e!==null?e:di(t.game,t.legalActions,t.publicState)}function KE(t,e,n){let r=JE(e),o=t==="texas_holdem"?za(r,n):t==="liars_dice"?Ja(r,n):Ya(r,n);return o.kind==="ok"?o.action:null}function JE(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function YE(t,e){let n=e.find(o=>ZE(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function di(t,e,n){return t==="texas_holdem"?Ua({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Ga({publicState:n,legalActions:e,yourPlayerId:"p0"}):Wa({publicState:n,legalActions:e,yourPlayerId:"p0"})}function QE(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function XE(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function ZE(t,e){return JSON.stringify(t)===JSON.stringify(e)}var ek="http://127.0.0.1:18789",tk="openclaw/default";function Xm(t){let e=(t.baseUrl??ek).replace(/\/+$/,""),n=t.model??tk,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:nk(t,o),body:JSON.stringify({model:n,input:rk(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=ok(s);return ik(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function nk(t,e){return{"Content-Type":"application/json","x-openclaw-session-key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function rk(t){return["You are an AIFight game-playing agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
210
+ `)}function ok(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function ik(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("OpenClaw response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;let n=e.output,r=sk(n);if(r)return r;let o=e.choices,i=ak(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function sk(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
211
+ `):null}function ak(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var ck="http://127.0.0.1:8642",lk="hermes-agent";function Zm(t){let e=(t.baseUrl??ck).replace(/\/+$/,""),n=t.model??lk,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:uk(t,o),body:JSON.stringify({model:n,input:dk(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=fk(s);return mk(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function uk(t,e){return{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`,"X-Hermes-Session-Key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`}:{}}}function dk(t){return["You are an AIFight game-playing Hermes Agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
212
+ `)}function fk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function mk(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("Hermes response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;let n=e.output,r=pk(n);if(r)return r;let o=e.choices,i=hk(o);if(i)return i;throw new Error("Hermes response did not contain text")}function pk(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(typeof r=="string"){e.push(r);continue}if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
213
+ `):null}function hk(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var fi=class{#e;#t=null;#n=null;constructor(e){this.#e=e}async start(){if(this.#t!==null)return this.#t.snapshot();let e=this.#e.runtimeProvider??Sk(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:Jf},r=new ui({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:Ym(e),...this.#e.connect!==void 0?{connect:this.#e.connect}:{},onReadinessCheck:async i=>this.#c(e,i),onNotify:i=>{this.#r(i.level,i.code,i.message)},onResult:(i,s)=>{this.#r("info","bridge.match_complete",yk(this.#e.config,i,s.game)),this.#a()},onFallbackRequired:i=>{this.#r("warning","bridge.fallback_required",`No action sent for match ${i.actionRequest.data.match_id}; runtime decision failed`)}});this.#t=r;let o=await r.start();if(this.#r("info","bridge.connected",`Connected ${this.#e.config.agentName}`),this.#e.autoJoinGame){let i=this.#e.autoJoinOneShot===!0;r.joinQueue(this.#e.autoJoinGame,this.#e.autoJoinMode,{oneShot:i}),this.#r("info","bridge.queue_joined",i?`Joined ${this.#e.autoJoinGame} for one manual match`:`Joined ${this.#e.autoJoinGame} for daily automatic matching`)}return o}async stop(){this.#t!==null&&(await this.#t.stop("bridge stop"),this.#t=null,this.#n=null)}snapshot(){return this.#t?.snapshot()??null}joinQueue(e,n,r={}){if(r.oneShot===!0||(r.count??1)>1){this.requestManualMatches(e,n,r.count??1);return}this.#o().joinQueue(e,n),this.#r("info","bridge.queue_joined",`Joined ${e} for ${n??"default"} matching`)}leaveQueue(){let e=this.#o();this.#n=null,e.leaveQueue()}requestManualMatches(e,n="ranked",r=1){if(!Number.isInteger(r)||r<1||r>20)throw new Error("manual match count must be an integer between 1 and 20");let o=this.#o(),i=o.snapshot().state?.phase;if(i==="confirming"||i==="matching"||i==="in_match"||i==="deciding"||i==="reporting")throw new Error("agent is already in or entering a match; try again after the current match completes");this.#n=r>1?{game:e,mode:n,remainingAfterCurrent:r-1}:null,o.joinQueue(e,n,{oneShot:!0}),this.#r("info","bridge.queue_joined",r===1?`Joined ${e} for one manual match`:`Joined ${e} for ${r} manual matches`)}#r(e,n,r){this.#e.onLog?.({level:e,code:n,message:r})}#o(){if(this.#t===null)throw new Error("bridge runner is not started");return this.#t}#a(){let e=this.#n,n=this.#t;if(!(e===null||n===null)){if(e.remainingAfterCurrent<=0){this.#n=null;return}try{n.joinQueue(e.game,e.mode,{oneShot:!0}),e.remainingAfterCurrent-=1,this.#r("info","bridge.queue_joined",e.remainingAfterCurrent===0?`Joined ${e.game} for the final manual match in this request`:`Joined ${e.game} for the next manual match; ${e.remainingAfterCurrent} remaining after this one`)}catch(r){this.#n=null,this.#r("error","bridge.manual_requeue_failed",`Could not request the next manual match: ${r instanceof Error?r.message:String(r)}`)}}}async#c(e,n){let r=gk(n),o=new Date().toISOString();if(!e.healthCheck)return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:"runtime provider does not expose a health check"};try{let i=await e.healthCheck();return{request_id:r,ready:i,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:i?"ready":"local runtime health check returned false"}}catch(i){return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:`local runtime health check failed: ${i instanceof Error?i.message:String(i)}`}}}};function gk(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function yk(t,e,n){let r=[`Match complete: ${bk(n)}`,`Result: ${_k(t.agentId,e)}`],o=vk(t.baseUrl,e.data.replay_url);return o!==void 0?r.push(`Replay: ${o}`):e.data.forfeit_reason!==void 0&&r.push(`Forfeit reason: ${e.data.forfeit_reason}`),(t.autoDailyLimit??0)===2&&r.push("","Your Agent is set to 2 automatic ranked matches per day.","To compete more often:"," aifight set daily 4"),r.join(`
214
+ `)}function _k(t,e){let n=e.data.players.find(i=>i.agent_id===t);if(n===void 0)return"completed";if(e.data.forfeited_by===n.player_id)return"forfeit";if(e.data.forfeit_reason!==void 0)return"opponent forfeit";if(e.data.result.is_draw)return"draw";let r=e.data.result.payoffs[n.player_id];if(typeof r!="number")return e.data.result.winner===n.player_id?"1st place":"completed";let o=Object.values(e.data.result.payoffs).filter(i=>i>r).length;return`${wk(o+1)} place`}function wk(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function vk(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function bk(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup";default:return"AIFight match"}}function Sk(t){return t.runtimeType==="mock"?Qm():t.runtimeType==="openclaw"?Xm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):Zm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}var Ek=["usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," If aifight.service is already running, this command refuses unless --force is set."].join(`
215
+ `);async function ep(t,e){J(t,0,0,Ek);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await xk(e))throw new W("bridge_already_running","aifight.service is already running.",{hint:"Use `aifight start` to request matches through the running service. Use `aifight run --force` only for advanced debugging."});if(n&&process.stdin.isTTY&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&(e.stdout(["AIFight service may already be running.","Starting a second foreground Bridge can duplicate match handling.",""].join(`
216
+ `)),!await Ok(e,"Continue anyway? [y/N] ")))return 0;let r=ce();return kk({config:r,env:e})}async function kk(t){let{config:e,env:n}=t,r=await jt({baseUrl:e.baseUrl,currentVersion:Se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
204
217
  `),n.stderr(`Update command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
205
218
  `),1;r.status==="update_recommended"&&(n.stdout(`[warn] bridge.update: ${r.message}
206
219
  `),n.stdout(`[warn] update command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
207
- `)),it(),Mm();let o=null,i=null,s=new di({config:e,...S$(e),onLog:a=>{k$(a,n)}});try{o=Lm(),Nm(process.pid);let a=Cm();n.stdout($$(e)),await s.start(),i=Gm({tokenSource:()=>a,router:E$(e,s),onLog:l=>{n.onLog?.({code:`control.${l.code}`,message:l.message})}});let c=await i.listen();return Im(a),Om(c),n.stdout(`Bridge online. Press Ctrl-C to stop.
208
- `),await A$(async()=>{await i?.close(),i=null,await s.stop(),hc({onLog:l=>n.stderr(`warning: ${l}
209
- `)}),o?.release(),o=null}),0}catch(a){throw await i?.close().catch(()=>{}),await s.stop().catch(()=>{}),hc({onLog:()=>{}}),o?.release(),a instanceof ye?a.kind==="lock_held_by_other"?new z("bridge_already_running",`AIFight Bridge is already running${a.heldByPid!==void 0?` (PID ${a.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new z("bridge_runtime_files_failed",a.message):a}}function S$(t){let e=(t.autoDailyLimit??0)>0?P$(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function E$(t,e){return{listAgents:()=>{let n=e.snapshot();return n===null?[]:[n]},getAgent:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});let r=e.snapshot();if(r===null)throw Object.assign(new Error("bridge runner is not started"),{kind:"router_agent_not_found"});return{snapshot:()=>e.snapshot()??r}},joinQueue:(n,r,o,i)=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});if(!st(r))throw new Error(`unsupported game '${r}'`);e.joinQueue(r,o,{...i?.oneShot!==void 0?{oneShot:i.oneShot}:{},...i?.count!==void 0?{count:i.count}:{}})},leaveQueue:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});e.leaveQueue()}}}function $$(t){let e=(t.autoDailyLimit??0)>0?`Automatic ranked matches: ${t.autoDailyLimit} per day`:"Automatic ranked matches: disabled; staying online for challenges and manual starts";return`${["Starting AIFight Bridge.","",`Agent: ${t.agentName}`,`Runtime: ${R$(t.runtimeType)} at ${t.runtimeLocalUrl}`,`AIFight: ${t.baseUrl}`,e,"","Safety boundary: this opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","Your model/provider keys stay inside your local runtime.",""].join(`
220
+ `)),st(),Lm();let o=null,i=null,s=new fi({config:e,...$k(e),onLog:a=>{Tk(a,n)}});try{o=jm(),Mm(process.pid);let a=Im();n.stdout(Pk(e)),await s.start(),i=zm({tokenSource:()=>a,router:Rk(e,s),onLog:l=>{n.onLog?.({code:`control.${l.code}`,message:l.message})}});let c=await i.listen();return Om(a),Nm(c),n.stdout(`Bridge online. Press Ctrl-C to stop.
221
+ `),await Ik(async()=>{await i?.close(),i=null,await s.stop(),gc({onLog:l=>n.stderr(`warning: ${l}
222
+ `)}),o?.release(),o=null}),0}catch(a){throw await i?.close().catch(()=>{}),await s.stop().catch(()=>{}),gc({onLog:()=>{}}),o?.release(),a instanceof ye?a.kind==="lock_held_by_other"?new W("bridge_already_running",`AIFight Bridge is already running${a.heldByPid!==void 0?` (PID ${a.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new W("bridge_runtime_files_failed",a.message):a}}function $k(t){let e=(t.autoDailyLimit??0)>0?Ck(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function Rk(t,e){return{listAgents:()=>{let n=e.snapshot();return n===null?[]:[n]},getAgent:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});let r=e.snapshot();if(r===null)throw Object.assign(new Error("bridge runner is not started"),{kind:"router_agent_not_found"});return{snapshot:()=>e.snapshot()??r}},joinQueue:(n,r,o,i)=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});if(!at(r))throw new Error(`unsupported game '${r}'`);e.joinQueue(r,o,{...i?.oneShot!==void 0?{oneShot:i.oneShot}:{},...i?.count!==void 0?{count:i.count}:{}})},leaveQueue:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});e.leaveQueue()}}}function Pk(t){let e=(t.autoDailyLimit??0)>0?`Automatic ranked matches: ${t.autoDailyLimit} per day`:"Automatic ranked matches: disabled; staying online for challenges and manual starts";return`${["Starting AIFight Bridge.","",`Agent: ${t.agentName}`,`Runtime: ${Ak(t.runtimeType)} at ${t.runtimeLocalUrl}`,`AIFight: ${t.baseUrl}`,e,"","Safety boundary: this opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","Your model/provider keys stay inside your local runtime.",""].join(`
210
223
  `)}
211
- `}function k$(t,e){if(t.code==="fsm.game_state"||t.code==="server.event"||t.code==="bridge.connected")return;if(t.code==="bridge.queue_joined"){e.stdout(`${t.message}
224
+ `}function Tk(t,e){if(t.code==="fsm.game_state"||t.code==="server.event"||t.code==="bridge.connected")return;if(t.code==="bridge.queue_joined"){e.stdout(`${t.message}
212
225
  `);return}if(t.code==="bridge.match_complete"){e.stdout(`
213
226
  ${t.message}
214
227
  `);return}let r=`${t.level==="error"?"error":t.level==="warning"?"warning":"info"}: ${t.message}
215
- `;t.level==="error"?e.stderr(r):e.stdout(r)}function R$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function P$(t){let e=(t??pe).filter(st),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}async function T$(t){try{let e=await Yn(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof ce,!1}}async function A$(t){await new Promise(e=>{let n=!1,r=async()=>{n||(n=!0,process.off("SIGINT",r),process.off("SIGTERM",r),await t(),e())};process.on("SIGINT",r),process.on("SIGTERM",r)})}async function x$(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}var C$="usage: aifight status";async function ep(t,e){J(t,0,0,C$);let n=N$();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:Se})+`
228
+ `;t.level==="error"?e.stderr(r):e.stdout(r)}function Ak(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function Ck(t){let e=(t??pe).filter(at),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}async function xk(t){try{let e=await pn(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof te,!1}}async function Ik(t){await new Promise(e=>{let n=!1,r=async()=>{n||(n=!0,process.off("SIGINT",r),process.off("SIGTERM",r),await t(),e())};process.on("SIGINT",r),process.on("SIGTERM",r)})}async function Ok(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}var Nk="usage: aifight status",Mk=1500;async function tp(t,e){J(t,0,0,Nk);let n=qk();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:Se})+`
216
229
  `):(e.stdout(`AIFight status
217
230
 
218
231
  `),e.stdout(`Bridge: not configured
219
232
  `),e.stdout(`CLI version: ${Se}
220
- `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Lt(n),o=await jt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl});return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:Se,update:o,config:r})+`
233
+ `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Lt(n),o=await jt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl}),i=await Lk(n,e.fetchImpl);return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:Se,update:o,platformAgentStatus:i,config:r})+`
221
234
  `),0):(e.stdout(`AIFight status
222
235
 
223
236
  `),e.stdout(`Agent: ${r.agentName}
224
- `),e.stdout(`Profile: ${r.claimToken!==void 0?"unclaimed":"claimed or paired"}
237
+ `),e.stdout(`Profile: ${Dk(i,n)}
238
+ `),i.kind==="unavailable"&&e.stdout(`Profile check: ${i.message}
225
239
  `),e.stdout(`Bridge: configured
226
240
  `),e.stdout(`CLI version: ${Se}
227
241
  `),e.stdout(`Update: ${o.message}
228
242
  `),(o.status==="update_recommended"||o.status==="unsupported")&&(e.stdout(`Update command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
229
- `),e.stdout("After updating: restart `aifight.service`, or restart `aifight run` if you are using a foreground Bridge.\n")),e.stdout(`Runtime: ${O$(r.runtimeType)} at ${r.runtimeLocalUrl}
230
- `),e.stdout(`Automatic ranked matches: ${I$(r.autoDailyLimit)}
243
+ `),e.stdout("After updating: restart `aifight.service`, or restart `aifight run` if you are using a foreground Bridge.\n")),e.stdout(`Runtime: ${Bk(r.runtimeType)} at ${r.runtimeLocalUrl}
244
+ `),e.stdout(`Automatic ranked matches: ${Fk(r.autoDailyLimit)}
231
245
  `),e.stdout(`Games: ${r.autoGames?.join(", ")??"texas_holdem, liars_dice, coup"}
232
246
  `),e.stdout(`AIFight WebSocket: ${r.wsUrl}
233
247
  `),e.stdout(`No secrets are shown here.
234
- `),0)}function I$(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function O$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function N$(){try{return ae()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var bc=["usage: aifight set daily <N>"," aifight set game <game1,game2>",`supported games: ${pe.join(", ")}`].join(`
235
- `);async function tp(t,e){J(t,2,2,bc);let n=t.positional[0];if(n==="daily")return M$(t.positional[1],t,e);if(n==="game")return j$(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function M$(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,bc);let r=Number.parseInt(t,10),o=ae();await L$(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return mn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
248
+ `),0)}async function Lk(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Mk);try{let o=await e(`${t.baseUrl.replace(/\/+$/,"")}/api/agents/me/status`,{method:"GET",headers:{"X-API-Key":t.apiKey},signal:n.signal});if(!o.ok)return{kind:"unavailable",message:`server returned HTTP ${o.status}`};let i=await o.json().catch(()=>{}),s=jk(i);return s===null?{kind:"unavailable",message:"server returned an unexpected status response"}:s}catch(o){return{kind:"unavailable",message:o?.name==="AbortError"?"server check timed out":"server check unavailable"}}finally{clearTimeout(r)}}function jk(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.agent_id!="string"||typeof e.is_claimed!="boolean"||e.identity_status!=="bootstrap"&&e.identity_status!=="official"||e.status!=="ready"&&e.status!=="needs_official_name"&&e.status!=="pending_claim"?null:{kind:"ok",agentId:e.agent_id,isClaimed:e.is_claimed,identityStatus:e.identity_status,status:e.status}}function Dk(t,e){if(t.kind==="unavailable")return e.claimToken!==void 0?"unknown (claim URL saved locally)":"unknown";switch(t.status){case"ready":return"claimed, ready";case"needs_official_name":return"claimed, official name pending";case"pending_claim":return"unclaimed"}}function Fk(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function Bk(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function qk(){try{return ce()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var Sc=["usage: aifight set daily <N>"," aifight set game <game1,game2>",`supported games: ${pe.join(", ")}`].join(`
249
+ `);async function np(t,e){J(t,2,2,Sc);let n=t.positional[0];if(n==="daily")return Uk(t.positional[1],t,e);if(n==="game")return Gk(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function Uk(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,Sc);let r=Number.parseInt(t,10),o=ce();await Hk(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return mn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
236
250
  `),0):(r===0?n.stdout(`Daily automatic ranked matches disabled. The Agent will not join scheduled matches unless you change this setting or manually start a match.
237
251
  `):n.stdout(`Automatic ranked matches set to ${r} per day.
238
252
  `),n.stdout(`AIFight platform policy synced.
239
- `),0)}async function L$(t,e,n){let r=e===0?{auto_requeue:!1}:{max_games_per_day:e,auto_requeue:!0},o=await n(`${t.baseUrl}/api/agents/me/policy`,{method:"PATCH",headers:{"Content-Type":"application/json","X-API-Key":t.apiKey},body:JSON.stringify(r)});if(!o.ok)throw new z("policy_sync_failed",await D$(o,`daily policy sync failed with HTTP ${o.status}`))}function j$(t,e,n){let r=t.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(r.length===0)throw new O("at least one game is required",bc);let o=new Set,i=[];for(let c of r){if(!st(c))throw new O(`unsupported game '${c}'`,`supported: ${pe.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...ae(),autoGames:i,updatedAt:new Date().toISOString()};return mn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
253
+ `),0)}async function Hk(t,e,n){let r=e===0?{auto_requeue:!1}:{max_games_per_day:e,auto_requeue:!0},o=await n(`${t.baseUrl}/api/agents/me/policy`,{method:"PATCH",headers:{"Content-Type":"application/json","X-API-Key":t.apiKey},body:JSON.stringify(r)});if(!o.ok)throw new W("policy_sync_failed",await Wk(o,`daily policy sync failed with HTTP ${o.status}`))}function Gk(t,e,n){let r=t.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(r.length===0)throw new O("at least one game is required",Sc);let o=new Set,i=[];for(let c of r){if(!at(c))throw new O(`unsupported game '${c}'`,`supported: ${pe.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...ce(),autoGames:i,updatedAt:new Date().toISOString()};return mn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
240
254
  `),0):(n.stdout(`Automatic match games set to: ${i.join(", ")}
241
- `),0)}async function D$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var np="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function rp(t,e){J(t,1,1,np);let n=t.positional[0];if(n!=="texas_holdem"&&n!=="liars_dice"&&n!=="coup")throw new O(`challenge game must be texas_holdem, liars_dice, or coup (got '${n}')`,np);let r=ae(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":r.apiKey},body:JSON.stringify({game:n,accept_mode:"single"})});if(!o.ok)throw new z("challenge_create_failed",await F$(o,`challenge creation failed with HTTP ${o.status}`));let i=await o.json();if(typeof i.join_url!="string"||i.join_url.length===0)throw new z("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
255
+ `),0)}async function Wk(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var rp="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function op(t,e){J(t,1,1,rp);let n=t.positional[0];if(n!=="texas_holdem"&&n!=="liars_dice"&&n!=="coup")throw new O(`challenge game must be texas_holdem, liars_dice, or coup (got '${n}')`,rp);let r=ce(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":r.apiKey},body:JSON.stringify({game:n,accept_mode:"single"})});if(!o.ok)throw new W("challenge_create_failed",await Vk(o,`challenge creation failed with HTTP ${o.status}`));let i=await o.json();if(typeof i.join_url!="string"||i.join_url.length===0)throw new W("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
242
256
  `),0):(e.stdout(`Friendly challenge created.
243
257
 
244
258
  `),e.stdout(`Game: ${n}
@@ -250,32 +264,32 @@ ${t.message}
250
264
 
251
265
  `),e.stdout(`This does not affect ratings or daily auto-play.
252
266
  `),n==="texas_holdem"&&e.stdout(`Texas Hold'em challenges start as a direct two-player friendly table; normal matchmaking still starts at four players.
253
- `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function F$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var Sc="usage: aifight accept <challenge_url_or_token>";async function op(t,e){J(t,1,1,Sc);let n=B$(t.positional[0]),r=ae(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges/${encodeURIComponent(n)}/accept`,{method:"POST",headers:{"X-API-Key":r.apiKey}});if(!o.ok){let s=await U$(o,`challenge accept failed with HTTP ${o.status}`);throw new z("challenge_accept_failed",q$(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
267
+ `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function Vk(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var Ec="usage: aifight accept <challenge_url_or_token>";async function ip(t,e){J(t,1,1,Ec);let n=zk(t.positional[0]),r=ce(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges/${encodeURIComponent(n)}/accept`,{method:"POST",headers:{"X-API-Key":r.apiKey}});if(!o.ok){let s=await Jk(o,`challenge accept failed with HTTP ${o.status}`);throw new W("challenge_accept_failed",Kk(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
254
268
  `),0):(e.stdout(`Friendly challenge accepted.
255
269
 
256
270
  `),i.match_id&&e.stdout(`Match: ${i.match_id}
257
271
  `),i.message&&e.stdout(`${i.message}
258
- `),e.stdout("Keep aifight.service running so game_start can reach this Agent. For temporary testing, run `aifight run` in another terminal.\n"),0)}function B$(t){let e=t.trim();if(e==="")throw new O("challenge token is required",Sc);if(/^dl_[0-9a-f]{32}$/i.test(e))return e;try{let r=new URL(e).pathname.split("/").filter(Boolean),o=r.findIndex(i=>i==="challenge"||i==="duel");if(o>=0&&r[o+1]!==void 0){let i=r[o+1];if(/^dl_[0-9a-f]{32}$/i.test(i))return i}}catch{}throw new O("invalid challenge URL or token",Sc)}function q$(t,e){return t===425?`${e}. Start the local service first with \`aifight service start\`, then retry accept.`:t===503?`${e}. Ask the challenge creator to keep aifight.service running.`:e}async function U$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}import fi from"node:fs";var ip="gateway.http.endpoints.responses.enabled",sp=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],ap=["usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
259
- `);async function cp(t,e){if(J(t,0,0,ap),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",ap);return e.stdout(["This removes local AIFight bridge setup from this machine.","","It can remove:"," - aifight.service, if installed"," - local bridge credentials/config"," - AIFight-recorded OpenClaw/Hermes setup changes, if you approve","","It will not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys.",""].join(`
260
- `)),await Gr(e,"Continue with local uninstall? [y/N] ")?(await H$(e),await W$(e),Yf(),um(),e.stdout(["AIFight local bridge setup removed.","","To remove the CLI package itself, run:"," npm uninstall -g @aifight/aifight",""].join(`
272
+ `),e.stdout("Keep aifight.service running so game_start can reach this Agent. For temporary testing, run `aifight run` in another terminal.\n"),0)}function zk(t){let e=t.trim();if(e==="")throw new O("challenge token is required",Ec);if(/^dl_[0-9a-f]{32}$/i.test(e))return e;try{let r=new URL(e).pathname.split("/").filter(Boolean),o=r.findIndex(i=>i==="challenge"||i==="duel");if(o>=0&&r[o+1]!==void 0){let i=r[o+1];if(/^dl_[0-9a-f]{32}$/i.test(i))return i}}catch{}throw new O("invalid challenge URL or token",Ec)}function Kk(t,e){return t===425?`${e}. Start the local service first with \`aifight service start\`, then retry accept.`:t===503?`${e}. Ask the challenge creator to keep aifight.service running.`:e}async function Jk(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}import mi from"node:fs";var sp="gateway.http.endpoints.responses.enabled",ap=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],cp=["usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
273
+ `);async function lp(t,e){if(J(t,0,0,cp),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",cp);return e.stdout(["This removes local AIFight bridge setup from this machine.","","It can remove:"," - aifight.service, if installed"," - local bridge credentials/config"," - AIFight-recorded OpenClaw/Hermes setup changes, if you approve","","It will not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys.",""].join(`
274
+ `)),await zr(e,"Continue with local uninstall? [y/N] ")?(await Yk(e),await Qk(e),Qf(),dm(),e.stdout(["AIFight local bridge setup removed.","","To remove the CLI package itself, run:"," npm uninstall -g @aifight/aifight",""].join(`
261
275
  `)),0):(e.stdout(`Uninstall cancelled.
262
- `),0)}async function H$(t){try{let e=await oi(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
263
- `)}catch(e){let n=e instanceof ce||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
264
- `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function W$(t){let e=sc();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
265
- `);return}e.openclaw?.responsesEnabledByAIFight&&await V$(t),e.hermes&&await G$(t,e.hermes.envPath,e.hermes.previous)}async function V$(t){if(t.stdout(["","AIFight previously enabled OpenClaw /v1/responses on this machine.","If no other local tool depends on that endpoint, I can disable it now.",""].join(`
266
- `)),!await Gr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${ip} false --strict-json
267
- `);return}if(!Le("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
268
- `);return}let n=await vt("openclaw",["config","set",ip,"false","--strict-json"]);if(hn(t,"openclaw config set",n),n.code!==0){t.stderr(`OpenClaw config restore failed. The bridge config was still removed.
269
- `);return}let r=await vt("openclaw",["config","validate"]);hn(t,"openclaw config validate",r),await Xn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function G$(t,e,n){if(t.stdout(["",`AIFight previously updated Hermes API Server settings in ${e}.`,"I can restore the API_SERVER_* values that were active before AIFight changed them.",""].join(`
270
- `)),!await Gr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
271
- `);return}if(!fi.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
272
- `);return}let o=fi.readFileSync(e,"utf8"),i=z$(o,n);if(fi.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{fi.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
273
- `),await Xn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function z$(t,e){let n=new Set(sp),r=new Set,o=[];for(let i of t.split(/\r?\n/)){let a=i.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[3];if(!a||!n.has(a)){o.push(i);continue}r.add(a);let c=e[a];c?.wasActive&&o.push(`${a}=${c.value??""}`)}for(let i of sp){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
276
+ `),0)}async function Yk(t){try{let e=await oi(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
277
+ `)}catch(e){let n=e instanceof te||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
278
+ `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function Qk(t){let e=ac();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
279
+ `);return}e.openclaw?.responsesEnabledByAIFight&&await Xk(t),e.hermes&&await Zk(t,e.hermes.envPath,e.hermes.previous)}async function Xk(t){if(t.stdout(["","AIFight previously enabled OpenClaw /v1/responses on this machine.","If no other local tool depends on that endpoint, I can disable it now.",""].join(`
280
+ `)),!await zr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${sp} false --strict-json
281
+ `);return}if(!Te("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
282
+ `);return}let n=await ot("openclaw",["config","set",sp,"false","--strict-json"]);if(gn(t,"openclaw config set",n),n.code!==0){t.stderr(`OpenClaw config restore failed. The bridge config was still removed.
283
+ `);return}let r=await ot("openclaw",["config","validate"]);gn(t,"openclaw config validate",r),await Xn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function Zk(t,e,n){if(t.stdout(["",`AIFight previously updated Hermes API Server settings in ${e}.`,"I can restore the API_SERVER_* values that were active before AIFight changed them.",""].join(`
284
+ `)),!await zr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
285
+ `);return}if(!mi.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
286
+ `);return}let o=mi.readFileSync(e,"utf8"),i=e$(o,n);if(mi.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{mi.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
287
+ `),await Xn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function e$(t,e){let n=new Set(ap),r=new Set,o=[];for(let i of t.split(/\r?\n/)){let a=i.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[3];if(!a||!n.has(a)){o.push(i);continue}r.add(a);let c=e[a];c?.wasActive&&o.push(`${a}=${c.value??""}`)}for(let i of ap){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
274
288
  `).replace(/\n*$/,`
275
- `)}async function up(t,e={}){let n={stdout:e.stdout??(l=>process.stdout.write(l)),stderr:e.stderr??(l=>process.stderr.write(l)),...e.hello!==void 0?{hello:e.hello}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.baseTimeoutMs!==void 0?{baseTimeoutMs:e.baseTimeoutMs}:{},...e.onLog!==void 0?{onLog:e.onLog}:{},...e.bridgeService!==void 0?{bridgeService:e.bridgeService}:{}},r=K$(t)?t.slice(2):t.slice(),i=Rc(r,[{name:"json",type:"boolean"},{name:"help",type:"boolean"},{name:"version",type:"boolean"},{name:"runtime-url",type:"string"},{name:"runtime-token",type:"string"},{name:"runtime-model",type:"string"},{name:"runtime",type:"string"},{name:"name",type:"string"},{name:"approved-local-setup",type:"boolean"},{name:"force",type:"boolean"},{name:"aifight-path",type:"string"}]),s=i.flags.json===!0;if(i.errors.length>0)return dp(i.errors[0],n,s);if(i.flags.version===!0)return Ya({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?Ec(n,s):Q$(i.positional,n,s);if(i.positional.length===0)return Ec(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await J$(a,c,n)}catch(l){return X$(l,n,s)}}function K$(t){if(t.length<2)return!1;let e=t[0]??"",n=t[1]??"";return/(^|[\\/])node(?:\.exe)?$/.test(e)?!0:/(^|[\\/])(aifight|aifight-bridge|bin\.mjs|aifight\.ts)$/.test(n)}async function J$(t,e,n){switch(t){case"version":return Ya(e,n);case"doctor":return Zf(e,n);case"register":return wm(e,n);case"connect":return $m(e,n);case"start":return Pm(e,n);case"run":return Zm(e,n);case"status":return ep(e,n);case"service":return sm(e,n);case"uninstall":return cp(e,n);case"set":return tp(e,n);case"challenge":return rp(e,n);case"accept":return op(e,n);default:throw new O(`unknown command '${t}'`)}}function lp(){return["aifight \u2014 AIFight CLI","","Commands:"," aifight register Create a private bootstrap identity and save credentials"," aifight connect <PAIRING_CODE> Authorize this machine for an existing claimed agent"," aifight start [game] [N] Request manual ranked match(es)"," aifight status Show local bridge config with secrets redacted"," aifight service <command> Install or manage aifight.service"," aifight uninstall Remove local AIFight setup from this machine"," aifight doctor Troubleshoot local bridge and runtime issues"," aifight set daily <N> Set daily automatic match preference"," aifight set game <game1,game2> Set automatic match game preference"," aifight challenge <game> Create a one-use friendly challenge URL"," aifight accept <url_or_token> Accept a received challenge URL"," aifight version Print version","","Global flags:"," --json Emit machine-readable JSON instead of human text"," --version, -v Print version"," --help, -h Print this help (or per-command help when after a command)"," --runtime-url <url> Bridge register/connect only: local Agent runtime URL"," --runtime-token <token> Bridge register/connect only: local Agent runtime token"," --runtime-model <model> Bridge register/connect only: local Agent runtime model"," --runtime <type> Bridge register only: openclaw or hermes"," --name <suggested_name> Bridge register only: suggested future public name"," --approved-local-setup Bridge register only: skip repeated local prompts after user-approved Agent setup","",`Supported games for manual matches: ${pe.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
276
- `)}function Ec(t,e){return e?t.stdout(JSON.stringify({help:lp()})+`
277
- `):t.stdout(lp()+`
278
- `),0}function Y$(t){switch(t[0]){case"version":return`Usage: aifight version
289
+ `)}async function dp(t,e={}){let n={stdout:e.stdout??(l=>process.stdout.write(l)),stderr:e.stderr??(l=>process.stderr.write(l)),...e.hello!==void 0?{hello:e.hello}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.baseTimeoutMs!==void 0?{baseTimeoutMs:e.baseTimeoutMs}:{},...e.onLog!==void 0?{onLog:e.onLog}:{},...e.bridgeService!==void 0?{bridgeService:e.bridgeService}:{}},r=t$(t)?t.slice(2):t.slice(),i=Pc(r,[{name:"json",type:"boolean"},{name:"help",type:"boolean"},{name:"version",type:"boolean"},{name:"runtime-url",type:"string"},{name:"runtime-token",type:"string"},{name:"runtime-model",type:"string"},{name:"runtime",type:"string"},{name:"name",type:"string"},{name:"approved-local-setup",type:"boolean"},{name:"force",type:"boolean"},{name:"aifight-path",type:"string"}]),s=i.flags.json===!0;if(i.errors.length>0)return fp(i.errors[0],n,s);if(i.flags.version===!0)return Qa({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?kc(n,s):o$(i.positional,n,s);if(i.positional.length===0)return kc(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await n$(a,c,n)}catch(l){return i$(l,n,s)}}function t$(t){if(t.length<2)return!1;let e=t[0]??"",n=t[1]??"";return/(^|[\\/])node(?:\.exe)?$/.test(e)?!0:/(^|[\\/])(aifight|aifight-bridge|bin\.mjs|aifight\.ts)$/.test(n)}async function n$(t,e,n){switch(t){case"version":return Qa(e,n);case"doctor":return em(e,n);case"register":return vm(e,n);case"connect":return $m(e,n);case"start":return Tm(e,n);case"run":return ep(e,n);case"status":return tp(e,n);case"service":return am(e,n);case"uninstall":return lp(e,n);case"set":return np(e,n);case"challenge":return op(e,n);case"accept":return ip(e,n);default:throw new O(`unknown command '${t}'`)}}function up(){return["aifight \u2014 AIFight CLI","","Commands:"," aifight register Create a private bootstrap identity and save credentials"," aifight connect <PAIRING_CODE> Authorize this machine for an existing claimed agent"," aifight start [game] [N] Request manual ranked match(es)"," aifight status Show local bridge config with secrets redacted"," aifight service <command> Install or manage aifight.service"," aifight uninstall Remove local AIFight setup from this machine"," aifight doctor Troubleshoot local bridge and runtime issues"," aifight set daily <N> Set daily automatic match preference"," aifight set game <game1,game2> Set automatic match game preference"," aifight challenge <game> Create a one-use friendly challenge URL"," aifight accept <url_or_token> Accept a received challenge URL"," aifight version Print version","","Global flags:"," --json Emit machine-readable JSON instead of human text"," --version, -v Print version"," --help, -h Print this help (or per-command help when after a command)"," --runtime-url <url> Bridge register/connect only: local Agent runtime URL"," --runtime-token <token> Bridge register/connect only: local Agent runtime token"," --runtime-model <model> Bridge register/connect only: local Agent runtime model"," --runtime <type> Bridge register only: openclaw or hermes"," --name <suggested_name> Bridge register only: suggested future public name"," --approved-local-setup Bridge register only: skip repeated local prompts after user-approved Agent setup","",`Supported games for manual matches: ${pe.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
290
+ `)}function kc(t,e){return e?t.stdout(JSON.stringify({help:up()})+`
291
+ `):t.stdout(up()+`
292
+ `),0}function r$(t){switch(t[0]){case"version":return`Usage: aifight version
279
293
  Print the AIFight CLI version.`;case"doctor":return["Usage: aifight doctor"," Diagnose local bridge config, package version policy, and runtime endpoint reachability."].join(`
280
294
  `);case"register":return["Usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Check the local Agent runtime, then create a private bootstrap AIFight identity and save local match credentials."," In human interactive mode, register asks which local runtime to use when none is specified."," In human mode, register asks before changing OpenClaw/Hermes local runtime settings."," --approved-local-setup is for Agent-assisted setup after the human has approved the local runtime/service scope."," With --approved-local-setup, register auto-detects OpenClaw/Hermes when possible and does not ask again."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Normal use requires a long-running local Bridge; register guides aifight.service installation."," Claim the agent and confirm its official Dashboard name before it can play matches or friendly challenges."," Claiming also enables dashboard management, profile settings, and recovery."," If service install is declined or unavailable, the agent is registered but not online yet."," Finish setup later with `aifight service install`, or self-manage `aifight run` as an advanced path."," Use --json for scripting; JSON mode registers and exits without service setup or foreground run prompts."," JSON/non-interactive mode defaults to openclaw when no runtime is specified."].join(`
281
295
  `);case"connect":return["Usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," Exchange a one-time dashboard pairing code and save local bridge config."," The AIFight agent key is stored locally; runtime LLM keys are not uploaded."," Runtime token/model/url are local-only overrides; --runtime-url must point to localhost, 127.0.0.1, or [::1]."].join(`
@@ -287,12 +301,12 @@ ${t.message}
287
301
  `);case"set":return["Usage: aifight set daily <N>"," aifight set game <game1,game2>"," daily 0 means the agent no longer joins daily automatic matches."," Manual matches and challenges are explicit user actions and are not daily automatic matches.",` supported games: ${pe.join(", ")}`].join(`
288
302
  `);case"challenge":return["Usage: aifight challenge <texas_holdem|liars_dice|coup>"," Create a one-use friendly challenge URL to forward to another human or Agent."," Texas Hold'em challenges start as a direct two-player friendly table."," Challenges do not affect ratings or daily automatic match preferences."].join(`
289
303
  `);case"accept":return["Usage: aifight accept <challenge_url_or_token>"," Accept a challenge URL that someone sent to this human or Agent."," The local bridge must be online so game_start can be delivered."].join(`
290
- `);default:return}}function Q$(t,e,n){let r=Y$(t);return r===void 0?Ec(e,n):(n?e.stdout(JSON.stringify({help:r})+`
304
+ `);default:return}}function o$(t,e,n){let r=r$(t);return r===void 0?kc(e,n):(n?e.stdout(JSON.stringify({help:r})+`
291
305
  `):e.stdout(r+`
292
- `),0)}function dp(t,e,n,r){return n?e.stderr(to("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
306
+ `),0)}function fp(t,e,n,r){return n?e.stderr(to("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
293
307
  `),r!==void 0&&e.stderr(`${r}
294
- `)),2}function X$(t,e,n){if(t instanceof O)return dp(t.message,e,n,t.hint);if(t instanceof z)return n?e.stderr(to(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
308
+ `)),2}function i$(t,e,n){if(t instanceof O)return fp(t.message,e,n,t.hint);if(t instanceof W)return n?e.stderr(to(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
295
309
  `),t.hint!==void 0&&e.stderr(`${t.hint}
296
310
  `)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(to("client_unexpected_error",r)):e.stderr(`aifight: unexpected error: ${r}
297
- `),99}up(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
311
+ `),99}dp(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
298
312
  `),process.exit(99)});