@aifight/aifight 0.1.0-alpha.6 → 0.1.0-alpha.7

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 $p=Object.create;var Ac=Object.defineProperty;var Rp=Object.getOwnPropertyDescriptor;var Pp=Object.getOwnPropertyNames;var Ap=Object.getPrototypeOf,Tp=Object.prototype.hasOwnProperty;var ee=(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 xp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pp(e))!Tp.call(t,o)&&o!==n&&Ac(t,o,{get:()=>e[o],enumerable:!(r=Rp(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?$p(Ap(t)):{},xp(e||!t||!t.__esModule?Ac(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 Ht=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=Ht;var Ce=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 Ht&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=Ce;D.nil=new Ce("");function Hc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Si(n,e[r]),n.push(t[++r]);return new Ce(n)}D._=Hc;var bi=new Ce("+");function Gc(t,...e){let n=[ar(t[0])],r=0;for(;r<e.length;)n.push(bi),Si(n,e[r]),n.push(bi,ar(t[++r]));return Gp(n),new Ce(n)}D.str=Gc;function Si(t,e){e instanceof Ce?t.push(...e._items):e instanceof Ht?t.push(e):t.push(zp(e))}D.addCodeArg=Si;function Gp(t){let e=1;for(;e<t.length-1;){if(t[e]===bi){let n=Vp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Vp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ht||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 Ht))return`"${t}${e.slice(1)}`}function Wp(t,e){return e.emptyStr()?t:t.emptyStr()?e:Gc`${t}${e}`}D.strConcat=Wp;function zp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ar(Array.isArray(t)?t.join(","):t)}function Kp(t){return new Ce(ar(t))}D.stringify=Kp;function ar(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=ar;function Jp(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new Ce(`.${t}`):Hc`[${t}]`}D.getProperty=Jp;function Yp(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new Ce(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Yp;function Qp(t){return new Ce(t.toString())}D.regexpCode=Qp});var $i=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.ValueScope=ve.ValueScopeName=ve.Scope=ve.varKinds=ve.UsedValueState=void 0;var we=cr(),Ei=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},io;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(io||(ve.UsedValueState=io={}));ve.varKinds={const:new we.Name("const"),let:new we.Name("let"),var:new we.Name("var")};var so=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof we.Name?e:this.name(e)}name(e){return new we.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}}};ve.Scope=so;var ao=class extends we.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,we._)`.${new we.Name(n)}[${r}]`}};ve.ValueScopeName=ao;var Xp=(0,we._)`\n`,ki=class extends so{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Xp:we.nil}}get(){return this._scope}name(e){return new ao(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,we._)`${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=we.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,io.Started);let u=n(l);if(u){let d=this.opts.es5?ve.varKinds.var:ve.varKinds.const;i=(0,we._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,we._)`${i}${u}${this.opts._n}`;else throw new Ei(l);c.set(l,io.Completed)})}return i}};ve.ValueScope=ki});var T=_(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=cr(),De=$i(),kt=cr();Object.defineProperty(C,"_",{enumerable:!0,get:function(){return kt._}});Object.defineProperty(C,"str",{enumerable:!0,get:function(){return kt.str}});Object.defineProperty(C,"strConcat",{enumerable:!0,get:function(){return kt.strConcat}});Object.defineProperty(C,"nil",{enumerable:!0,get:function(){return kt.nil}});Object.defineProperty(C,"getProperty",{enumerable:!0,get:function(){return kt.getProperty}});Object.defineProperty(C,"stringify",{enumerable:!0,get:function(){return kt.stringify}});Object.defineProperty(C,"regexpCode",{enumerable:!0,get:function(){return kt.regexpCode}});Object.defineProperty(C,"Name",{enumerable:!0,get:function(){return kt.Name}});var fo=$i();Object.defineProperty(C,"Scope",{enumerable:!0,get:function(){return fo.Scope}});Object.defineProperty(C,"ValueScope",{enumerable:!0,get:function(){return fo.ValueScope}});Object.defineProperty(C,"ValueScopeName",{enumerable:!0,get:function(){return fo.ValueScopeName}});Object.defineProperty(C,"varKinds",{enumerable:!0,get:function(){return fo.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 lt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Ri=class extends lt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?De.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:{}}},co=class extends lt{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 uo(e,this.rhs)}},Pi=class extends co{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ai=class extends lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ti=class extends lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},xi=class extends lt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ci=class extends lt{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 lt{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)||(Zp(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),{})}},ut=class extends lr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ii=class extends lr{},vn=class extends ut{};vn.kind="else";var Gt=class t extends ut{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(Vc(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 uo(e,this.condition),this.else&&Wt(e,this.else.names),e}};Gt.kind="if";var Vt=class extends ut{};Vt.kind="for";var Oi=class extends Vt{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)}},Ni=class extends Vt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?De.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=uo(super.names,this.from);return uo(e,this.to)}},lo=class extends Vt{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 ut{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 Li=class extends ut{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 ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fr.kind="catch";var mr=class extends ut{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Mi=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
- `:""},this._extScope=e,this._scope=new De.Scope({parent:e}),this._nodes=[new Ii]}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 Ri(e,i,r)),i}const(e,n,r){return this._def(De.varKinds.const,e,n,r)}let(e,n,r){return this._def(De.varKinds.let,e,n,r)}var(e,n,r){return this._def(De.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new co(e,n,r))}add(e,n){return this._leafNode(new Pi(e,C.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ci(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 Gt(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 Gt(e))}else(){return this._elseNode(new vn)}endIf(){return this._endBlockNode(Gt,vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Oi(e),n)}forRange(e,n,r,o,i=this.opts.es5?De.varKinds.var:De.varKinds.let){let s=this._scope.toName(e);return this._for(new Ni(i,s,n,r),()=>o(s))}forOf(e,n,r,o=De.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 lo("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?De.varKinds.var:De.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 lo("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Vt)}label(e){return this._leafNode(new Ai(e))}break(e){return this._leafNode(new Ti(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 Li;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 xi(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 Gt))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=Mi;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function uo(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 Zp(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Vc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${ji(t)}`}C.not=Vc;var eh=Wc(C.operators.AND);function th(...t){return t.reduce(eh)}C.and=th;var nh=Wc(C.operators.OR);function rh(...t){return t.reduce(nh)}C.or=rh;function Wc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${ji(e)} ${t} ${ji(n)}`}function ji(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var L=_(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=T(),oh=cr();function ih(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=ih;function sh(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Jc(t,e),!Yc(e,t.self.RULES.all))}I.alwaysValidSchema=sh;function Jc(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]||Zc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Jc;function Yc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=Yc;function ah(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=ah;function ch({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=ch;function lh(t){return Qc(decodeURIComponent(t))}I.unescapeFragment=lh;function uh(t){return encodeURIComponent(Fi(t))}I.escapeFragment=uh;function Fi(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=Fi;function Qc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Qc;function dh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=dh;function zc({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:zc({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} || {}`),Bi(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Xc}),items:zc({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 Xc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Bi(t,n,e),n}I.evaluatedPropsToName=Xc;function Bi(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Bi;var Kc={};function fh(t,e){return t.scopeValue("func",{ref:e,code:Kc[e.code]||(Kc[e.code]=new oh._Code(e.code))})}I.useFunc=fh;var Di;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Di||(I.Type=Di={}));function mh(t,e,n){if(t instanceof q.Name){let r=e===Di.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():"/"+Fi(t)}I.getErrorPath=mh;function Zc(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=Zc});var dt=_(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var ue=T(),ph={data:new ue.Name("data"),valCxt:new ue.Name("valCxt"),instancePath:new ue.Name("instancePath"),parentData:new ue.Name("parentData"),parentDataProperty:new ue.Name("parentDataProperty"),rootData:new ue.Name("rootData"),dynamicAnchors:new ue.Name("dynamicAnchors"),vErrors:new ue.Name("vErrors"),errors:new ue.Name("errors"),this:new ue.Name("this"),self:new ue.Name("self"),scope:new ue.Name("scope"),json:new ue.Name("json"),jsonPos:new ue.Name("jsonPos"),jsonLen:new ue.Name("jsonLen"),jsonPart:new ue.Name("jsonPart")};Ui.default=ph});var pr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.extendErrors=de.resetErrorsCount=de.reportExtraError=de.reportError=de.keyword$DataError=de.keywordError=void 0;var M=T(),mo=L(),ge=dt();de.keywordError={message:({keyword:t})=>(0,M.str)`must pass "${t}" keyword validation`};de.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,M.str)`"${t}" keyword must be ${e} ($data)`:(0,M.str)`"${t}" keyword is invalid ($data)`};function hh(t,e=de.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=nl(t,e,n);r??(s||a)?el(i,c):tl(o,(0,M._)`[${c}]`)}de.reportError=hh;function gh(t,e=de.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=nl(t,e,n);el(o,a),i||s||tl(r,ge.default.vErrors)}de.reportExtraError=gh;function yh(t,e){t.assign(ge.default.errors,e),t.if((0,M._)`${ge.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,M._)`${ge.default.vErrors}.length`,e),()=>t.assign(ge.default.vErrors,null)))}de.resetErrorsCount=yh;function _h({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,ge.default.errors,a=>{t.const(s,(0,M._)`${ge.default.vErrors}[${a}]`),t.if((0,M._)`${s}.instancePath === undefined`,()=>t.assign((0,M._)`${s}.instancePath`,(0,M.strConcat)(ge.default.instancePath,i.errorPath))),t.assign((0,M._)`${s}.schemaPath`,(0,M.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,M._)`${s}.schema`,n),t.assign((0,M._)`${s}.data`,r))})}de.extendErrors=_h;function el(t,e){let n=t.const("err",e);t.if((0,M._)`${ge.default.vErrors} === null`,()=>t.assign(ge.default.vErrors,(0,M._)`[${n}]`),(0,M._)`${ge.default.vErrors}.push(${n})`),t.code((0,M._)`${ge.default.errors}++`)}function tl(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,M._)`new ${t.ValidationError}(${e})`):(n.assign((0,M._)`${r}.errors`,e),n.return(!1))}var zt={keyword:new M.Name("keyword"),schemaPath:new M.Name("schemaPath"),params:new M.Name("params"),propertyName:new M.Name("propertyName"),message:new M.Name("message"),schema:new M.Name("schema"),parentSchema:new M.Name("parentSchema")};function nl(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,M._)`{}`:wh(t,e,n)}function wh(t,e,n={}){let{gen:r,it:o}=t,i=[vh(o,n),bh(t,n)];return Sh(t,e,i),r.object(...i)}function vh({errorPath:t},{instancePath:e}){let n=e?(0,M.str)`${t}${(0,mo.getErrorPath)(e,mo.Type.Str)}`:t;return[ge.default.instancePath,(0,M.strConcat)(ge.default.instancePath,n)]}function bh({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,M.str)`${e}/${t}`;return n&&(o=(0,M.str)`${o}${(0,mo.getErrorPath)(n,mo.Type.Str)}`),[zt.schemaPath,o]}function Sh(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([zt.keyword,o],[zt.params,typeof e=="function"?e(t):e||(0,M._)`{}`]),c.messages&&r.push([zt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([zt.schema,s],[zt.parentSchema,(0,M._)`${u}${d}`],[ge.default.data,i]),l&&r.push([zt.propertyName,l])}});var ol=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.boolOrEmptySchema=Sn.topBoolOrEmptySchema=void 0;var Eh=pr(),kh=T(),$h=dt(),Rh={message:"boolean schema is false"};function Ph(t){let{gen:e,schema:n,validateName:r}=t;n===!1?rl(t,!1):typeof n=="object"&&n.$async===!0?e.return($h.default.data):(e.assign((0,kh._)`${r}.errors`,null),e.return(!0))}Sn.topBoolOrEmptySchema=Ph;function Ah(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),rl(t)):n.var(e,!0)}Sn.boolOrEmptySchema=Ah;function rl(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,Eh.reportError)(o,Rh,void 0,e)}});var qi=_(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var Th=["string","number","integer","boolean","null","object","array"],xh=new Set(Th);function Ch(t){return typeof t=="string"&&xh.has(t)}En.isJSONType=Ch;function Ih(){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=Ih});var Hi=_($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function Oh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&il(t,r)}$t.schemaHasRulesForType=Oh;function il(t,e){return e.rules.some(n=>sl(t,n))}$t.shouldUseGroup=il;function sl(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))}$t.shouldUseRule=sl});var hr=_(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.reportTypeError=fe.checkDataTypes=fe.checkDataType=fe.coerceAndCheckDataType=fe.getJSONTypes=fe.getSchemaTypes=fe.DataType=void 0;var Nh=qi(),Lh=Hi(),Mh=pr(),A=T(),al=L(),kn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(kn||(fe.DataType=kn={}));function jh(t){let e=cl(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}fe.getSchemaTypes=jh;function cl(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Nh.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}fe.getJSONTypes=cl;function Dh(t,e){let{gen:n,data:r,opts:o}=t,i=Fh(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Lh.schemaHasRulesForType)(t,e[0]));if(s){let a=Vi(e,r,o.strictNumbers,kn.Wrong);n.if(a,()=>{i.length?Bh(t,e,i):Wi(t)})}return s}fe.coerceAndCheckDataType=Dh;var ll=new Set(["string","number","integer","boolean","null"]);function Fh(t,e){return e?t.filter(n=>ll.has(n)||e==="array"&&n==="array"):[]}function Bh(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,A._)`typeof ${o}`),a=r.let("coerced",(0,A._)`undefined`);i.coerceTypes==="array"&&r.if((0,A._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,A._)`${o}[0]`).assign(s,(0,A._)`typeof ${o}`).if(Vi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,A._)`${a} !== undefined`);for(let l of n)(ll.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),Wi(t),r.endIf(),r.if((0,A._)`${a} !== undefined`,()=>{r.assign(o,a),Uh(t,a)});function c(l){switch(l){case"string":r.elseIf((0,A._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,A._)`"" + ${o}`).elseIf((0,A._)`${o} === null`).assign(a,(0,A._)`""`);return;case"number":r.elseIf((0,A._)`${s} == "boolean" || ${o} === null
5
- || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,A._)`+${o}`);return;case"integer":r.elseIf((0,A._)`${s} === "boolean" || ${o} === null
6
- || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,A._)`+${o}`);return;case"boolean":r.elseIf((0,A._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,A._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,A._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,A._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,A._)`[${o}]`)}}}function Uh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,A._)`${e} !== undefined`,()=>t.assign((0,A._)`${e}[${n}]`,r))}function Gi(t,e,n,r=kn.Correct){let o=r===kn.Correct?A.operators.EQ:A.operators.NEQ,i;switch(t){case"null":return(0,A._)`${e} ${o} null`;case"array":i=(0,A._)`Array.isArray(${e})`;break;case"object":i=(0,A._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,A._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,A._)`typeof ${e} ${o} ${t}`}return r===kn.Correct?i:(0,A.not)(i);function s(a=A.nil){return(0,A.and)((0,A._)`typeof ${e} == "number"`,a,n?(0,A._)`isFinite(${e})`:A.nil)}}fe.checkDataType=Gi;function Vi(t,e,n,r){if(t.length===1)return Gi(t[0],e,n,r);let o,i=(0,al.toHash)(t);if(i.array&&i.object){let s=(0,A._)`typeof ${e} != "object"`;o=i.null?s:(0,A._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=A.nil;i.number&&delete i.integer;for(let s in i)o=(0,A.and)(o,Gi(s,e,n,r));return o}fe.checkDataTypes=Vi;var qh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,A._)`{type: ${t}}`:(0,A._)`{type: ${e}}`};function Wi(t){let e=Hh(t);(0,Mh.reportError)(e,qh)}fe.reportTypeError=Wi;function Hh(t){let{gen:e,data:n,schema:r}=t,o=(0,al.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var dl=_(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.assignDefaults=void 0;var $n=T(),Gh=L();function Vh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)ul(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>ul(t,i,o.default))}po.assignDefaults=Vh;function ul(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,Gh.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 G=T(),zi=L(),Rt=dt(),Wh=L();function zh(t,e){let{gen:n,data:r,it:o}=t;n.if(Ji(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,G._)`${e}`},!0),t.error()})}F.checkReportMissingProp=zh;function Kh({gen:t,data:e,it:{opts:n}},r,o){return(0,G.or)(...r.map(i=>(0,G.and)(Ji(t,e,i,n.ownProperties),(0,G._)`${o} = ${i}`)))}F.checkMissingProp=Kh;function Jh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Jh;function fl(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,G._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=fl;function Ki(t,e,n){return(0,G._)`${fl(t)}.call(${e}, ${n})`}F.isOwnProperty=Ki;function Yh(t,e,n,r){let o=(0,G._)`${e}${(0,G.getProperty)(n)} !== undefined`;return r?(0,G._)`${o} && ${Ki(t,e,n)}`:o}F.propertyInData=Yh;function Ji(t,e,n,r){let o=(0,G._)`${e}${(0,G.getProperty)(n)} === undefined`;return r?(0,G.or)(o,(0,G.not)(Ki(t,e,n))):o}F.noPropertyInData=Ji;function ml(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ml;function Qh(t,e){return ml(e).filter(n=>!(0,zi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Qh;function Xh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,G._)`${t}, ${e}, ${r}${o}`:e,d=[[Rt.default.instancePath,(0,G.strConcat)(Rt.default.instancePath,i)],[Rt.default.parentData,s.parentData],[Rt.default.parentDataProperty,s.parentDataProperty],[Rt.default.rootData,Rt.default.rootData]];s.opts.dynamicRef&&d.push([Rt.default.dynamicAnchors,Rt.default.dynamicAnchors]);let h=(0,G._)`${u}, ${n.object(...d)}`;return c!==G.nil?(0,G._)`${a}.call(${c}, ${h})`:(0,G._)`${a}(${h})`}F.callValidateCode=Xh;var Zh=(0,G._)`new RegExp`;function eg({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,G._)`${o.code==="new RegExp"?Zh:(0,Wh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=eg;function tg(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,G._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:zi.Type.Num},i),e.if((0,G.not)(i),a)})}}F.validateArray=tg;function ng(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,zi.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,G._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,G.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=ng});var gl=_(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var ye=T(),Kt=dt(),rg=Ie(),og=pr();function ig(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=hl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ye.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Ye.macroKeywordCode=ig;function sg(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;cg(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=hl(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&&pl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&pl(t),g(()=>ag(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ye._)`await `),v=>r.assign(d,!1).if((0,ye._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ye._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ye._)`${u}.errors`;return r.assign(y,null),m(ye.nil),y}function m(y=e.async?(0,ye._)`await `:ye.nil){let v=c.opts.passContext?Kt.default.this:Kt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ye._)`${y}${(0,rg.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ye.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Ye.funcKeywordCode=sg;function pl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ye._)`${r.parentData}[${r.parentDataProperty}]`))}function ag(t,e){let{gen:n}=t;n.if((0,ye._)`Array.isArray(${e})`,()=>{n.assign(Kt.default.vErrors,(0,ye._)`${Kt.default.vErrors} === null ? ${e} : ${Kt.default.vErrors}.concat(${e})`).assign(Kt.default.errors,(0,ye._)`${Kt.default.vErrors}.length`),(0,og.extendErrors)(t)},()=>t.error())}function cg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function hl(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,ye.stringify)(n)})}function lg(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")}Ye.validSchemaType=lg;function ug({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)}}Ye.validateKeywordUsage=ug});var _l=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendSubschemaMode=Pt.extendSubschemaData=Pt.getSubschema=void 0;var Qe=T(),yl=L();function dg(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,Qe._)`${t.schemaPath}${(0,Qe.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Qe._)`${t.schemaPath}${(0,Qe.getProperty)(e)}${(0,Qe.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,yl.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')}Pt.getSubschema=dg;function fg(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,Qe._)`${e.data}${(0,Qe.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Qe.str)`${l}${(0,yl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Qe._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Qe.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]}}Pt.extendSubschemaData=fg;function mg(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}Pt.extendSubschemaMode=mg});var Yi=_((aR,wl)=>{"use strict";wl.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 bl=_((cR,vl)=>{"use strict";var At=vl.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(){};ho(e,r,o,t,"",t)};At.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};At.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};At.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};At.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 ho(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 At.arrayKeywords)for(var h=0;h<d.length;h++)ho(t,e,n,d[h],o+"/"+u+"/"+h,i,o,u,r,h)}else if(u in At.propsKeywords){if(d&&typeof d=="object")for(var p in d)ho(t,e,n,d[p],o+"/"+u+"/"+pg(p),i,o,u,r,p)}else(u in At.keywords||t.allKeys&&!(u in At.skipKeywords))&&ho(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function pg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gr=_(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.getSchemaRefs=be.resolveUrl=be.normalizeId=be._getFullPath=be.getFullPath=be.inlineRef=void 0;var hg=L(),gg=Yi(),yg=bl(),_g=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Qi(t):e?Sl(t)<=e:!1}be.inlineRef=wg;var vg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qi(t){for(let e in t){if(vg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Qi)||typeof n=="object"&&Qi(n))return!0}return!1}function Sl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!_g.has(n)&&(typeof t[n]=="object"&&(0,hg.eachItem)(t[n],r=>e+=Sl(r)),e===1/0))return 1/0}return e}function El(t,e="",n){n!==!1&&(e=Rn(e));let r=t.parse(e);return kl(t,r)}be.getFullPath=El;function kl(t,e){return t.serialize(e).split("#")[0]+"#"}be._getFullPath=kl;var bg=/#\/?$/;function Rn(t){return t?t.replace(bg,""):""}be.normalizeId=Rn;function Sg(t,e,n){return n=Rn(n),t.resolve(e,n)}be.resolveUrl=Sg;var Eg=/^[a-z_][-a-z0-9._]*$/i;function kg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Rn(t[n]||e),i={"":o},s=El(r,o,!1),a={},c=new Set;return yg(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(!Eg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,h,p){if(h!==void 0&&!gg(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}be.getSchemaRefs=kg});var wr=_(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var Tl=ol(),$l=hr(),Zi=Hi(),go=hr(),$g=dl(),_r=gl(),Xi=_l(),b=T(),P=dt(),Rg=gr(),ft=L(),yr=pr();function Pg(t){if(Il(t)&&(Ol(t),Cl(t))){xg(t);return}xl(t,()=>(0,Tl.topBoolOrEmptySchema)(t))}Tt.validateFunctionCode=Pg;function xl({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"; ${Rl(n,o)}`),Tg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${Ag(o)}`,r.$async,()=>t.code(Rl(n,o)).code(i))}function Ag(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 Tg(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 xg(t){let{schema:e,opts:n,gen:r}=t;xl(t,()=>{n.$comment&&e.$comment&&Ll(t),Lg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&Cg(t),Nl(t),Dg(t)})}function Cg(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 Rl(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 Ig(t,e){if(Il(t)&&(Ol(t),Cl(t))){Og(t,e);return}(0,Tl.boolOrEmptySchema)(t,e)}function Cl({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 Il(t){return typeof t.schema!="boolean"}function Og(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Ll(t),Mg(t),jg(t);let i=r.const("_errs",P.default.errors);Nl(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Ol(t){(0,ft.checkUnknownRules)(t),Ng(t)}function Nl(t,e){if(t.opts.jtd)return Pl(t,[],!1,e);let n=(0,$l.getSchemaTypes)(t.schema),r=(0,$l.coerceAndCheckDataType)(t,n);Pl(t,n,!r,e)}function Ng(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ft.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Lg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ft.checkStrictMode)(t,"default is ignored in the schema root")}function Mg(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Rg.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function jg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ll({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 Dg(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&&Fg(t),e.return((0,b._)`${P.default.errors} === 0`))}function Fg({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 Pl(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,ft.schemaHasRulesButRef)(i,u))){o.block(()=>jl(t,"$ref",u.all.$ref.definition));return}c.jtd||Bg(t,e),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Zi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,go.checkDataType)(h.type,s,c.strictNumbers)),Al(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,go.reportTypeError)(t)),o.endIf()):Al(t,h),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function Al(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,Zi.shouldUseRule)(r,i)&&jl(t,i.keyword,i.definition,e.type)})}function Bg(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ug(t,e),t.opts.allowUnionTypes||qg(t,e),Hg(t,t.dataTypes))}function Ug(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Ml(t.dataTypes,n)||es(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Vg(t,e)}}function qg(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&es(t,"use allowUnionTypes to allow union type keyword")}function Hg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Zi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Gg(e,s))&&es(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function Gg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ml(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Vg(t,e){let n=[];for(let r of t.dataTypes)Ml(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function es(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ft.checkStrictMode)(t,e,t.opts.strictTypes)}var yo=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,ft.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",Dl(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,go.checkDataTypes)(c,n,i.opts.strictNumbers,go.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,Xi.getSubschema)(this.it,e);(0,Xi.extendSubschemaData)(r,this.it,e),(0,Xi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return Ig(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ft.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ft.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}};Tt.KeywordCxt=yo;function jl(t,e,n,r){let o=new yo(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 Wg=/^\/(?:[^~]|~0|~1)*$/,zg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Dl(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Wg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=zg.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,ft.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Tt.getData=Dl});var _o=_(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var ts=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ns.default=ts});var vr=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});var rs=gr(),os=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,rs.resolveUrl)(e,n,r),this.missingSchema=(0,rs.normalizeId)((0,rs.getFullPath)(e,this.missingRef))}};is.default=os});var vo=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Fe=T(),Kg=_o(),Jt=dt(),Be=gr(),Fl=L(),Jg=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,Be.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 as(t){let e=Bl.call(this,t);if(e)return e;let n=(0,Be.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Fe.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:Kg.default,code:(0,Fe._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Jt.default.data,parentData:Jt.default.parentData,parentDataProperty:Jt.default.parentDataProperty,dataNames:[Jt.default.data],dataPathArr:[Fe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Fe.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:Fe.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Fe._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Jg.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Jt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Jt.default.self}`,`${Jt.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 Fe.Name?void 0:f,items:m instanceof Fe.Name?void 0:m,dynamicProps:f instanceof Fe.Name,dynamicItems:m instanceof Fe.Name},p.source&&(p.source.evaluated=(0,Fe.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=as;function Yg(t,e,n){var r;n=(0,Be.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Zg.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]=Qg.call(this,i)}Oe.resolveRef=Yg;function Qg(t){return(0,Be.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:as.call(this,t)}function Bl(t){for(let e of this._compilations)if(Xg(e,t))return e}Oe.getCompilingSchema=Bl;function Xg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Zg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||wo.call(this,t,e)}function wo(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Be._getFullPath)(this.opts.uriResolver,n),o=(0,Be.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return ss.call(this,n,t);let i=(0,Be.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=wo.call(this,t,s);return typeof a?.schema!="object"?void 0:ss.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||as.call(this,s),i===(0,Be.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Be.resolveUrl)(this.opts.uriResolver,o,l)),new Pn({schema:a,schemaId:c,root:t,baseId:o})}return ss.call(this,n,s)}}Oe.resolveSchema=wo;var ey=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ss(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,Fl.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!ey.has(a)&&l&&(e=(0,Be.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Fl.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Be.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=wo.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 Ul=_((pR,ty)=>{ty.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 ls=_((hR,Vl)=>{"use strict";var ny=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Hl=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 cs(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 ry=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ql(t){return t.length=0,!0}function oy(t,e,n){if(t.length){let r=cs(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function iy(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=oy;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=ql}else{o.push(l);continue}}return o.length&&(a===ql?n.zone=o.join(""):s?r.push(o.join("")):r.push(cs(o))),n.address=r.join(""),n}function Gl(t){if(sy(t,":")<2)return{host:t,isIPV6:!1};let e=iy(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 sy(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function ay(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 cy(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 ly(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Hl(n)){let r=Gl(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}Vl.exports={nonSimpleDomain:ry,recomposeAuthority:ly,normalizeComponentEncoding:cy,removeDotSegments:ay,isIPv4:Hl,isUUID:ny,normalizeIPv6:Gl,stringArrayToHexStripped:cs}});var Yl=_((gR,Jl)=>{"use strict";var{isUUID:uy}=ls(),dy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fy=["http","https","ws","wss","urn","urn:uuid"];function my(t){return fy.indexOf(t)!==-1}function us(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 Wl(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function zl(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 py(t){return t.secure=us(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function hy(t){if((t.port===(us(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 gy(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(dy);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=ds(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function yy(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=ds(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 _y(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!uy(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function wy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Kl={scheme:"http",domainHost:!0,parse:Wl,serialize:zl},vy={scheme:"https",domainHost:Kl.domainHost,parse:Wl,serialize:zl},bo={scheme:"ws",domainHost:!0,parse:py,serialize:hy},by={scheme:"wss",domainHost:bo.domainHost,parse:bo.parse,serialize:bo.serialize},Sy={scheme:"urn",parse:gy,serialize:yy,skipNormalize:!0},Ey={scheme:"urn:uuid",parse:_y,serialize:wy,skipNormalize:!0},So={http:Kl,https:vy,ws:bo,wss:by,urn:Sy,"urn:uuid":Ey};Object.setPrototypeOf(So,null);function ds(t){return t&&(So[t]||So[t.toLowerCase()])||void 0}Jl.exports={wsIsSecure:us,SCHEMES:So,isValidSchemeName:my,getSchemeHandler:ds}});var Zl=_((yR,ko)=>{"use strict";var{normalizeIPv6:ky,removeDotSegments:br,recomposeAuthority:$y,normalizeComponentEncoding:Eo,isIPv4:Ry,nonSimpleDomain:Py}=ls(),{SCHEMES:Ay,getSchemeHandler:Ql}=Yl();function Ty(t,e){return typeof t=="string"?t=Xe(mt(t,e),e):typeof t=="object"&&(t=mt(Xe(t,e),e)),t}function xy(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Xl(mt(t,r),mt(e,r),r,!0);return r.skipEscape=!0,Xe(o,r)}function Xl(t,e,n,r){let o={};return r||(t=mt(Xe(t,n),n),e=mt(Xe(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 Cy(t,e,n){return typeof t=="string"?(t=unescape(t),t=Xe(Eo(mt(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Xe(Eo(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Xe(Eo(mt(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Xe(Eo(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Xe(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=Ql(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 Iy=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function mt(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(Iy);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(Ry(r.host)===!1){let c=ky(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=Ql(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&Py(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 fs={SCHEMES:Ay,normalize:Ty,resolve:xy,resolveComponent:Xl,equal:Cy,serialize:Xe,parse:mt};ko.exports=fs;ko.exports.default=fs;ko.exports.fastUri=fs});var tu=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var eu=Zl();eu.code='require("ajv/dist/runtime/uri").default';ms.default=eu});var lu=_(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.CodeGen=ce.Name=ce.nil=ce.stringify=ce.str=ce._=ce.KeywordCxt=void 0;var Oy=wr();Object.defineProperty(ce,"KeywordCxt",{enumerable:!0,get:function(){return Oy.KeywordCxt}});var An=T();Object.defineProperty(ce,"_",{enumerable:!0,get:function(){return An._}});Object.defineProperty(ce,"str",{enumerable:!0,get:function(){return An.str}});Object.defineProperty(ce,"stringify",{enumerable:!0,get:function(){return An.stringify}});Object.defineProperty(ce,"nil",{enumerable:!0,get:function(){return An.nil}});Object.defineProperty(ce,"Name",{enumerable:!0,get:function(){return An.Name}});Object.defineProperty(ce,"CodeGen",{enumerable:!0,get:function(){return An.CodeGen}});var Ny=_o(),su=vr(),Ly=qi(),Sr=vo(),My=T(),Er=gr(),$o=hr(),hs=L(),nu=Ul(),jy=tu(),au=(t,e)=>new RegExp(t,e);au.code="new RegExp";var Dy=["removeAdditional","useDefaults","coerceTypes"],Fy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),By={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."},Uy={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ru=200;function qy(t){var e,n,r,o,i,s,a,c,l,u,d,h,p,f,m,g,y,v,S,R,$,K,X,ae,Ke;let st=t.strict,nr=(e=t.code)===null||e===void 0?void 0:e.optimize,Je=nr===!0||nr===void 0?1:nr||0,re=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:au,Ut=(o=t.uriResolver)!==null&&o!==void 0?o:jy.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:st)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:st)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:st)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:st)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:st)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Je,regExp:re}:{optimize:Je,regExp:re},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:ru,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:ru,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:(K=t.validateSchema)!==null&&K!==void 0?K:!0,validateFormats:(X=t.validateFormats)!==null&&X!==void 0?X:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(Ke=t.int32range)!==null&&Ke!==void 0?Ke:!0,uriResolver:Ut}}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,...qy(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new My.ValueScope({scope:{},prefixes:Fy,es5:n,lines:r}),this.logger=Ky(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ly.getRules)(),ou.call(this,By,e,"NOT SUPPORTED"),ou.call(this,Uy,e,"DEPRECATED","warn"),this._metaOpts=Wy.call(this),e.formats&&Gy.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Vy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Hy.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=nu;r==="id"&&(o={...nu},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 su.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=iu.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=iu.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(Yy.call(this,r,n),!n)return(0,hs.eachItem)(r,i=>ps.call(this,i)),this;Xy.call(this,n);let o={...n,type:(0,$o.getJSONTypes)(n.type),schemaType:(0,$o.getJSONTypes)(n.schemaType)};return(0,hs.eachItem)(r,o.type.length===0?i=>ps.call(this,i,o):i=>o.type.forEach(s=>ps.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]=cu(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=Ny.default;kr.MissingRefError=su.default;ce.default=kr;function ou(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 iu(t){return t=(0,Er.normalizeId)(t),this.schemas[t]||this.refs[t]}function Hy(){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 Gy(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Vy(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 Wy(){let t={...this.opts};for(let e of Dy)delete t[e];return t}var zy={log(){},warn(){},error(){}};function Ky(t){if(t===!1)return zy;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 Jy=/^[a-z_$][a-z0-9_$:-]*$/i;function Yy(t,e){let{RULES:n}=this;if((0,hs.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Jy.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 ps(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?Qy.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 Qy(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 Xy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=cu(e)),t.validateSchema=this.compile(e,!0))}var Zy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function cu(t){return{anyOf:[t,Zy]}}});var uu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var e_={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gs.default=e_});var pu=_(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.callRef=Yt.getValidate=void 0;var t_=vr(),du=Ie(),Se=T(),Tn=dt(),fu=vo(),Ro=L(),n_={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=fu.resolveRef.call(c,l,o,n);if(u===void 0)throw new t_.default(r.opts.uriResolver,o,n);if(u instanceof fu.SchemaEnv)return h(u);return p(u);function d(){if(i===l)return Po(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return Po(t,(0,Se._)`${f}.validate`,l,l.$async)}function h(f){let m=mu(t,f);Po(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Se.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:Se.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function mu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Se._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Yt.getValidate=mu;function Po(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?Tn.default.this:Se.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,Se._)`await ${(0,du.callValidateCode)(t,e,l)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,Se._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,du.callValidateCode)(t,e,l),()=>p(e),()=>h(e))}function h(f){let m=(0,Se._)`${f}.errors`;o.assign(Tn.default.vErrors,(0,Se._)`${Tn.default.vErrors} === null ? ${m} : ${Tn.default.vErrors}.concat(${m})`),o.assign(Tn.default.errors,(0,Se._)`${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=Ro.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,Se._)`${f}.evaluated.props`);i.props=Ro.mergeEvaluated.props(o,y,i.props,Se.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Ro.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,Se._)`${f}.evaluated.items`);i.items=Ro.mergeEvaluated.items(o,y,i.items,Se.Name)}}}Yt.callRef=Po;Yt.default=n_});var hu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var r_=uu(),o_=pu(),i_=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",r_.default,o_.default];ys.default=i_});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var Ao=T(),xt=Ao.operators,To={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},s_={message:({keyword:t,schemaCode:e})=>(0,Ao.str)`must be ${To[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ao._)`{comparison: ${To[t].okStr}, limit: ${e}}`},a_={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:s_,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Ao._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};_s.default=a_});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var $r=T(),c_={message:({schemaCode:t})=>(0,$r.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$r._)`{multipleOf: ${t}}`},l_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:c_,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}))`)}};ws.default=l_});var wu=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});function _u(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}vs.default=_u;_u.code='require("ajv/dist/runtime/ucs2length").default'});var vu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Qt=T(),u_=L(),d_=wu(),f_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},m_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:f_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,s=o.opts.unicode===!1?(0,Qt._)`${n}.length`:(0,Qt._)`${(0,u_.useFunc)(t.gen,d_.default)}(${n})`;t.fail$data((0,Qt._)`${s} ${i} ${r}`)}};bs.default=m_});var bu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var p_=Ie(),h_=L(),xn=T(),g_={message:({schemaCode:t})=>(0,xn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xn._)`{pattern: ${t}}`},y_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:g_,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,xn._)`new RegExp`:(0,h_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,xn._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,xn._)`!${u}`)}else{let c=(0,p_.usePattern)(t,o);t.fail$data((0,xn._)`!${c}.test(${n})`)}}};Ss.default=y_});var Su=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Rr=T(),__={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}}`},w_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:__,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}`)}};Es.default=w_});var Eu=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Pr=Ie(),Ar=T(),v_=L(),b_={message:({params:{missingProperty:t}})=>(0,Ar.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ar._)`{missingProperty: ${t}}`},S_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:b_,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,v_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(Ar.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,Ar.not)(f),()=>{t.error(),e.break()})},Ar.nil)}}};ks.default=S_});var ku=_($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var Tr=T(),E_={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}}`},k_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:E_,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}`)}};$s.default=k_});var xo=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var $u=Yi();$u.code='require("ajv/dist/runtime/equal").default';Rs.default=$u});var Ru=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Ps=hr(),le=T(),$_=L(),R_=xo(),P_={message:({params:{i:t,j:e}})=>(0,le.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,le._)`{i: ${t}, j: ${e}}`},A_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:P_,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,Ps.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,le._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,le._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,le._)`${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,Ps.checkDataTypes)(l,g,a.opts.strictNumbers,Ps.DataType.Wrong),v=e.const("indices",(0,le._)`{}`);e.for((0,le._)`;${f}--;`,()=>{e.let(g,(0,le._)`${n}[${f}]`),e.if(y,(0,le._)`continue`),l.length>1&&e.if((0,le._)`typeof ${g} == "string"`,(0,le._)`${g} += "_"`),e.if((0,le._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,le._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,le._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,$_.useFunc)(e,R_.default),y=e.name("outer");e.label(y).for((0,le._)`;${f}--;`,()=>e.for((0,le._)`${m} = ${f}; ${m}--;`,()=>e.if((0,le._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};As.default=A_});var Pu=_(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var Ts=T(),T_=L(),x_=xo(),C_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ts._)`{allowedValue: ${t}}`},I_={keyword:"const",$data:!0,error:C_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Ts._)`!${(0,T_.useFunc)(e,x_.default)}(${n}, ${o})`):t.fail((0,Ts._)`${i} !== ${n}`)}};xs.default=I_});var Au=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var xr=T(),O_=L(),N_=xo(),L_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,xr._)`{allowedValues: ${t}}`},M_={keyword:"enum",schemaType:"array",$data:!0,error:L_,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,O_.useFunc)(e,N_.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,xr.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,xr._)`${l()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,xr._)`${l()}(${n}, ${p}[${f}])`:(0,xr._)`${n} === ${m}`}}};Cs.default=M_});var Tu=_(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var j_=gu(),D_=yu(),F_=vu(),B_=bu(),U_=Su(),q_=Eu(),H_=ku(),G_=Ru(),V_=Pu(),W_=Au(),z_=[j_.default,D_.default,F_.default,B_.default,U_.default,q_.default,H_.default,G_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},V_.default,W_.default];Is.default=z_});var Ns=_(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.validateAdditionalItems=void 0;var Xt=T(),Os=L(),K_={message:({params:{len:t}})=>(0,Xt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xt._)`{limit: ${t}}`},J_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:K_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Os.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}xu(t,r)}};function xu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Xt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Os.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Xt._)`${a} <= ${e.length}`);n.if((0,Xt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:Os.Type.Num},l),s.allErrors||n.if((0,Xt.not)(l),()=>n.break())})}}Cr.validateAdditionalItems=xu;Cr.default=J_});var Ls=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var Cu=T(),Co=L(),Y_=Ie(),Q_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Iu(t,"additionalItems",e);n.items=!0,!(0,Co.alwaysValidSchema)(n,e)&&t.ok((0,Y_.validateArray)(t))}};function Iu(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,Cu._)`${i}.length`);n.forEach((d,h)=>{(0,Co.alwaysValidSchema)(a,d)||(r.if((0,Cu._)`${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=Iu;Ir.default=Q_});var Ou=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var X_=Ls(),Z_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,X_.validateTuple)(t,"items")};Ms.default=Z_});var Lu=_(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Nu=T(),ew=L(),tw=Ie(),nw=Ns(),rw={message:({params:{len:t}})=>(0,Nu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Nu._)`{limit: ${t}}`},ow={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rw,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,ew.alwaysValidSchema)(r,e)&&(o?(0,nw.validateAdditionalItems)(t,o):t.ok((0,tw.validateArray)(t)))}};js.default=ow});var Mu=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Ne=T(),Io=L(),iw={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}}`},sw={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iw,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,Io.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Io.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Io.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:Io.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)))}}};Ds.default=sw});var Fu=_(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.validateSchemaDeps=Ze.validatePropertyDeps=Ze.error=void 0;var Fs=T(),aw=L(),Or=Ie();Ze.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Fs.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Fs._)`{property: ${t},
3
+ var Rp=Object.create;var Pc=Object.defineProperty;var Ap=Object.getOwnPropertyDescriptor;var Pp=Object.getOwnPropertyNames;var Tp=Object.getPrototypeOf,Cp=Object.prototype.hasOwnProperty;var te=(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 xp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pp(e))!Cp.call(t,o)&&o!==n&&Pc(t,o,{get:()=>e[o],enumerable:!(r=Ap(e,o))||r.enumerable});return t};var Ce=(t,e,n)=>(n=t!=null?Rp(Tp(t)):{},xp(e||!t||!t.__esModule?Pc(n,"default",{value:t,enumerable:!0}):n,t));var lr=_(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 ar=class{};D._CodeOrName=ar;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ht=class extends ar{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=Ht;var xe=class extends ar{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 Ht&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=xe;D.nil=new xe("");function Hc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Si(n,e[r]),n.push(t[++r]);return new xe(n)}D._=Hc;var bi=new xe("+");function Gc(t,...e){let n=[cr(t[0])],r=0;for(;r<e.length;)n.push(bi),Si(n,e[r]),n.push(bi,cr(t[++r]));return Vp(n),new xe(n)}D.str=Gc;function Si(t,e){e instanceof xe?t.push(...e._items):e instanceof Ht?t.push(e):t.push(Kp(e))}D.addCodeArg=Si;function Vp(t){let e=1;for(;e<t.length-1;){if(t[e]===bi){let n=Wp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Wp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ht||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 Ht))return`"${t}${e.slice(1)}`}function zp(t,e){return e.emptyStr()?t:t.emptyStr()?e:Gc`${t}${e}`}D.strConcat=zp;function Kp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:cr(Array.isArray(t)?t.join(","):t)}function Jp(t){return new xe(cr(t))}D.stringify=Jp;function cr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=cr;function Yp(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new xe(`.${t}`):Hc`[${t}]`}D.getProperty=Yp;function Qp(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=Qp;function Xp(t){return new xe(t.toString())}D.regexpCode=Xp});var $i=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.ValueScope=ve.ValueScopeName=ve.Scope=ve.varKinds=ve.UsedValueState=void 0;var we=lr(),Ei=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},io;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(io||(ve.UsedValueState=io={}));ve.varKinds={const:new we.Name("const"),let:new we.Name("let"),var:new we.Name("var")};var so=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof we.Name?e:this.name(e)}name(e){return new we.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}}};ve.Scope=so;var ao=class extends we.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,we._)`.${new we.Name(n)}[${r}]`}};ve.ValueScopeName=ao;var Zp=(0,we._)`\n`,ki=class extends so{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Zp:we.nil}}get(){return this._scope}name(e){return new ao(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 l=a.get(s);if(l)return l}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),u=c.length;return c[u]=n.ref,o.setValue(n,{property:i,itemIndex:u}),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,we._)`${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=we.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,io.Started);let l=n(u);if(l){let d=this.opts.es5?ve.varKinds.var:ve.varKinds.const;i=(0,we._)`${i}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))i=(0,we._)`${i}${l}${this.opts._n}`;else throw new Ei(u);c.set(u,io.Completed)})}return i}};ve.ValueScope=ki});var T=_(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=lr(),De=$i(),kt=lr();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return kt._}});Object.defineProperty(x,"str",{enumerable:!0,get:function(){return kt.str}});Object.defineProperty(x,"strConcat",{enumerable:!0,get:function(){return kt.strConcat}});Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return kt.nil}});Object.defineProperty(x,"getProperty",{enumerable:!0,get:function(){return kt.getProperty}});Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return kt.stringify}});Object.defineProperty(x,"regexpCode",{enumerable:!0,get:function(){return kt.regexpCode}});Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return kt.Name}});var fo=$i();Object.defineProperty(x,"Scope",{enumerable:!0,get:function(){return fo.Scope}});Object.defineProperty(x,"ValueScope",{enumerable:!0,get:function(){return fo.ValueScope}});Object.defineProperty(x,"ValueScopeName",{enumerable:!0,get:function(){return fo.ValueScopeName}});Object.defineProperty(x,"varKinds",{enumerable:!0,get:function(){return fo.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 lt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Ri=class extends lt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?De.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:{}}},co=class extends lt{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 uo(e,this.rhs)}},Ai=class extends co{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Pi=class extends lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ti=class extends lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ci=class extends lt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},xi=class extends lt{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:{}}},ur=class extends lt{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)||(eh(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),{})}},ut=class extends ur{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ii=class extends ur{},vn=class extends ut{};vn.kind="else";var Gt=class t extends ut{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(Vc(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 uo(e,this.condition),this.else&&Wt(e,this.else.names),e}};Gt.kind="if";var Vt=class extends ut{};Vt.kind="for";var Oi=class extends Vt{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)}},Ni=class extends Vt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?De.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=uo(super.names,this.from);return uo(e,this.to)}},lo=class extends Vt{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)}},dr=class extends ut{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)}};dr.kind="func";var fr=class extends ur{render(e){return"return "+super.render(e)}};fr.kind="return";var Li=class extends ut{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}},mr=class extends ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};mr.kind="catch";var pr=class extends ut{render(e){return"finally"+super.render(e)}};pr.kind="finally";var Mi=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
+ `:""},this._extScope=e,this._scope=new De.Scope({parent:e}),this._nodes=[new Ii]}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 Ri(e,i,r)),i}const(e,n,r){return this._def(De.varKinds.const,e,n,r)}let(e,n,r){return this._def(De.varKinds.let,e,n,r)}var(e,n,r){return this._def(De.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new co(e,n,r))}add(e,n){return this._leafNode(new Ai(e,x.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new xi(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 Gt(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 Gt(e))}else(){return this._elseNode(new vn)}endIf(){return this._endBlockNode(Gt,vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Oi(e),n)}forRange(e,n,r,o,i=this.opts.es5?De.varKinds.var:De.varKinds.let){let s=this._scope.toName(e);return this._for(new Ni(i,s,n,r),()=>o(s))}forOf(e,n,r,o=De.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 lo("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?De.varKinds.var:De.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 lo("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Vt)}label(e){return this._leafNode(new Pi(e))}break(e){return this._leafNode(new Ti(e))}return(e){let n=new fr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Li;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new mr(i),n(i)}return r&&(this._currNode=o.finally=new pr,this.code(r)),this._endBlockNode(mr,pr)}throw(e){return this._leafNode(new Ci(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 dr(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(dr)}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 Gt))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=Mi;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function uo(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 eh(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Vc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${ji(t)}`}x.not=Vc;var th=Wc(x.operators.AND);function nh(...t){return t.reduce(th)}x.and=nh;var rh=Wc(x.operators.OR);function oh(...t){return t.reduce(rh)}x.or=oh;function Wc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${ji(e)} ${t} ${ji(n)}`}function ji(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var L=_(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=T(),ih=lr();function sh(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=sh;function ah(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Jc(t,e),!Yc(e,t.self.RULES.all))}I.alwaysValidSchema=ah;function Jc(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]||Zc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Jc;function Yc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=Yc;function ch(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=ch;function lh({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=lh;function uh(t){return Qc(decodeURIComponent(t))}I.unescapeFragment=uh;function dh(t){return encodeURIComponent(Bi(t))}I.escapeFragment=dh;function Bi(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=Bi;function Qc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Qc;function fh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=fh;function zc({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:zc({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} || {}`),Fi(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Xc}),items:zc({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 Xc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Fi(t,n,e),n}I.evaluatedPropsToName=Xc;function Fi(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Fi;var Kc={};function mh(t,e){return t.scopeValue("func",{ref:e,code:Kc[e.code]||(Kc[e.code]=new ih._Code(e.code))})}I.useFunc=mh;var Di;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Di||(I.Type=Di={}));function ph(t,e,n){if(t instanceof q.Name){let r=e===Di.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():"/"+Bi(t)}I.getErrorPath=ph;function Zc(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=Zc});var dt=_(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var ue=T(),hh={data:new ue.Name("data"),valCxt:new ue.Name("valCxt"),instancePath:new ue.Name("instancePath"),parentData:new ue.Name("parentData"),parentDataProperty:new ue.Name("parentDataProperty"),rootData:new ue.Name("rootData"),dynamicAnchors:new ue.Name("dynamicAnchors"),vErrors:new ue.Name("vErrors"),errors:new ue.Name("errors"),this:new ue.Name("this"),self:new ue.Name("self"),scope:new ue.Name("scope"),json:new ue.Name("json"),jsonPos:new ue.Name("jsonPos"),jsonLen:new ue.Name("jsonLen"),jsonPart:new ue.Name("jsonPart")};Ui.default=hh});var hr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.extendErrors=de.resetErrorsCount=de.reportExtraError=de.reportError=de.keyword$DataError=de.keywordError=void 0;var M=T(),mo=L(),ge=dt();de.keywordError={message:({keyword:t})=>(0,M.str)`must pass "${t}" keyword validation`};de.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,M.str)`"${t}" keyword must be ${e} ($data)`:(0,M.str)`"${t}" keyword is invalid ($data)`};function gh(t,e=de.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=nl(t,e,n);r??(s||a)?el(i,c):tl(o,(0,M._)`[${c}]`)}de.reportError=gh;function yh(t,e=de.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=nl(t,e,n);el(o,a),i||s||tl(r,ge.default.vErrors)}de.reportExtraError=yh;function _h(t,e){t.assign(ge.default.errors,e),t.if((0,M._)`${ge.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,M._)`${ge.default.vErrors}.length`,e),()=>t.assign(ge.default.vErrors,null)))}de.resetErrorsCount=_h;function wh({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,ge.default.errors,a=>{t.const(s,(0,M._)`${ge.default.vErrors}[${a}]`),t.if((0,M._)`${s}.instancePath === undefined`,()=>t.assign((0,M._)`${s}.instancePath`,(0,M.strConcat)(ge.default.instancePath,i.errorPath))),t.assign((0,M._)`${s}.schemaPath`,(0,M.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,M._)`${s}.schema`,n),t.assign((0,M._)`${s}.data`,r))})}de.extendErrors=wh;function el(t,e){let n=t.const("err",e);t.if((0,M._)`${ge.default.vErrors} === null`,()=>t.assign(ge.default.vErrors,(0,M._)`[${n}]`),(0,M._)`${ge.default.vErrors}.push(${n})`),t.code((0,M._)`${ge.default.errors}++`)}function tl(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,M._)`new ${t.ValidationError}(${e})`):(n.assign((0,M._)`${r}.errors`,e),n.return(!1))}var zt={keyword:new M.Name("keyword"),schemaPath:new M.Name("schemaPath"),params:new M.Name("params"),propertyName:new M.Name("propertyName"),message:new M.Name("message"),schema:new M.Name("schema"),parentSchema:new M.Name("parentSchema")};function nl(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,M._)`{}`:vh(t,e,n)}function vh(t,e,n={}){let{gen:r,it:o}=t,i=[bh(o,n),Sh(t,n)];return Eh(t,e,i),r.object(...i)}function bh({errorPath:t},{instancePath:e}){let n=e?(0,M.str)`${t}${(0,mo.getErrorPath)(e,mo.Type.Str)}`:t;return[ge.default.instancePath,(0,M.strConcat)(ge.default.instancePath,n)]}function Sh({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,M.str)`${e}/${t}`;return n&&(o=(0,M.str)`${o}${(0,mo.getErrorPath)(n,mo.Type.Str)}`),[zt.schemaPath,o]}function Eh(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([zt.keyword,o],[zt.params,typeof e=="function"?e(t):e||(0,M._)`{}`]),c.messages&&r.push([zt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([zt.schema,s],[zt.parentSchema,(0,M._)`${l}${d}`],[ge.default.data,i]),u&&r.push([zt.propertyName,u])}});var ol=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.boolOrEmptySchema=Sn.topBoolOrEmptySchema=void 0;var kh=hr(),$h=T(),Rh=dt(),Ah={message:"boolean schema is false"};function Ph(t){let{gen:e,schema:n,validateName:r}=t;n===!1?rl(t,!1):typeof n=="object"&&n.$async===!0?e.return(Rh.default.data):(e.assign((0,$h._)`${r}.errors`,null),e.return(!0))}Sn.topBoolOrEmptySchema=Ph;function Th(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),rl(t)):n.var(e,!0)}Sn.boolOrEmptySchema=Th;function rl(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,kh.reportError)(o,Ah,void 0,e)}});var qi=_(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var Ch=["string","number","integer","boolean","null","object","array"],xh=new Set(Ch);function Ih(t){return typeof t=="string"&&xh.has(t)}En.isJSONType=Ih;function Oh(){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=Oh});var Hi=_($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function Nh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&il(t,r)}$t.schemaHasRulesForType=Nh;function il(t,e){return e.rules.some(n=>sl(t,n))}$t.shouldUseGroup=il;function sl(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))}$t.shouldUseRule=sl});var gr=_(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.reportTypeError=fe.checkDataTypes=fe.checkDataType=fe.coerceAndCheckDataType=fe.getJSONTypes=fe.getSchemaTypes=fe.DataType=void 0;var Lh=qi(),Mh=Hi(),jh=hr(),P=T(),al=L(),kn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(kn||(fe.DataType=kn={}));function Dh(t){let e=cl(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}fe.getSchemaTypes=Dh;function cl(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Lh.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}fe.getJSONTypes=cl;function Bh(t,e){let{gen:n,data:r,opts:o}=t,i=Fh(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Mh.schemaHasRulesForType)(t,e[0]));if(s){let a=Vi(e,r,o.strictNumbers,kn.Wrong);n.if(a,()=>{i.length?Uh(t,e,i):Wi(t)})}return s}fe.coerceAndCheckDataType=Bh;var ll=new Set(["string","number","integer","boolean","null"]);function Fh(t,e){return e?t.filter(n=>ll.has(n)||e==="array"&&n==="array"):[]}function Uh(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,P._)`typeof ${o}`),a=r.let("coerced",(0,P._)`undefined`);i.coerceTypes==="array"&&r.if((0,P._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,P._)`${o}[0]`).assign(s,(0,P._)`typeof ${o}`).if(Vi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,P._)`${a} !== undefined`);for(let u of n)(ll.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);r.else(),Wi(t),r.endIf(),r.if((0,P._)`${a} !== undefined`,()=>{r.assign(o,a),qh(t,a)});function c(u){switch(u){case"string":r.elseIf((0,P._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,P._)`"" + ${o}`).elseIf((0,P._)`${o} === null`).assign(a,(0,P._)`""`);return;case"number":r.elseIf((0,P._)`${s} == "boolean" || ${o} === null
5
+ || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,P._)`+${o}`);return;case"integer":r.elseIf((0,P._)`${s} === "boolean" || ${o} === null
6
+ || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,P._)`+${o}`);return;case"boolean":r.elseIf((0,P._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,P._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,P._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,P._)`${s} === "string" || ${s} === "number"
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,P._)`[${o}]`)}}}function qh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,P._)`${e} !== undefined`,()=>t.assign((0,P._)`${e}[${n}]`,r))}function Gi(t,e,n,r=kn.Correct){let o=r===kn.Correct?P.operators.EQ:P.operators.NEQ,i;switch(t){case"null":return(0,P._)`${e} ${o} null`;case"array":i=(0,P._)`Array.isArray(${e})`;break;case"object":i=(0,P._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,P._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,P._)`typeof ${e} ${o} ${t}`}return r===kn.Correct?i:(0,P.not)(i);function s(a=P.nil){return(0,P.and)((0,P._)`typeof ${e} == "number"`,a,n?(0,P._)`isFinite(${e})`:P.nil)}}fe.checkDataType=Gi;function Vi(t,e,n,r){if(t.length===1)return Gi(t[0],e,n,r);let o,i=(0,al.toHash)(t);if(i.array&&i.object){let s=(0,P._)`typeof ${e} != "object"`;o=i.null?s:(0,P._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=P.nil;i.number&&delete i.integer;for(let s in i)o=(0,P.and)(o,Gi(s,e,n,r));return o}fe.checkDataTypes=Vi;var Hh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,P._)`{type: ${t}}`:(0,P._)`{type: ${e}}`};function Wi(t){let e=Gh(t);(0,jh.reportError)(e,Hh)}fe.reportTypeError=Wi;function Gh(t){let{gen:e,data:n,schema:r}=t,o=(0,al.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var dl=_(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.assignDefaults=void 0;var $n=T(),Vh=L();function Wh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)ul(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>ul(t,i,o.default))}po.assignDefaults=Wh;function ul(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,Vh.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 G=T(),zi=L(),Rt=dt(),zh=L();function Kh(t,e){let{gen:n,data:r,it:o}=t;n.if(Ji(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,G._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Kh;function Jh({gen:t,data:e,it:{opts:n}},r,o){return(0,G.or)(...r.map(i=>(0,G.and)(Ji(t,e,i,n.ownProperties),(0,G._)`${o} = ${i}`)))}F.checkMissingProp=Jh;function Yh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Yh;function fl(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,G._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=fl;function Ki(t,e,n){return(0,G._)`${fl(t)}.call(${e}, ${n})`}F.isOwnProperty=Ki;function Qh(t,e,n,r){let o=(0,G._)`${e}${(0,G.getProperty)(n)} !== undefined`;return r?(0,G._)`${o} && ${Ki(t,e,n)}`:o}F.propertyInData=Qh;function Ji(t,e,n,r){let o=(0,G._)`${e}${(0,G.getProperty)(n)} === undefined`;return r?(0,G.or)(o,(0,G.not)(Ki(t,e,n))):o}F.noPropertyInData=Ji;function ml(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ml;function Xh(t,e){return ml(e).filter(n=>!(0,zi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Xh;function Zh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,u){let l=u?(0,G._)`${t}, ${e}, ${r}${o}`:e,d=[[Rt.default.instancePath,(0,G.strConcat)(Rt.default.instancePath,i)],[Rt.default.parentData,s.parentData],[Rt.default.parentDataProperty,s.parentDataProperty],[Rt.default.rootData,Rt.default.rootData]];s.opts.dynamicRef&&d.push([Rt.default.dynamicAnchors,Rt.default.dynamicAnchors]);let h=(0,G._)`${l}, ${n.object(...d)}`;return c!==G.nil?(0,G._)`${a}.call(${c}, ${h})`:(0,G._)`${a}(${h})`}F.callValidateCode=Zh;var eg=(0,G._)`new RegExp`;function tg({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,G._)`${o.code==="new RegExp"?eg:(0,zh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=tg;function ng(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,G._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:zi.Type.Num},i),e.if((0,G.not)(i),a)})}}F.validateArray=ng;function rg(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,zi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(s,(0,G._)`${s} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,G.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=rg});var gl=_(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var ye=T(),Kt=dt(),og=Ie(),ig=hr();function sg(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=hl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:ye.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ye.macroKeywordCode=sg;function ag(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;lg(c,e);let u=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,l=hl(r,o,u),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&&pl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&pl(t),g(()=>cg(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ye._)`await `),v=>r.assign(d,!1).if((0,ye._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ye._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ye._)`${l}.errors`;return r.assign(y,null),m(ye.nil),y}function m(y=e.async?(0,ye._)`await `:ye.nil){let v=c.opts.passContext?Kt.default.this:Kt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ye._)`${y}${(0,og.callValidateCode)(t,l,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ye.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Ye.funcKeywordCode=ag;function pl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ye._)`${r.parentData}[${r.parentDataProperty}]`))}function cg(t,e){let{gen:n}=t;n.if((0,ye._)`Array.isArray(${e})`,()=>{n.assign(Kt.default.vErrors,(0,ye._)`${Kt.default.vErrors} === null ? ${e} : ${Kt.default.vErrors}.concat(${e})`).assign(Kt.default.errors,(0,ye._)`${Kt.default.vErrors}.length`),(0,ig.extendErrors)(t)},()=>t.error())}function lg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function hl(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,ye.stringify)(n)})}function ug(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")}Ye.validSchemaType=ug;function dg({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)}}Ye.validateKeywordUsage=dg});var _l=_(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.extendSubschemaMode=At.extendSubschemaData=At.getSubschema=void 0;var Qe=T(),yl=L();function fg(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,Qe._)`${t.schemaPath}${(0,Qe.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Qe._)`${t.schemaPath}${(0,Qe.getProperty)(e)}${(0,Qe.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,yl.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')}At.getSubschema=fg;function mg(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:u,dataPathArr:l,opts:d}=e,h=a.let("data",(0,Qe._)`${e.data}${(0,Qe.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Qe.str)`${u}${(0,yl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Qe._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Qe.Name?o:a.let("data",o,!0);c(u),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}At.extendSubschemaData=mg;function pg(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}At.extendSubschemaMode=pg});var Yi=_((mR,wl)=>{"use strict";wl.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 bl=_((pR,vl)=>{"use strict";var Pt=vl.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(){};ho(e,r,o,t,"",t)};Pt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Pt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Pt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Pt.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 ho(t,e,n,r,o,i,s,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Pt.arrayKeywords)for(var h=0;h<d.length;h++)ho(t,e,n,d[h],o+"/"+l+"/"+h,i,o,l,r,h)}else if(l in Pt.propsKeywords){if(d&&typeof d=="object")for(var p in d)ho(t,e,n,d[p],o+"/"+l+"/"+hg(p),i,o,l,r,p)}else(l in Pt.keywords||t.allKeys&&!(l in Pt.skipKeywords))&&ho(t,e,n,d,o+"/"+l,i,o,l,r)}n(r,o,i,s,a,c,u)}}function hg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var yr=_(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.getSchemaRefs=be.resolveUrl=be.normalizeId=be._getFullPath=be.getFullPath=be.inlineRef=void 0;var gg=L(),yg=Yi(),_g=bl(),wg=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Qi(t):e?Sl(t)<=e:!1}be.inlineRef=vg;var bg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qi(t){for(let e in t){if(bg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Qi)||typeof n=="object"&&Qi(n))return!0}return!1}function Sl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!wg.has(n)&&(typeof t[n]=="object"&&(0,gg.eachItem)(t[n],r=>e+=Sl(r)),e===1/0))return 1/0}return e}function El(t,e="",n){n!==!1&&(e=Rn(e));let r=t.parse(e);return kl(t,r)}be.getFullPath=El;function kl(t,e){return t.serialize(e).split("#")[0]+"#"}be._getFullPath=kl;var Sg=/#\/?$/;function Rn(t){return t?t.replace(Sg,""):""}be.normalizeId=Rn;function Eg(t,e,n){return n=Rn(n),t.resolve(e,n)}be.resolveUrl=Eg;var kg=/^[a-z_][-a-z0-9._]*$/i;function $g(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Rn(t[n]||e),i={"":o},s=El(r,o,!1),a={},c=new Set;return _g(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 l(S);c.add(S);let $=this.refs[S];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,S):S!==Rn(m)&&(S[0]==="#"?(u(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!kg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function u(d,h,p){if(h!==void 0&&!yg(d,h))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}be.getSchemaRefs=$g});var vr=_(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var Tl=ol(),$l=gr(),Zi=Hi(),go=gr(),Rg=dl(),wr=gl(),Xi=_l(),b=T(),A=dt(),Ag=yr(),ft=L(),_r=hr();function Pg(t){if(Il(t)&&(Ol(t),xl(t))){xg(t);return}Cl(t,()=>(0,Tl.topBoolOrEmptySchema)(t))}Tt.validateFunctionCode=Pg;function Cl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${A.default.data}, ${A.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${Rl(n,o)}`),Cg(t,o),t.code(i)}):t.func(e,(0,b._)`${A.default.data}, ${Tg(o)}`,r.$async,()=>t.code(Rl(n,o)).code(i))}function Tg(t){return(0,b._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${t.dynamicRef?(0,b._)`, ${A.default.dynamicAnchors}={}`:b.nil}}={}`}function Cg(t,e){t.if(A.default.valCxt,()=>{t.var(A.default.instancePath,(0,b._)`${A.default.valCxt}.${A.default.instancePath}`),t.var(A.default.parentData,(0,b._)`${A.default.valCxt}.${A.default.parentData}`),t.var(A.default.parentDataProperty,(0,b._)`${A.default.valCxt}.${A.default.parentDataProperty}`),t.var(A.default.rootData,(0,b._)`${A.default.valCxt}.${A.default.rootData}`),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,b._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{t.var(A.default.instancePath,(0,b._)`""`),t.var(A.default.parentData,(0,b._)`undefined`),t.var(A.default.parentDataProperty,(0,b._)`undefined`),t.var(A.default.rootData,A.default.data),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,b._)`{}`)})}function xg(t){let{schema:e,opts:n,gen:r}=t;Cl(t,()=>{n.$comment&&e.$comment&&Ll(t),Mg(t),r.let(A.default.vErrors,null),r.let(A.default.errors,0),n.unevaluated&&Ig(t),Nl(t),Bg(t)})}function Ig(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 Rl(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 Og(t,e){if(Il(t)&&(Ol(t),xl(t))){Ng(t,e);return}(0,Tl.boolOrEmptySchema)(t,e)}function xl({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 Il(t){return typeof t.schema!="boolean"}function Ng(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Ll(t),jg(t),Dg(t);let i=r.const("_errs",A.default.errors);Nl(t,i),r.var(e,(0,b._)`${i} === ${A.default.errors}`)}function Ol(t){(0,ft.checkUnknownRules)(t),Lg(t)}function Nl(t,e){if(t.opts.jtd)return Al(t,[],!1,e);let n=(0,$l.getSchemaTypes)(t.schema),r=(0,$l.coerceAndCheckDataType)(t,n);Al(t,n,!r,e)}function Lg(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ft.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Mg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ft.checkStrictMode)(t,"default is ignored in the schema root")}function jg(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Ag.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Dg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ll({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${A.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._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Bg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${A.default.errors} === 0`,()=>e.return(A.default.data),()=>e.throw((0,b._)`new ${o}(${A.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,A.default.vErrors),i.unevaluated&&Fg(t),e.return((0,b._)`${A.default.errors} === 0`))}function Fg({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 Al(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ft.schemaHasRulesButRef)(i,l))){o.block(()=>jl(t,"$ref",l.all.$ref.definition));return}c.jtd||Ug(t,e),o.block(()=>{for(let h of l.rules)d(h);d(l.post)});function d(h){(0,Zi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,go.checkDataType)(h.type,s,c.strictNumbers)),Pl(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,go.reportTypeError)(t)),o.endIf()):Pl(t,h),a||o.if((0,b._)`${A.default.errors} === ${r||0}`))}}function Pl(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,Rg.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Zi.shouldUseRule)(r,i)&&jl(t,i.keyword,i.definition,e.type)})}function Ug(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(qg(t,e),t.opts.allowUnionTypes||Hg(t,e),Gg(t,t.dataTypes))}function qg(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Ml(t.dataTypes,n)||es(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Wg(t,e)}}function Hg(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&es(t,"use allowUnionTypes to allow union type keyword")}function Gg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Zi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Vg(e,s))&&es(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function Vg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ml(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Wg(t,e){let n=[];for(let r of t.dataTypes)Ml(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function es(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ft.checkStrictMode)(t,e,t.opts.strictTypes)}var yo=class{constructor(e,n,r){if((0,wr.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,ft.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",Dl(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,wr.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",A.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?_r.reportExtraError:_r.reportError)(this,this.def.error,n)}$dataError(){(0,_r.reportError)(this,this.def.$dataError||_r.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,_r.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,go.checkDataTypes)(c,n,i.opts.strictNumbers,go.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,Xi.getSubschema)(this.it,e);(0,Xi.extendSubschemaData)(r,this.it,e),(0,Xi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return Og(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ft.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ft.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}};Tt.KeywordCxt=yo;function jl(t,e,n,r){let o=new yo(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,wr.funcKeywordCode)(o,n):"macro"in n?(0,wr.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,wr.funcKeywordCode)(o,n)}var zg=/^\/(?:[^~]|~0|~1)*$/,Kg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Dl(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return A.default.rootData;if(t[0]==="/"){if(!zg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=A.default.rootData}else{let u=Kg.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(i=n[e-l],!o)return i}let s=i,a=o.split("/");for(let u of a)u&&(i=(0,b._)`${i}${(0,b.getProperty)((0,ft.unescapeJsonPointer)(u))}`,s=(0,b._)`${s} && ${i}`);return s;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Tt.getData=Dl});var _o=_(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var ts=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ns.default=ts});var br=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});var rs=yr(),os=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,rs.resolveUrl)(e,n,r),this.missingSchema=(0,rs.normalizeId)((0,rs.getFullPath)(e,this.missingRef))}};is.default=os});var vo=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Be=T(),Jg=_o(),Jt=dt(),Fe=yr(),Bl=L(),Yg=vr(),An=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=An;function as(t){let e=Fl.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 Be.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:Jg.default,code:(0,Be._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let u={gen:s,allErrors:this.opts.allErrors,data:Jt.default.data,parentData:Jt.default.parentData,parentDataProperty:Jt.default.parentDataProperty,dataNames:[Jt.default.data],dataPathArr:[Be.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Be.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:Be.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Be._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Yg.validateFunctionCode)(u),s.optimize(this.opts.code.optimize);let d=s.toString();l=`${s.scopeRefs(Jt.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${Jt.default.self}`,`${Jt.default.scope}`,l)(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}=u;p.evaluated={props:f instanceof Be.Name?void 0:f,items:m instanceof Be.Name?void 0:m,dynamicProps:f instanceof Be.Name,dynamicItems:m instanceof Be.Name},p.source&&(p.source.evaluated=(0,Be.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Oe.compileSchema=as;function Qg(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=ey.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 An({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Xg.call(this,i)}Oe.resolveRef=Qg;function Xg(t){return(0,Fe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:as.call(this,t)}function Fl(t){for(let e of this._compilations)if(Zg(e,t))return e}Oe.getCompilingSchema=Fl;function Zg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function ey(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||wo.call(this,t,e)}function wo(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 ss.call(this,n,t);let i=(0,Fe.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=wo.call(this,t,s);return typeof a?.schema!="object"?void 0:ss.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||as.call(this,s),i===(0,Fe.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,u)),new An({schema:a,schemaId:c,root:t,baseId:o})}return ss.call(this,n,s)}}Oe.resolveSchema=wo;var ty=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ss(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,Bl.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!ty.has(a)&&u&&(e=(0,Fe.resolveUrl)(this.opts.uriResolver,e,u))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Bl.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=wo.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new An({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Ul=_((vR,ny)=>{ny.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 ls=_((bR,Vl)=>{"use strict";var ry=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Hl=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 cs(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 oy=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ql(t){return t.length=0,!0}function iy(t,e,n){if(t.length){let r=cs(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function sy(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=iy;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){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(u==="%"){if(!a(o,r,n))break;a=ql}else{o.push(u);continue}}return o.length&&(a===ql?n.zone=o.join(""):s?r.push(o.join("")):r.push(cs(o))),n.address=r.join(""),n}function Gl(t){if(ay(t,":")<2)return{host:t,isIPV6:!1};let e=sy(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 ay(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function cy(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 ly(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 uy(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Hl(n)){let r=Gl(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}Vl.exports={nonSimpleDomain:oy,recomposeAuthority:uy,normalizeComponentEncoding:ly,removeDotSegments:cy,isIPv4:Hl,isUUID:ry,normalizeIPv6:Gl,stringArrayToHexStripped:cs}});var Yl=_((SR,Jl)=>{"use strict";var{isUUID:dy}=ls(),fy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,my=["http","https","ws","wss","urn","urn:uuid"];function py(t){return my.indexOf(t)!==-1}function us(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 Wl(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function zl(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 hy(t){return t.secure=us(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gy(t){if((t.port===(us(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 yy(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(fy);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=ds(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function _y(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=ds(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 wy(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!dy(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function vy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Kl={scheme:"http",domainHost:!0,parse:Wl,serialize:zl},by={scheme:"https",domainHost:Kl.domainHost,parse:Wl,serialize:zl},bo={scheme:"ws",domainHost:!0,parse:hy,serialize:gy},Sy={scheme:"wss",domainHost:bo.domainHost,parse:bo.parse,serialize:bo.serialize},Ey={scheme:"urn",parse:yy,serialize:_y,skipNormalize:!0},ky={scheme:"urn:uuid",parse:wy,serialize:vy,skipNormalize:!0},So={http:Kl,https:by,ws:bo,wss:Sy,urn:Ey,"urn:uuid":ky};Object.setPrototypeOf(So,null);function ds(t){return t&&(So[t]||So[t.toLowerCase()])||void 0}Jl.exports={wsIsSecure:us,SCHEMES:So,isValidSchemeName:py,getSchemeHandler:ds}});var Zl=_((ER,ko)=>{"use strict";var{normalizeIPv6:$y,removeDotSegments:Sr,recomposeAuthority:Ry,normalizeComponentEncoding:Eo,isIPv4:Ay,nonSimpleDomain:Py}=ls(),{SCHEMES:Ty,getSchemeHandler:Ql}=Yl();function Cy(t,e){return typeof t=="string"?t=Xe(mt(t,e),e):typeof t=="object"&&(t=mt(Xe(t,e),e)),t}function xy(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Xl(mt(t,r),mt(e,r),r,!0);return r.skipEscape=!0,Xe(o,r)}function Xl(t,e,n,r){let o={};return r||(t=mt(Xe(t,n),n),e=mt(Xe(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=Sr(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=Sr(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Sr(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=Sr(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 Iy(t,e,n){return typeof t=="string"?(t=unescape(t),t=Xe(Eo(mt(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Xe(Eo(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Xe(Eo(mt(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Xe(Eo(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Xe(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=Ql(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=Ry(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=Sr(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 Oy=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function mt(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(Oy);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(Ay(r.host)===!1){let c=$y(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=Ql(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&Py(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 fs={SCHEMES:Ty,normalize:Cy,resolve:xy,resolveComponent:Xl,equal:Iy,serialize:Xe,parse:mt};ko.exports=fs;ko.exports.default=fs;ko.exports.fastUri=fs});var tu=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var eu=Zl();eu.code='require("ajv/dist/runtime/uri").default';ms.default=eu});var lu=_(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.CodeGen=ce.Name=ce.nil=ce.stringify=ce.str=ce._=ce.KeywordCxt=void 0;var Ny=vr();Object.defineProperty(ce,"KeywordCxt",{enumerable:!0,get:function(){return Ny.KeywordCxt}});var Pn=T();Object.defineProperty(ce,"_",{enumerable:!0,get:function(){return Pn._}});Object.defineProperty(ce,"str",{enumerable:!0,get:function(){return Pn.str}});Object.defineProperty(ce,"stringify",{enumerable:!0,get:function(){return Pn.stringify}});Object.defineProperty(ce,"nil",{enumerable:!0,get:function(){return Pn.nil}});Object.defineProperty(ce,"Name",{enumerable:!0,get:function(){return Pn.Name}});Object.defineProperty(ce,"CodeGen",{enumerable:!0,get:function(){return Pn.CodeGen}});var Ly=_o(),su=br(),My=qi(),Er=vo(),jy=T(),kr=yr(),$o=gr(),hs=L(),nu=Ul(),Dy=tu(),au=(t,e)=>new RegExp(t,e);au.code="new RegExp";var By=["removeAdditional","useDefaults","coerceTypes"],Fy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Uy={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."},qy={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ru=200;function Hy(t){var e,n,r,o,i,s,a,c,u,l,d,h,p,f,m,g,y,v,S,R,$,J,Z,ae,Ke;let st=t.strict,rr=(e=t.code)===null||e===void 0?void 0:e.optimize,Je=rr===!0||rr===void 0?1:rr||0,re=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:au,Ut=(o=t.uriResolver)!==null&&o!==void 0?o:Dy.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:st)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:st)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:st)!==null&&l!==void 0?l:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:st)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:st)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Je,regExp:re}:{optimize:Je,regExp:re},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:ru,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:ru,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:(J=t.validateSchema)!==null&&J!==void 0?J:!0,validateFormats:(Z=t.validateFormats)!==null&&Z!==void 0?Z:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(Ke=t.int32range)!==null&&Ke!==void 0?Ke:!0,uriResolver:Ut}}var $r=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Hy(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new jy.ValueScope({scope:{},prefixes:Fy,es5:n,lines:r}),this.logger=Jy(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,My.getRules)(),ou.call(this,Uy,e,"NOT SUPPORTED"),ou.call(this,qy,e,"DEPRECATED","warn"),this._metaOpts=zy.call(this),e.formats&&Vy.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Wy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Gy.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=nu;r==="id"&&(o={...nu},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(l,d){await i.call(this,l.$schema);let h=this._addSchema(l,d);return h.validate||s.call(this,h)}async function i(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof su.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await i.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}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,kr.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=iu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Er.SchemaEnv({schema:{},schemaId:r});if(n=Er.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=iu.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,kr.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(Qy.call(this,r,n),!n)return(0,hs.eachItem)(r,i=>ps.call(this,i)),this;Zy.call(this,n);let o={...n,type:(0,$o.getJSONTypes)(n.type),schemaType:(0,$o.getJSONTypes)(n.schemaType)};return(0,hs.eachItem)(r,o.type.length===0?i=>ps.call(this,i,o):i=>o.type.forEach(s=>ps.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:u}=c.definition,l=s[a];u&&l&&(s[a]=cu(l))}}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,kr.normalizeId)(s||r);let u=kr.getSchemaRefs.call(this,e,r);return c=new Er.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),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):Er.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{Er.compileSchema.call(this,e)}finally{this.opts=n}}};$r.ValidationError=Ly.default;$r.MissingRefError=su.default;ce.default=$r;function ou(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 iu(t){return t=(0,kr.normalizeId)(t),this.schemas[t]||this.refs[t]}function Gy(){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 Vy(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Wy(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 zy(){let t={...this.opts};for(let e of By)delete t[e];return t}var Ky={log(){},warn(){},error(){}};function Jy(t){if(t===!1)return Ky;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 Yy=/^[a-z_$][a-z0-9_$:-]*$/i;function Qy(t,e){let{RULES:n}=this;if((0,hs.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Yy.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 ps(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?Xy.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 Xy(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 Zy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=cu(e)),t.validateSchema=this.compile(e,!0))}var e_={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function cu(t){return{anyOf:[t,e_]}}});var uu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var t_={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gs.default=t_});var pu=_(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.callRef=Yt.getValidate=void 0;var n_=br(),du=Ie(),Se=T(),Tn=dt(),fu=vo(),Ro=L(),r_={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:u}=i;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=fu.resolveRef.call(c,u,o,n);if(l===void 0)throw new n_.default(r.opts.uriResolver,o,n);if(l instanceof fu.SchemaEnv)return h(l);return p(l);function d(){if(i===u)return Ao(t,s,i,i.$async);let f=e.scopeValue("root",{ref:u});return Ao(t,(0,Se._)`${f}.validate`,u,u.$async)}function h(f){let m=mu(t,f);Ao(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Se.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:Se.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function mu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Se._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Yt.getValidate=mu;function Ao(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,u=c.passContext?Tn.default.this:Se.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Se._)`await ${(0,du.callValidateCode)(t,e,u)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,Se._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,du.callValidateCode)(t,e,u),()=>p(e),()=>h(e))}function h(f){let m=(0,Se._)`${f}.errors`;o.assign(Tn.default.vErrors,(0,Se._)`${Tn.default.vErrors} === null ? ${m} : ${Tn.default.vErrors}.concat(${m})`),o.assign(Tn.default.errors,(0,Se._)`${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=Ro.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,Se._)`${f}.evaluated.props`);i.props=Ro.mergeEvaluated.props(o,y,i.props,Se.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Ro.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,Se._)`${f}.evaluated.items`);i.items=Ro.mergeEvaluated.items(o,y,i.items,Se.Name)}}}Yt.callRef=Ao;Yt.default=r_});var hu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var o_=uu(),i_=pu(),s_=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",o_.default,i_.default];ys.default=s_});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var Po=T(),Ct=Po.operators,To={maximum:{okStr:"<=",ok:Ct.LTE,fail:Ct.GT},minimum:{okStr:">=",ok:Ct.GTE,fail:Ct.LT},exclusiveMaximum:{okStr:"<",ok:Ct.LT,fail:Ct.GTE},exclusiveMinimum:{okStr:">",ok:Ct.GT,fail:Ct.LTE}},a_={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}}`},c_={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:a_,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Po._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};_s.default=c_});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var Rr=T(),l_={message:({schemaCode:t})=>(0,Rr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Rr._)`{multipleOf: ${t}}`},u_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:l_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,Rr._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Rr._)`${s} !== parseInt(${s})`;t.fail$data((0,Rr._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};ws.default=u_});var wu=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});function _u(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}vs.default=_u;_u.code='require("ajv/dist/runtime/ucs2length").default'});var vu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Qt=T(),d_=L(),f_=wu(),m_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},p_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:m_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,s=o.opts.unicode===!1?(0,Qt._)`${n}.length`:(0,Qt._)`${(0,d_.useFunc)(t.gen,f_.default)}(${n})`;t.fail$data((0,Qt._)`${s} ${i} ${r}`)}};bs.default=p_});var bu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var h_=Ie(),g_=L(),Cn=T(),y_={message:({schemaCode:t})=>(0,Cn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Cn._)`{pattern: ${t}}`},__={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:y_,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,u=c.code==="new RegExp"?(0,Cn._)`new RegExp`:(0,g_.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Cn._)`${u}(${i}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Cn._)`!${l}`)}else{let c=(0,h_.usePattern)(t,o);t.fail$data((0,Cn._)`!${c}.test(${n})`)}}};Ss.default=__});var Su=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Ar=T(),w_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ar.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ar._)`{limit: ${t}}`},v_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:w_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ar.operators.GT:Ar.operators.LT;t.fail$data((0,Ar._)`Object.keys(${n}).length ${o} ${r}`)}};Es.default=v_});var Eu=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Pr=Ie(),Tr=T(),b_=L(),S_={message:({params:{missingProperty:t}})=>(0,Tr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Tr._)`{missingProperty: ${t}}`},E_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:S_,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?u():l(),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,b_.checkStrictMode)(s,y,s.opts.strictRequired)}}function u(){if(c||i)t.block$data(Tr.nil,d);else for(let p of n)(0,Pr.checkReportMissingProp)(t,p)}function l(){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)}}};ks.default=E_});var ku=_($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var Cr=T(),k_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Cr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Cr._)`{limit: ${t}}`},$_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:k_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Cr.operators.GT:Cr.operators.LT;t.fail$data((0,Cr._)`${n}.length ${o} ${r}`)}};$s.default=$_});var Co=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var $u=Yi();$u.code='require("ajv/dist/runtime/equal").default';Rs.default=$u});var Ru=_(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var As=gr(),le=T(),R_=L(),A_=Co(),P_={message:({params:{i:t,j:e}})=>(0,le.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,le._)`{i: ${t}, j: ${e}}`},T_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:P_,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"),u=i.items?(0,As.getSchemaTypes)(i.items):[];t.block$data(c,l,(0,le._)`${s} === false`),t.ok(c);function l(){let f=e.let("i",(0,le._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,le._)`${f} > 1`,()=>(d()?h:p)(f,m))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function h(f,m){let g=e.name("item"),y=(0,As.checkDataTypes)(u,g,a.opts.strictNumbers,As.DataType.Wrong),v=e.const("indices",(0,le._)`{}`);e.for((0,le._)`;${f}--;`,()=>{e.let(g,(0,le._)`${n}[${f}]`),e.if(y,(0,le._)`continue`),u.length>1&&e.if((0,le._)`typeof ${g} == "string"`,(0,le._)`${g} += "_"`),e.if((0,le._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,le._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,le._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,R_.useFunc)(e,A_.default),y=e.name("outer");e.label(y).for((0,le._)`;${f}--;`,()=>e.for((0,le._)`${m} = ${f}; ${m}--;`,()=>e.if((0,le._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Ps.default=T_});var Au=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var Ts=T(),C_=L(),x_=Co(),I_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ts._)`{allowedValue: ${t}}`},O_={keyword:"const",$data:!0,error:I_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Ts._)`!${(0,C_.useFunc)(e,x_.default)}(${n}, ${o})`):t.fail((0,Ts._)`${i} !== ${n}`)}};Cs.default=O_});var Pu=_(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var xr=T(),N_=L(),L_=Co(),M_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,xr._)`{allowedValues: ${t}}`},j_={keyword:"enum",schemaType:"array",$data:!0,error:M_,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,u=()=>c??(c=(0,N_.useFunc)(e,L_.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);l=(0,xr.or)(...o.map((f,m)=>h(p,m)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",i,p=>e.if((0,xr._)`${u()}(${n}, ${p})`,()=>e.assign(l,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,xr._)`${u()}(${n}, ${p}[${f}])`:(0,xr._)`${n} === ${m}`}}};xs.default=j_});var Tu=_(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var D_=gu(),B_=yu(),F_=vu(),U_=bu(),q_=Su(),H_=Eu(),G_=ku(),V_=Ru(),W_=Au(),z_=Pu(),K_=[D_.default,B_.default,F_.default,U_.default,q_.default,H_.default,G_.default,V_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},W_.default,z_.default];Is.default=K_});var Ns=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateAdditionalItems=void 0;var Xt=T(),Os=L(),J_={message:({params:{len:t}})=>(0,Xt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xt._)`{limit: ${t}}`},Y_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:J_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Os.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Cu(t,r)}};function Cu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Xt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Os.alwaysValidSchema)(s,r)){let u=n.var("valid",(0,Xt._)`${a} <= ${e.length}`);n.if((0,Xt.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:i,dataProp:l,dataPropType:Os.Type.Num},u),s.allErrors||n.if((0,Xt.not)(u),()=>n.break())})}}Ir.validateAdditionalItems=Cu;Ir.default=Y_});var Ls=_(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.validateTuple=void 0;var xu=T(),xo=L(),Q_=Ie(),X_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Iu(t,"additionalItems",e);n.items=!0,!(0,xo.alwaysValidSchema)(n,e)&&t.ok((0,Q_.validateArray)(t))}};function Iu(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=xo.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,xu._)`${i}.length`);n.forEach((d,h)=>{(0,xo.alwaysValidSchema)(a,d)||(r.if((0,xu._)`${u} > ${h}`,()=>t.subschema({keyword:s,schemaProp:h,dataProp:h},c)),t.ok(c))});function l(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)}}}Or.validateTuple=Iu;Or.default=X_});var Ou=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var Z_=Ls(),ew={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Z_.validateTuple)(t,"items")};Ms.default=ew});var Lu=_(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Nu=T(),tw=L(),nw=Ie(),rw=Ns(),ow={message:({params:{len:t}})=>(0,Nu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Nu._)`{limit: ${t}}`},iw={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ow,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,tw.alwaysValidSchema)(r,e)&&(o?(0,rw.validateAdditionalItems)(t,o):t.ok((0,nw.validateArray)(t)))}};js.default=iw});var Mu=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Ne=T(),Io=L(),sw={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}}`},aw={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:sw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:u}=r;i.opts.next?(s=c===void 0?1:c,a=u):s=1;let l=e.const("len",(0,Ne._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Io.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Io.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Io.alwaysValidSchema)(i,n)){let m=(0,Ne._)`${l} >= ${s}`;a!==void 0&&(m=(0,Ne._)`${m} && ${l} <= ${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,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Io.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)))}}};Ds.default=aw});var Bu=_(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.validateSchemaDeps=Ze.validatePropertyDeps=Ze.error=void 0;var Bs=T(),cw=L(),Nr=Ie();Ze.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Bs.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Bs._)`{property: ${t},
8
8
  missingProperty: ${r},
9
9
  depsCount: ${e},
10
- deps: ${n}}`};var cw={keyword:"dependencies",type:"object",schemaType:"object",error:Ze.error,code(t){let[e,n]=lw(t);ju(t,e),Du(t,n)}};function lw({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 ju(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,Fs._)`${c} && (${(0,Or.checkMissingProp)(t,a,i)})`),(0,Or.reportMissingProp)(t,i),n.else())}}Ze.validatePropertyDeps=ju;function Du(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,aw.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))}Ze.validateSchemaDeps=Du;Ze.default=cw});var Uu=_(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var Bu=T(),uw=L(),dw={message:"property name must be valid",params:({params:t})=>(0,Bu._)`{propertyName: ${t.propertyName}}`},fw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dw,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,uw.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,Bu.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Bs.default=fw});var qs=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Oo=Ie(),Ue=T(),mw=dt(),No=L(),pw={message:"must NOT have additional properties",params:({params:t})=>(0,Ue._)`{additionalProperty: ${t.additionalProperty}}`},hw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:pw,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,No.alwaysValidSchema)(s,n))return;let l=(0,Oo.allSchemaProperties)(r.properties),u=(0,Oo.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Ue._)`${i} === ${mw.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,No.schemaRefOrVal)(s,r.properties,"properties");y=(0,Oo.isOwnProperty)(e,v,g)}else l.length?y=(0,Ue.or)(...l.map(v=>(0,Ue._)`${g} === ${v}`)):y=Ue.nil;return u.length&&(y=(0,Ue.or)(y,...u.map(v=>(0,Ue._)`${(0,Oo.usePattern)(t,v)}.test(${g})`))),(0,Ue.not)(y)}function p(g){e.code((0,Ue._)`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,No.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Ue.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Ue.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:No.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Us.default=hw});var Gu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var gw=wr(),qu=Ie(),Hs=L(),Hu=qs(),yw={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&&Hu.default.code(new gw.KeywordCxt(i,Hu.default,"additionalProperties"));let s=(0,qu.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Hs.mergeEvaluated.props(e,(0,Hs.toHash)(s),i.props));let a=s.filter(d=>!(0,Hs.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,qu.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)}}};Gs.default=yw});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Vu=Ie(),Lo=T(),Wu=L(),zu=L(),_w={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,Vu.allSchemaProperties)(n),c=a.filter(m=>(0,Wu.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 Lo.Name)&&(i.props=(0,zu.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,Wu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,Lo._)`${(0,Vu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:zu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,Lo._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,Lo.not)(u),()=>e.break())})})}}};Vs.default=_w});var Ju=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var ww=L(),vw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,ww.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"}};Ws.default=vw});var Yu=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var bw=Ie(),Sw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:bw.validateUnion,error:{message:"must match a schema in anyOf"}};zs.default=Sw});var Qu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Mo=T(),Ew=L(),kw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},$w={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kw,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,Ew.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)})})}}};Ks.default=$w});var Xu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Rw=L(),Pw={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,Rw.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};Js.default=Pw});var td=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var jo=T(),ed=L(),Aw={message:({params:t})=>(0,jo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jo._)`{failingKeyword: ${t.ifClause}}`},Tw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Aw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,ed.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Zu(r,"then"),i=Zu(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,jo.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,jo._)`${u}`):t.setParams({ifClause:u})}}}};function Zu(t,e){let n=t.schema[e];return n!==void 0&&!(0,ed.alwaysValidSchema)(t,n)}Ys.default=Tw});var nd=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var xw=L(),Cw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,xw.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Qs.default=Cw});var rd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Iw=Ns(),Ow=Ou(),Nw=Ls(),Lw=Lu(),Mw=Mu(),jw=Fu(),Dw=Uu(),Fw=qs(),Bw=Gu(),Uw=Ku(),qw=Ju(),Hw=Yu(),Gw=Qu(),Vw=Xu(),Ww=td(),zw=nd();function Kw(t=!1){let e=[qw.default,Hw.default,Gw.default,Vw.default,Ww.default,zw.default,Dw.default,Fw.default,jw.default,Bw.default,Uw.default];return t?e.push(Ow.default,Lw.default):e.push(Iw.default,Nw.default),e.push(Mw.default),e}Xs.default=Kw});var od=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Y=T(),Jw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Yw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Jw,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 K=$ instanceof RegExp?(0,Y.regexpCode)($):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,X=n.scopeValue("formats",{key:i,ref:$,code:K});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Y._)`${X}.validate`]:["string",$,X]}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})`}}}};Zs.default=Yw});var id=_(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var Qw=od(),Xw=[Qw.default];ea.default=Xw});var sd=_(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.contentVocabulary=Cn.metadataVocabulary=void 0;Cn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Cn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cd=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var Zw=hu(),ev=Tu(),tv=rd(),nv=id(),ad=sd(),rv=[Zw.default,ev.default,(0,tv.default)(),nv.default,ad.metadataVocabulary,ad.contentVocabulary];ta.default=rv});var ud=_(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.DiscrError=void 0;var ld;(function(t){t.Tag="tag",t.Mapping="mapping"})(ld||(Do.DiscrError=ld={}))});var fd=_(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var In=T(),na=ud(),dd=vo(),ov=vr(),iv=L(),sv={message:({params:{discrError:t,tagName:e}})=>t===na.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}}`},av={keyword:"discriminator",type:"object",schemaType:"object",error:sv,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:na.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:na.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,iv.schemaHasRulesButRef)($,i.self.RULES)){let X=$.$ref;if($=dd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,X),$ instanceof dd.SchemaEnv&&($=$.schema),$===void 0)throw new ov.default(i.opts.uriResolver,i.baseId,X)}let K=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof K!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y($)),v(K,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 K of R.enum)S(K,$);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]=$}}}};ra.default=av});var md=_((iP,cv)=>{cv.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 Bo=_((V,oa)=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.MissingRefError=V.ValidationError=V.CodeGen=V.Name=V.nil=V.stringify=V.str=V._=V.KeywordCxt=V.Ajv=void 0;var lv=lu(),uv=cd(),dv=fd(),pd=md(),fv=["/properties"],Fo="http://json-schema.org/draft-07/schema",On=class extends lv.default{_addVocabularies(){super._addVocabularies(),uv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(dv.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(pd,fv):pd;this.addMetaSchema(e,Fo,!1),this.refs["http://json-schema.org/schema"]=Fo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Fo)?Fo:void 0)}};V.Ajv=On;oa.exports=V=On;oa.exports.Ajv=On;Object.defineProperty(V,"__esModule",{value:!0});V.default=On;var mv=wr();Object.defineProperty(V,"KeywordCxt",{enumerable:!0,get:function(){return mv.KeywordCxt}});var Nn=T();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(V,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var pv=_o();Object.defineProperty(V,"ValidationError",{enumerable:!0,get:function(){return pv.default}});var hv=vr();Object.defineProperty(V,"MissingRefError",{enumerable:!0,get:function(){return hv.default}})});var Sd=_(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.formatNames=tt.fastFormats=tt.fullFormats=void 0;function et(t,e){return{validate:t,compare:e}}tt.fullFormats={date:et(_d,ca),time:et(sa(!0),la),"date-time":et(hd(!0),vd),"iso-time":et(sa(),wd),"iso-date-time":et(hd(),bd),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:bv,"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:Av,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:Sv,int32:{type:"number",validate:$v},int64:{type:"number",validate:Rv},float:{type:"number",validate:yd},double:{type:"number",validate:yd},password:!0,binary:!0};tt.fastFormats={...tt.fullFormats,date:et(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ca),time:et(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,la),"date-time":et(/^\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,vd),"iso-time":et(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wd),"iso-date-time":et(/^\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,bd),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};tt.formatNames=Object.keys(tt.fullFormats);function gv(t){return t%4===0&&(t%100!==0||t%400===0)}var yv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_v=[0,31,28,31,30,31,30,31,31,30,31,30,31];function _d(t){let e=yv.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&&gv(n)?29:_v[r])}function ca(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ia=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function sa(t){return function(n){let r=ia.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 la(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 wd(t,e){if(!(t&&e))return;let n=ia.exec(t),r=ia.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 aa=/t|\s/i;function hd(t){let e=sa(t);return function(r){let o=r.split(aa);return o.length===2&&_d(o[0])&&e(o[1])}}function vd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function bd(t,e){if(!(t&&e))return;let[n,r]=t.split(aa),[o,i]=e.split(aa),s=ca(n,o);if(s!==void 0)return s||la(r,i)}var wv=/\/|:/,vv=/^(?:[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 bv(t){return wv.test(t)&&vv.test(t)}var gd=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Sv(t){return gd.lastIndex=0,gd.test(t)}var Ev=-(2**31),kv=2**31-1;function $v(t){return Number.isInteger(t)&&t<=kv&&t>=Ev}function Rv(t){return Number.isInteger(t)}function yd(){return!0}var Pv=/[^\\]\\Z/;function Av(t){if(Pv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ed=_(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.formatLimitDefinition=void 0;var Tv=Bo(),qe=T(),Ct=qe.operators,Uo={formatMaximum:{okStr:"<=",ok:Ct.LTE,fail:Ct.GT},formatMinimum:{okStr:">=",ok:Ct.GTE,fail:Ct.LT},formatExclusiveMaximum:{okStr:"<",ok:Ct.LT,fail:Ct.GTE},formatExclusiveMinimum:{okStr:">",ok:Ct.GT,fail:Ct.LTE}},xv={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Uo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Uo[t].okStr}, limit: ${e}}`};Ln.formatLimitDefinition={keyword:Object.keys(Uo),type:"string",schemaType:"string",$data:!0,error:xv,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 Tv.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}) ${Uo[o].fail} 0`}},dependencies:["format"]};var Cv=t=>(t.addKeyword(Ln.formatLimitDefinition),t);Ln.default=Cv});var fa=_((Nr,Rd)=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});var Mn=Sd(),Iv=Ed(),ua=T(),kd=new ua.Name("fullFormats"),Ov=new ua.Name("fastFormats"),da=(t,e={keywords:!0})=>{if(Array.isArray(e))return $d(t,e,Mn.fullFormats,kd),t;let[n,r]=e.mode==="fast"?[Mn.fastFormats,Ov]:[Mn.fullFormats,kd],o=e.formats||Mn.formatNames;return $d(t,o,n,r),e.keywords&&(0,Iv.default)(t),t};da.get=(t,e="full")=>{let r=(e==="fast"?Mn.fastFormats:Mn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function $d(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ua._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Rd.exports=Nr=da;Object.defineProperty(Nr,"__esModule",{value:!0});Nr.default=da});var ht=_((AP,Ld)=>{"use strict";var Od=["nodebuffer","arraybuffer","fragments"],Nd=typeof Blob<"u";Nd&&Od.push("blob");Ld.exports={BINARY_TYPES:Od,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Nd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Lr=_((TP,qo)=>{"use strict";var{EMPTY_BUFFER:Vv}=ht(),pa=Buffer[Symbol.species];function Wv(t,e){if(t.length===0)return Vv;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 pa(n.buffer,n.byteOffset,r):n}function Md(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function jd(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function zv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ha(t){if(ha.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pa(t):ArrayBuffer.isView(t)?e=new pa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ha.readOnly=!1),e}qo.exports={concat:Wv,mask:Md,toArrayBuffer:zv,toBuffer:ha,unmask:jd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ee("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Md(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?jd(e,n):t.unmask(e,n)}}catch{}});var Bd=_((xP,Fd)=>{"use strict";var Dd=Symbol("kDone"),ga=Symbol("kRun"),ya=class{constructor(e){this[Dd]=()=>{this.pending--,this[ga]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ga]()}[ga](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Dd])}}};Fd.exports=ya});var Un=_((CP,Gd)=>{"use strict";var Mr=ee("zlib"),Ud=Lr(),Kv=Bd(),{kStatusCode:qd}=ht(),Jv=Buffer[Symbol.species],Yv=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),gt=Symbol("total-length"),Fn=Symbol("callback"),It=Symbol("buffers"),Bn=Symbol("error"),Ho,_a=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,!Ho){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new Kv(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){Ho.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Ho.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[Go]=this,this._inflate[gt]=0,this._inflate[It]=[],this._inflate.on("error",Xv),this._inflate.on("data",Hd)}this._inflate[Fn]=r,this._inflate.write(e),n&&this._inflate.write(Yv),this._inflate.flush(()=>{let i=this._inflate[Bn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Ud.concat(this._inflate[It],this._inflate[gt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gt]=0,this._inflate[It]=[],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[gt]=0,this._deflate[It]=[],this._deflate.on("data",Qv)}this._deflate[Fn]=r,this._deflate.write(e),this._deflate.flush(Mr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ud.concat(this._deflate[It],this._deflate[gt]);n&&(i=new Jv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Fn]=null,this._deflate[gt]=0,this._deflate[It]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Gd.exports=_a;function Qv(t){this[It].push(t),this[gt]+=t.length}function Hd(t){if(this[gt]+=t.length,this[Go]._maxPayload<1||this[gt]<=this[Go]._maxPayload){this[It].push(t);return}this[Bn]=new RangeError("Max payload size exceeded"),this[Bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Bn][qd]=1009,this.removeListener("data",Hd),this.reset()}function Xv(t){if(this[Go]._inflate=null,this[Bn]){this[Fn](this[Bn]);return}t[qd]=1007,this[Fn](t)}});var qn=_((IP,Vo)=>{"use strict";var{isUtf8:Vd}=ee("buffer"),{hasBlob:Zv}=ht(),eb=[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 tb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function wa(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 nb(t){return Zv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Vo.exports={isBlob:nb,isValidStatusCode:tb,isValidUTF8:wa,tokenChars:eb};if(Vd)Vo.exports.isValidUTF8=function(t){return t.length<24?wa(t):Vd(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ee("utf-8-validate");Vo.exports.isValidUTF8=function(e){return e.length<32?wa(e):t(e)}}catch{}});var ka=_((OP,Xd)=>{"use strict";var{Writable:rb}=ee("stream"),Wd=Un(),{BINARY_TYPES:ob,EMPTY_BUFFER:zd,kStatusCode:ib,kWebSocket:sb}=ht(),{concat:va,toArrayBuffer:ab,unmask:cb}=Lr(),{isValidStatusCode:lb,isValidUTF8:Kd}=qn(),Wo=Buffer[Symbol.species],Le=0,Jd=1,Yd=2,Qd=3,ba=4,Sa=5,zo=6,Ea=class extends rb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ob[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[sb]=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=Le}_write(e,n,r){if(this._opcode===8&&this._state==Le)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 Le:this.getInfo(e);break;case Jd:this.getPayloadLength16(e);break;case Yd:this.getPayloadLength64(e);break;case Qd:this.getMask();break;case ba:this.getData(e);break;case Sa:case zo: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[Wd.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=Jd:this._payloadLength===127?this._state=Yd: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=Qd:this._state=ba}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ba}getData(e){let n=zd;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]&&cb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Sa,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wd.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===Le&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Le;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=va(r,n):this._binaryType==="arraybuffer"?o=ab(va(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit("message",o,!0),this._state=Le,this.startLoop(e)}))}else{let o=va(r,n);if(!this._skipUTF8Validation&&!Kd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Sa||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit("message",o,!1),this._state=Le,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,zd),this.end();else{let r=e.readUInt16BE(0);if(!lb(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&&!Kd(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=Le;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Le,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[ib]=o,s}};Xd.exports=Ea});var Pa=_((LP,tf)=>{"use strict";var{Duplex:NP}=ee("stream"),{randomFillSync:ub}=ee("crypto"),Zd=Un(),{EMPTY_BUFFER:db,kWebSocket:fb,NOOP:mb}=ht(),{isBlob:Hn,isValidStatusCode:pb}=qn(),{mask:ef,toBuffer:nn}=Lr(),Me=Symbol("kByteLength"),hb=Buffer.alloc(4),Ko=8*1024,rn,Gn=Ko,He=0,gb=1,yb=2,$a=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=He,this.onerror=mb,this[fb]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||hb,n.generateMask?n.generateMask(r):(Gn===Ko&&(rn===void 0&&(rn=Buffer.alloc(Ko)),ub(rn,0,Ko),Gn=0),r[0]=rn[Gn++],r[1]=rn[Gn++],r[2]=rn[Gn++],r[3]=rn[Gn++]),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?(ef(e,r,l,i,a),[l]):(ef(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=db;else{if(typeof e!="number"||!pb(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!==He?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=nn(e),o=e.length,i=nn.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};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==He?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=nn(e),o=e.length,i=nn.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};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==He?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Zd.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=nn(e),a=e.length,c=nn.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};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==He?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=yb,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ra,this,a,o);return}this._bufferedBytes-=r[Me];let s=nn(i);n?this.dispatch(s,n,r,o):(this._state=He,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(_b,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Zd.extensionName];this._bufferedBytes+=r[Me],this._state=gb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ra(this,c,o);return}this._bufferedBytes-=r[Me],this._state=He,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===He&&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)}};tf.exports=$a;function Ra(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 _b(t,e,n){Ra(t,e,n),t.onerror(e)}});var df=_((MP,uf)=>{"use strict";var{kForOnEventAttribute:jr,kListener:Aa}=ht(),nf=Symbol("kCode"),rf=Symbol("kData"),of=Symbol("kError"),sf=Symbol("kMessage"),af=Symbol("kReason"),Vn=Symbol("kTarget"),cf=Symbol("kType"),lf=Symbol("kWasClean"),yt=class{constructor(e){this[Vn]=null,this[cf]=e}get target(){return this[Vn]}get type(){return this[cf]}};Object.defineProperty(yt.prototype,"target",{enumerable:!0});Object.defineProperty(yt.prototype,"type",{enumerable:!0});var on=class extends yt{constructor(e,n={}){super(e),this[nf]=n.code===void 0?0:n.code,this[af]=n.reason===void 0?"":n.reason,this[lf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[nf]}get reason(){return this[af]}get wasClean(){return this[lf]}};Object.defineProperty(on.prototype,"code",{enumerable:!0});Object.defineProperty(on.prototype,"reason",{enumerable:!0});Object.defineProperty(on.prototype,"wasClean",{enumerable:!0});var Wn=class extends yt{constructor(e,n={}){super(e),this[of]=n.error===void 0?null:n.error,this[sf]=n.message===void 0?"":n.message}get error(){return this[of]}get message(){return this[sf]}};Object.defineProperty(Wn.prototype,"error",{enumerable:!0});Object.defineProperty(Wn.prototype,"message",{enumerable:!0});var Dr=class extends yt{constructor(e,n={}){super(e),this[rf]=n.data===void 0?null:n.data}get data(){return this[rf]}};Object.defineProperty(Dr.prototype,"data",{enumerable:!0});var wb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[jr]&&o[Aa]===e&&!o[jr])return;let r;if(t==="message")r=function(i,s){let a=new Dr("message",{data:s?i:i.toString()});a[Vn]=this,Jo(e,this,a)};else if(t==="close")r=function(i,s){let a=new on("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Vn]=this,Jo(e,this,a)};else if(t==="error")r=function(i){let s=new Wn("error",{error:i,message:i.message});s[Vn]=this,Jo(e,this,s)};else if(t==="open")r=function(){let i=new yt("open");i[Vn]=this,Jo(e,this,i)};else return;r[jr]=!!n[jr],r[Aa]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Aa]===e&&!n[jr]){this.removeListener(t,n);break}}};uf.exports={CloseEvent:on,ErrorEvent:Wn,Event:yt,EventTarget:wb,MessageEvent:Dr};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Yo=_((jP,ff)=>{"use strict";var{tokenChars:Fr}=qn();function nt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function vb(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?(nt(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),nt(n,t.slice(c,u),!0),l===44&&(nt(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),nt(n,a,p),l===44&&(nt(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?nt(e,h,n):(a===void 0?nt(n,h,!0):r?nt(n,a,h.replace(/\\/g,"")):nt(n,a,h),nt(e,s,n)),e}function bb(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(", ")}ff.exports={format:bb,parse:vb}});var ei=_((BP,kf)=>{"use strict";var Sb=ee("events"),Eb=ee("https"),kb=ee("http"),hf=ee("net"),$b=ee("tls"),{randomBytes:Rb,createHash:Pb}=ee("crypto"),{Duplex:DP,Readable:FP}=ee("stream"),{URL:Ta}=ee("url"),Ot=Un(),Ab=ka(),Tb=Pa(),{isBlob:xb}=qn(),{BINARY_TYPES:mf,CLOSE_TIMEOUT:Cb,EMPTY_BUFFER:Qo,GUID:Ib,kForOnEventAttribute:xa,kListener:Ob,kStatusCode:Nb,kWebSocket:ie,NOOP:gf}=ht(),{EventTarget:{addEventListener:Lb,removeEventListener:Mb}}=df(),{format:jb,parse:Db}=Yo(),{toBuffer:Fb}=Lr(),yf=Symbol("kAborted"),Ca=[8,13],_t=["CONNECTING","OPEN","CLOSING","CLOSED"],Bb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,z=class t extends Sb{constructor(e,n,r){super(),this._binaryType=mf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Qo,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]),_f(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){mf.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 Ab({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Tb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[ie]=this,i[ie]=this,e[ie]=this,o.on("conclude",Hb),o.on("drain",Gb),o.on("error",Vb),o.on("message",Wb),o.on("ping",zb),o.on("pong",Kb),i.onerror=Jb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bf),e.on("data",Zo),e.on("end",Sf),e.on("error",Ef),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[Ot.extensionName]&&this._extensions[Ot.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())}),vf(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){Ia(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Qo,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){Ia(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Qo,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){Ia(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ot.extensionName]||(o.compress=!1),this._sender.send(e||Qo,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(z,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(z.prototype,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(z,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(z.prototype,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(z,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(z.prototype,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(z,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});Object.defineProperty(z.prototype,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(z.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(z.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[xa])return e[Ob];return null},set(e){for(let n of this.listeners(t))if(n[xa]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[xa]:!0})}})});z.prototype.addEventListener=Lb;z.prototype.removeEventListener=Mb;kf.exports=z;function _f(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Cb,protocolVersion:Ca[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,!Ca.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ca.join(", ")})`);let i;if(e instanceof Ta)i=e;else try{i=new Ta(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;Xo(t,m);return}let l=s?443:80,u=Rb(16).toString("base64"),d=s?Eb.request:kb.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?qb:Ub),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 Ot({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=jb({[Ot.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Bb.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[yf]||(f=t._req=null,Xo(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 Ta(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Xo(t,R);return}_f(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!==z.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=Pb("sha1").update(u+Ib).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 K=m.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){$e(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let X;try{X=Db(K)}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ae=Object.keys(X);if(ae.length!==1||ae[0]!==Ot.extensionName){$e(t,g,"Server indicated an extension that was not requested");return}try{p.accept(X[Ot.extensionName])}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ot.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 Xo(t,e){t._readyState=z.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ub(t){return t.path=t.socketPath,hf.connect(t)}function qb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hf.isIP(t.host)?"":t.host),$b.connect(t)}function $e(t,e,n){t._readyState=z.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[yf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ia(t,e,n){if(e){let r=xb(e)?e.size:Fb(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_t[t.readyState]})`);process.nextTick(n,r)}}function Hb(t,e){let n=this[ie];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ie]!==void 0&&(n._socket.removeListener("data",Zo),process.nextTick(wf,n._socket),t===1005?n.close():n.close(t,e))}function Gb(){let t=this[ie];t.isPaused||t._socket.resume()}function Vb(t){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",Zo),process.nextTick(wf,e._socket),e.close(t[Nb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function pf(){this[ie].emitClose()}function Wb(t,e){this[ie].emit("message",t,e)}function zb(t){let e=this[ie];e._autoPong&&e.pong(t,!this._isServer,gf),e.emit("ping",t)}function Kb(t){this[ie].emit("pong",t)}function wf(t){t.resume()}function Jb(t){let e=this[ie];e.readyState!==z.CLOSED&&(e.readyState===z.OPEN&&(e._readyState=z.CLOSING,vf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function vf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bf(){let t=this[ie];if(this.removeListener("close",bf),this.removeListener("data",Zo),this.removeListener("end",Sf),t._readyState=z.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[ie]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",pf),t._receiver.on("finish",pf))}function Zo(t){this[ie]._receiver.write(t)||this.pause()}function Sf(){let t=this[ie];t._readyState=z.CLOSING,t._receiver.end(),this.end()}function Ef(){let t=this[ie];this.removeListener("error",Ef),this.on("error",gf),t&&(t._readyState=z.CLOSING,this.destroy())}});var Af=_((qP,Pf)=>{"use strict";var UP=ei(),{Duplex:Yb}=ee("stream");function $f(t){t.emit("close")}function Qb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Rf(t){this.removeListener("error",Rf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Xb(t,e){let n=!0,r=new Yb({...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($f,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick($f,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",Qb),r.on("error",Rf),r}Pf.exports=Xb});var Oa=_((HP,Tf)=>{"use strict";var{tokenChars:Zb}=qn();function eS(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&&Zb[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}Tf.exports={parse:eS}});var Mf=_((VP,Lf)=>{"use strict";var tS=ee("events"),ti=ee("http"),{Duplex:GP}=ee("stream"),{createHash:nS}=ee("crypto"),xf=Yo(),sn=Un(),rS=Oa(),oS=ei(),{CLOSE_TIMEOUT:iS,GUID:sS,kWebSocket:aS}=ht(),cS=/^[+/0-9A-Za-z]{22}==$/,Cf=0,If=1,Nf=2,Na=class extends tS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:iS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:oS,...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=ti.createServer((r,o)=>{let i=ti.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=lS(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=Cf}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===Nf){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!==If)if(this._state=If,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",Of);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){an(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){an(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!cS.test(i)){an(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){an(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ur(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=rS.parse(c)}catch{an(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 sn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=xf.parse(u);p[sn.extensionName]&&(h.accept(p[sn.extensionName]),d[sn.extensionName]=h)}catch{an(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 Ur(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(h))return Ur(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[aS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Cf)return Ur(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${nS("sha1").update(n+sS).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[sn.extensionName]){let d=e[sn.extensionName].params,h=xf.format({[sn.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 lw={keyword:"dependencies",type:"object",schemaType:"object",error:Ze.error,code(t){let[e,n]=uw(t);ju(t,e),Du(t,n)}};function uw({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 ju(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,Nr.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Nr.checkReportMissingProp)(t,u)}):(n.if((0,Bs._)`${c} && (${(0,Nr.checkMissingProp)(t,a,i)})`),(0,Nr.reportMissingProp)(t,i),n.else())}}Ze.validatePropertyDeps=ju;function Du(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,cw.alwaysValidSchema)(i,e[a])||(n.if((0,Nr.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))}Ze.validateSchemaDeps=Du;Ze.default=lw});var Uu=_(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Fu=T(),dw=L(),fw={message:"property name must be valid",params:({params:t})=>(0,Fu._)`{propertyName: ${t.propertyName}}`},mw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fw,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,dw.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,Fu.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Fs.default=mw});var qs=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Oo=Ie(),Ue=T(),pw=dt(),No=L(),hw={message:"must NOT have additional properties",params:({params:t})=>(0,Ue._)`{additionalProperty: ${t.additionalProperty}}`},gw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hw,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,No.alwaysValidSchema)(s,n))return;let u=(0,Oo.allSchemaProperties)(r.properties),l=(0,Oo.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Ue._)`${i} === ${pw.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?f(g):e.if(h(g),()=>f(g))})}function h(g){let y;if(u.length>8){let v=(0,No.schemaRefOrVal)(s,r.properties,"properties");y=(0,Oo.isOwnProperty)(e,v,g)}else u.length?y=(0,Ue.or)(...u.map(v=>(0,Ue._)`${g} === ${v}`)):y=Ue.nil;return l.length&&(y=(0,Ue.or)(y,...l.map(v=>(0,Ue._)`${(0,Oo.usePattern)(t,v)}.test(${g})`))),(0,Ue.not)(y)}function p(g){e.code((0,Ue._)`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,No.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Ue.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Ue.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:No.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Us.default=gw});var Gu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var yw=vr(),qu=Ie(),Hs=L(),Hu=qs(),_w={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&&Hu.default.code(new yw.KeywordCxt(i,Hu.default,"additionalProperties"));let s=(0,qu.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Hs.mergeEvaluated.props(e,(0,Hs.toHash)(s),i.props));let a=s.filter(d=>!(0,Hs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,qu.propertyInData)(e,o,d,i.opts.ownProperties)),l(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Gs.default=_w});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Vu=Ie(),Lo=T(),Wu=L(),zu=L(),ww={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,Vu.allSchemaProperties)(n),c=a.filter(m=>(0,Wu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=s.strictSchema&&!s.allowMatchingProperties&&o.properties,l=e.name("valid");i.props!==!0&&!(i.props instanceof Lo.Name)&&(i.props=(0,zu.evaluatedPropsToName)(e,i.props));let{props:d}=i;h();function h(){for(let m of a)u&&p(m),i.allErrors?f(m):(e.var(l,!0),f(m),e.if(l))}function p(m){for(let g in u)new RegExp(m).test(g)&&(0,Wu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,Lo._)`${(0,Vu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:zu.Type.Str},l),i.opts.unevaluated&&d!==!0?e.assign((0,Lo._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,Lo.not)(l),()=>e.break())})})}}};Vs.default=ww});var Ju=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var vw=L(),bw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,vw.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"}};Ws.default=bw});var Yu=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var Sw=Ie(),Ew={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Sw.validateUnion,error:{message:"must match a schema in anyOf"}};zs.default=Ew});var Qu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Mo=T(),kw=L(),$w={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},Rw={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$w,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(u),t.result(s,()=>t.reset(),()=>t.error(!0));function u(){i.forEach((l,d)=>{let h;(0,kw.alwaysValidSchema)(o,l)?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)})})}}};Ks.default=Rw});var Xu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Aw=L(),Pw={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,Aw.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};Js.default=Pw});var td=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var jo=T(),ed=L(),Tw={message:({params:t})=>(0,jo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jo._)`{failingKeyword: ${t.ifClause}}`},Cw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Tw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,ed.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Zu(r,"then"),i=Zu(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,jo.not)(a),u("else"));t.pass(s,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let h=t.subschema({keyword:l},a);e.assign(s,a),t.mergeValidEvaluated(h,s),d?e.assign(d,(0,jo._)`${l}`):t.setParams({ifClause:l})}}}};function Zu(t,e){let n=t.schema[e];return n!==void 0&&!(0,ed.alwaysValidSchema)(t,n)}Ys.default=Cw});var nd=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var xw=L(),Iw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,xw.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Qs.default=Iw});var rd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Ow=Ns(),Nw=Ou(),Lw=Ls(),Mw=Lu(),jw=Mu(),Dw=Bu(),Bw=Uu(),Fw=qs(),Uw=Gu(),qw=Ku(),Hw=Ju(),Gw=Yu(),Vw=Qu(),Ww=Xu(),zw=td(),Kw=nd();function Jw(t=!1){let e=[Hw.default,Gw.default,Vw.default,Ww.default,zw.default,Kw.default,Bw.default,Fw.default,Dw.default,Uw.default,qw.default];return t?e.push(Nw.default,Mw.default):e.push(Ow.default,Lw.default),e.push(jw.default),e}Xs.default=Jw});var od=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Q=T(),Yw={message:({schemaCode:t})=>(0,Q.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Q._)`{format: ${t}}`},Qw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Yw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,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,Q._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Q._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Q._)`${m}.type || "string"`).assign(y,(0,Q._)`${m}.validate`),()=>n.assign(g,(0,Q._)`"string"`).assign(y,m)),t.fail$data((0,Q.or)(v(),S()));function v(){return c.strictSchema===!1?Q.nil:(0,Q._)`${s} && !${y}`}function S(){let R=l.$async?(0,Q._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Q._)`${y}(${r})`,$=(0,Q._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Q._)`${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 "${u}"`}}function S($){let J=$ instanceof RegExp?(0,Q.regexpCode)($):c.code.formats?(0,Q._)`${c.code.formats}${(0,Q.getProperty)(i)}`:void 0,Z=n.scopeValue("formats",{key:i,ref:$,code:J});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Q._)`${Z}.validate`]:["string",$,Z]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Q._)`await ${y}(${r})`}return typeof g=="function"?(0,Q._)`${y}(${r})`:(0,Q._)`${y}.test(${r})`}}}};Zs.default=Qw});var id=_(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var Xw=od(),Zw=[Xw.default];ea.default=Zw});var sd=_(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 cd=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var ev=hu(),tv=Tu(),nv=rd(),rv=id(),ad=sd(),ov=[ev.default,tv.default,(0,nv.default)(),rv.default,ad.metadataVocabulary,ad.contentVocabulary];ta.default=ov});var ud=_(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.DiscrError=void 0;var ld;(function(t){t.Tag="tag",t.Mapping="mapping"})(ld||(Do.DiscrError=ld={}))});var fd=_(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var In=T(),na=ud(),dd=vo(),iv=br(),sv=L(),av={message:({params:{discrError:t,tagName:e}})=>t===na.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}}`},cv={keyword:"discriminator",type:"object",schemaType:"object",error:av,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),u=e.const("tag",(0,In._)`${n}${(0,In.getProperty)(a)}`);e.if((0,In._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:na.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let p=h();e.if(!1);for(let f in p)e.elseIf((0,In._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:na.DiscrError.Mapping,tag:u,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,sv.schemaHasRulesButRef)($,i.self.RULES)){let Z=$.$ref;if($=dd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Z),$ instanceof dd.SchemaEnv&&($=$.schema),$===void 0)throw new iv.default(i.opts.uriResolver,i.baseId,Z)}let J=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof J!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y($)),v(J,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 J of R.enum)S(J,$);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]=$}}}};ra.default=cv});var md=_((dA,lv)=>{lv.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=_((V,oa)=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.MissingRefError=V.ValidationError=V.CodeGen=V.Name=V.nil=V.stringify=V.str=V._=V.KeywordCxt=V.Ajv=void 0;var uv=lu(),dv=cd(),fv=fd(),pd=md(),mv=["/properties"],Bo="http://json-schema.org/draft-07/schema",On=class extends uv.default{_addVocabularies(){super._addVocabularies(),dv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fv.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(pd,mv):pd;this.addMetaSchema(e,Bo,!1),this.refs["http://json-schema.org/schema"]=Bo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bo)?Bo:void 0)}};V.Ajv=On;oa.exports=V=On;oa.exports.Ajv=On;Object.defineProperty(V,"__esModule",{value:!0});V.default=On;var pv=vr();Object.defineProperty(V,"KeywordCxt",{enumerable:!0,get:function(){return pv.KeywordCxt}});var Nn=T();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(V,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var hv=_o();Object.defineProperty(V,"ValidationError",{enumerable:!0,get:function(){return hv.default}});var gv=br();Object.defineProperty(V,"MissingRefError",{enumerable:!0,get:function(){return gv.default}})});var Sd=_(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.formatNames=tt.fastFormats=tt.fullFormats=void 0;function et(t,e){return{validate:t,compare:e}}tt.fullFormats={date:et(_d,ca),time:et(sa(!0),la),"date-time":et(hd(!0),vd),"iso-time":et(sa(),wd),"iso-date-time":et(hd(),bd),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Sv,"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:Tv,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:Ev,int32:{type:"number",validate:Rv},int64:{type:"number",validate:Av},float:{type:"number",validate:yd},double:{type:"number",validate:yd},password:!0,binary:!0};tt.fastFormats={...tt.fullFormats,date:et(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ca),time:et(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,la),"date-time":et(/^\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,vd),"iso-time":et(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wd),"iso-date-time":et(/^\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,bd),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};tt.formatNames=Object.keys(tt.fullFormats);function yv(t){return t%4===0&&(t%100!==0||t%400===0)}var _v=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,wv=[0,31,28,31,30,31,30,31,31,30,31,30,31];function _d(t){let e=_v.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&&yv(n)?29:wv[r])}function ca(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ia=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function sa(t){return function(n){let r=ia.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-l*c,h=o-u*c-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function la(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 wd(t,e){if(!(t&&e))return;let n=ia.exec(t),r=ia.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 aa=/t|\s/i;function hd(t){let e=sa(t);return function(r){let o=r.split(aa);return o.length===2&&_d(o[0])&&e(o[1])}}function vd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function bd(t,e){if(!(t&&e))return;let[n,r]=t.split(aa),[o,i]=e.split(aa),s=ca(n,o);if(s!==void 0)return s||la(r,i)}var vv=/\/|:/,bv=/^(?:[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 Sv(t){return vv.test(t)&&bv.test(t)}var gd=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Ev(t){return gd.lastIndex=0,gd.test(t)}var kv=-(2**31),$v=2**31-1;function Rv(t){return Number.isInteger(t)&&t<=$v&&t>=kv}function Av(t){return Number.isInteger(t)}function yd(){return!0}var Pv=/[^\\]\\Z/;function Tv(t){if(Pv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ed=_(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.formatLimitDefinition=void 0;var Cv=Fo(),qe=T(),xt=qe.operators,Uo={formatMaximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},formatMinimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},formatExclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},formatExclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},xv={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Uo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Uo[t].okStr}, limit: ${e}}`};Ln.formatLimitDefinition={keyword:Object.keys(Uo),type:"string",schemaType:"string",$data:!0,error:xv,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 Cv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){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 l(){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}) ${Uo[o].fail} 0`}},dependencies:["format"]};var Iv=t=>(t.addKeyword(Ln.formatLimitDefinition),t);Ln.default=Iv});var fa=_((Lr,Rd)=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});var Mn=Sd(),Ov=Ed(),ua=T(),kd=new ua.Name("fullFormats"),Nv=new ua.Name("fastFormats"),da=(t,e={keywords:!0})=>{if(Array.isArray(e))return $d(t,e,Mn.fullFormats,kd),t;let[n,r]=e.mode==="fast"?[Mn.fastFormats,Nv]:[Mn.fullFormats,kd],o=e.formats||Mn.formatNames;return $d(t,o,n,r),e.keywords&&(0,Ov.default)(t),t};da.get=(t,e="full")=>{let r=(e==="fast"?Mn.fastFormats:Mn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function $d(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ua._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Rd.exports=Lr=da;Object.defineProperty(Lr,"__esModule",{value:!0});Lr.default=da});var ht=_((NA,Ld)=>{"use strict";var Od=["nodebuffer","arraybuffer","fragments"],Nd=typeof Blob<"u";Nd&&Od.push("blob");Ld.exports={BINARY_TYPES:Od,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Nd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Mr=_((LA,qo)=>{"use strict";var{EMPTY_BUFFER:Wv}=ht(),pa=Buffer[Symbol.species];function zv(t,e){if(t.length===0)return Wv;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 pa(n.buffer,n.byteOffset,r):n}function Md(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function jd(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Kv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ha(t){if(ha.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pa(t):ArrayBuffer.isView(t)?e=new pa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ha.readOnly=!1),e}qo.exports={concat:zv,mask:Md,toArrayBuffer:Kv,toBuffer:ha,unmask:jd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=te("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Md(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?jd(e,n):t.unmask(e,n)}}catch{}});var Fd=_((MA,Bd)=>{"use strict";var Dd=Symbol("kDone"),ga=Symbol("kRun"),ya=class{constructor(e){this[Dd]=()=>{this.pending--,this[ga]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ga]()}[ga](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Dd])}}};Bd.exports=ya});var Un=_((jA,Gd)=>{"use strict";var jr=te("zlib"),Ud=Mr(),Jv=Fd(),{kStatusCode:qd}=ht(),Yv=Buffer[Symbol.species],Qv=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),gt=Symbol("total-length"),Bn=Symbol("callback"),It=Symbol("buffers"),Fn=Symbol("error"),Ho,_a=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,!Ho){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new Jv(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[Bn];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){Ho.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Ho.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"?jr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=jr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Go]=this,this._inflate[gt]=0,this._inflate[It]=[],this._inflate.on("error",Zv),this._inflate.on("data",Hd)}this._inflate[Bn]=r,this._inflate.write(e),n&&this._inflate.write(Qv),this._inflate.flush(()=>{let i=this._inflate[Fn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Ud.concat(this._inflate[It],this._inflate[gt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gt]=0,this._inflate[It]=[],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"?jr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=jr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[gt]=0,this._deflate[It]=[],this._deflate.on("data",Xv)}this._deflate[Bn]=r,this._deflate.write(e),this._deflate.flush(jr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ud.concat(this._deflate[It],this._deflate[gt]);n&&(i=new Yv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Bn]=null,this._deflate[gt]=0,this._deflate[It]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Gd.exports=_a;function Xv(t){this[It].push(t),this[gt]+=t.length}function Hd(t){if(this[gt]+=t.length,this[Go]._maxPayload<1||this[gt]<=this[Go]._maxPayload){this[It].push(t);return}this[Fn]=new RangeError("Max payload size exceeded"),this[Fn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fn][qd]=1009,this.removeListener("data",Hd),this.reset()}function Zv(t){if(this[Go]._inflate=null,this[Fn]){this[Bn](this[Fn]);return}t[qd]=1007,this[Bn](t)}});var qn=_((DA,Vo)=>{"use strict";var{isUtf8:Vd}=te("buffer"),{hasBlob:eb}=ht(),tb=[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 nb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function wa(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 rb(t){return eb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Vo.exports={isBlob:rb,isValidStatusCode:nb,isValidUTF8:wa,tokenChars:tb};if(Vd)Vo.exports.isValidUTF8=function(t){return t.length<24?wa(t):Vd(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=te("utf-8-validate");Vo.exports.isValidUTF8=function(e){return e.length<32?wa(e):t(e)}}catch{}});var ka=_((BA,Xd)=>{"use strict";var{Writable:ob}=te("stream"),Wd=Un(),{BINARY_TYPES:ib,EMPTY_BUFFER:zd,kStatusCode:sb,kWebSocket:ab}=ht(),{concat:va,toArrayBuffer:cb,unmask:lb}=Mr(),{isValidStatusCode:ub,isValidUTF8:Kd}=qn(),Wo=Buffer[Symbol.species],Le=0,Jd=1,Yd=2,Qd=3,ba=4,Sa=5,zo=6,Ea=class extends ob{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ib[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ab]=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=Le}_write(e,n,r){if(this._opcode===8&&this._state==Le)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 Le:this.getInfo(e);break;case Jd:this.getPayloadLength16(e);break;case Yd:this.getPayloadLength64(e);break;case Qd:this.getMask();break;case ba:this.getData(e);break;case Sa:case zo: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[Wd.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=Jd:this._payloadLength===127?this._state=Yd: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=Qd:this._state=ba}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ba}getData(e){let n=zd;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]&&lb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Sa,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wd.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===Le&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Le;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=va(r,n):this._binaryType==="arraybuffer"?o=cb(va(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit("message",o,!0),this._state=Le,this.startLoop(e)}))}else{let o=va(r,n);if(!this._skipUTF8Validation&&!Kd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Sa||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit("message",o,!1),this._state=Le,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,zd),this.end();else{let r=e.readUInt16BE(0);if(!ub(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&&!Kd(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=Le;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Le,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[sb]=o,s}};Xd.exports=Ea});var Aa=_((UA,tf)=>{"use strict";var{Duplex:FA}=te("stream"),{randomFillSync:db}=te("crypto"),Zd=Un(),{EMPTY_BUFFER:fb,kWebSocket:mb,NOOP:pb}=ht(),{isBlob:Hn,isValidStatusCode:hb}=qn(),{mask:ef,toBuffer:nn}=Mr(),Me=Symbol("kByteLength"),gb=Buffer.alloc(4),Ko=8*1024,rn,Gn=Ko,He=0,yb=1,_b=2,$a=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=He,this.onerror=pb,this[mb]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||gb,n.generateMask?n.generateMask(r):(Gn===Ko&&(rn===void 0&&(rn=Buffer.alloc(Ko)),db(rn,0,Ko),Gn=0),r[0]=rn[Gn++],r[1]=rn[Gn++],r[2]=rn[Gn++],r[3]=rn[Gn++]),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 u=Buffer.allocUnsafe(o?a+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],s?[u,e]:o?(ef(e,r,u,i,a),[u]):(ef(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,o){let i;if(e===void 0)i=fb;else{if(typeof e!="number"||!hb(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!==He?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=nn(e),o=e.length,i=nn.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};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==He?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=nn(e),o=e.length,i=nn.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};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==He?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Zd.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=nn(e),a=e.length,c=nn.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 u={[Me]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==He?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Me],this._state=_b,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ra,this,a,o);return}this._bufferedBytes-=r[Me];let s=nn(i);n?this.dispatch(s,n,r,o):(this._state=He,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(wb,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Zd.extensionName];this._bufferedBytes+=r[Me],this._state=yb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ra(this,c,o);return}this._bufferedBytes-=r[Me],this._state=He,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===He&&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)}};tf.exports=$a;function Ra(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 wb(t,e,n){Ra(t,e,n),t.onerror(e)}});var df=_((qA,uf)=>{"use strict";var{kForOnEventAttribute:Dr,kListener:Pa}=ht(),nf=Symbol("kCode"),rf=Symbol("kData"),of=Symbol("kError"),sf=Symbol("kMessage"),af=Symbol("kReason"),Vn=Symbol("kTarget"),cf=Symbol("kType"),lf=Symbol("kWasClean"),yt=class{constructor(e){this[Vn]=null,this[cf]=e}get target(){return this[Vn]}get type(){return this[cf]}};Object.defineProperty(yt.prototype,"target",{enumerable:!0});Object.defineProperty(yt.prototype,"type",{enumerable:!0});var on=class extends yt{constructor(e,n={}){super(e),this[nf]=n.code===void 0?0:n.code,this[af]=n.reason===void 0?"":n.reason,this[lf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[nf]}get reason(){return this[af]}get wasClean(){return this[lf]}};Object.defineProperty(on.prototype,"code",{enumerable:!0});Object.defineProperty(on.prototype,"reason",{enumerable:!0});Object.defineProperty(on.prototype,"wasClean",{enumerable:!0});var Wn=class extends yt{constructor(e,n={}){super(e),this[of]=n.error===void 0?null:n.error,this[sf]=n.message===void 0?"":n.message}get error(){return this[of]}get message(){return this[sf]}};Object.defineProperty(Wn.prototype,"error",{enumerable:!0});Object.defineProperty(Wn.prototype,"message",{enumerable:!0});var Br=class extends yt{constructor(e,n={}){super(e),this[rf]=n.data===void 0?null:n.data}get data(){return this[rf]}};Object.defineProperty(Br.prototype,"data",{enumerable:!0});var vb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[Dr]&&o[Pa]===e&&!o[Dr])return;let r;if(t==="message")r=function(i,s){let a=new Br("message",{data:s?i:i.toString()});a[Vn]=this,Jo(e,this,a)};else if(t==="close")r=function(i,s){let a=new on("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Vn]=this,Jo(e,this,a)};else if(t==="error")r=function(i){let s=new Wn("error",{error:i,message:i.message});s[Vn]=this,Jo(e,this,s)};else if(t==="open")r=function(){let i=new yt("open");i[Vn]=this,Jo(e,this,i)};else return;r[Dr]=!!n[Dr],r[Pa]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Pa]===e&&!n[Dr]){this.removeListener(t,n);break}}};uf.exports={CloseEvent:on,ErrorEvent:Wn,Event:yt,EventTarget:vb,MessageEvent:Br};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Yo=_((HA,ff)=>{"use strict";var{tokenChars:Fr}=qn();function nt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function bb(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&Fr[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let p=t.slice(c,l);u===44?(nt(e,p,n),n=Object.create(null)):s=p,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&Fr[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),nt(n,t.slice(c,l),!0),u===44&&(nt(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Fr[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Fr[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)i=!1,l=d;else if(u===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)i=!0;else if(l===-1&&Fr[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let p=t.slice(c,l);r&&(p=p.replace(/\\/g,""),r=!1),nt(n,a,p),u===44&&(nt(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let h=t.slice(c,l);return s===void 0?nt(e,h,n):(a===void 0?nt(n,h,!0):r?nt(n,a,h.replace(/\\/g,"")):nt(n,a,h),nt(e,s,n)),e}function Sb(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(", ")}ff.exports={format:Sb,parse:bb}});var ei=_((WA,kf)=>{"use strict";var Eb=te("events"),kb=te("https"),$b=te("http"),hf=te("net"),Rb=te("tls"),{randomBytes:Ab,createHash:Pb}=te("crypto"),{Duplex:GA,Readable:VA}=te("stream"),{URL:Ta}=te("url"),Ot=Un(),Tb=ka(),Cb=Aa(),{isBlob:xb}=qn(),{BINARY_TYPES:mf,CLOSE_TIMEOUT:Ib,EMPTY_BUFFER:Qo,GUID:Ob,kForOnEventAttribute:Ca,kListener:Nb,kStatusCode:Lb,kWebSocket:ie,NOOP:gf}=ht(),{EventTarget:{addEventListener:Mb,removeEventListener:jb}}=df(),{format:Db,parse:Bb}=Yo(),{toBuffer:Fb}=Mr(),yf=Symbol("kAborted"),xa=[8,13],_t=["CONNECTING","OPEN","CLOSING","CLOSED"],Ub=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,K=class t extends Eb{constructor(e,n,r){super(),this._binaryType=mf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Qo,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]),_f(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){mf.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 Tb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Cb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[ie]=this,i[ie]=this,e[ie]=this,o.on("conclude",Gb),o.on("drain",Vb),o.on("error",Wb),o.on("message",zb),o.on("ping",Kb),o.on("pong",Jb),i.onerror=Yb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bf),e.on("data",Zo),e.on("end",Sf),e.on("error",Ef),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[Ot.extensionName]&&this._extensions[Ot.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())}),vf(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){Ia(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Qo,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){Ia(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Qo,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){Ia(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ot.extensionName]||(o.compress=!1),this._sender.send(e||Qo,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(K,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(K.prototype,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(K,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(K.prototype,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(K,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(K.prototype,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(K,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});Object.defineProperty(K.prototype,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(K.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(K.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ca])return e[Nb];return null},set(e){for(let n of this.listeners(t))if(n[Ca]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ca]:!0})}})});K.prototype.addEventListener=Mb;K.prototype.removeEventListener=jb;kf.exports=K;function _f(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ib,protocolVersion:xa[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,!xa.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${xa.join(", ")})`);let i;if(e instanceof Ta)i=e;else try{i=new Ta(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;Xo(t,m);return}let u=s?443:80,l=Ab(16).toString("base64"),d=s?kb.request:$b.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?Hb:qb),o.defaultPort=o.defaultPort||u,o.port=i.port||u,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new Ot({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Db({[Ot.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Ub.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[yf]||(f=t._req=null,Xo(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 Ta(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Xo(t,R);return}_f(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!==K.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=Pb("sha1").update(l+Ob).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 J=m.headers["sec-websocket-extensions"];if(J!==void 0){if(!p){$e(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Z;try{Z=Bb(J)}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ae=Object.keys(Z);if(ae.length!==1||ae[0]!==Ot.extensionName){$e(t,g,"Server indicated an extension that was not requested");return}try{p.accept(Z[Ot.extensionName])}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ot.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 Xo(t,e){t._readyState=K.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qb(t){return t.path=t.socketPath,hf.connect(t)}function Hb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hf.isIP(t.host)?"":t.host),Rb.connect(t)}function $e(t,e,n){t._readyState=K.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[yf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ia(t,e,n){if(e){let r=xb(e)?e.size:Fb(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_t[t.readyState]})`);process.nextTick(n,r)}}function Gb(t,e){let n=this[ie];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ie]!==void 0&&(n._socket.removeListener("data",Zo),process.nextTick(wf,n._socket),t===1005?n.close():n.close(t,e))}function Vb(){let t=this[ie];t.isPaused||t._socket.resume()}function Wb(t){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",Zo),process.nextTick(wf,e._socket),e.close(t[Lb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function pf(){this[ie].emitClose()}function zb(t,e){this[ie].emit("message",t,e)}function Kb(t){let e=this[ie];e._autoPong&&e.pong(t,!this._isServer,gf),e.emit("ping",t)}function Jb(t){this[ie].emit("pong",t)}function wf(t){t.resume()}function Yb(t){let e=this[ie];e.readyState!==K.CLOSED&&(e.readyState===K.OPEN&&(e._readyState=K.CLOSING,vf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function vf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bf(){let t=this[ie];if(this.removeListener("close",bf),this.removeListener("data",Zo),this.removeListener("end",Sf),t._readyState=K.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[ie]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",pf),t._receiver.on("finish",pf))}function Zo(t){this[ie]._receiver.write(t)||this.pause()}function Sf(){let t=this[ie];t._readyState=K.CLOSING,t._receiver.end(),this.end()}function Ef(){let t=this[ie];this.removeListener("error",Ef),this.on("error",gf),t&&(t._readyState=K.CLOSING,this.destroy())}});var Pf=_((KA,Af)=>{"use strict";var zA=ei(),{Duplex:Qb}=te("stream");function $f(t){t.emit("close")}function Xb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Rf(t){this.removeListener("error",Rf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Zb(t,e){let n=!0,r=new Qb({...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($f,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick($f,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",Xb),r.on("error",Rf),r}Af.exports=Zb});var Oa=_((JA,Tf)=>{"use strict";var{tokenChars:eS}=qn();function tS(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&&eS[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}Tf.exports={parse:tS}});var Mf=_((QA,Lf)=>{"use strict";var nS=te("events"),ti=te("http"),{Duplex:YA}=te("stream"),{createHash:rS}=te("crypto"),Cf=Yo(),sn=Un(),oS=Oa(),iS=ei(),{CLOSE_TIMEOUT:sS,GUID:aS,kWebSocket:cS}=ht(),lS=/^[+/0-9A-Za-z]{22}==$/,xf=0,If=1,Nf=2,Na=class extends nS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:sS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:iS,...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=ti.createServer((r,o)=>{let i=ti.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=uS(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=xf}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===Nf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ur,this);return}if(e&&this.once("close",e),this._state!==If)if(this._state=If,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(Ur,this):process.nextTick(Ur,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ur(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",Of);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){an(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){an(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!lS.test(i)){an(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){an(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"],u=new Set;if(c!==void 0)try{u=oS.parse(c)}catch{an(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let h=new sn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Cf.parse(l);p[sn.extensionName]&&(h.accept(p[sn.extensionName]),d[sn.extensionName]=h)}catch{an(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,u,e,n,r,o)});return}if(!this.options.verifyClient(h))return qr(n,401)}this.completeUpgrade(d,i,u,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[cS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>xf)return qr(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${rS("sha1").update(n+aS).digest("base64")}`],l=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&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[sn.extensionName]){let d=e[sn.extensionName].params,h=Cf.format({[sn.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${h}`),l._extensions=e}this.emit("headers",u,o),i.write(u.concat(`\r
11
11
  `).join(`\r
12
- `)),i.removeListener("error",Of),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)}};Lf.exports=Na;function lS(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=Nf,t.emit("close")}function Of(){this.destroy()}function Ur(t,e,n,r){n=n||ti.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} ${ti.STATUS_CODES[e]}\r
12
+ `)),i.removeListener("error",Of),l.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ur,this)})),a(l,o)}};Lf.exports=Na;function uS(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 Ur(t){t._state=Nf,t.emit("close")}function Of(){this.destroy()}function qr(t,e,n,r){n=n||ti.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} ${ti.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 an(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,an),t.emit("wsClientError",s,n,e)}else Ur(n,r,o,i)}});var Tc={"-v":"version","-h":"help"};function Cp(t){return t.startsWith("--")?!0:Tc[t]!==void 0}function xc(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||Cp(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=Tc[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 Oc from"node:path";import Nc from"node:fs";import Cc from"node:fs";import Ip from"node:os";import Ic from"node:path";var Op=Ic.join(".aifight","runtime");function oe(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Ic.join(Ip.homedir(),Op)}function at(){let t=oe();if(Cc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{Cc.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 Np(){return Oc.join(oe(),"token")}function Lp(){return Oc.join(oe(),"port")}function Lc(){let t=Np(),e;try{e=Nc.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 Mc(){let t=Lp(),e;try{e=Nc.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 Mp=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function jp(t){return typeof t=="string"&&Mp.has(t)}function Dp(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 jp(n.code)&&typeof n.message=="string"}var pe=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}},Fp="127.0.0.1",Bp=1e4;function jc(t){let e=t.host??Fp,n=t.baseTimeoutMs??Bp,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new pe("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new pe("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 K;try{K=await r(S,u(f,g,y,R.signal))}catch(ae){throw l(ae)?new pe("request_timeout",`request timed out after ${n}ms`,{cause:ae}):new pe("daemon_unreachable",`AIFight Bridge not running: ${ae.message}`,{cause:ae})}let X;try{X=await K.text()}catch(ae){throw l(ae)?new pe("request_timeout",`request timed out after ${n}ms`,{cause:ae}):new pe("transport_unparseable",`failed to read response body (status ${K.status})`,{status:K.status,cause:ae})}if(X.length===0)return{status:K.status,parsedBody:void 0,parseFailed:!1};try{return{status:K.status,parsedBody:JSON.parse(X),parseFailed:!1}}catch{return{status:K.status,parsedBody:X,parseFailed:!0}}}finally{clearTimeout($)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new pe("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!Dp(f.parsedBody))throw new pe("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new pe("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 pe("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 pe("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 Dc(t,e={}){return jc({tokenSource:Lc,portSource:Mc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var he=["texas_holdem","liars_dice","coup"];function ct(t){return he.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},U=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 W(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 no(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
- `}import oo from"node:fs";import or from"node:path";import{fileURLToPath as Up}from"node:url";var Fc=["./schemas","../../../protocol/schema","../../protocol/schema"],ro=null;function ir(t=qp()){if(ro)return ro;for(let e of Fc){let n=or.resolve(t,e);if(Bc(n)&&Bc(or.join(n,"messages")))return ro=n,ro}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Fc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function qp(){return or.dirname(Up(import.meta.url))}function Bc(t){try{return oo.statSync(t).isDirectory()}catch{return!1}}var Hp={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 wi(){return Object.keys(Hp)}function qt(){let t=ir(),e=new Map;return qc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=oo.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function qc(t,e){for(let n of oo.readdirSync(t,{withFileTypes:!0})){let r=or.join(t,n.name);n.isDirectory()?qc(r,e):n.isFile()&&e(r)}}var Uc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function vi(t){let e=Uc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Uc).join(", ")}`);let n=ir(),r=or.join(n,e),o=oo.readFileSync(r,"utf8");return JSON.parse(o)}var Pd=xe(Bo(),1),Ad=xe(fa(),1);var jn=class extends Error{},pt=class extends jn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Zt=class extends jn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},en=class extends jn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var Nv=3e4,tn="/api/agents/register",Lv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Dn=null;function Mv(){if(Dn)return Dn;let t=new Pd.default({strict:!1,allErrors:!0});(0,Ad.default)(t);let e=qt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(Lv);if(n)return Dn=n,Dn;let r=vi("register_response");return Dn=t.compile(r),Dn}async function ma(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??Nv,r=t.baseUrl.replace(/\/+$/,"")+tn,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 pt(`POST ${tn} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new pt(`POST ${tn} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new pt(`POST ${tn} 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 Zt(s.status,p,`POST ${tn} returned HTTP ${s.status}`)}if(l!==null)throw new en([],`POST ${tn} returned 201 with non-JSON body: ${l.message}`);if(typeof c!="object"||c===null)throw new en([],`POST ${tn} returned 201 with non-object body`);let u=Mv();if(!u(c)){let p=(u.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new en(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 hP from"better-sqlite3";var Td=`-- runtime/src/store/schema.sql
16
+ `+n)}function an(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,an),t.emit("wsClientError",s,n,e)}else qr(n,r,o,i)}});var Tc={"-v":"version","-h":"help"};function Ip(t){return t.startsWith("--")?!0:Tc[t]!==void 0}function Cc(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 u=c.indexOf("="),l=u>=0?c.slice(2,u):c.slice(2),d=u>=0?c.slice(u+1):void 0,h=i.get(l);if(!h){o.push(`unknown flag: --${l}`),a+=1;continue}if(h.type==="boolean"){d===void 0||d==="true"?r[l]=!0:d==="false"?r[l]=!1:o.push(`flag --${l} 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||Ip(f)){o.push(`flag --${l} requires a value`),a+=1;continue}p=f,a+=2}if(h.type==="number"){if(!/^-?\d+(\.\d+)?$/.test(p)){o.push(`flag --${l} requires a number (got "${p}")`);continue}r[l]=Number(p);continue}r[l]=p;continue}if(c.startsWith("-")&&c.length>1){let u=Tc[c];if(!u){o.push(`unknown flag: ${c}`),a+=1;continue}let l=i.get(u);if(!l||l.type!=="boolean"){o.push(`unknown flag: ${c}`),a+=1;continue}r[u]=!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 Oc from"node:path";import Nc from"node:fs";import xc from"node:fs";import Op from"node:os";import Ic from"node:path";var Np=Ic.join(".aifight","runtime");function oe(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Ic.join(Op.homedir(),Np)}function at(){let t=oe();if(xc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{xc.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 Lp(){return Oc.join(oe(),"token")}function Mp(){return Oc.join(oe(),"port")}function Lc(){let t=Lp(),e;try{e=Nc.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 Mc(){let t=Mp(),e;try{e=Nc.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 jp=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function Dp(t){return typeof t=="string"&&jp.has(t)}function Bp(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 Dp(n.code)&&typeof n.message=="string"}var pe=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}},Fp="127.0.0.1",Up=1e4;function jc(t){let e=t.host??Fp,n=t.baseTimeoutMs??Up,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new pe("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new pe("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 u(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function l(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 J;try{J=await r(S,l(f,g,y,R.signal))}catch(ae){throw u(ae)?new pe("request_timeout",`request timed out after ${n}ms`,{cause:ae}):new pe("daemon_unreachable",`AIFight Bridge not running: ${ae.message}`,{cause:ae})}let Z;try{Z=await J.text()}catch(ae){throw u(ae)?new pe("request_timeout",`request timed out after ${n}ms`,{cause:ae}):new pe("transport_unparseable",`failed to read response body (status ${J.status})`,{status:J.status,cause:ae})}if(Z.length===0)return{status:J.status,parsedBody:void 0,parseFailed:!1};try{return{status:J.status,parsedBody:JSON.parse(Z),parseFailed:!1}}catch{return{status:J.status,parsedBody:Z,parseFailed:!0}}}finally{clearTimeout($)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new pe("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!Bp(f.parsedBody))throw new pe("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new pe("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 pe("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 pe("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 Dc(t,e={}){return jc({tokenSource:Lc,portSource:Mc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var he=["texas_holdem","liars_dice","coup"];function ct(t){return he.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},B=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 z(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 no(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
+ `}import oo from"node:fs";import ir from"node:path";import{fileURLToPath as qp}from"node:url";var Bc=["./schemas","../../../protocol/schema","../../protocol/schema"],ro=null;function sr(t=Hp()){if(ro)return ro;for(let e of Bc){let n=ir.resolve(t,e);if(Fc(n)&&Fc(ir.join(n,"messages")))return ro=n,ro}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Bc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function Hp(){return ir.dirname(qp(import.meta.url))}function Fc(t){try{return oo.statSync(t).isDirectory()}catch{return!1}}var Gp={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 wi(){return Object.keys(Gp)}function qt(){let t=sr(),e=new Map;return qc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=oo.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function qc(t,e){for(let n of oo.readdirSync(t,{withFileTypes:!0})){let r=ir.join(t,n.name);n.isDirectory()?qc(r,e):n.isFile()&&e(r)}}var Uc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function vi(t){let e=Uc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Uc).join(", ")}`);let n=sr(),r=ir.join(n,e),o=oo.readFileSync(r,"utf8");return JSON.parse(o)}var Ad=Ce(Fo(),1),Pd=Ce(fa(),1);var jn=class extends Error{},pt=class extends jn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Zt=class extends jn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},en=class extends jn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var Lv=3e4,tn="/api/agents/register",Mv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Dn=null;function jv(){if(Dn)return Dn;let t=new Ad.default({strict:!1,allErrors:!0});(0,Pd.default)(t);let e=qt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(Mv);if(n)return Dn=n,Dn;let r=vi("register_response");return Dn=t.compile(r),Dn}async function ma(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??Lv,r=t.baseUrl.replace(/\/+$/,"")+tn,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 pt(`POST ${tn} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new pt(`POST ${tn} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new pt(`POST ${tn} failed: ${f}`,p)}let a=await s.text(),c,u=null;if(a.length>0)try{c=JSON.parse(a)}catch(p){u=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 Zt(s.status,p,`POST ${tn} returned HTTP ${s.status}`)}if(u!==null)throw new en([],`POST ${tn} returned 201 with non-JSON body: ${u.message}`);if(typeof c!="object"||c===null)throw new en([],`POST ${tn} returned 201 with non-object body`);let l=jv();if(!l(c)){let p=(l.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new en(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 bA from"better-sqlite3";var Td=`-- 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 xd=[{version:1,up:t=>{t.exec(Td)}},{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 Cd=[{version:1,up:t=>{t.exec(Td)}},{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,19 +64,19 @@ 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
- `)}}],wP=xd[xd.length-1].version;import{Entry as SP}from"@napi-rs/keyring";var Cd="AIFIGHT_KEYCHAIN_V1:",Id="AIFIGHT_CRYPTO_V1:";var $P=Buffer.byteLength(Cd,"ascii"),RP=Buffer.byteLength(Id,"ascii");var uS=xe(Af(),1),dS=xe(Yo(),1),fS=xe(Un(),1),mS=xe(ka(),1),pS=xe(Pa(),1),hS=xe(Oa(),1),La=xe(ei(),1),gS=xe(Mf(),1);var me=class extends Error{},Nt=class extends me{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Lt=class extends me{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},cn=class extends me{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Mt=class extends me{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},ln=class extends me{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},un=class extends me{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends me{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},rt=class extends me{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},wt=class extends me{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},vt=class extends me{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var jf=xe(Bo(),1),Df=xe(fa(),1);var ja=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),Da=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Ff="https://aifight.ai/protocol/v1/messages/";function yS(t){return`${Ff}client_${t}.schema.json`}function _S(t){return`${Ff}server_${t}.schema.json`}var Ma=null;function Bf(){if(Ma)return Ma;let t=new jf.default({strict:!1,allErrors:!0});(0,Df.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Ma=t,t}function Uf(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function qf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hf(t){if(!qf(t))throw new rt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new rt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(Da.has(e))throw new rt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!ja.has(e))throw new rt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...ja].join(", ")})`);let n=Bf(),r=yS(e),o=n.getSchema(r);if(!o)throw new rt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new rt(e,Uf(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function Fa(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(!qf(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(!Da.has(r))throw ja.has(r)?new wt(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new wt(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...Da].join(", ")})`);let o=Bf(),i=_S(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,Uf(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var wS=1e4,vS=25e3;function Gf(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 Ba=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??vS;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=Fa(n)}catch(o){if(o instanceof Re||o instanceof wt)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 un(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Hf(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 Ua(t){let e=t.welcomeTimeoutMs??wS;return t.signal?.aborted?Promise.reject(new vt(`createWSClient aborted before start: ${Gf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new La.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new Nt(`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 vt(`createWSClient aborted during handshake: ${Gf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new Nt(`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 Lt(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;l(()=>r(new Lt(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new cn(`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=Fa(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 wt?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 Mt(S,R))});return}if(h.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Mt([],`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 ln(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new Ba(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}},bS=1e3,SS=2,ES=3e4,kS="full",$S=5*60*1e3,RS=15*60*1e3,PS=new Set([1001,1006,1011,1012]);function AS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function TS(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 xS(t){return t.code>=4e3&&t.code<5e3?!1:PS.has(t.code)}function CS(t){if(t instanceof vt||t instanceof Mt||t instanceof ln)return!1;if(t instanceof Nt||t instanceof cn)return!0;if(t instanceof Lt){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function IS(t){return t>=RS?"error":t>=$S?"warning":"info"}var qa=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 un(`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 Ua({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(!xS(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 me&&(e=a),!CS(a)){let c=a instanceof me?a:void 0,l=a instanceof vt?"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=AS(this.#u,this.#e.initialBackoffMs??bS,this.#e.backoffFactor??SS,this.#e.maxBackoffMs??ES),o=TS(r,this.#e.jitter??kS),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"?IS(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 Ha(t){let e=new qa(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var OS=["check","call","fold","raise","allin"];function Ga(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 OS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Wa(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=NS(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=LS(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 NS(t){let e=MS(t);if(!e)return;let n=Va(e,"min_quantity"),r=Va(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Va(e,"max_quantity")}}function LS(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 MS(t){return t!==null&&typeof t=="object"?t:void 0}function Va(t,e){let n=t[e];return typeof n=="number"?n:void 0}var jS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],DS=["pass","challenge"],FS=["pass","block"],BS=["lose_card"],US=["return_cards"];function za(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,jS);case"challenge_action":case"challenge_block":return qr(n,DS);case"block":return qr(n,FS);case"lose_influence":return qr(n,BS);case"exchange_return":return qr(n,US);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 qS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ja(t,e,n=500){let r=t.trim(),o=VS(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(!HS.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==="raise"){let d=GS(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 HS=new Set(["fold","check","call","raise","allin"]);function GS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ni(t.data)?t.data:void 0,o=Ka(r,"amount"),i=Ka(r,"min")??o,s=Ka(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function VS(t){let e=t.match(qS);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 WS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Qa(t,e,n=500){let r=t.trim(),o=JS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!ri(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&&!ri(c))return fn("missing_fields",r,n);let l=ri(c)?c:void 0;if(!zS.has(s))return fn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return fn("action_not_legal",r,n);if(s==="bid"){let d=KS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var zS=new Set(["bid","challenge"]);function KS(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=ri(t.data)?t.data:void 0,i=Ya(o,"min_quantity"),s=Ya(o,"min_face"),a=Ya(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 JS(t){let e=t.match(WS);return e?e[1].trim():t}function ri(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ya(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var YS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,QS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Xa(t,e,n=500){let r=t.trim(),o=ZS(r),i;try{i=JSON.parse(o)}catch{return mn("json_parse",r,n)}if(!Kn(i))return mn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return mn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Kn(c))return mn("missing_fields",r,n);let l=Kn(c)?c:void 0;if(!QS.has(s))return mn("unknown_action_type",r,n);let u=e.filter(h=>h.type===s);if(u.length===0)return mn("action_not_legal",r,n);let d=XS(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:mn("data_validation",r,n)}function XS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Vf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Vf(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=>e0(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=t0(o.data,"return_indices");return i!==void 0&&n0(i,r)})}default:return e[0]}}function ZS(t){let e=t.match(YS);return e?e[1].trim():t}function Kn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vf(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function e0(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function t0(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 n0(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 mn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var se="0.1.0-alpha.6",Xf="v1.0.0";function Zf(){let t=ir(),e=qt(),n=wi();return{ok:!0,runtimeVersion:se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Za(t,e){return W(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:se})+`
67
+ `)}}],$A=Cd[Cd.length-1].version;import{Entry as PA}from"@napi-rs/keyring";var xd="AIFIGHT_KEYCHAIN_V1:",Id="AIFIGHT_CRYPTO_V1:";var xA=Buffer.byteLength(xd,"ascii"),IA=Buffer.byteLength(Id,"ascii");var dS=Ce(Pf(),1),fS=Ce(Yo(),1),mS=Ce(Un(),1),pS=Ce(ka(),1),hS=Ce(Aa(),1),gS=Ce(Oa(),1),La=Ce(ei(),1),yS=Ce(Mf(),1);var me=class extends Error{},Nt=class extends me{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Lt=class extends me{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},cn=class extends me{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Mt=class extends me{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},ln=class extends me{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},un=class extends me{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends me{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},rt=class extends me{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},wt=class extends me{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},vt=class extends me{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var jf=Ce(Fo(),1),Df=Ce(fa(),1);var ja=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),Da=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Bf="https://aifight.ai/protocol/v1/messages/";function _S(t){return`${Bf}client_${t}.schema.json`}function wS(t){return`${Bf}server_${t}.schema.json`}var Ma=null;function Ff(){if(Ma)return Ma;let t=new jf.default({strict:!1,allErrors:!0});(0,Df.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Ma=t,t}function Uf(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function qf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hf(t){if(!qf(t))throw new rt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new rt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(Da.has(e))throw new rt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!ja.has(e))throw new rt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...ja].join(", ")})`);let n=Ff(),r=_S(e),o=n.getSchema(r);if(!o)throw new rt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new rt(e,Uf(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function Ba(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let u=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${u}`)}if(!qf(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(!Da.has(r))throw ja.has(r)?new wt(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new wt(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...Da].join(", ")})`);let o=Ff(),i=wS(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,Uf(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var vS=1e4,bS=25e3;function Gf(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 Fa=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??bS;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=Ba(n)}catch(o){if(o instanceof Re||o instanceof wt)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 un(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Hf(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 Ua(t){let e=t.welcomeTimeoutMs??vS;return t.signal?.aborted?Promise.reject(new vt(`createWSClient aborted before start: ${Gf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new La.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(l){let d=l instanceof Error?l.message:String(l);r(new Nt(`failed to construct WebSocket for ${t.url}: ${d}`,l));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",()=>{})},u=l=>{i||(i=!0,c(),l())};t.signal&&(a=()=>{u(()=>{try{o.terminate()}catch{}r(new vt(`createWSClient aborted during handshake: ${Gf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",l=>{u(()=>{try{o.terminate()}catch{}r(new Nt(`WebSocket connect failed for ${t.url}: ${l.message}`,l))})}),o.once("unexpected-response",(l,d)=>{let h="";d.setEncoding("utf8"),d.on("data",p=>{h+=p}),d.on("end",()=>{let p=d.statusCode??0,f=d.statusMessage??"";try{l.destroy()}catch{}u(()=>r(new Lt(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;u(()=>r(new Lt(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{u(()=>{try{o.terminate()}catch{}r(new cn(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",l=>{let d=typeof l=="string"||Buffer.isBuffer(l)?l:Buffer.from(l),h;try{h=Ba(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 wt?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),u(()=>{try{o.terminate()}catch{}r(new Mt(S,R))});return}if(h.type!=="welcome"){u(()=>{try{o.terminate()}catch{}r(new Mt([],`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){u(()=>{try{o.terminate()}catch{}r(new ln(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}u(()=>{let v=new Fa(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}},SS=1e3,ES=2,kS=3e4,$S="full",RS=5*60*1e3,AS=15*60*1e3,PS=new Set([1001,1006,1011,1012]);function TS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function CS(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 xS(t){return t.code>=4e3&&t.code<5e3?!1:PS.has(t.code)}function IS(t){if(t instanceof vt||t instanceof Mt||t instanceof ln)return!1;if(t instanceof Nt||t instanceof cn)return!0;if(t instanceof Lt){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function OS(t){return t>=AS?"error":t>=RS?"warning":"info"}var qa=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 un(`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 Ua({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 u=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??u.code,closeReason:this.#i.reason??u.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!xS(u)){let l=new zn("fatal-close",void 0,`close code ${u.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:u.code,closeReason:u.reason,cause:l});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof me&&(e=a),!IS(a)){let c=a instanceof me?a:void 0,u=a instanceof vt?"signal":"fatal-error",l=a instanceof Error?a.message:"non-retriable error";this.#S(u,c,l);return}this.#u++,this.state="backoff"}let r=TS(this.#u,this.#e.initialBackoffMs??SS,this.#e.backoffFactor??ES,this.#e.maxBackoffMs??kS),o=CS(r,this.#e.jitter??$S),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"?OS(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let u of c)try{u(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 Ha(t){let e=new qa(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var NS=["check","call","fold","raise","allin"];function Ga(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 NS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Wa(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=LS(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=MS(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 LS(t){let e=jS(t);if(!e)return;let n=Va(e,"min_quantity"),r=Va(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Va(e,"max_quantity")}}function MS(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 jS(t){return t!==null&&typeof t=="object"?t:void 0}function Va(t,e){let n=t[e];return typeof n=="number"?n:void 0}var DS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],BS=["pass","challenge"],FS=["pass","block"],US=["lose_card"],qS=["return_cards"];function za(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 Hr(n,DS);case"challenge_action":case"challenge_block":return Hr(n,BS);case"block":return Hr(n,FS);case"lose_influence":return Hr(n,US);case"exchange_return":return Hr(n,qS);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function Hr(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var HS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ja(t,e,n=500){let r=t.trim(),o=WS(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 u=ni(c)?c:void 0;if(!GS.has(s))return dn("unknown_action_type",r,n);let l=e.find(d=>d.type===s);if(!l)return dn("action_not_legal",r,n);if(s==="raise"){let d=VS(l,u);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:l,summary:a}:{kind:"ok",action:l}}var GS=new Set(["fold","check","call","raise","allin"]);function VS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ni(t.data)?t.data:void 0,o=Ka(r,"amount"),i=Ka(r,"min")??o,s=Ka(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function WS(t){let e=t.match(HS);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 zS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Qa(t,e,n=500){let r=t.trim(),o=YS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!ri(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&&!ri(c))return fn("missing_fields",r,n);let u=ri(c)?c:void 0;if(!KS.has(s))return fn("unknown_action_type",r,n);let l=e.find(d=>d.type===s);if(!l)return fn("action_not_legal",r,n);if(s==="bid"){let d=JS(l,u);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:l,summary:a}:{kind:"ok",action:l}}var KS=new Set(["bid","challenge"]);function JS(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=ri(t.data)?t.data:void 0,i=Ya(o,"min_quantity"),s=Ya(o,"min_face"),a=Ya(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 YS(t){let e=t.match(zS);return e?e[1].trim():t}function ri(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ya(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var QS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,XS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Xa(t,e,n=500){let r=t.trim(),o=e0(r),i;try{i=JSON.parse(o)}catch{return mn("json_parse",r,n)}if(!Kn(i))return mn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return mn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Kn(c))return mn("missing_fields",r,n);let u=Kn(c)?c:void 0;if(!XS.has(s))return mn("unknown_action_type",r,n);let l=e.filter(h=>h.type===s);if(l.length===0)return mn("action_not_legal",r,n);let d=ZS(s,l,u);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:mn("data_validation",r,n)}function ZS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Vf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Vf(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=>t0(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=n0(o.data,"return_indices");return i!==void 0&&r0(i,r)})}default:return e[0]}}function e0(t){let e=t.match(QS);return e?e[1].trim():t}function Kn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vf(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function t0(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function n0(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 r0(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 mn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var se="0.1.0-alpha.7",Xf="v1.0.0";function Zf(){let t=sr(),e=qt(),n=wi();return{ok:!0,runtimeVersion:se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Za(t,e){return z(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:se})+`
68
68
  `):e.stdout(`${se}
69
- `),0}import Hr from"node:fs";import i0 from"node:path";var Ge=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 Ge("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Ge("runtime URL must use http:// or https://");if(!l0(r.hostname))throw new Ge("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new Ge("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new Ge("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function jt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function tc(){return i0.join(oe(),"bridge.json")}function em(){Hr.rmSync(tc(),{force:!0})}function pn(t){at();let e=tc(),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 ne(){let t=tc(),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(!a0(n))throw new Error("bridge config is invalid; run connect again");return n}function Dt(t){return{...t,apiKey:ec(t.apiKey),...t.claimUrl!==void 0?{claimUrl:s0(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:ec(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:ec(t.runtimeLocalToken)}:{}}}function ec(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function s0(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 a0(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"&&c0(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 c0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Gr(t,e),!0}catch{return!1}}function l0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var u0="npm install -g @aifight/aifight@alpha";async function je(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${f0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return nc(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=m0(s);return a===null?nc(t.currentVersion,"version check returned invalid policy"):d0(t.currentVersion,a)}catch(i){let s=i?.name;return nc(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function d0(t,e){let n=tm(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=tm(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 nc(t,e){return{status:"unknown",currentVersion:t,message:e}}function f0(t){return t.replace(/\/+$/,"")}function m0(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:u0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function tm(t,e){let n=nm(t),r=nm(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 p0(n.prerelease,r.prerelease)}function nm(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 p0(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 h0=1500;async function rm(t,e){W(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Zf)()}catch(i){return t.jsonMode?e.stderr(JSON.stringify({error:{code:"client_doctor_schema",message:i.message}})+`
69
+ `),0}import Gr from"node:fs";import s0 from"node:path";var Ge=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 Vr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new Ge("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Ge("runtime URL must use http:// or https://");if(!u0(r.hostname))throw new Ge("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new Ge("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new Ge("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function jt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function tc(){return s0.join(oe(),"bridge.json")}function em(){Gr.rmSync(tc(),{force:!0})}function pn(t){at();let e=tc(),n=`${e}.tmp`;if(Gr.writeFileSync(n,JSON.stringify(t,null,2)+`
70
+ `,{mode:384}),Gr.renameSync(n,e),process.platform!=="win32")try{Gr.chmodSync(e,384)}catch{}}function W(){let t=tc(),e;try{e=Gr.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(!c0(n))throw new Error("bridge config is invalid; run connect again");return n}function Dt(t){return{...t,apiKey:ec(t.apiKey),...t.claimUrl!==void 0?{claimUrl:a0(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:ec(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:ec(t.runtimeLocalToken)}:{}}}function ec(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function a0(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 c0(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"&&l0(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 l0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Vr(t,e),!0}catch{return!1}}function u0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var d0="npm install -g @aifight/aifight@alpha";async function je(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${m0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return nc(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=p0(s);return a===null?nc(t.currentVersion,"version check returned invalid policy"):f0(t.currentVersion,a)}catch(i){let s=i?.name;return nc(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function f0(t,e){let n=tm(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=tm(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 nc(t,e){return{status:"unknown",currentVersion:t,message:e}}function m0(t){return t.replace(/\/+$/,"")}function p0(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:d0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function tm(t,e){let n=nm(t),r=nm(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 h0(n.prerelease,r.prerelease)}function nm(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 h0(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 g0=1500;async function rm(t,e){z(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Zf)()}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 g0(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 y0(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 : aifight update --yes"),o.push(` manual npm : ${r.update.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}`))),o.push(""),e.stdout(o.join(`
74
- `)),0}async function g0(t,e){try{let n=ne(),r=await je({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Dt(n),runtime:await y0(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 y0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??jt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),h0);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=_0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${w0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function _0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function w0(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 tE from"node:os";import{randomBytes as nE}from"node:crypto";import{execFile as v0}from"node:child_process";import Pe from"node:fs";import rc from"node:os";import bt from"node:path";import{promisify as b0}from"node:util";var Ft="aifight.service",oi="ai.aifight.service",Q=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},S0=b0(v0),Ve=async(t,e)=>{try{let{stdout:n,stderr:r}=await S0(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 oc(t={}){let e=await Qn(t),n=t.execFile??Ve;E0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",ot(t),e.unitPath]);let o=await ic(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",Ft]),e.platform==="linux-systemd-user"){let o=await R0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await P0(e,t),new Q("service_install_failed",`failed to install ${Ft}: ${Yn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function ii(t={}){let e=await Qn(t),n=t.execFile??Ve;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),e;let r=hn(e.platform);return await n("systemctl",[...r,"disable","--now",Ft]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function am(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",ot(t),e.unitPath]).catch(()=>{}),await ic(t),e):(await n("systemctl",[...hn(e.platform),"start",Ft]),e)}async function cm(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...hn(e.platform),"stop",Ft]),e)}async function zr(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",ot(t),e.unitPath]),await ic(t),e):(await n("systemctl",[...hn(e.platform),"restart",Ft]),e)}async function St(t={}){let e=await Qn(t),n=t.execFile??Ve;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",`${ot(t)}/${oi}`]),{...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",Ft])).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??rc.homedir(),o=t.runtimeHome??oe(),i=await A0(t),s=T0(t);if(e==="linux")return await om("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??bt.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await om("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??bt.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new Q("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function E0(t){Pe.mkdirSync(bt.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?$0(t):k0(t);C0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function k0(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=${im(t.nodeExec)} ${im(t.aifightExec)} run`,sm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),sm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
- `)}function $0(t){let e=bt.dirname(t.unitPath).includes("LaunchAgents")?bt.join(rc.homedir(),"Library","Logs","aifight"):bt.join(bt.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>${oi}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Vr(t.nodeExec)}</string>`,` <string>${Vr(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Vr(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Vr(bt.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Vr(bt.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
- `)}function hn(t){return t==="linux-systemd-user"?["--user"]:[]}function ot(t){return`gui/${t.uid??process.getuid?.()??0}`}async function ic(t){let e=t.execFile??Ve,n=`${ot(t)}/${oi}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${oi} is loaded: ${Yn(r)}`}catch{throw r}}}async function R0(t){let e=t.username??rc.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??Ve;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 P0(t,e){let n=e.execFile??Ve;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",ot(e),t.unitPath]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0});return}let r=hn(t.platform);await n("systemctl",[...r,"disable","--now",Ft]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function A0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Wr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!x0(n))try{return Wr(n)}catch{}let r=t.execFile??Ve;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
- `)[0];if(i)return Wr(i)}catch{}throw new Q("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 T0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Wr(e);try{return Wr(process.execPath)}catch{throw new Q("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 Wr(t){let e=Pe.realpathSync(t);return Pe.accessSync(e,Pe.constants.X_OK),e}function x0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function om(t,e,n){let r=n.execFile??Ve;try{await r(t,e)}catch(o){throw new Q("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 im(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function sm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function C0(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 Vr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var sc=["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 um(t,e){W(t,1,1,sc);let n=t.positional[0],r=I0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",sc);try{switch(n){case"install":{ne();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await oc(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
74
+ `)),0}async function y0(t,e){try{let n=W(),r=await je({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Dt(n),runtime:await _0(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 _0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??jt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),g0);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=w0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${v0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function w0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function v0(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 nE from"node:os";import{randomBytes as rE}from"node:crypto";import{execFile as b0}from"node:child_process";import Ae from"node:fs";import rc from"node:os";import bt from"node:path";import{promisify as S0}from"node:util";var Bt="aifight.service",oi="ai.aifight.service",X=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},E0=S0(b0),Ve=async(t,e)=>{try{let{stdout:n,stderr:r}=await E0(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 oc(t={}){let e=await Qn(t),n=t.execFile??Ve;k0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",ot(t),e.unitPath]);let o=await ic(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",Bt]),e.platform==="linux-systemd-user"){let o=await A0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await P0(e,t),new X("service_install_failed",`failed to install ${Bt}: ${Yn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function ii(t={}){let e=await Qn(t),n=t.execFile??Ve;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),Ae.rmSync(e.unitPath,{force:!0}),e;let r=hn(e.platform);return await n("systemctl",[...r,"disable","--now",Bt]).catch(()=>{}),Ae.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function am(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",ot(t),e.unitPath]).catch(()=>{}),await ic(t),e):(await n("systemctl",[...hn(e.platform),"start",Bt]),e)}async function cm(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...hn(e.platform),"stop",Bt]),e)}async function Kr(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",ot(t),e.unitPath]),await ic(t),e):(await n("systemctl",[...hn(e.platform),"restart",Bt]),e)}async function St(t={}){let e=await Qn(t),n=t.execFile??Ve;if(!Ae.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${ot(t)}/${oi}`]),{...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",Bt])).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??rc.homedir(),o=t.runtimeHome??oe(),i=await T0(t),s=C0(t);if(e==="linux")return await om("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??bt.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await om("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??bt.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new X("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function k0(t){Ae.mkdirSync(bt.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?R0(t):$0(t);I0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function $0(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=${im(t.nodeExec)} ${im(t.aifightExec)} run`,sm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),sm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
+ `)}function R0(t){let e=bt.dirname(t.unitPath).includes("LaunchAgents")?bt.join(rc.homedir(),"Library","Logs","aifight"):bt.join(bt.dirname(t.unitPath),"logs");return Ae.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>${oi}</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(bt.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Wr(bt.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
+ `)}function hn(t){return t==="linux-systemd-user"?["--user"]:[]}function ot(t){return`gui/${t.uid??process.getuid?.()??0}`}async function ic(t){let e=t.execFile??Ve,n=`${ot(t)}/${oi}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${oi} is loaded: ${Yn(r)}`}catch{throw r}}}async function A0(t){let e=t.username??rc.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??Ve;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 P0(t,e){let n=e.execFile??Ve;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",ot(e),t.unitPath]).catch(()=>{}),Ae.rmSync(t.unitPath,{force:!0});return}let r=hn(t.platform);await n("systemctl",[...r,"disable","--now",Bt]).catch(()=>{}),Ae.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function T0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return zr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!x0(n))try{return zr(n)}catch{}let r=t.execFile??Ve;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
+ `)[0];if(i)return zr(i)}catch{}throw new X("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 C0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return zr(e);try{return zr(process.execPath)}catch{throw new X("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 zr(t){let e=Ae.realpathSync(t);return Ae.accessSync(e,Ae.constants.X_OK),e}function x0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function om(t,e,n){let r=n.execFile??Ve;try{await r(t,e)}catch(o){throw new X("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 im(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function sm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function I0(t,e,n){let r=`${t}.${process.pid}.tmp`;Ae.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Ae.chmodSync(r,n),Ae.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 sc=["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 um(t,e){z(t,1,1,sc);let n=t.positional[0],r=O0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",sc);try{switch(n){case"install":{W();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await oc(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}
@@ -87,195 +87,198 @@ CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
87
87
  `),e.stdout(`run: aifight service install
88
88
  `)),0}case"start":{let o=await am(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
89
89
  `),0}case"stop":{let o=await cm(e.bridgeService);return e.stdout(`aifight.service stopped (${o.platform}).
90
- `),0}case"restart":{let o=await zr(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
90
+ `),0}case"restart":{let o=await Kr(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
91
91
  `),0}case"uninstall":{let o=await ii(e.bridgeService);return e.stdout(`aifight.service uninstalled (${o.platform}).
92
- `),0}default:throw new O(`unknown service command '${n}'`,sc)}}catch(o){if(o instanceof O)throw o;if(o instanceof Q)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}'`,sc)}}catch(o){if(o instanceof O)throw o;if(o instanceof X)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 I0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function dm(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";let n=await O0(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(`
97
+ `),1}}function O0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function dm(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";let n=await N0(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
98
  `)),!(e.approvedLocalSetup===!0?!0:await lm(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 zr(t.bridgeService);return t.stdout(`aifight.service restarted (${i.platform}).
99
+ `);try{let i=await Kr(t.bridgeService);return t.stdout(`aifight.service restarted (${i.platform}).
100
100
  `),t.stdout(`unit: ${i.unitPath}
101
- `),"installed"}catch(i){let s=(i instanceof Q,i.message),a=i instanceof Q?i.hint:void 0;return t.stderr(`aifight.service could not be restarted: ${s}
101
+ `),"installed"}catch(i){let s=(i instanceof X,i.message),a=i instanceof X?i.hint:void 0;return t.stderr(`aifight.service could not be restarted: ${s}
102
102
  `),a&&t.stderr(`${a}
103
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
104
  `)),!(e.approvedLocalSetup===!0?!0:await lm(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
105
  `);try{let o=await oc(t.bridgeService);return t.stdout(`aifight.service installed and started (${o.platform}).
106
106
  `),t.stdout(`unit: ${o.unitPath}
107
107
  `),o.warning&&t.stderr(`warning: ${o.warning}
108
- `),"installed"}catch(o){let i=(o instanceof Q,o.message),s=o instanceof Q?o.hint:void 0;return t.stderr(`aifight.service could not be installed: ${i}
108
+ `),"installed"}catch(o){let i=(o instanceof X,o.message),s=o instanceof X?o.hint:void 0;return t.stderr(`aifight.service could not be installed: ${i}
109
109
  `),s&&t.stderr(`${s}
110
- `),"unavailable"}}async function O0(t){try{return await St(t.bridgeService)}catch{return}}async function lm(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 N0}from"node:child_process";import fm from"node:fs";import mm from"node:path";var L0=3e4;function Ae(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(mm.delimiter))if(r)for(let o of n){let i=mm.join(r,`${t}${o}`);try{return fm.accessSync(i,fm.constants.X_OK),i}catch{}}}async function it(t,e){let n=Ae(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};N0(n,e,{timeout:L0},(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()}
110
+ `),"unavailable"}}async function N0(t){try{return await St(t.bridgeService)}catch{return}}async function lm(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 L0}from"node:child_process";import fm from"node:fs";import mm from"node:path";var M0=3e4;function Pe(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(mm.delimiter))if(r)for(let o of n){let i=mm.join(r,`${t}${o}`);try{return fm.accessSync(i,fm.constants.X_OK),i}catch{}}}async function it(t,e){let n=Pe(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};L0(n,e,{timeout:M0},(a,c,u)=>{let l=a?.code;i({code:typeof l=="number"?l:a?1:0,stdout:String(c??""),stderr:String(u??"")})}).on("error",a=>{i({code:1,stdout:"",stderr:a.message})})})}function gn(t,e,n){n.stdout.trim()&&t.stdout(`${e}: ${n.stdout.trim()}
111
111
  `),n.stderr.trim()&&t.stderr(`${e}: ${n.stderr.trim()}
112
- `)}async function si(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 Kr(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 M0(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: ${B0(e)}`,""].join(`
112
+ `)}async function si(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 Xn(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 Zn(t,e,n,r={}){let o=await j0(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: ${U0(e)}`,""].join(`
113
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(`
114
114
  `)+`
115
- `),!(r.approvedLocalSetup===!0?!0:await Kr(t,"Restart now? [y/N] ")))return t.stdout(`Skipped restart. Run when ready: ${o.manualCommand}
115
+ `),!(r.approvedLocalSetup===!0?!0:await Xn(t,"Restart now? [y/N] ")))return t.stdout(`Skipped restart. Run when ready: ${o.manualCommand}
116
116
 
117
117
  `),!1;r.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting now.
118
118
  `);let a=await it(o.command,o.args);return gn(t,o.manualCommand,a),e==="hermes"&&F0(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}
119
119
 
120
120
  `),!1):(t.stdout(`${i} restart requested.
121
121
 
122
- `),!0)}async function M0(t){let e=await j0(t);if(e)return e;if(t==="openclaw"&&Ae("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"&&Ae("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 j0(t){if(process.platform!=="linux"||!Ae("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 it("systemctl",[...n,"is-active",r]);if(D0(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 D0(t){return t.code===0&&t.stdout.trim()==="active"}function F0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
123
- ${t.stderr}`)}function B0(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 H0}from"node:crypto";import Zn from"node:fs";import G0 from"node:os";import hm from"node:path";import Jr from"node:fs";import U0 from"node:path";function ac(){return U0.join(oe(),"runtime-setup.json")}function cc(){try{let t=Jr.readFileSync(ac(),"utf8"),e=JSON.parse(t);return q0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function lc(t){at();let e=cc(),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=ac(),o=`${r}.tmp`;if(Jr.writeFileSync(o,JSON.stringify(n,null,2)+`
124
- `,{mode:384}),Jr.renameSync(o,r),process.platform!=="win32")try{Jr.chmodSync(r,384)}catch{}}function pm(){Jr.rmSync(ac(),{force:!0})}function q0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var dc="gateway.http.endpoints.responses.enabled",gm=4e3,V0=6e3,ym=1e4;async function _m(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return W0(t);case"hermes":return z0(t);case"mock":return{}}}async function W0(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}).
122
+ `),!0)}async function j0(t){let e=await D0(t);if(e)return e;if(t==="openclaw"&&Pe("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"&&Pe("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 D0(t){if(process.platform!=="linux"||!Pe("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 it("systemctl",[...n,"is-active",r]);if(B0(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 B0(t){return t.code===0&&t.stdout.trim()==="active"}function F0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
123
+ ${t.stderr}`)}function U0(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 G0}from"node:crypto";import er from"node:fs";import V0 from"node:os";import hm from"node:path";import Jr from"node:fs";import q0 from"node:path";function ac(){return q0.join(oe(),"runtime-setup.json")}function cc(){try{let t=Jr.readFileSync(ac(),"utf8"),e=JSON.parse(t);return H0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function lc(t){at();let e=cc(),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=ac(),o=`${r}.tmp`;if(Jr.writeFileSync(o,JSON.stringify(n,null,2)+`
124
+ `,{mode:384}),Jr.renameSync(o,r),process.platform!=="win32")try{Jr.chmodSync(r,384)}catch{}}function pm(){Jr.rmSync(ac(),{force:!0})}function H0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var dc="gateway.http.endpoints.responses.enabled",gm=4e3,W0=6e3,ym=1e4;async function _m(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return z0(t);case"hermes":return K0(t);case"mock":return{}}}async function z0(t){let e=await tr(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}).
125
125
 
126
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}).
127
127
 
128
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
129
  `)),!(t.approvedLocalSetup===!0?!0:await si(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 X0();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}).
130
+ `);let l=await Z0();if(l.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 l){let h=await tr(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}).
131
131
 
132
132
  `),{runtimeLocalToken:d}}return t.env.stdout(`OpenClaw did not accept any discovered local Gateway token.
133
133
 
134
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 ${dc} true --strict-json`," openclaw config validate",""].join(`
135
- `)),!Ae("openclaw"))return t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
135
+ `)),!Pe("openclaw"))return t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
136
136
 
137
137
  `),{};if(!(t.approvedLocalSetup===!0?!0:await si(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.
138
138
 
139
139
  `),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; applying OpenClaw config now.
140
- `);let r=await eE(),o=await it("openclaw",["config","set",dc,"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.
140
+ `);let r=await tE(),o=await it("openclaw",["config","set",dc,"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.
141
141
 
142
142
  `),{};let i=await it("openclaw",["config","validate"]);gn(t.env,"openclaw config validate",i),lc({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 fc(V0);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}
143
+ `),await fc(W0);let s=await tr(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}
144
144
 
145
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.
146
+ `),!await Zn(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.
147
147
 
148
148
  `),{};t.env.stdout(`Waiting 10 seconds before checking OpenClaw /v1/responses again...
149
- `),await fc(ym);let c=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);return t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
149
+ `),await fc(ym);let c=await tr(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);return t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
150
150
 
151
- `),{}}async function z0(t){let e=await ai(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}).
151
+ `),{}}async function K0(t){let e=await ai(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
152
 
153
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=${vm(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
154
- `)),!Ae("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
154
+ `)),!Pe("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
155
155
 
156
156
  `),{};if(!(t.approvedLocalSetup===!0?!0:await si(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.
157
157
 
158
158
  `),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; updating Hermes .env now.
159
- `);let r=K0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(lc({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=J0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(lc({hermes:{envPath:r.envPath,previous:r.previous,updatedAt:new Date().toISOString()}}),t.env.stdout(`Hermes .env updated and backed up if it already existed.
160
160
  `),t.env.stdout(`Hermes does not hot-reload API_SERVER_* settings.
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.
161
+ `),!await Zn(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.
162
162
 
163
163
  `),{runtimeLocalToken:o};t.env.stdout(`Waiting 10 seconds before checking Hermes /v1/responses again...
164
164
  `),await fc(ym);let s=await ai(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
165
165
 
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(),gm);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 ai(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await uc(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 uc(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 uc(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 uc(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),gm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function K0(t){let e=process.env.HERMES_HOME??hm.join(G0.homedir(),".hermes");Zn.mkdirSync(e,{recursive:!0,mode:448});let n=hm.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=wm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${H0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:Y0(t.runtimeLocalUrl),API_SERVER_PORT:String(vm(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=Q0(r,Object.keys(s)),c=J0(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 J0(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 tr(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),gm);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 ai(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await uc(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 uc(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 u={"Content-Type":"application/json",...a},l;try{l=await uc(o,`${i}/v1/responses`,{method:"POST",headers:u,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 l.status===404?{status:"disabled",detail:"Hermes /v1/responses returned HTTP 404"}:l.status===401||l.status===403?{status:"auth_failed",detail:`Hermes /v1/responses HTTP ${l.status}; check API_SERVER_KEY and --runtime-token`}:l.ok?{status:"ready",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${l.status}`}:{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${l.status}`}}catch(s){return{status:"unreachable",detail:`Hermes API Server is not reachable (${s instanceof Error?s.message:String(s)})`}}}async function uc(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),gm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function J0(t){let e=process.env.HERMES_HOME??hm.join(V0.homedir(),".hermes");er.mkdirSync(e,{recursive:!0,mode:448});let n=hm.join(e,".env"),r=er.existsSync(n)?er.readFileSync(n,"utf8"):"";if(r!==""){let u=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");er.copyFileSync(n,`${n}.aifight-backup-${u}`)}let o=wm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${G0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:Q0(t.runtimeLocalUrl),API_SERVER_PORT:String(vm(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=X0(r,Object.keys(s)),c=Y0(r,s);if(er.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{er.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function Y0(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(`
167
167
  `).replace(/\n*$/,`
168
- `)}function wm(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 Y0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function vm(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function Q0(t,e){let n={};for(let r of e){let o=wm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function X0(){let t=[],e=o=>{o&&!t.includes(o)&&t.push(o)},n=process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e(n),!Ae("openclaw"))return t;let r=await it("openclaw",["config","get","gateway.auth.token"]);return r.code===0&&e(Z0(r.stdout)),t}function Z0(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 eE(){let t=await it("openclaw",["config","get",dc]);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 fc(t){return new Promise(e=>setTimeout(e,t))}var rE="https://aifight.ai",bm=2,oE="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 Em(t,e){W(t,0,1,yn);let n=t.flags[oE]===!0;if(t.jsonMode&&n)throw new O("--approved-local-setup cannot be combined with --json",yn);let r=await iE(t,e,n),o=cE(t,r),i=lE(process.env.AIFIGHT_BASE_URL??rE),s=Yr(t.flags,"runtime-model")??jt(r),a=dE(Yr(t.flags,"runtime-url")??Jn(r),r),c=Yr(t.flags,"runtime-token");try{let l=await _m({env:e,runtimeType:r,runtimeLocalUrl:a,runtimeLocalToken:c,runtimeModel:s,jsonMode:t.jsonMode,approvedLocalSetup:n});if(l.blockedReason!==void 0)throw new U("runtime_setup_incomplete",l.blockedReason);c=c??l.runtimeLocalToken;let u=await ma({baseUrl:i,request:{name:o,model:s,description:`AIFight Bridge agent (${r})`},fetchImpl:e.fetchImpl}),d={version:1,baseUrl:i,wsUrl:uE(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:bm,updatedAt:new Date().toISOString()};return pn(d),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:u.claimUrl,config:Dt(d)})+`
168
+ `)}function wm(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 Q0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function vm(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function X0(t,e){let n={};for(let r of e){let o=wm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function Z0(){let t=[],e=o=>{o&&!t.includes(o)&&t.push(o)},n=process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e(n),!Pe("openclaw"))return t;let r=await it("openclaw",["config","get","gateway.auth.token"]);return r.code===0&&e(eE(r.stdout)),t}function eE(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 tE(){let t=await it("openclaw",["config","get",dc]);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 fc(t){return new Promise(e=>setTimeout(e,t))}var oE="https://aifight.ai",bm=2,iE="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 Em(t,e){z(t,0,1,yn);let n=dE();if(n!==void 0)throw new B("bridge_already_configured",[`This machine already has local AIFight bridge credentials for ${n.agentName} (${n.agentId}).`,"Register creates a new bootstrap Agent and would replace the local identity, so it is blocked by default.","Use `aifight update --yes` to upgrade the CLI, `aifight service install` to restore the background service,","or use Dashboard `Connect Bridge` plus `aifight connect <PAIRING_CODE>` to authorize this machine for an existing claimed Agent.","If you intentionally want to remove this local identity first, run `aifight uninstall`."].join(`
170
+ `));let r=t.flags[iE]===!0;if(t.jsonMode&&r)throw new O("--approved-local-setup cannot be combined with --json",yn);let o=await sE(t,e,r),i=lE(t,o),s=uE(process.env.AIFIGHT_BASE_URL??oE),a=Yr(t.flags,"runtime-model")??jt(o),c=mE(Yr(t.flags,"runtime-url")??Jn(o),o),u=Yr(t.flags,"runtime-token");try{let l=await _m({env:e,runtimeType:o,runtimeLocalUrl:c,runtimeLocalToken:u,runtimeModel:a,jsonMode:t.jsonMode,approvedLocalSetup:r});if(l.blockedReason!==void 0)throw new B("runtime_setup_incomplete",l.blockedReason);u=u??l.runtimeLocalToken;let d=await ma({baseUrl:s,request:{name:i,model:a,description:`AIFight Bridge agent (${o})`},fetchImpl:e.fetchImpl}),h={version:1,baseUrl:s,wsUrl:fE(s),agentId:d.agentId,agentName:d.response.agent.name,suggestedName:d.response.agent.suggested_name??i,apiKey:d.apiKey,claimUrl:d.claimUrl,claimToken:d.claimToken,runtimeType:o,runtimeLocalUrl:c,...u!==void 0?{runtimeLocalToken:u}:{},runtimeModel:a,autoDailyLimit:bm,updatedAt:new Date().toISOString()};return pn(h),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:d.claimUrl,config:Dt(h)})+`
170
171
  `),0):(e.stdout(`AIFight Agent registered.
171
172
 
172
- `),e.stdout(`Bootstrap ID: ${d.agentName}
173
- `),e.stdout(`Suggested name: ${d.suggestedName??o}
173
+ `),e.stdout(`Bootstrap ID: ${h.agentName}
174
+ `),e.stdout(`Suggested name: ${h.suggestedName??i}
174
175
  `),e.stdout(`Status: unclaimed, official name pending
175
- `),e.stdout(`Runtime: ${km(d.runtimeType)} at ${d.runtimeLocalUrl}
176
+ `),e.stdout(`Runtime: ${km(h.runtimeType)} at ${h.runtimeLocalUrl}
176
177
  `),e.stdout(`Automatic ranked matches: ${bm} per day
177
178
  `),e.stdout(`Local credentials saved on this machine.
178
179
 
179
180
  `),e.stdout(`Claim URL:
180
- `),e.stdout(`${u.claimUrl}
181
+ `),e.stdout(`${d.claimUrl}
181
182
 
182
183
  `),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.
183
184
 
184
- `),await dm(e,{approvedLocalSetup:n})==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
185
+ `),await dm(e,{approvedLocalSetup:r})==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
185
186
 
186
187
  `),e.stdout(`Normal use requires a long-running local Bridge.
187
188
  `),e.stdout(`Finish setup with:
188
189
  `),e.stdout(` aifight service install
189
190
 
190
191
  `),e.stdout(`Advanced alternatives:
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 Zt){let u=typeof l.body=="object"?l.body.error:void 0;throw new U("registration_failed",u??`registration failed with HTTP ${l.status}`)}throw l instanceof pt?new U("registration_failed",l.message):l}}function km(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function iE(t,e,n){let r=t.positional[0],o=Yr(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 sE(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${km(a.runtimeType)} (${a.detail}).
192
+ `),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 Zt){let d=typeof l.body=="object"?l.body.error:void 0;throw new B("registration_failed",d??`registration failed with HTTP ${l.status}`)}throw l instanceof pt?new B("registration_failed",l.message):l}}function km(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function sE(t,e,n){let r=t.positional[0],o=Yr(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 aE(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${km(a.runtimeType)} (${a.detail}).
192
193
 
193
194
  `),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(`
194
- `),yn)}return!t.jsonMode&&process.stdin.isTTY?aE(e):"openclaw"}throw new O(`runtime must be openclaw or hermes (got '${s}')`,yn)}async function sE(t){let[e,n]=await Promise.all([er(t,Jn("openclaw"),void 0,jt("openclaw")),ai(t,Jn("hermes"),void 0,jt("hermes"))]),r=Sm(e),o=Sm(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=Ae("openclaw")!==void 0,s=Ae("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 Sm(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function aE(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 cE(t,e){let n=Yr(t.flags,"name");if(n!==void 0)return n;let r=tE.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${nE(3).toString("hex")}`.slice(0,50)}function lE(t){return t.replace(/\/+$/,"")}function uE(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 Yr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function dE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof Ge?new O(n.message,yn):n}}var fE="https://aifight.ai";async function $m(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=mE(t.baseUrl??process.env.AIFIGHT_BASE_URL??fE),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 pE(o);throw new Error(l)}let i=await o.json(),s=hE(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:jt(a),updatedAt:c().toISOString()}}function mE(t){return t.replace(/\/+$/,"")}async function pE(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 hE(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 Pm=["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 Am(t,e){W(t,1,1,Pm);let n=t.positional[0],r;try{r=await $m({pairingCode:n,fetchImpl:e.fetchImpl})}catch(l){let u=l instanceof Error?l.message:String(l);throw new U("pairing_failed",u)}let o={...r,...Rm(t.flags,"runtime-token","runtimeLocalToken"),...Rm(t.flags,"runtime-model","runtimeModel")},i=t.flags["runtime-url"],s=typeof i=="string"&&i.trim()!==""?i.trim():void 0,a=gE(s??o.runtimeLocalUrl,o.runtimeType),c={...o,runtimeLocalUrl:a};return pn(c),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Dt(c)})+`
197
- `),0):(e.stdout(`Bridge configured for ${c.agentName} (${c.runtimeType}).
198
- `),e.stdout(`Runtime local URL: ${c.runtimeLocalUrl}
199
- `),c.runtimeLocalToken&&e.stdout(`Runtime local token: configured locally (redacted)
195
+ `),yn)}return!t.jsonMode&&process.stdin.isTTY?cE(e):"openclaw"}throw new O(`runtime must be openclaw or hermes (got '${s}')`,yn)}async function aE(t){let[e,n]=await Promise.all([tr(t,Jn("openclaw"),void 0,jt("openclaw")),ai(t,Jn("hermes"),void 0,jt("hermes"))]),r=Sm(e),o=Sm(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=Pe("openclaw")!==void 0,s=Pe("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 Sm(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function cE(t){t.stdout(["Which local Agent runtime should this Bridge use?"," 1) OpenClaw (default)"," 2) Hermes","","Runtime [OpenClaw]: "].join(`
196
+ `)),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 lE(t,e){let n=Yr(t.flags,"name");if(n!==void 0)return n;let r=nE.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${rE(3).toString("hex")}`.slice(0,50)}function uE(t){return t.replace(/\/+$/,"")}function dE(){try{return W()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}function fE(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 Yr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function mE(t,e){try{return Vr(t,e)}catch(n){throw n instanceof Ge?new O(n.message,yn):n}}var pE="https://aifight.ai";async function $m(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=hE(t.baseUrl??process.env.AIFIGHT_BASE_URL??pE),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 u=await gE(o);throw new Error(u)}let i=await o.json(),s=yE(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:jt(a),updatedAt:c().toISOString()}}function hE(t){return t.replace(/\/+$/,"")}async function gE(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 yE(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 Pm=["usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--replace-local-identity]"," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," --runtime-token is local only; it is never sent to AIFight."," --replace-local-identity confirms that an existing local bridge identity may be replaced."].join(`
197
+ `);async function Tm(t,e){z(t,1,1,Pm);let n=t.positional[0],r=t.flags["runtime-url"],o=typeof r=="string"&&r.trim()!==""?Am(r.trim(),"openclaw"):void 0,i=_E(),s=t.flags["replace-local-identity"]===!0;if(i!==void 0&&!s)throw new B("local_identity_exists",[`This machine already has local AIFight bridge credentials for ${i.agentName} (${i.agentId}).`,"A pairing code rotates an Agent API key and replaces local bridge credentials.","To avoid consuming a one-time pairing code by accident, this command is blocked until you approve local identity replacement.","If you are intentionally reconnecting this machine from Dashboard, rerun:",` aifight connect ${n} --replace-local-identity`].join(`
198
+ `));let a;try{a=await $m({pairingCode:n,fetchImpl:e.fetchImpl})}catch(d){let h=d instanceof Error?d.message:String(d);throw new B("pairing_failed",h)}let c={...a,...Rm(t.flags,"runtime-token","runtimeLocalToken"),...Rm(t.flags,"runtime-model","runtimeModel")},u=Am(o??c.runtimeLocalUrl,c.runtimeType),l={...c,runtimeLocalUrl:u};return pn(l),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Dt(l)})+`
199
+ `),0):(i!==void 0&&e.stdout(`Replaced local bridge identity ${i.agentName} (${i.agentId}).
200
+ `),e.stdout(`Bridge configured for ${l.agentName} (${l.runtimeType}).
201
+ `),e.stdout(`Runtime local URL: ${l.runtimeLocalUrl}
202
+ `),l.runtimeLocalToken&&e.stdout(`Runtime local token: configured locally (redacted)
200
203
  `),e.stdout(`Next: aifight service install
201
- `),0)}function Rm(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function gE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof Ge?new O(n.message,Pm):n}}var mc=20,ci=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${mc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${he.join(", ")}`].join(`
202
- `);async function Cm(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,ci)}let n=yE(),r=_E(t.positional,n),o=await je({baseUrl:n.baseUrl,currentVersion:se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
204
+ `),0)}function _E(){try{return W()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}function Rm(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function Am(t,e){try{return Vr(t,e)}catch(n){throw n instanceof Ge?new O(n.message,Pm):n}}var mc=20,ci=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${mc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${he.join(", ")}`].join(`
205
+ `);async function Im(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,ci)}let n=wE(),r=vE(t.positional,n),o=await je({baseUrl:n.baseUrl,currentVersion:se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
203
206
  `),e.stderr(`Run: aifight update --yes
204
207
  `),e.stderr(`Manual npm command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
205
208
  `),1;o.status==="update_recommended"&&(e.stdout(`[warn] bridge.update: ${o.message}
206
209
  `),e.stdout(`[warn] update when ready: aifight update --yes
207
- `));try{await Dc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof pe?new U(wE(i),vE(i),{hint:await bE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
208
- `);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${SE(r.game)} ${i} for ${n.agentName}.
210
+ `));try{await Dc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof pe?new B(bE(i),SE(i),{hint:await EE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
211
+ `);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${kE(r.game)} ${i} for ${n.agentName}.
209
212
  `),e.stdout(`The running Bridge will keep your Agent online and handle the match when AIFight pairs it.
210
- `)}return 0}function yE(){try{return ne()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new U("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 _E(t,e){if(t.length===0)return{game:xm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Tm(n);if(i!==null)return{game:xm(e.autoGames),count:i};if(ct(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,ci)}let r=t[1];if(!ct(n))throw new O(`unsupported game '${n}'`,ci);let o=Tm(r);if(o===null)throw new O(`N must be an integer between 1 and ${mc}`,ci);return{game:n,count:o}}function Tm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>mc?null:e}function xm(t){let e=(t??he).filter(ct),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}function wE(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 vE(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 bE(t){try{let e=await St(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 Q))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function SE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Bt from"node:path";import te from"node:fs";import EE from"node:crypto";var _e=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 Om(){return Bt.join(oe(),"token")}function Nm(){return Bt.join(oe(),"port")}function hc(){return Bt.join(oe(),"pid")}function kE(){return Bt.join(oe(),"lock")}var Im=0,$E=/^[0-9a-f]{64}$/;function gc(t,e,n){let r=Bt.dirname(t),o=Bt.basename(t);Im+=1;let i=Bt.join(r,`${o}.${process.pid}.${Im}.tmp`),s;try{if(s=te.openSync(i,"w",n),te.writeSync(s,e),te.closeSync(s),s=void 0,process.platform!=="win32")try{te.chmodSync(i,n)}catch{}te.renameSync(i,t)}catch(a){if(s!==void 0)try{te.closeSync(s)}catch{}try{te.unlinkSync(i)}catch{}throw new _e("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Lm(){return EE.randomBytes(32).toString("hex")}function Mm(t){let e=Om();if(!$E.test(t))throw new _e("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);gc(e,t,384)}function jm(t){let e=Nm();if(!Number.isInteger(t)||t<1||t>65535)throw new _e("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);gc(e,String(t),420)}function Dm(t){let e=hc();if(!Number.isInteger(t)||t<1)throw new _e("write_failed",e,`pid must be a positive integer but received ${t}`);gc(e,String(t),420)}function yc(t){for(let e of[Om(),Nm(),hc()])try{te.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Fm(){let t=oe(),e;try{e=te.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{te.unlinkSync(Bt.join(t,n))}catch{}}var pc=new Set;function RE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function PE(t){let e;try{e=te.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 Bm(t){let e=kE(),n=hc(),r=t?.processIsAlive??RE;if(pc.has(e))throw new _e("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=te.openSync(e,te.constants.O_WRONLY|te.constants.O_CREAT|te.constants.O_EXCL,384);if(te.closeSync(i),process.platform!=="win32")try{te.chmodSync(e,384)}catch{}return pc.add(e),AE(e)}catch(i){if(i.code!=="EEXIST")throw new _e("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=PE(n);if(a.kind==="missing")throw new _e("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 _e("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 _e("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 _e("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{te.unlinkSync(e)}catch{}try{te.unlinkSync(n)}catch{}}throw new _e("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function AE(t){let e=!1;return{release(){if(!e){e=!0,pc.delete(t);try{te.unlinkSync(t)}catch{}}}}}import*as Wm from"node:http";import{Buffer as vc}from"node:buffer";import*as zm 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 Km="0.1.0-alpha.6",Um=`aifight-runtime/${Km}`,TE="127.0.0.1",xE=0,CE=1048576,IE=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 Jm(t){return t.split("/").filter(e=>e.length>0)}function Te(t){let e=Jm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function OE(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 qm(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=vc.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 Hm(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 _c(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function Gm(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 Vm(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 NE(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 Ym(t){let e=t.host??TE,n=t.port??xE,r=t.bodyLimitBytes??CE,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:$},{method:"POST",pattern:Te("/v1/agents/:name/schedule"),handler:K},{method:"POST",pattern:Te("/v1/agents/:name/schedule/pause"),handler:X},{method:"POST",pattern:Te("/v1/agents/:name/schedule/resume"),handler:ae},{method:"POST",pattern:Te("/v1/shutdown"),handler:st},{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),k=t.tokenSource();if(k===null)return{ok:!1,reason:"token_unset"};let j=vc.from(x,"utf8"),Z=vc.from(k,"utf8");return j.length!==Z.length?{ok:!1,reason:"token_mismatch"}:zm.timingSafeEqual(j,Z)?{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",Um),w.statusCode=E,w.end(JSON.stringify(x)))}function d(w,E,x,k,j){u(w,E,j===void 0?{error:{code:x,message:k}}:{error:{code:x,message:k,details:j}})}function h(w){u(w.res,200,{status:"ok",version:Km,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",Um),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Vm);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 _c(j)?new B(404,"not_found",`agent '${E}' not found`):j}let k=x.snapshot();u(w.res,200,{agent:Vm(k)})}async function S(w){let E=w.params.name,x=await qm(w.req,r);Hm(x,["game"],"/v1/agents/:name/join");let k=x;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 Z=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...Z!==void 0?{oneShot:Z}:{},...typeof j=="number"?{count:j}:{}})}catch(J){throw _c(J)?new B(404,"not_found",`agent '${E}' not found`):J}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(x){throw _c(x)?new B(404,"not_found",`agent '${E}' not found`):x}g(w.res)}function $(w){let E=w.params.name,x=f(E),k=m(E),j=NE(x.snapshot());u(w.res,200,{schedule:k,snapshot:j})}async function K(w){let E=w.params.name,x=f(E),k=await qm(w.req,r),j;if(k===null)j=null;else{Hm(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let Z=k;if(typeof Z.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof Z.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof Z.days!="object"||Z.days===null||Array.isArray(Z.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{x.setSchedule(j)}catch(Z){let J=Gm(Z);throw J||Z}a.set(E,j),g(w.res)}function X(w){Ke(w,!1)}function ae(w){Ke(w,!0)}function Ke(w,E){let x=w.params.name,k=f(x),j=m(x);if(j===null){let J=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${J}; POST /schedule first or configure initial schedule`)}let Z={...j,enabled:E};try{k.setSchedule(Z)}catch(J){let to=Gm(J);throw to||J}a.set(x,Z),g(w.res)}function st(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: ${wc(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function nr(w,E){let x=o.now(),k=w.method??"GET",j=w.url??"/",Z=`http://${w.headers.host??"localhost"}`,J;try{J=new URL(j,Z)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${k} ${j} -> 400 (${o.now()-x}ms)`,method:k,path:j,status:400,durationMs:o.now()-x});return}let to=Jm(J.pathname),rr=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${J.pathname}: auth failed (${Ee.reason})`,method:k,path:J.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let gi=s.map(Et=>({route:Et,params:OE(Et.pattern,to)})).filter(Et=>Et.params!==null);if(gi.length===0)throw new B(404,"not_found","path not found");let yi=gi.find(Et=>Et.route.method===k);if(!yi){let Et=gi.map(_i=>_i.route.method).filter((_i,Ep,kp)=>kp.indexOf(_i)===Ep).join(", ");throw E.headersSent||E.setHeader("Allow",Et),new B(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${J.pathname}`,method:k,path:J.pathname}),await yi.route.handler({req:w,res:E,url:J,params:yi.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} ${J.pathname}: ${wc(Ee)}`,method:k,path:J.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} ${J.pathname} -> ${rr} (${o.now()-x}ms)`,method:k,path:J.pathname,status:rr,durationMs:o.now()-x})}}let Je=Wm.createServer((w,E)=>{nr(w,E).catch(x=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${wc(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{}}})}),re="pre-listen",Ut=null,wn=null,eo=null;function vp(){return re==="listening"?Promise.reject(new _n("invalid_state","server already listening")):re==="closing"||re==="closed"||re==="bind-failed"?Promise.reject(new _n("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let x=k=>{re="bind-failed",E(new _n("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Je.once("error",x),Je.listen({host:e,port:n},()=>{Je.off("error",x);let k=Je.address();if(typeof k=="string"||k===null){re="bind-failed",E(new _n("bind_failed","unexpected listen address shape from server.address()"));return}Ut=k.address,wn=k.port,re="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Ut}:${wn}`,host:Ut,port:wn}),w(wn)})})}function bp(){return re!=="listening"||Ut===null||wn===null?null:{host:Ut,port:wn}}function Sp(){return re==="pre-listen"||re==="bind-failed"?(re="closed",Promise.resolve()):re==="closed"?Promise.resolve():(re==="closing"&&eo||(re="closing",eo=new Promise(w=>{let E=!1,x=()=>{E||(E=!0,clearTimeout(j),re="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Je.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Je)}catch{}x()},IE);j.unref(),Je.close(()=>x())})),eo)}return{listen:vp,address:bp,close:Sp}}function wc(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 bc(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 Qm(t,e){if(e.type==="start")return H(bc(e));if(t.phase==="closed")return e.type==="stop"?H(t):ze(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return LE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return ME(t);case"command.confirm_match":return jE(t,e.confirmId);case"ws.message":return DE(t,e.message,e.now);case"decision.ready":return VE(t,e.action);case"decision.failed":return WE(t,e.reason);case"reconnect.event":return YE(t,e.event);case"reconnect.close":return QE(t,e.info);case"stop":return H({...t,phase:"closed",transport:"closed"})}}function LE(t,e,n,r){if(!t.availableGames.includes(e))return ze(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Qr(n),...r===!0?{one_shot:!0}:{}};return H({...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 ME(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?ze(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function jE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?ze(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):H({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function DE(t,e,n){switch(e.type){case"queue_joined":return FE(t,e);case"queue_left":return H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return BE(t,e);case"match_cancelled":return UE(t,e);case"game_start":return qE(t,e,n);case"game_state":return HE(t,e);case"action_request":return GE(t,e);case"game_over":return zE(t,e);case"error":return KE(t,e);case"event":return JE(t,e);default:return ze(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function FE(t,e){return H({...t,phase:"queuing",queue:{game:e.data.game,mode:Qr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function BE(t,e){let n={game:e.data.game,mode:Qr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?H({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):H({...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 UE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Qr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Qr(e.data.mode)}:n;return H({...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 H({...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 qE(t,e,n){return H({...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 HE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?ze(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function GE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?ze(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?ze(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function VE(t,e){return t.phase!=="deciding"||!t.pendingAction?ze(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):H({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function WE(t,e){return t.phase!=="deciding"||!t.pendingAction?ze(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):H(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function zE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?ze(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):H({...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 KE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return H({...t,lastError:n},[We("error","server.error",n)])}function JE(t,e){return H(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function YE(t,e){return e.type==="attempt-success"?H({...t,transport:"connected"}):e.type==="attempt-start"?H({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?H({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):H({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function QE(t,e){return H({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function H(t,e=[]){return{state:t,effects:e}}function ze(t,e,n){return H(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Qr(t){return t&&t.length>0?t:"ranked"}var tr=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Xr=class extends tr{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Zr=class extends tr{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},ui=class extends tr{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},Sc=class extends tr{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},di=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 ui(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Xr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??Ha,n;try{n=await e(this.#e.ws)}catch(r){throw new Xr(`failed to start agent '${this.#e.name}': ${li(r)}`,r)}if(n.welcome===null)throw new Xr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=bc({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=XE(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:ZE(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Xm(`readiness check failed: ${li(r)}`)}})}}#s(e){let n=this.#S(),r=Qm(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: ${li(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}: ${li(r)}`,cause:new Sc(`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 Zr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new ui(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Zr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Zr(`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 li(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function XE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function ZE(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=Xm(n.detail)),n}function Xm(t){return t.length>240?t.slice(0,240):t}function Zm(t){return{async decide(e){let n=ok(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:ik(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 fi(n,o,r.state)}}return ek({game:n,raw:s,legalActions:o,publicState:r.state})}}}function ep(){return{name:"mock",async decide(t){return fi(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function ek(t){if(typeof t.raw!="string")return rk(t.raw,t.legalActions)??fi(t.game,t.legalActions,t.publicState);let e=tk(t.game,t.raw,t.legalActions);return e!==null?e:fi(t.game,t.legalActions,t.publicState)}function tk(t,e,n){let r=nk(e),o=t==="texas_holdem"?Ja(r,n):t==="liars_dice"?Qa(r,n):Xa(r,n);return o.kind==="ok"?o.action:null}function nk(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function rk(t,e){let n=e.find(o=>sk(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function fi(t,e,n){return t==="texas_holdem"?Ga({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Wa({publicState:n,legalActions:e,yourPlayerId:"p0"}):za({publicState:n,legalActions:e,yourPlayerId:"p0"})}function ok(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function ik(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function sk(t,e){return JSON.stringify(t)===JSON.stringify(e)}var ak="http://127.0.0.1:18789",ck="openclaw/default";function tp(t){let e=(t.baseUrl??ak).replace(/\/+$/,""),n=t.model??ck,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:lk(t,o),body:JSON.stringify({model:n,input:uk(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=dk(s);return fk(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 lk(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 uk(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(`
211
- `)}function dk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function fk(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=mk(n);if(r)return r;let o=e.choices,i=pk(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function mk(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(`
212
- `):null}function pk(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 hk="http://127.0.0.1:8642",gk="hermes-agent";function np(t){let e=(t.baseUrl??hk).replace(/\/+$/,""),n=t.model??gk,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:yk(t,o),body:JSON.stringify({model:n,input:_k(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=wk(s);return vk(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 yk(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 _k(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(`
213
- `)}function wk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function vk(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=bk(n);if(r)return r;let o=e.choices,i=Sk(o);if(i)return i;throw new Error("Hermes response did not contain text")}function bk(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(`
214
- `):null}function Sk(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 mi=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??Tk(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:Xf},r=new di({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:Zm(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",kk(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=Ek(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 Ek(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function kk(t,e,n){let r=[`Match complete: ${Ak(n)}`,`Result: ${$k(t.agentId,e)}`],o=Pk(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(`
215
- `)}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`${Rk(o+1)} place`}function Rk(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 Pk(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function Ak(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 Tk(t){return t.runtimeType==="mock"?ep():t.runtimeType==="openclaw"?tp({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):np({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}import{execFile as xk}from"node:child_process";import{promisify as Ck}from"node:util";var Ik="@aifight/aifight@alpha",Ok=10*60*1e3,Nk=6*60*60*1e3,Lk=Ck(xk),Mk=async(t,e)=>{let{stdout:n,stderr:r}=await Lk(t,[...e],{timeout:12e4,maxBuffer:524288});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}};function op(t){let e=!1,n=!1,r=null,o=t.intervalMs??Nk,i=t.initialDelayMs??Ok,s=c=>{e||(r=setTimeout(()=>{a()},c))},a=async()=>{if(e||n)return null;n=!0;try{return await jk(t)}finally{n=!1,s(o)}};return s(i),{stop:()=>{e=!0,r!==null&&(clearTimeout(r),r=null)},triggerNow:async()=>(r!==null&&(clearTimeout(r),r=null),a())}}async function jk(t){let e=await je({baseUrl:t.baseUrl,currentVersion:se,fetchImpl:t.fetchImpl});if(e.status==="current"||e.status==="unknown")return{status:e.status,update:e};let r=t.snapshot()?.state?.phase??null;if(!Dk(r))return t.onLog?.({level:"info",code:"bridge.auto_update_busy",message:`Bridge update available, but agent is busy (${r??"not connected"}); will retry later.`}),{status:"busy",phase:r,update:e};t.onLog?.({level:"info",code:"bridge.auto_update_start",message:`Updating AIFight Bridge to ${e.policy?.recommendedVersion??"recommended version"} while idle.`});try{await Ec({execFile:t.execFile})}catch(o){let i=rp(o);return t.onLog?.({level:"warning",code:"bridge.auto_update_failed",message:`Automatic AIFight Bridge update failed: ${i}`}),{status:"failed",update:e,error:i}}t.onLog?.({level:"info",code:"bridge.auto_update_done",message:"AIFight Bridge package updated; restarting service process to use the new version."});try{t.onRestartRequired?.()}catch(o){t.onLog?.({level:"warning",code:"bridge.auto_update_restart_signal_failed",message:`AIFight Bridge package updated, but restart signal failed: ${rp(o)}`})}return{status:"updated",update:e}}async function Ec(t={}){await(t.execFile??Mk)("npm",["install","-g",Ik])}function Dk(t){return t==="connected"||t==="queuing"}function rp(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
216
- `)[0]:t instanceof Error?t.message:String(t)}var Fk=["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(`
217
- `);async function sp(t,e){W(t,0,0,Fk);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await Wk(e))throw new U("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(`
218
- `)),!await Kk(e,"Continue anyway? [y/N] ")))return 0;let r=ne();return Bk({config:r,env:e})}async function Bk(t){let{config:e,env:n}=t,r=await je({baseUrl:e.baseUrl,currentVersion:se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
213
+ `)}return 0}function wE(){try{return W()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new B("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 vE(t,e){if(t.length===0)return{game:xm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Cm(n);if(i!==null)return{game:xm(e.autoGames),count:i};if(ct(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,ci)}let r=t[1];if(!ct(n))throw new O(`unsupported game '${n}'`,ci);let o=Cm(r);if(o===null)throw new O(`N must be an integer between 1 and ${mc}`,ci);return{game:n,count:o}}function Cm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>mc?null:e}function xm(t){let e=(t??he).filter(ct),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}function bE(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 SE(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 EE(t){try{let e=await St(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 X))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function kE(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 ne from"node:fs";import $E from"node:crypto";var _e=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 Nm(){return Ft.join(oe(),"token")}function Lm(){return Ft.join(oe(),"port")}function hc(){return Ft.join(oe(),"pid")}function RE(){return Ft.join(oe(),"lock")}var Om=0,AE=/^[0-9a-f]{64}$/;function gc(t,e,n){let r=Ft.dirname(t),o=Ft.basename(t);Om+=1;let i=Ft.join(r,`${o}.${process.pid}.${Om}.tmp`),s;try{if(s=ne.openSync(i,"w",n),ne.writeSync(s,e),ne.closeSync(s),s=void 0,process.platform!=="win32")try{ne.chmodSync(i,n)}catch{}ne.renameSync(i,t)}catch(a){if(s!==void 0)try{ne.closeSync(s)}catch{}try{ne.unlinkSync(i)}catch{}throw new _e("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Mm(){return $E.randomBytes(32).toString("hex")}function jm(t){let e=Nm();if(!AE.test(t))throw new _e("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);gc(e,t,384)}function Dm(t){let e=Lm();if(!Number.isInteger(t)||t<1||t>65535)throw new _e("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);gc(e,String(t),420)}function Bm(t){let e=hc();if(!Number.isInteger(t)||t<1)throw new _e("write_failed",e,`pid must be a positive integer but received ${t}`);gc(e,String(t),420)}function yc(t){for(let e of[Nm(),Lm(),hc()])try{ne.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Fm(){let t=oe(),e;try{e=ne.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{ne.unlinkSync(Ft.join(t,n))}catch{}}var pc=new Set;function PE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function TE(t){let e;try{e=ne.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 Um(t){let e=RE(),n=hc(),r=t?.processIsAlive??PE;if(pc.has(e))throw new _e("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=ne.openSync(e,ne.constants.O_WRONLY|ne.constants.O_CREAT|ne.constants.O_EXCL,384);if(ne.closeSync(i),process.platform!=="win32")try{ne.chmodSync(e,384)}catch{}return pc.add(e),CE(e)}catch(i){if(i.code!=="EEXIST")throw new _e("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=TE(n);if(a.kind==="missing")throw new _e("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 _e("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 _e("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 _e("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{ne.unlinkSync(e)}catch{}try{ne.unlinkSync(n)}catch{}}throw new _e("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function CE(t){let e=!1;return{release(){if(!e){e=!0,pc.delete(t);try{ne.unlinkSync(t)}catch{}}}}}import*as zm from"node:http";import{Buffer as vc}from"node:buffer";import*as Km 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 Jm="0.1.0-alpha.7",qm=`aifight-runtime/${Jm}`,xE="127.0.0.1",IE=0,OE=1048576,NE=5e3,U=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 Ym(t){return t.split("/").filter(e=>e.length>0)}function Te(t){let e=Ym(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function LE(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 Hm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new U(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 u=c;if(i+=u.length,i>e)throw s=!0,new U(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(u)}let a=vc.concat(o).toString("utf8");if(a.length===0)throw new U(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new U(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function Gm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new U(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 U(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function _c(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function Vm(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 U(400,"bad_request",n,{validation:e}):e==="invalid_state"?new U(503,"service_unavailable","scheduler stopped"):null}function Wm(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 ME(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 Qm(t){let e=t.host??xE,n=t.port??IE,r=t.bodyLimitBytes??OE,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:$},{method:"POST",pattern:Te("/v1/agents/:name/schedule"),handler:J},{method:"POST",pattern:Te("/v1/agents/:name/schedule/pause"),handler:Z},{method:"POST",pattern:Te("/v1/agents/:name/schedule/resume"),handler:ae},{method:"POST",pattern:Te("/v1/shutdown"),handler:st},{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 u(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=vc.from(C,"utf8"),ee=vc.from(k,"utf8");return j.length!==ee.length?{ok:!1,reason:"token_mismatch"}:Km.timingSafeEqual(j,ee)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function l(w,E,C){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",qm),w.statusCode=E,w.end(JSON.stringify(C)))}function d(w,E,C,k,j){l(w,E,j===void 0?{error:{code:C,message:k}}:{error:{code:C,message:k,details:j}})}function h(w){l(w.res,200,{status:"ok",version:Jm,uptimeMs:o.now()-i})}function p(w){return E=>{let C=E.url.pathname;throw new U(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 U(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",qm),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Wm);l(w.res,200,{agents:E})}function v(w){let E=w.params.name,C;try{C=t.router.getAgent({name:E})}catch(j){throw _c(j)?new U(404,"not_found",`agent '${E}' not found`):j}let k=C.snapshot();l(w.res,200,{agent:Wm(k)})}async function S(w){let E=w.params.name,C=await Hm(w.req,r);Gm(C,["game"],"/v1/agents/:name/join");let k=C;if(typeof k.game!="string"||k.game.length===0)throw new U(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 U(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 U(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 U(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 U(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let ee=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...ee!==void 0?{oneShot:ee}:{},...typeof j=="number"?{count:j}:{}})}catch(Y){throw _c(Y)?new U(404,"not_found",`agent '${E}' not found`):Y}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(C){throw _c(C)?new U(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=ME(C.snapshot());l(w.res,200,{schedule:k,snapshot:j})}async function J(w){let E=w.params.name,C=f(E),k=await Hm(w.req,r),j;if(k===null)j=null;else{Gm(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let ee=k;if(typeof ee.enabled!="boolean")throw new U(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof ee.timezone!="string")throw new U(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof ee.days!="object"||ee.days===null||Array.isArray(ee.days))throw new U(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{C.setSchedule(j)}catch(ee){let Y=Vm(ee);throw Y||ee}a.set(E,j),g(w.res)}function Z(w){Ke(w,!1)}function ae(w){Ke(w,!0)}function Ke(w,E){let C=w.params.name,k=f(C),j=m(C);if(j===null){let Y=E?"resume":"pause";throw new U(400,"bad_request",`no schedule to ${Y}; POST /schedule first or configure initial schedule`)}let ee={...j,enabled:E};try{k.setSchedule(ee)}catch(Y){let to=Vm(Y);throw to||Y}a.set(C,ee),g(w.res)}function st(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),l(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${wc(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function rr(w,E){let C=o.now(),k=w.method??"GET",j=w.url??"/",ee=`http://${w.headers.host??"localhost"}`,Y;try{Y=new URL(j,ee)}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 to=Ym(Y.pathname),or=0;try{let Ee=u(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${Y.pathname}: auth failed (${Ee.reason})`,method:k,path:Y.pathname,reason:Ee.reason}),new U(401,"unauthorized",`authentication required: ${Ee.reason}`);let gi=s.map(Et=>({route:Et,params:LE(Et.pattern,to)})).filter(Et=>Et.params!==null);if(gi.length===0)throw new U(404,"not_found","path not found");let yi=gi.find(Et=>Et.route.method===k);if(!yi){let Et=gi.map(_i=>_i.route.method).filter((_i,kp,$p)=>$p.indexOf(_i)===kp).join(", ");throw E.headersSent||E.setHeader("Allow",Et),new U(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${Y.pathname}`,method:k,path:Y.pathname}),await yi.route.handler({req:w,res:E,url:Y,params:yi.params}),or=E.statusCode}catch(Ee){Ee instanceof U?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),or=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${k} ${Y.pathname}: ${wc(Ee)}`,method:k,path:Y.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),or=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${k} ${Y.pathname} -> ${or} (${o.now()-C}ms)`,method:k,path:Y.pathname,status:or,durationMs:o.now()-C})}}let Je=zm.createServer((w,E)=>{rr(w,E).catch(C=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${wc(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{}}})}),re="pre-listen",Ut=null,wn=null,eo=null;function bp(){return re==="listening"?Promise.reject(new _n("invalid_state","server already listening")):re==="closing"||re==="closed"||re==="bind-failed"?Promise.reject(new _n("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let C=k=>{re="bind-failed",E(new _n("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Je.once("error",C),Je.listen({host:e,port:n},()=>{Je.off("error",C);let k=Je.address();if(typeof k=="string"||k===null){re="bind-failed",E(new _n("bind_failed","unexpected listen address shape from server.address()"));return}Ut=k.address,wn=k.port,re="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Ut}:${wn}`,host:Ut,port:wn}),w(wn)})})}function Sp(){return re!=="listening"||Ut===null||wn===null?null:{host:Ut,port:wn}}function Ep(){return re==="pre-listen"||re==="bind-failed"?(re="closed",Promise.resolve()):re==="closed"?Promise.resolve():(re==="closing"&&eo||(re="closing",eo=new Promise(w=>{let E=!1,C=()=>{E||(E=!0,clearTimeout(j),re="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Je.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Je)}catch{}C()},NE);j.unref(),Je.close(()=>C())})),eo)}return{listen:bp,address:Sp,close:Ep}}function wc(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 bc(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 Xm(t,e){if(e.type==="start")return H(bc(e));if(t.phase==="closed")return e.type==="stop"?H(t):ze(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return jE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return DE(t);case"command.confirm_match":return BE(t,e.confirmId);case"ws.message":return FE(t,e.message,e.now);case"decision.ready":return zE(t,e.action);case"decision.failed":return KE(t,e.reason);case"reconnect.event":return XE(t,e.event);case"reconnect.close":return ZE(t,e.info);case"stop":return H({...t,phase:"closed",transport:"closed"})}}function jE(t,e,n,r){if(!t.availableGames.includes(e))return ze(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Qr(n),...r===!0?{one_shot:!0}:{}};return H({...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 DE(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?ze(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function BE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?ze(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):H({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function FE(t,e,n){switch(e.type){case"queue_joined":return UE(t,e);case"queue_left":return H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return qE(t,e);case"match_cancelled":return HE(t,e);case"game_start":return GE(t,e,n);case"game_state":return VE(t,e);case"action_request":return WE(t,e);case"game_over":return JE(t,e);case"error":return YE(t,e);case"event":return QE(t,e);default:return ze(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function UE(t,e){return H({...t,phase:"queuing",queue:{game:e.data.game,mode:Qr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function qE(t,e){let n={game:e.data.game,mode:Qr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?H({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):H({...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 HE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Qr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Qr(e.data.mode)}:n;return H({...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 H({...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 GE(t,e,n){return H({...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 VE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?ze(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function WE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?ze(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?ze(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function zE(t,e){return t.phase!=="deciding"||!t.pendingAction?ze(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):H({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function KE(t,e){return t.phase!=="deciding"||!t.pendingAction?ze(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):H(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function JE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?ze(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):H({...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 YE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return H({...t,lastError:n},[We("error","server.error",n)])}function QE(t,e){return H(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function XE(t,e){return e.type==="attempt-success"?H({...t,transport:"connected"}):e.type==="attempt-start"?H({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?H({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):H({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function ZE(t,e){return H({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function H(t,e=[]){return{state:t,effects:e}}function ze(t,e,n){return H(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Qr(t){return t&&t.length>0?t:"ranked"}var nr=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Xr=class extends nr{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Zr=class extends nr{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},ui=class extends nr{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},Sc=class extends nr{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},di=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 ui(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Xr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??Ha,n;try{n=await e(this.#e.ws)}catch(r){throw new Xr(`failed to start agent '${this.#e.name}': ${li(r)}`,r)}if(n.welcome===null)throw new Xr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=bc({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=ek(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:tk(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Zm(`readiness check failed: ${li(r)}`)}})}}#s(e){let n=this.#S(),r=Xm(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: ${li(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}: ${li(r)}`,cause:new Sc(`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 Zr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new ui(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Zr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Zr(`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 li(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function ek(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function tk(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=Zm(n.detail)),n}function Zm(t){return t.length>240?t.slice(0,240):t}function ep(t){return{async decide(e){let n=sk(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:ak(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 fi(n,o,r.state)}}return nk({game:n,raw:s,legalActions:o,publicState:r.state})}}}function tp(){return{name:"mock",async decide(t){return fi(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function nk(t){if(typeof t.raw!="string")return ik(t.raw,t.legalActions)??fi(t.game,t.legalActions,t.publicState);let e=rk(t.game,t.raw,t.legalActions);return e!==null?e:fi(t.game,t.legalActions,t.publicState)}function rk(t,e,n){let r=ok(e),o=t==="texas_holdem"?Ja(r,n):t==="liars_dice"?Qa(r,n):Xa(r,n);return o.kind==="ok"?o.action:null}function ok(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function ik(t,e){let n=e.find(o=>ck(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function fi(t,e,n){return t==="texas_holdem"?Ga({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Wa({publicState:n,legalActions:e,yourPlayerId:"p0"}):za({publicState:n,legalActions:e,yourPlayerId:"p0"})}function sk(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function ak(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function ck(t,e){return JSON.stringify(t)===JSON.stringify(e)}var lk="http://127.0.0.1:18789",uk="openclaw/default";function np(t){let e=(t.baseUrl??lk).replace(/\/+$/,""),n=t.model??uk,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:dk(t,o),body:JSON.stringify({model:n,input:fk(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=mk(s);return pk(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 dk(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 fk(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(`
214
+ `)}function mk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function pk(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=hk(n);if(r)return r;let o=e.choices,i=gk(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function hk(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(`
215
+ `):null}function gk(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 yk="http://127.0.0.1:8642",_k="hermes-agent";function rp(t){let e=(t.baseUrl??yk).replace(/\/+$/,""),n=t.model??_k,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:wk(t,o),body:JSON.stringify({model:n,input:vk(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=bk(s);return Sk(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 wk(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 vk(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(`
216
+ `)}function bk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function Sk(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=Ek(n);if(r)return r;let o=e.choices,i=kk(o);if(i)return i;throw new Error("Hermes response did not contain text")}function Ek(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(`
217
+ `):null}function kk(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 mi=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??xk(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:Xf},r=new di({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:ep(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",Rk(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=$k(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 $k(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function Rk(t,e,n){let r=[`Match complete: ${Ck(n)}`,`Result: ${Ak(t.agentId,e)}`],o=Tk(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(`
218
+ `)}function Ak(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`${Pk(o+1)} place`}function Pk(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 Tk(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function Ck(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 xk(t){return t.runtimeType==="mock"?tp():t.runtimeType==="openclaw"?np({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):rp({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}import{execFile as Ik}from"node:child_process";import{promisify as Ok}from"node:util";var Nk="@aifight/aifight@alpha",Lk=10*60*1e3,Mk=6*60*60*1e3,jk=Ok(Ik),Dk=async(t,e)=>{let{stdout:n,stderr:r}=await jk(t,[...e],{timeout:12e4,maxBuffer:524288});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}};function ip(t){let e=!1,n=!1,r=null,o=t.intervalMs??Mk,i=t.initialDelayMs??Lk,s=c=>{e||(r=setTimeout(()=>{a()},c))},a=async()=>{if(e||n)return null;n=!0;try{return await Bk(t)}finally{n=!1,s(o)}};return s(i),{stop:()=>{e=!0,r!==null&&(clearTimeout(r),r=null)},triggerNow:async()=>(r!==null&&(clearTimeout(r),r=null),a())}}async function Bk(t){let e=await je({baseUrl:t.baseUrl,currentVersion:se,fetchImpl:t.fetchImpl});if(e.status==="current"||e.status==="unknown")return{status:e.status,update:e};let r=t.snapshot()?.state?.phase??null;if(!Fk(r))return t.onLog?.({level:"info",code:"bridge.auto_update_busy",message:`Bridge update available, but agent is busy (${r??"not connected"}); will retry later.`}),{status:"busy",phase:r,update:e};t.onLog?.({level:"info",code:"bridge.auto_update_start",message:`Updating AIFight Bridge to ${e.policy?.recommendedVersion??"recommended version"} while idle.`});try{await Ec({execFile:t.execFile})}catch(o){let i=op(o);return t.onLog?.({level:"warning",code:"bridge.auto_update_failed",message:`Automatic AIFight Bridge update failed: ${i}`}),{status:"failed",update:e,error:i}}t.onLog?.({level:"info",code:"bridge.auto_update_done",message:"AIFight Bridge package updated; restarting service process to use the new version."});try{t.onRestartRequired?.()}catch(o){t.onLog?.({level:"warning",code:"bridge.auto_update_restart_signal_failed",message:`AIFight Bridge package updated, but restart signal failed: ${op(o)}`})}return{status:"updated",update:e}}async function Ec(t={}){await(t.execFile??Dk)("npm",["install","-g",Nk])}function Fk(t){return t==="connected"||t==="queuing"}function op(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
219
+ `)[0]:t instanceof Error?t.message:String(t)}var Uk=["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(`
220
+ `);async function ap(t,e){z(t,0,0,Uk);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await Kk(e))throw new B("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(`
221
+ `)),!await Yk(e,"Continue anyway? [y/N] ")))return 0;let r=W();return qk({config:r,env:e})}async function qk(t){let{config:e,env:n}=t,r=await je({baseUrl:e.baseUrl,currentVersion:se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
219
222
  `),n.stderr(`Run: aifight update --yes
220
223
  `),n.stderr(`Manual npm command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
221
224
  `),1;r.status==="update_recommended"&&(n.stdout(`[warn] bridge.update: ${r.message}
222
225
  `),n.stdout(`[warn] update when ready: aifight update --yes
223
- `)),at(),Fm();let o=null,i=null,s=null,a=new mi({config:e,...Uk(e),onLog:c=>{ip(c,n)}});try{o=Bm(),Dm(process.pid);let c=Lm();n.stdout(Hk(e)),await a.start(),i=Ym({tokenSource:()=>c,router:qk(e,a),onLog:u=>{n.onLog?.({code:`control.${u.code}`,message:u.message})}});let l=await i.listen();return Mm(c),jm(l),process.env.AIFIGHT_SERVICE_RUN==="1"&&(s=op({baseUrl:e.baseUrl,fetchImpl:n.fetchImpl,snapshot:()=>a.snapshot(),execFile:n.bridgeService?.execFile,onLog:u=>ip(u,n),onRestartRequired:()=>{n.stdout(`AIFight Bridge updated; stopping so aifight.service can restart with the new package.
226
+ `)),at(),Fm();let o=null,i=null,s=null,a=new mi({config:e,...Hk(e),onLog:c=>{sp(c,n)}});try{o=Um(),Bm(process.pid);let c=Mm();n.stdout(Vk(e)),await a.start(),i=Qm({tokenSource:()=>c,router:Gk(e,a),onLog:l=>{n.onLog?.({code:`control.${l.code}`,message:l.message})}});let u=await i.listen();return jm(c),Dm(u),process.env.AIFIGHT_SERVICE_RUN==="1"&&(s=ip({baseUrl:e.baseUrl,fetchImpl:n.fetchImpl,snapshot:()=>a.snapshot(),execFile:n.bridgeService?.execFile,onLog:l=>sp(l,n),onRestartRequired:()=>{n.stdout(`AIFight Bridge updated; stopping so aifight.service can restart with the new package.
224
227
  `),process.kill(process.pid,"SIGTERM")}})),n.stdout(`Bridge online. Press Ctrl-C to stop.
225
- `),await zk(async()=>{s?.stop(),s=null,await i?.close(),i=null,await a.stop(),yc({onLog:u=>n.stderr(`warning: ${u}
226
- `)}),o?.release(),o=null}),0}catch(c){throw s?.stop(),await i?.close().catch(()=>{}),await a.stop().catch(()=>{}),yc({onLog:()=>{}}),o?.release(),c instanceof _e?c.kind==="lock_held_by_other"?new U("bridge_already_running",`AIFight Bridge is already running${c.heldByPid!==void 0?` (PID ${c.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new U("bridge_runtime_files_failed",c.message):c}}function Uk(t){let e=(t.autoDailyLimit??0)>0?Vk(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function qk(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(!ct(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 Hk(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: ${Gk(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(`
228
+ `),await Jk(async()=>{s?.stop(),s=null,await i?.close(),i=null,await a.stop(),yc({onLog:l=>n.stderr(`warning: ${l}
229
+ `)}),o?.release(),o=null}),0}catch(c){throw s?.stop(),await i?.close().catch(()=>{}),await a.stop().catch(()=>{}),yc({onLog:()=>{}}),o?.release(),c instanceof _e?c.kind==="lock_held_by_other"?new B("bridge_already_running",`AIFight Bridge is already running${c.heldByPid!==void 0?` (PID ${c.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new B("bridge_runtime_files_failed",c.message):c}}function Hk(t){let e=(t.autoDailyLimit??0)>0?zk(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function Gk(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(!ct(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 Vk(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: ${Wk(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(`
227
230
  `)}
228
- `}function ip(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}
231
+ `}function sp(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}
229
232
  `);return}if(t.code==="bridge.match_complete"){e.stdout(`
230
233
  ${t.message}
231
234
  `);return}let r=`${t.level==="error"?"error":t.level==="warning"?"warning":"info"}: ${t.message}
232
- `;t.level==="error"?e.stderr(r):e.stdout(r)}function Gk(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function Vk(t){let e=(t??he).filter(ct),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}async function Wk(t){try{let e=await St(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof Q,!1}}async function zk(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 Kk(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 Jk="usage: aifight status",Yk=1500;async function ap(t,e){W(t,0,0,Jk);let n=n$();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:se})+`
235
+ `;t.level==="error"?e.stderr(r):e.stdout(r)}function Wk(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function zk(t){let e=(t??he).filter(ct),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}async function Kk(t){try{let e=await St(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof X,!1}}async function Jk(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 Yk(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 Qk="usage: aifight status",Xk=1500;async function cp(t,e){z(t,0,0,Qk);let n=o$();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:se})+`
233
236
  `):(e.stdout(`AIFight status
234
237
 
235
238
  `),e.stdout(`Bridge: not configured
236
239
  `),e.stdout(`CLI version: ${se}
237
- `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Dt(n),o=await je({baseUrl:n.baseUrl,currentVersion:se,fetchImpl:e.fetchImpl}),i=await Qk(n,e.fetchImpl);return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:se,update:o,platformAgentStatus:i,config:r})+`
240
+ `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Dt(n),o=await je({baseUrl:n.baseUrl,currentVersion:se,fetchImpl:e.fetchImpl}),i=await Zk(n,e.fetchImpl);return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:se,update:o,platformAgentStatus:i,config:r})+`
238
241
  `),0):(e.stdout(`AIFight status
239
242
 
240
243
  `),e.stdout(`Agent: ${r.agentName}
241
- `),e.stdout(`Profile: ${Zk(i,n)}
244
+ `),e.stdout(`Profile: ${t$(i,n)}
242
245
  `),i.kind==="unavailable"&&e.stdout(`Profile check: ${i.message}
243
246
  `),e.stdout(`Bridge: configured
244
247
  `),e.stdout(`CLI version: ${se}
245
248
  `),e.stdout(`Update: ${o.message}
246
249
  `),(o.status==="update_recommended"||o.status==="unsupported")&&(e.stdout(`Update command: aifight update --yes
247
250
  `),e.stdout(`Manual npm command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
248
- `),e.stdout("The update command keeps local credentials and restarts `aifight.service` when it is installed.\n")),e.stdout(`Runtime: ${t$(r.runtimeType)} at ${r.runtimeLocalUrl}
249
- `),e.stdout(`Automatic ranked matches: ${e$(r.autoDailyLimit)}
251
+ `),e.stdout("The update command keeps local credentials and restarts `aifight.service` when it is installed.\n")),e.stdout(`Runtime: ${r$(r.runtimeType)} at ${r.runtimeLocalUrl}
252
+ `),e.stdout(`Automatic ranked matches: ${n$(r.autoDailyLimit)}
250
253
  `),e.stdout(`Games: ${r.autoGames?.join(", ")??"texas_holdem, liars_dice, coup"}
251
254
  `),e.stdout(`AIFight WebSocket: ${r.wsUrl}
252
255
  `),e.stdout(`No secrets are shown here.
253
- `),0)}async function Qk(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Yk);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=Xk(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 Xk(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 Zk(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 e$(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function t$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function n$(){try{return ne()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var r$=["usage: aifight update [--yes]"," Update the AIFight CLI package from npm, then restart aifight.service if it is installed."," Use --yes only after the human has approved the local AIFight package update."].join(`
254
- `),o$="https://aifight.ai",pi="@aifight/aifight@alpha";async function cp(t,e){W(t,0,0,r$);let n=t.flags.yes===!0,r=await je({baseUrl:i$(),currentVersion:se,fetchImpl:e.fetchImpl});if(r.status==="current")return t.jsonMode?e.stdout(JSON.stringify({status:"current",update:r})+`
256
+ `),0)}async function Zk(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Xk);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=e$(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 e$(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 t$(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 n$(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function r$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function o$(){try{return W()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var i$=["usage: aifight update [--yes]"," Update the AIFight CLI package from npm, then restart aifight.service if it is installed."," Use --yes only after the human has approved the local AIFight package update."].join(`
257
+ `),s$="https://aifight.ai",pi="@aifight/aifight@alpha";async function lp(t,e){z(t,0,0,i$);let n=t.flags.yes===!0,r=await je({baseUrl:a$(),currentVersion:se,fetchImpl:e.fetchImpl});if(r.status==="current")return t.jsonMode?e.stdout(JSON.stringify({status:"current",update:r})+`
255
258
  `):(e.stdout(`${r.message}
256
259
  `),e.stdout(`No npm update is required.
257
- `)),0;if(!n&&t.jsonMode)throw new U("update_confirmation_required","AIFight CLI update requires explicit confirmation.",{hint:"Run `aifight update --yes` after the human approves the npm package update."});if(t.jsonMode||(e.stdout(`${r.message}
260
+ `)),0;if(!n&&t.jsonMode)throw new B("update_confirmation_required","AIFight CLI update requires explicit confirmation.",{hint:"Run `aifight update --yes` after the human approves the npm package update."});if(t.jsonMode||(e.stdout(`${r.message}
258
261
  `),r.policy!==void 0&&(e.stdout(`Latest: ${r.policy.latestVersion}
259
262
  `),e.stdout(`Update package: ${pi}
260
263
  `))),!n){if(!process.stdin.isTTY)return e.stderr(`aifight: update requires confirmation in non-interactive mode.
261
- `),e.stderr("Run `aifight update --yes` after the human approves the local package update.\n"),1;if(!await c$(e,"Run npm update now? [y/N] "))return e.stdout(`Update skipped.
262
- `),0}await s$(e,t.jsonMode);let o=await a$(e,t.jsonMode);return t.jsonMode&&e.stdout(JSON.stringify({status:"updated",package:pi,service:o})+`
263
- `),0}function i$(){try{return ne().baseUrl}catch{return process.env.AIFIGHT_BASE_URL?.replace(/\/+$/,"")??o$}}async function s$(t,e){e||t.stdout(`Updating AIFight CLI: npm install -g ${pi}
264
- `);try{await Ec({execFile:t.bridgeService?.execFile})}catch(n){throw new U("update_failed",`npm update failed: ${kc(n)}`,{hint:`Run manually: npm install -g ${pi}`})}e||t.stdout(`AIFight CLI package updated.
265
- `)}async function a$(t,e){let n;try{n=await St(t.bridgeService)}catch(r){return e||(t.stderr(`warning: could not inspect aifight.service: ${kc(r)}
264
+ `),e.stderr("Run `aifight update --yes` after the human approves the local package update.\n"),1;if(!await u$(e,"Run npm update now? [y/N] "))return e.stdout(`Update skipped.
265
+ `),0}await c$(e,t.jsonMode);let o=await l$(e,t.jsonMode);return t.jsonMode&&e.stdout(JSON.stringify({status:"updated",package:pi,service:o})+`
266
+ `),0}function a$(){try{return W().baseUrl}catch{return process.env.AIFIGHT_BASE_URL?.replace(/\/+$/,"")??s$}}async function c$(t,e){e||t.stdout(`Updating AIFight CLI: npm install -g ${pi}
267
+ `);try{await Ec({execFile:t.bridgeService?.execFile})}catch(n){throw new B("update_failed",`npm update failed: ${kc(n)}`,{hint:`Run manually: npm install -g ${pi}`})}e||t.stdout(`AIFight CLI package updated.
268
+ `)}async function l$(t,e){let n;try{n=await St(t.bridgeService)}catch(r){return e||(t.stderr(`warning: could not inspect aifight.service: ${kc(r)}
266
269
  `),t.stderr("If you use a foreground Bridge, stop it and run `aifight run` again.\n")),{installed:!1}}if(!n.installed)return e||t.stdout("aifight.service is not installed. If you use a foreground Bridge, stop it and run `aifight run` again.\n"),{installed:!1};if(n.running!==!0)return e||t.stdout("aifight.service is installed but not running. Start it with `aifight service start` when ready.\n"),{installed:!0,restarted:!1,running:n.running,detail:n.detail};e||t.stdout(`Restarting aifight.service so it uses the updated CLI.
267
- `);try{await zr(t.bridgeService)}catch(r){let o=r instanceof Q?r.hint:void 0;return e||(t.stderr(`warning: aifight.service restart failed: ${kc(r)}
270
+ `);try{await Kr(t.bridgeService)}catch(r){let o=r instanceof X?r.hint:void 0;return e||(t.stderr(`warning: aifight.service restart failed: ${kc(r)}
268
271
  `),o&&t.stderr(`${o}
269
272
  `),t.stderr("Run `aifight service restart` after resolving the service manager issue.\n")),{installed:!0,restarted:!1,running:n.running,detail:n.detail}}return e||t.stdout(`aifight.service restarted.
270
273
  `),{installed:!0,restarted:!0,running:!0,detail:"restarted"}}function kc(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
271
- `)[0]:t instanceof Error?t.message:String(t)}async function c$(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 set daily <N>"," aifight set game <game1,game2>",`supported games: ${he.join(", ")}`].join(`
272
- `);async function lp(t,e){W(t,2,2,$c);let n=t.positional[0];if(n==="daily")return l$(t.positional[1],t,e);if(n==="game")return d$(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function l$(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,$c);let r=Number.parseInt(t,10),o=ne();await u$(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return pn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
274
+ `)[0]:t instanceof Error?t.message:String(t)}async function u$(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 set daily <N>"," aifight set game <game1,game2>",`supported games: ${he.join(", ")}`].join(`
275
+ `);async function up(t,e){z(t,2,2,$c);let n=t.positional[0];if(n==="daily")return d$(t.positional[1],t,e);if(n==="game")return m$(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function d$(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,$c);let r=Number.parseInt(t,10),o=W();await f$(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return pn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
273
276
  `),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.
274
277
  `):n.stdout(`Automatic ranked matches set to ${r} per day.
275
278
  `),n.stdout(`AIFight platform policy synced.
276
- `),0)}async function u$(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 U("policy_sync_failed",await f$(o,`daily policy sync failed with HTTP ${o.status}`))}function d$(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",$c);let o=new Set,i=[];for(let c of r){if(!ct(c))throw new O(`unsupported game '${c}'`,`supported: ${he.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...ne(),autoGames:i,updatedAt:new Date().toISOString()};return pn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
279
+ `),0)}async function f$(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 B("policy_sync_failed",await p$(o,`daily policy sync failed with HTTP ${o.status}`))}function m$(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",$c);let o=new Set,i=[];for(let c of r){if(!ct(c))throw new O(`unsupported game '${c}'`,`supported: ${he.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...W(),autoGames:i,updatedAt:new Date().toISOString()};return pn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
277
280
  `),0):(n.stdout(`Automatic match games set to: ${i.join(", ")}
278
- `),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 up="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function dp(t,e){W(t,1,1,up);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}')`,up);let r=ne(),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 U("challenge_create_failed",await m$(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 U("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
281
+ `),0)}async function p$(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 dp="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function fp(t,e){z(t,1,1,dp);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}')`,dp);let r=W(),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 B("challenge_create_failed",await h$(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 B("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
279
282
  `),0):(e.stdout(`Friendly challenge created.
280
283
 
281
284
  `),e.stdout(`Game: ${n}
@@ -287,35 +290,47 @@ ${t.message}
287
290
 
288
291
  `),e.stdout(`This does not affect ratings or daily auto-play.
289
292
  `),n==="texas_holdem"&&e.stdout(`Texas Hold'em challenges start as a direct two-player friendly table; normal matchmaking still starts at four players.
290
- `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function m$(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 Rc="usage: aifight accept <challenge_url_or_token>";async function fp(t,e){W(t,1,1,Rc);let n=p$(t.positional[0]),r=ne(),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 g$(o,`challenge accept failed with HTTP ${o.status}`);throw new U("challenge_accept_failed",h$(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
293
+ `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function h$(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 Rc="usage: aifight accept <challenge_url_or_token>";async function mp(t,e){z(t,1,1,Rc);let n=g$(t.positional[0]),r=W(),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 _$(o,`challenge accept failed with HTTP ${o.status}`);throw new B("challenge_accept_failed",y$(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
291
294
  `),0):(e.stdout(`Friendly challenge accepted.
292
295
 
293
296
  `),i.match_id&&e.stdout(`Match: ${i.match_id}
294
297
  `),i.message&&e.stdout(`${i.message}
295
- `),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 p$(t){let e=t.trim();if(e==="")throw new O("challenge token is required",Rc);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",Rc)}function h$(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 g$(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 hi from"node:fs";var mp="gateway.http.endpoints.responses.enabled",pp=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],hp=["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(`
296
- `);async function gp(t,e){if(W(t,0,0,hp),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",hp);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(`
297
- `)),await Kr(e,"Continue with local uninstall? [y/N] ")?(await y$(e),await _$(e),em(),pm(),e.stdout(["AIFight local bridge setup removed.","","To remove the CLI package itself, run:"," npm uninstall -g @aifight/aifight",""].join(`
298
- `)),0):(e.stdout(`Uninstall cancelled.
299
- `),0)}async function y$(t){try{let e=await ii(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
300
- `)}catch(e){let n=e instanceof Q||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
301
- `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function _$(t){let e=cc();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
302
- `);return}e.openclaw?.responsesEnabledByAIFight&&await w$(t),e.hermes&&await v$(t,e.hermes.envPath,e.hermes.previous)}async function w$(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(`
303
- `)),!await Kr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${mp} false --strict-json
304
- `);return}if(!Ae("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
305
- `);return}let n=await it("openclaw",["config","set",mp,"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.
306
- `);return}let r=await it("openclaw",["config","validate"]);gn(t,"openclaw config validate",r),await Xn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function v$(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(`
307
- `)),!await Kr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
298
+ `),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 g$(t){let e=t.trim();if(e==="")throw new O("challenge token is required",Rc);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",Rc)}function y$(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 _$(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 hi from"node:fs";var pp="gateway.http.endpoints.responses.enabled",hp=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],gp=["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(`
299
+ `);async function yp(t,e){if(z(t,0,0,gp),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",gp);e.stdout(["This removes local AIFight bridge setup from this machine.","","It can remove:"," - aifight.service, if installed"," - AIFight-recorded OpenClaw/Hermes setup changes, if you approve"," - local bridge credentials/config, only if you explicitly approve that destructive step","","It will not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys.","By default it keeps local bridge credentials so reinstalling the npm package can reuse this Agent.",""].join(`
300
+ `));let n=v$();if(n!==void 0){let i=await b$(n,e.fetchImpl);e.stdout([`Local bridge identity: ${n.agentName} (${n.agentId})`,`Profile: ${i}`,""].join(`
301
+ `))}else e.stdout(`No local bridge credentials were found.
302
+
303
+ `);if(!await Xn(e,"Continue with local uninstall? [y/N] "))return e.stdout(`Uninstall cancelled.
304
+ `),0;await E$(e),await k$(e);let o=await w$(e,n);return(n===void 0||o)&&pm(),e.stdout(`AIFight local uninstall finished.
305
+
306
+ `),n!==void 0&&(e.stdout(`If local bridge credentials were kept, reinstalling the npm package can reuse this Agent.
307
+ `),e.stdout("For a claimed Agent on a new machine, use Dashboard `Connect Bridge` to generate a pairing code.\n\n")),e.stdout(`To remove the CLI package itself, run:
308
+ npm uninstall -g @aifight/aifight
309
+
310
+ `),0}async function w$(t,e){if(e===void 0)return!1;if(t.stdout(["","Local bridge credentials are still present.","Keeping them is the safe default: npm reinstall or `aifight service install` can reuse the same Agent.","Deleting them removes this machine's plaintext bridge API key. Claimed Agents must be restored from Dashboard `Connect Bridge`.",""].join(`
311
+ `)),!await Xn(t,"Delete local bridge credentials too? [y/N] "))return t.stdout(`Kept local bridge credentials.
312
+ `),!1;let r=e.agentId.slice(-6);return t.stdout(`Type the last 6 characters of the Agent ID (${r}) to confirm credential deletion: `),(await S$()).trim()!==r?(t.stdout(`Confirmation did not match. Kept local bridge credentials.
313
+ `),!1):(em(),t.stdout(`Local bridge credentials removed from this machine.
314
+ `),!0)}function v$(){try{return W()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}async function b$(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),1500);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`unknown (server returned HTTP ${o.status})`;let i=await o.json().catch(()=>{});if(!i||typeof i!="object")return"unknown";let s=i.status;return s==="ready"?"claimed, ready":s==="needs_official_name"?"claimed, official name pending":s==="pending_claim"?"unclaimed":"unknown"}catch{return"unknown (server check unavailable)"}finally{clearTimeout(r)}}async function S$(){process.stdin.resume(),process.stdin.setEncoding("utf8");let t=await new Promise(e=>{process.stdin.once("data",n=>e(String(n)))});return process.stdin.pause(),t}async function E$(t){try{let e=await ii(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
315
+ `)}catch(e){let n=e instanceof X||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
316
+ `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function k$(t){let e=cc();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
317
+ `);return}e.openclaw?.responsesEnabledByAIFight&&await $$(t),e.hermes&&await R$(t,e.hermes.envPath,e.hermes.previous)}async function $$(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(`
318
+ `)),!await Xn(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${pp} false --strict-json
319
+ `);return}if(!Pe("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
320
+ `);return}let n=await it("openclaw",["config","set",pp,"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.
321
+ `);return}let r=await it("openclaw",["config","validate"]);gn(t,"openclaw config validate",r),await Zn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function R$(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(`
322
+ `)),!await Xn(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
308
323
  `);return}if(!hi.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
309
- `);return}let o=hi.readFileSync(e,"utf8"),i=b$(o,n);if(hi.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{hi.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
310
- `),await Xn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function b$(t,e){let n=new Set(pp),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 pp){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
324
+ `);return}let o=hi.readFileSync(e,"utf8"),i=A$(o,n);if(hi.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{hi.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
325
+ `),await Zn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function A$(t,e){let n=new Set(hp),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 hp){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
311
326
  `).replace(/\n*$/,`
312
- `)}async function _p(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=S$(t)?t.slice(2):t.slice(),i=xc(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"},{name:"yes",type:"boolean"}]),s=i.flags.json===!0;if(i.errors.length>0)return wp(i.errors[0],n,s);if(i.flags.version===!0)return Za({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?Pc(n,s):$$(i.positional,n,s);if(i.positional.length===0)return Pc(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await E$(a,c,n)}catch(l){return R$(l,n,s)}}function S$(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 E$(t,e,n){switch(t){case"version":return Za(e,n);case"doctor":return rm(e,n);case"register":return Em(e,n);case"connect":return Am(e,n);case"start":return Cm(e,n);case"run":return sp(e,n);case"status":return ap(e,n);case"update":return cp(e,n);case"service":return um(e,n);case"uninstall":return gp(e,n);case"set":return lp(e,n);case"challenge":return dp(e,n);case"accept":return fp(e,n);default:throw new O(`unknown command '${t}'`)}}function yp(){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 update Update the CLI package and restart service if installed"," 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"," --yes Update only: run npm update without an interactive confirmation","",`Supported games for manual matches: ${he.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
313
- `)}function Pc(t,e){return e?t.stdout(JSON.stringify({help:yp()})+`
314
- `):t.stdout(yp()+`
315
- `),0}function k$(t){switch(t[0]){case"version":return`Usage: aifight version
327
+ `)}async function wp(t,e={}){let n={stdout:e.stdout??(u=>process.stdout.write(u)),stderr:e.stderr??(u=>process.stderr.write(u)),...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=P$(t)?t.slice(2):t.slice(),i=Cc(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"},{name:"yes",type:"boolean"},{name:"replace-local-identity",type:"boolean"}]),s=i.flags.json===!0;if(i.errors.length>0)return vp(i.errors[0],n,s);if(i.flags.version===!0)return Za({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?Ac(n,s):x$(i.positional,n,s);if(i.positional.length===0)return Ac(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await T$(a,c,n)}catch(u){return I$(u,n,s)}}function P$(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 T$(t,e,n){switch(t){case"version":return Za(e,n);case"doctor":return rm(e,n);case"register":return Em(e,n);case"connect":return Tm(e,n);case"start":return Im(e,n);case"run":return ap(e,n);case"status":return cp(e,n);case"update":return lp(e,n);case"service":return um(e,n);case"uninstall":return yp(e,n);case"set":return up(e,n);case"challenge":return fp(e,n);case"accept":return mp(e,n);default:throw new O(`unknown command '${t}'`)}}function _p(){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 update Update the CLI package and restart service if installed"," 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"," --yes Update only: run npm update without an interactive confirmation"," --replace-local-identity Bridge connect only: approve replacing existing local bridge credentials","",`Supported games for manual matches: ${he.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
328
+ `)}function Ac(t,e){return e?t.stdout(JSON.stringify({help:_p()})+`
329
+ `):t.stdout(_p()+`
330
+ `),0}function C$(t){switch(t[0]){case"version":return`Usage: aifight version
316
331
  Print the AIFight CLI version.`;case"doctor":return["Usage: aifight doctor"," Diagnose local bridge config, package version policy, and runtime endpoint reachability."].join(`
317
332
  `);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 installs or reloads aifight.service when approved."," If local runtime auth is enabled, register stores the runtime token only in local bridge credentials."," 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(`
318
- `);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(`
333
+ `);case"connect":return["Usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--replace-local-identity]"," Exchange a one-time dashboard pairing code and save local bridge config."," Pairing rotates the Agent bridge API key; old local bridge credentials stop working."," 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]."," If this machine already has local bridge credentials, approve replacement with --replace-local-identity."].join(`
319
334
  `);case"start":return["Usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running Bridge."," Manual starts do not consume the daily automatic match limit."," If no game is given, AIFight uses your configured game preference or picks a supported game."," N must be between 1 and 20.",` supported games: ${he.join(", ")}`].join(`
320
335
  `);case"run":return["Usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," Normal installs should use aifight.service; use `aifight start` to request matches."," If aifight.service is already running, run refuses unless --force is set."].join(`
321
336
  `);case"status":return["Usage: aifight status"," Show local bridge config with API key and runtime token redacted."].join(`
@@ -325,12 +340,12 @@ ${t.message}
325
340
  `);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: ${he.join(", ")}`].join(`
326
341
  `);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(`
327
342
  `);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(`
328
- `);default:return}}function $$(t,e,n){let r=k$(t);return r===void 0?Pc(e,n):(n?e.stdout(JSON.stringify({help:r})+`
343
+ `);default:return}}function x$(t,e,n){let r=C$(t);return r===void 0?Ac(e,n):(n?e.stdout(JSON.stringify({help:r})+`
329
344
  `):e.stdout(r+`
330
- `),0)}function wp(t,e,n,r){return n?e.stderr(no("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
345
+ `),0)}function vp(t,e,n,r){return n?e.stderr(no("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
331
346
  `),r!==void 0&&e.stderr(`${r}
332
- `)),2}function R$(t,e,n){if(t instanceof O)return wp(t.message,e,n,t.hint);if(t instanceof U)return n?e.stderr(no(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
347
+ `)),2}function I$(t,e,n){if(t instanceof O)return vp(t.message,e,n,t.hint);if(t instanceof B)return n?e.stderr(no(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
333
348
  `),t.hint!==void 0&&e.stderr(`${t.hint}
334
349
  `)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(no("client_unexpected_error",r)):e.stderr(`aifight: unexpected error: ${r}
335
- `),99}_p(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
350
+ `),99}wp(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
336
351
  `),process.exit(99)});