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

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.
Files changed (96) hide show
  1. package/README.md +73 -6
  2. package/dist/bin.mjs +193 -144
  3. package/dist/index.mjs +1 -1
  4. package/dist/types/index.d.ts +1 -1
  5. package/package.json +3 -2
  6. package/dist/types/agents/agent.d.ts +0 -82
  7. package/dist/types/agents/state-machine.d.ts +0 -96
  8. package/dist/types/bridge/auto-update.d.ts +0 -53
  9. package/dist/types/bridge/config.d.ts +0 -35
  10. package/dist/types/bridge/hermes-provider.d.ts +0 -9
  11. package/dist/types/bridge/openclaw-provider.d.ts +0 -9
  12. package/dist/types/bridge/pairing.d.ts +0 -18
  13. package/dist/types/bridge/provider.d.ts +0 -18
  14. package/dist/types/bridge/runner.d.ts +0 -30
  15. package/dist/types/bridge/service.d.ts +0 -55
  16. package/dist/types/bridge/update-check.d.ts +0 -23
  17. package/dist/types/cli/agent-resolver.d.ts +0 -25
  18. package/dist/types/cli/argv.d.ts +0 -13
  19. package/dist/types/cli/commands/agent-list.d.ts +0 -2
  20. package/dist/types/cli/commands/agent-status.d.ts +0 -2
  21. package/dist/types/cli/commands/bridge-accept.d.ts +0 -2
  22. package/dist/types/cli/commands/bridge-challenge.d.ts +0 -2
  23. package/dist/types/cli/commands/bridge-connect.d.ts +0 -2
  24. package/dist/types/cli/commands/bridge-register.d.ts +0 -7
  25. package/dist/types/cli/commands/bridge-run.d.ts +0 -7
  26. package/dist/types/cli/commands/bridge-service.d.ts +0 -5
  27. package/dist/types/cli/commands/bridge-set.d.ts +0 -2
  28. package/dist/types/cli/commands/bridge-start.d.ts +0 -2
  29. package/dist/types/cli/commands/bridge-status.d.ts +0 -2
  30. package/dist/types/cli/commands/bridge-uninstall.d.ts +0 -4
  31. package/dist/types/cli/commands/bridge-update.d.ts +0 -2
  32. package/dist/types/cli/commands/config-init.d.ts +0 -2
  33. package/dist/types/cli/commands/config-probe.d.ts +0 -2
  34. package/dist/types/cli/commands/config-validate.d.ts +0 -2
  35. package/dist/types/cli/commands/daily-off.d.ts +0 -2
  36. package/dist/types/cli/commands/daily-on.d.ts +0 -2
  37. package/dist/types/cli/commands/daily-set.d.ts +0 -2
  38. package/dist/types/cli/commands/daily-show.d.ts +0 -2
  39. package/dist/types/cli/commands/doctor.d.ts +0 -2
  40. package/dist/types/cli/commands/init.d.ts +0 -2
  41. package/dist/types/cli/commands/join.d.ts +0 -2
  42. package/dist/types/cli/commands/leave.d.ts +0 -2
  43. package/dist/types/cli/commands/mcp.d.ts +0 -2
  44. package/dist/types/cli/commands/runtime-management.d.ts +0 -18
  45. package/dist/types/cli/commands/runtime-setup-state.d.ts +0 -21
  46. package/dist/types/cli/commands/runtime-setup.d.ts +0 -25
  47. package/dist/types/cli/commands/serve.d.ts +0 -2
  48. package/dist/types/cli/commands/service/launchd.d.ts +0 -71
  49. package/dist/types/cli/commands/service/platform.d.ts +0 -69
  50. package/dist/types/cli/commands/service/systemd.d.ts +0 -55
  51. package/dist/types/cli/commands/service/types.d.ts +0 -64
  52. package/dist/types/cli/commands/service-install.d.ts +0 -29
  53. package/dist/types/cli/commands/setup.d.ts +0 -2
  54. package/dist/types/cli/commands/shutdown.d.ts +0 -2
  55. package/dist/types/cli/commands/stubs.d.ts +0 -24
  56. package/dist/types/cli/commands/version.d.ts +0 -2
  57. package/dist/types/cli/control-client.d.ts +0 -59
  58. package/dist/types/cli/format.d.ts +0 -52
  59. package/dist/types/cli/main.d.ts +0 -18
  60. package/dist/types/cli/runtime-files.d.ts +0 -11
  61. package/dist/types/cli/shared.d.ts +0 -74
  62. package/dist/types/controlapi/profile-routes.d.ts +0 -49
  63. package/dist/types/controlapi/server.d.ts +0 -3
  64. package/dist/types/controlapi/types.d.ts +0 -136
  65. package/dist/types/daemon/agent-decision-adapter.d.ts +0 -40
  66. package/dist/types/daemon/lifecycle.d.ts +0 -85
  67. package/dist/types/daemon/router.d.ts +0 -97
  68. package/dist/types/daemon/runtime-files-write.d.ts +0 -76
  69. package/dist/types/identity/identity-manager.d.ts +0 -59
  70. package/dist/types/llm/adapter-registry.d.ts +0 -27
  71. package/dist/types/llm/adapters/anthropic-messages.d.ts +0 -2
  72. package/dist/types/llm/adapters/deepseek-chat-completions.d.ts +0 -2
  73. package/dist/types/llm/adapters/openai-chat-compat.d.ts +0 -2
  74. package/dist/types/llm/adapters/openai-chat-completions.d.ts +0 -2
  75. package/dist/types/llm/adapters/openai-responses.d.ts +0 -2
  76. package/dist/types/llm/adapters/types.d.ts +0 -128
  77. package/dist/types/llm/capabilities/validate-capabilities.d.ts +0 -68
  78. package/dist/types/mcp/control-client.d.ts +0 -54
  79. package/dist/types/mcp/profile-tools.d.ts +0 -10
  80. package/dist/types/mcp/server.d.ts +0 -10
  81. package/dist/types/mcp/tools.d.ts +0 -31
  82. package/dist/types/mcp/types.d.ts +0 -27
  83. package/dist/types/profile/config-schema.d.ts +0 -199
  84. package/dist/types/profile/identity-schema.d.ts +0 -75
  85. package/dist/types/profile/index.d.ts +0 -7
  86. package/dist/types/profile/migrate.d.ts +0 -16
  87. package/dist/types/profile/profile-loader.d.ts +0 -64
  88. package/dist/types/profile/secret-ref.d.ts +0 -82
  89. package/dist/types/profile/soul.d.ts +0 -46
  90. package/dist/types/profile/strategy-schema.d.ts +0 -70
  91. package/dist/types/reflection/proposal-store.d.ts +0 -50
  92. package/dist/types/reflection/reflection-engine.d.ts +0 -81
  93. package/dist/types/scheduler/daily.d.ts +0 -47
  94. package/dist/types/scheduler/types.d.ts +0 -42
  95. package/dist/types/session/match-session-manager.d.ts +0 -113
  96. package/dist/types/session/session-context-builder.d.ts +0 -68
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 th=Object.create;var Fc=Object.defineProperty;var nh=Object.getOwnPropertyDescriptor;var rh=Object.getOwnPropertyNames;var oh=Object.getPrototypeOf,ih=Object.prototype.hasOwnProperty;var ne=(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 sh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of rh(e))!ih.call(t,o)&&o!==n&&Fc(t,o,{get:()=>e[o],enumerable:!(r=nh(e,o))||r.enumerable});return t};var Ce=(t,e,n)=>(n=t!=null?th(oh(t)):{},sh(e||!t||!t.__esModule?Fc(n,"default",{value:t,enumerable:!0}):n,t));var pr=_(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 fr=class{};D._CodeOrName=fr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wt=class extends fr{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=Wt;var Ie=class extends fr{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 Wt&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=Ie;D.nil=new Ie("");function tl(t,...e){let n=[t[0]],r=0;for(;r<e.length;)xi(n,e[r]),n.push(t[++r]);return new Ie(n)}D._=tl;var Pi=new Ie("+");function nl(t,...e){let n=[mr(t[0])],r=0;for(;r<e.length;)n.push(Pi),xi(n,e[r]),n.push(Pi,mr(t[++r]));return bh(n),new Ie(n)}D.str=nl;function xi(t,e){e instanceof Ie?t.push(...e._items):e instanceof Wt?t.push(e):t.push(Eh(e))}D.addCodeArg=xi;function bh(t){let e=1;for(;e<t.length-1;){if(t[e]===Pi){let n=Sh(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Sh(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Wt||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 Wt))return`"${t}${e.slice(1)}`}function vh(t,e){return e.emptyStr()?t:t.emptyStr()?e:nl`${t}${e}`}D.strConcat=vh;function Eh(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:mr(Array.isArray(t)?t.join(","):t)}function kh(t){return new Ie(mr(t))}D.stringify=kh;function mr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=mr;function $h(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new Ie(`.${t}`):tl`[${t}]`}D.getProperty=$h;function Rh(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new Ie(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Rh;function Ah(t){return new Ie(t.toString())}D.regexpCode=Ah});var Oi=_(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.ValueScope=be.ValueScopeName=be.Scope=be.varKinds=be.UsedValueState=void 0;var we=pr(),Ci=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},uo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(uo||(be.UsedValueState=uo={}));be.varKinds={const:new we.Name("const"),let:new we.Name("let"),var:new we.Name("var")};var fo=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}}};be.Scope=fo;var mo=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}]`}};be.ValueScopeName=mo;var Th=(0,we._)`\n`,Ii=class extends fo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Th:we.nil}}get(){return this._scope}name(e){return new mo(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,uo.Started);let l=n(u);if(l){let d=this.opts.es5?be.varKinds.var:be.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 Ci(u);c.set(u,uo.Completed)})}return i}};be.ValueScope=Ii});var x=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.or=I.and=I.not=I.CodeGen=I.operators=I.varKinds=I.ValueScopeName=I.ValueScope=I.Scope=I.Name=I.regexpCode=I.stringify=I.getProperty=I.nil=I.strConcat=I.str=I._=void 0;var M=pr(),Ue=Oi(),Rt=pr();Object.defineProperty(I,"_",{enumerable:!0,get:function(){return Rt._}});Object.defineProperty(I,"str",{enumerable:!0,get:function(){return Rt.str}});Object.defineProperty(I,"strConcat",{enumerable:!0,get:function(){return Rt.strConcat}});Object.defineProperty(I,"nil",{enumerable:!0,get:function(){return Rt.nil}});Object.defineProperty(I,"getProperty",{enumerable:!0,get:function(){return Rt.getProperty}});Object.defineProperty(I,"stringify",{enumerable:!0,get:function(){return Rt.stringify}});Object.defineProperty(I,"regexpCode",{enumerable:!0,get:function(){return Rt.regexpCode}});Object.defineProperty(I,"Name",{enumerable:!0,get:function(){return Rt.Name}});var yo=Oi();Object.defineProperty(I,"Scope",{enumerable:!0,get:function(){return yo.Scope}});Object.defineProperty(I,"ValueScope",{enumerable:!0,get:function(){return yo.ValueScope}});Object.defineProperty(I,"ValueScopeName",{enumerable:!0,get:function(){return yo.ValueScopeName}});Object.defineProperty(I,"varKinds",{enumerable:!0,get:function(){return yo.varKinds}});I.operators={GT:new M._Code(">"),GTE:new M._Code(">="),LT:new M._Code("<"),LTE:new M._Code("<="),EQ:new M._Code("==="),NEQ:new M._Code("!=="),NOT:new M._Code("!"),OR:new M._Code("||"),AND:new M._Code("&&"),ADD:new M._Code("+")};var dt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Mi=class extends dt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?Ue.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=kn(this.rhs,e,n)),this}get names(){return this.rhs instanceof M._CodeOrName?this.rhs.names:{}}},po=class extends dt{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 M.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=kn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof M.Name?{}:{...this.lhs.names};return go(e,this.rhs)}},Ni=class extends po{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Li=class extends dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ji=class extends dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Di=class extends dt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Bi=class extends dt{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=kn(this.code,e,n),this}get names(){return this.code instanceof M._CodeOrName?this.code.names:{}}},hr=class extends dt{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)||(Ph(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Kt(e,n.names),{})}},ft=class extends hr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Fi=class extends hr{},En=class extends ft{};En.kind="else";var Vt=class t extends ft{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 En(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(rl(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=kn(this.condition,e,n),this}get names(){let e=super.names;return go(e,this.condition),this.else&&Kt(e,this.else.names),e}};Vt.kind="if";var zt=class extends ft{};zt.kind="for";var Ui=class extends zt{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=kn(this.iteration,e,n),this}get names(){return Kt(super.names,this.iteration.names)}},Hi=class extends zt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?Ue.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=go(super.names,this.from);return go(e,this.to)}},ho=class extends zt{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=kn(this.iterable,e,n),this}get names(){return Kt(super.names,this.iterable.names)}},gr=class extends ft{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)}};gr.kind="func";var yr=class extends hr{render(e){return"return "+super.render(e)}};yr.kind="return";var qi=class extends ft{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&&Kt(e,this.catch.names),this.finally&&Kt(e,this.finally.names),e}},_r=class extends ft{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};_r.kind="catch";var wr=class extends ft{render(e){return"finally"+super.render(e)}};wr.kind="finally";var Gi=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
+ `:""},this._extScope=e,this._scope=new Ue.Scope({parent:e}),this._nodes=[new Fi]}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 Mi(e,i,r)),i}const(e,n,r){return this._def(Ue.varKinds.const,e,n,r)}let(e,n,r){return this._def(Ue.varKinds.let,e,n,r)}var(e,n,r){return this._def(Ue.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new po(e,n,r))}add(e,n){return this._leafNode(new Ni(e,I.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==M.nil&&this._leafNode(new Bi(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,M.addCodeArg)(n,o));return n.push("}"),new M._Code(n)}if(e,n,r){if(this._blockNode(new Vt(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 Vt(e))}else(){return this._elseNode(new En)}endIf(){return this._endBlockNode(Vt,En)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Ui(e),n)}forRange(e,n,r,o,i=this.opts.es5?Ue.varKinds.var:Ue.varKinds.let){let s=this._scope.toName(e);return this._for(new Hi(i,s,n,r),()=>o(s))}forOf(e,n,r,o=Ue.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof M.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,M._)`${s}.length`,a=>{this.var(i,(0,M._)`${s}[${a}]`),r(i)})}return this._for(new ho("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?Ue.varKinds.var:Ue.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,M._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new ho("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(zt)}label(e){return this._leafNode(new Li(e))}break(e){return this._leafNode(new ji(e))}return(e){let n=new yr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(yr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new qi;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new _r(i),n(i)}return r&&(this._currNode=o.finally=new wr,this.code(r)),this._endBlockNode(_r,wr)}throw(e){return this._leafNode(new Di(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=M.nil,r,o){return this._blockNode(new gr(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(gr)}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 Vt))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}};I.CodeGen=Gi;function Kt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function go(t,e){return e instanceof M._CodeOrName?Kt(t,e.names):t}function kn(t,e,n){if(t instanceof M.Name)return r(t);if(!o(t))return t;return new M._Code(t._items.reduce((i,s)=>(s instanceof M.Name&&(s=r(s)),s instanceof M._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 M._Code&&i._items.some(s=>s instanceof M.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Ph(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function rl(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,M._)`!${Wi(t)}`}I.not=rl;var xh=ol(I.operators.AND);function Ch(...t){return t.reduce(xh)}I.and=Ch;var Ih=ol(I.operators.OR);function Oh(...t){return t.reduce(Ih)}I.or=Oh;function ol(t){return(e,n)=>e===M.nil?n:n===M.nil?e:(0,M._)`${Wi(e)} ${t} ${Wi(n)}`}function Wi(t){return t instanceof M.Name?t:(0,M._)`(${t})`}});var N=_(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.checkStrictMode=O.getErrorPath=O.Type=O.useFunc=O.setEvaluated=O.evaluatedPropsToName=O.mergeEvaluated=O.eachItem=O.unescapeJsonPointer=O.escapeJsonPointer=O.escapeFragment=O.unescapeFragment=O.schemaRefOrVal=O.schemaHasRulesButRef=O.schemaHasRules=O.checkUnknownRules=O.alwaysValidSchema=O.toHash=void 0;var G=x(),Mh=pr();function Nh(t){let e={};for(let n of t)e[n]=!0;return e}O.toHash=Nh;function Lh(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(al(t,e),!cl(e,t.self.RULES.all))}O.alwaysValidSchema=Lh;function al(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]||dl(t,`unknown keyword: "${i}"`)}O.checkUnknownRules=al;function cl(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}O.schemaHasRules=cl;function jh(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}O.schemaHasRulesButRef=jh;function Dh({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,G._)`${n}`}return(0,G._)`${t}${e}${(0,G.getProperty)(r)}`}O.schemaRefOrVal=Dh;function Bh(t){return ll(decodeURIComponent(t))}O.unescapeFragment=Bh;function Fh(t){return encodeURIComponent(zi(t))}O.escapeFragment=Fh;function zi(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}O.escapeJsonPointer=zi;function ll(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}O.unescapeJsonPointer=ll;function Uh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}O.eachItem=Uh;function il({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof G.Name?(i instanceof G.Name?t(o,i,s):e(o,i,s),s):i instanceof G.Name?(e(o,s,i),i):n(i,s);return a===G.Name&&!(c instanceof G.Name)?r(o,c):c}}O.mergeEvaluated={props:il({mergeNames:(t,e,n)=>t.if((0,G._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,G._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,G._)`${n} || {}`).code((0,G._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,G._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,G._)`${n} || {}`),Ki(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ul}),items:il({mergeNames:(t,e,n)=>t.if((0,G._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,G._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,G._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,G._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ul(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,G._)`{}`);return e!==void 0&&Ki(t,n,e),n}O.evaluatedPropsToName=ul;function Ki(t,e,n){Object.keys(n).forEach(r=>t.assign((0,G._)`${e}${(0,G.getProperty)(r)}`,!0))}O.setEvaluated=Ki;var sl={};function Hh(t,e){return t.scopeValue("func",{ref:e,code:sl[e.code]||(sl[e.code]=new Mh._Code(e.code))})}O.useFunc=Hh;var Vi;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vi||(O.Type=Vi={}));function qh(t,e,n){if(t instanceof G.Name){let r=e===Vi.Num;return n?r?(0,G._)`"[" + ${t} + "]"`:(0,G._)`"['" + ${t} + "']"`:r?(0,G._)`"/" + ${t}`:(0,G._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,G.getProperty)(t).toString():"/"+zi(t)}O.getErrorPath=qh;function dl(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}O.checkStrictMode=dl});var mt=_(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});var de=x(),Gh={data:new de.Name("data"),valCxt:new de.Name("valCxt"),instancePath:new de.Name("instancePath"),parentData:new de.Name("parentData"),parentDataProperty:new de.Name("parentDataProperty"),rootData:new de.Name("rootData"),dynamicAnchors:new de.Name("dynamicAnchors"),vErrors:new de.Name("vErrors"),errors:new de.Name("errors"),this:new de.Name("this"),self:new de.Name("self"),scope:new de.Name("scope"),json:new de.Name("json"),jsonPos:new de.Name("jsonPos"),jsonLen:new de.Name("jsonLen"),jsonPart:new de.Name("jsonPart")};Ji.default=Gh});var br=_(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.extendErrors=fe.resetErrorsCount=fe.reportExtraError=fe.reportError=fe.keyword$DataError=fe.keywordError=void 0;var L=x(),_o=N(),ge=mt();fe.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};fe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function Wh(t,e=fe.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=pl(t,e,n);r??(s||a)?fl(i,c):ml(o,(0,L._)`[${c}]`)}fe.reportError=Wh;function Vh(t,e=fe.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=pl(t,e,n);fl(o,a),i||s||ml(r,ge.default.vErrors)}fe.reportExtraError=Vh;function zh(t,e){t.assign(ge.default.errors,e),t.if((0,L._)`${ge.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${ge.default.vErrors}.length`,e),()=>t.assign(ge.default.vErrors,null)))}fe.resetErrorsCount=zh;function Kh({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,L._)`${ge.default.vErrors}[${a}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(ge.default.instancePath,i.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,r))})}fe.extendErrors=Kh;function fl(t,e){let n=t.const("err",e);t.if((0,L._)`${ge.default.vErrors} === null`,()=>t.assign(ge.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${ge.default.vErrors}.push(${n})`),t.code((0,L._)`${ge.default.errors}++`)}function ml(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${r}.errors`,e),n.return(!1))}var Jt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function pl(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,L._)`{}`:Jh(t,e,n)}function Jh(t,e,n={}){let{gen:r,it:o}=t,i=[Yh(o,n),Qh(t,n)];return Xh(t,e,i),r.object(...i)}function Yh({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,_o.getErrorPath)(e,_o.Type.Str)}`:t;return[ge.default.instancePath,(0,L.strConcat)(ge.default.instancePath,n)]}function Qh({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,L.str)`${e}/${t}`;return n&&(o=(0,L.str)`${o}${(0,_o.getErrorPath)(n,_o.Type.Str)}`),[Jt.schemaPath,o]}function Xh(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([Jt.keyword,o],[Jt.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),c.messages&&r.push([Jt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Jt.schema,s],[Jt.parentSchema,(0,L._)`${l}${d}`],[ge.default.data,i]),u&&r.push([Jt.propertyName,u])}});var gl=_($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.boolOrEmptySchema=$n.topBoolOrEmptySchema=void 0;var Zh=br(),eg=x(),tg=mt(),ng={message:"boolean schema is false"};function rg(t){let{gen:e,schema:n,validateName:r}=t;n===!1?hl(t,!1):typeof n=="object"&&n.$async===!0?e.return(tg.default.data):(e.assign((0,eg._)`${r}.errors`,null),e.return(!0))}$n.topBoolOrEmptySchema=rg;function og(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),hl(t)):n.var(e,!0)}$n.boolOrEmptySchema=og;function hl(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,Zh.reportError)(o,ng,void 0,e)}});var Yi=_(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.getRules=Rn.isJSONType=void 0;var ig=["string","number","integer","boolean","null","object","array"],sg=new Set(ig);function ag(t){return typeof t=="string"&&sg.has(t)}Rn.isJSONType=ag;function cg(){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:{}}}Rn.getRules=cg});var Qi=_(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.shouldUseRule=At.shouldUseGroup=At.schemaHasRulesForType=void 0;function lg({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&yl(t,r)}At.schemaHasRulesForType=lg;function yl(t,e){return e.rules.some(n=>_l(t,n))}At.shouldUseGroup=yl;function _l(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))}At.shouldUseRule=_l});var Sr=_(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.reportTypeError=me.checkDataTypes=me.checkDataType=me.coerceAndCheckDataType=me.getJSONTypes=me.getSchemaTypes=me.DataType=void 0;var ug=Yi(),dg=Qi(),fg=br(),P=x(),wl=N(),An;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(An||(me.DataType=An={}));function mg(t){let e=bl(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}me.getSchemaTypes=mg;function bl(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(ug.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}me.getJSONTypes=bl;function pg(t,e){let{gen:n,data:r,opts:o}=t,i=hg(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,dg.schemaHasRulesForType)(t,e[0]));if(s){let a=Zi(e,r,o.strictNumbers,An.Wrong);n.if(a,()=>{i.length?gg(t,e,i):es(t)})}return s}me.coerceAndCheckDataType=pg;var Sl=new Set(["string","number","integer","boolean","null"]);function hg(t,e){return e?t.filter(n=>Sl.has(n)||e==="array"&&n==="array"):[]}function gg(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(Zi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,P._)`${a} !== undefined`);for(let u of n)(Sl.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);r.else(),es(t),r.endIf(),r.if((0,P._)`${a} !== undefined`,()=>{r.assign(o,a),yg(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 yg({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,P._)`${e} !== undefined`,()=>t.assign((0,P._)`${e}[${n}]`,r))}function Xi(t,e,n,r=An.Correct){let o=r===An.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===An.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)}}me.checkDataType=Xi;function Zi(t,e,n,r){if(t.length===1)return Xi(t[0],e,n,r);let o,i=(0,wl.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,Xi(s,e,n,r));return o}me.checkDataTypes=Zi;var _g={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,P._)`{type: ${t}}`:(0,P._)`{type: ${e}}`};function es(t){let e=wg(t);(0,fg.reportError)(e,_g)}me.reportTypeError=es;function wg(t){let{gen:e,data:n,schema:r}=t,o=(0,wl.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var El=_(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.assignDefaults=void 0;var Tn=x(),bg=N();function Sg(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)vl(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>vl(t,i,o.default))}wo.assignDefaults=Sg;function vl(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,Tn._)`${i}${(0,Tn.getProperty)(e)}`;if(o){(0,bg.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Tn._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,Tn._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Tn._)`${a} = ${(0,Tn.stringify)(n)}`)}});var Oe=_(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.validateUnion=H.validateArray=H.usePattern=H.callValidateCode=H.schemaProperties=H.allSchemaProperties=H.noPropertyInData=H.propertyInData=H.isOwnProperty=H.hasPropFunc=H.reportMissingProp=H.checkMissingProp=H.checkReportMissingProp=void 0;var V=x(),ts=N(),Tt=mt(),vg=N();function Eg(t,e){let{gen:n,data:r,it:o}=t;n.if(rs(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,V._)`${e}`},!0),t.error()})}H.checkReportMissingProp=Eg;function kg({gen:t,data:e,it:{opts:n}},r,o){return(0,V.or)(...r.map(i=>(0,V.and)(rs(t,e,i,n.ownProperties),(0,V._)`${o} = ${i}`)))}H.checkMissingProp=kg;function $g(t,e){t.setParams({missingProperty:e},!0),t.error()}H.reportMissingProp=$g;function kl(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,V._)`Object.prototype.hasOwnProperty`})}H.hasPropFunc=kl;function ns(t,e,n){return(0,V._)`${kl(t)}.call(${e}, ${n})`}H.isOwnProperty=ns;function Rg(t,e,n,r){let o=(0,V._)`${e}${(0,V.getProperty)(n)} !== undefined`;return r?(0,V._)`${o} && ${ns(t,e,n)}`:o}H.propertyInData=Rg;function rs(t,e,n,r){let o=(0,V._)`${e}${(0,V.getProperty)(n)} === undefined`;return r?(0,V.or)(o,(0,V.not)(ns(t,e,n))):o}H.noPropertyInData=rs;function $l(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}H.allSchemaProperties=$l;function Ag(t,e){return $l(e).filter(n=>!(0,ts.alwaysValidSchema)(t,e[n]))}H.schemaProperties=Ag;function Tg({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,u){let l=u?(0,V._)`${t}, ${e}, ${r}${o}`:e,d=[[Tt.default.instancePath,(0,V.strConcat)(Tt.default.instancePath,i)],[Tt.default.parentData,s.parentData],[Tt.default.parentDataProperty,s.parentDataProperty],[Tt.default.rootData,Tt.default.rootData]];s.opts.dynamicRef&&d.push([Tt.default.dynamicAnchors,Tt.default.dynamicAnchors]);let h=(0,V._)`${l}, ${n.object(...d)}`;return c!==V.nil?(0,V._)`${a}.call(${c}, ${h})`:(0,V._)`${a}(${h})`}H.callValidateCode=Tg;var Pg=(0,V._)`new RegExp`;function xg({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,V._)`${o.code==="new RegExp"?Pg:(0,vg.useFunc)(t,o)}(${n}, ${r})`})}H.usePattern=xg;function Cg(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,V._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:ts.Type.Num},i),e.if((0,V.not)(i),a)})}}H.validateArray=Cg;function Ig(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,ts.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,V._)`${s} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,V.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}H.validateUnion=Ig});var Tl=_(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.validateKeywordUsage=Ze.validSchemaType=Ze.funcKeywordCode=Ze.macroKeywordCode=void 0;var ye=x(),Yt=mt(),Og=Oe(),Mg=br();function Ng(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=Al(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))}Ze.macroKeywordCode=Ng;function Lg(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;Dg(c,e);let u=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,l=Al(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&&Rl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&Rl(t),g(()=>jg(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ye._)`await `),b=>r.assign(d,!1).if((0,ye._)`${b} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ye._)`${b}.errors`),()=>r.throw(b))),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 b=c.opts.passContext?Yt.default.this:Yt.default.self,v=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ye._)`${y}${(0,Og.callValidateCode)(t,l,b,v)}`,e.modifying)}function g(y){var b;r.if((0,ye.not)((b=e.valid)!==null&&b!==void 0?b:d),y)}}Ze.funcKeywordCode=Lg;function Rl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ye._)`${r.parentData}[${r.parentDataProperty}]`))}function jg(t,e){let{gen:n}=t;n.if((0,ye._)`Array.isArray(${e})`,()=>{n.assign(Yt.default.vErrors,(0,ye._)`${Yt.default.vErrors} === null ? ${e} : ${Yt.default.vErrors}.concat(${e})`).assign(Yt.default.errors,(0,ye._)`${Yt.default.vErrors}.length`),(0,Mg.extendErrors)(t)},()=>t.error())}function Dg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Al(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 Bg(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")}Ze.validSchemaType=Bg;function Fg({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)}}Ze.validateKeywordUsage=Fg});var xl=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendSubschemaMode=Pt.extendSubschemaData=Pt.getSubschema=void 0;var et=x(),Pl=N();function Ug(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,et._)`${t.schemaPath}${(0,et.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,et._)`${t.schemaPath}${(0,et.getProperty)(e)}${(0,et.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Pl.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Pt.getSubschema=Ug;function Hg(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,et._)`${e.data}${(0,et.getProperty)(n)}`,!0);c(h),t.errorPath=(0,et.str)`${u}${(0,Pl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,et._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof et.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]}}Pt.extendSubschemaData=Hg;function qg(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=qg});var os=_((SA,Cl)=>{"use strict";Cl.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 Ol=_((vA,Il)=>{"use strict";var xt=Il.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(){};bo(e,r,o,t,"",t)};xt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xt.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 bo(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 xt.arrayKeywords)for(var h=0;h<d.length;h++)bo(t,e,n,d[h],o+"/"+l+"/"+h,i,o,l,r,h)}else if(l in xt.propsKeywords){if(d&&typeof d=="object")for(var p in d)bo(t,e,n,d[p],o+"/"+l+"/"+Gg(p),i,o,l,r,p)}else(l in xt.keywords||t.allKeys&&!(l in xt.skipKeywords))&&bo(t,e,n,d,o+"/"+l,i,o,l,r)}n(r,o,i,s,a,c,u)}}function Gg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var vr=_(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.getSchemaRefs=Se.resolveUrl=Se.normalizeId=Se._getFullPath=Se.getFullPath=Se.inlineRef=void 0;var Wg=N(),Vg=os(),zg=Ol(),Kg=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Jg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!is(t):e?Ml(t)<=e:!1}Se.inlineRef=Jg;var Yg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function is(t){for(let e in t){if(Yg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(is)||typeof n=="object"&&is(n))return!0}return!1}function Ml(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!Kg.has(n)&&(typeof t[n]=="object"&&(0,Wg.eachItem)(t[n],r=>e+=Ml(r)),e===1/0))return 1/0}return e}function Nl(t,e="",n){n!==!1&&(e=Pn(e));let r=t.parse(e);return Ll(t,r)}Se.getFullPath=Nl;function Ll(t,e){return t.serialize(e).split("#")[0]+"#"}Se._getFullPath=Ll;var Qg=/#\/?$/;function Pn(t){return t?t.replace(Qg,""):""}Se.normalizeId=Pn;function Xg(t,e,n){return n=Pn(n),t.resolve(e,n)}Se.resolveUrl=Xg;var Zg=/^[a-z_][-a-z0-9._]*$/i;function ey(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Pn(t[n]||e),i={"":o},s=Nl(r,o,!1),a={},c=new Set;return zg(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])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[h]=g;function y(v){let R=this.opts.uriResolver.resolve;if(v=Pn(g?R(g,v):v),c.has(v))throw l(v);c.add(v);let $=this.refs[v];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,v):v!==Pn(m)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=m),v}function b(v){if(typeof v=="string"){if(!Zg.test(v))throw new Error(`invalid anchor "${v}"`);y.call(this,`#${v}`)}}}),a;function u(d,h,p){if(h!==void 0&&!Vg(d,h))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Se.getSchemaRefs=ey});var $r=_(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.getData=Ct.KeywordCxt=Ct.validateFunctionCode=void 0;var Ul=gl(),jl=Sr(),as=Qi(),So=Sr(),ty=El(),kr=Tl(),ss=xl(),S=x(),A=mt(),ny=vr(),pt=N(),Er=br();function ry(t){if(Gl(t)&&(Wl(t),ql(t))){sy(t);return}Hl(t,()=>(0,Ul.topBoolOrEmptySchema)(t))}Ct.validateFunctionCode=ry;function Hl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,S._)`${A.default.data}, ${A.default.valCxt}`,r.$async,()=>{t.code((0,S._)`"use strict"; ${Dl(n,o)}`),iy(t,o),t.code(i)}):t.func(e,(0,S._)`${A.default.data}, ${oy(o)}`,r.$async,()=>t.code(Dl(n,o)).code(i))}function oy(t){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${t.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function iy(t,e){t.if(A.default.valCxt,()=>{t.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),t.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),t.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),t.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{t.var(A.default.instancePath,(0,S._)`""`),t.var(A.default.parentData,(0,S._)`undefined`),t.var(A.default.parentDataProperty,(0,S._)`undefined`),t.var(A.default.rootData,A.default.data),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function sy(t){let{schema:e,opts:n,gen:r}=t;Hl(t,()=>{n.$comment&&e.$comment&&zl(t),dy(t),r.let(A.default.vErrors,null),r.let(A.default.errors,0),n.unevaluated&&ay(t),Vl(t),py(t)})}function ay(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,S._)`${n}.evaluated`),e.if((0,S._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,S._)`${t.evaluated}.props`,(0,S._)`undefined`)),e.if((0,S._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,S._)`${t.evaluated}.items`,(0,S._)`undefined`))}function Dl(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,S._)`/*# sourceURL=${n} */`:S.nil}function cy(t,e){if(Gl(t)&&(Wl(t),ql(t))){ly(t,e);return}(0,Ul.boolOrEmptySchema)(t,e)}function ql({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 Gl(t){return typeof t.schema!="boolean"}function ly(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&zl(t),fy(t),my(t);let i=r.const("_errs",A.default.errors);Vl(t,i),r.var(e,(0,S._)`${i} === ${A.default.errors}`)}function Wl(t){(0,pt.checkUnknownRules)(t),uy(t)}function Vl(t,e){if(t.opts.jtd)return Bl(t,[],!1,e);let n=(0,jl.getSchemaTypes)(t.schema),r=(0,jl.coerceAndCheckDataType)(t,n);Bl(t,n,!r,e)}function uy(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,pt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function dy(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,pt.checkStrictMode)(t,"default is ignored in the schema root")}function fy(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,ny.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function my(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function zl({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function py(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,S._)`${A.default.errors} === 0`,()=>e.return(A.default.data),()=>e.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(e.assign((0,S._)`${r}.errors`,A.default.vErrors),i.unevaluated&&hy(t),e.return((0,S._)`${A.default.errors} === 0`))}function hy({gen:t,evaluated:e,props:n,items:r}){n instanceof S.Name&&t.assign((0,S._)`${e}.props`,n),r instanceof S.Name&&t.assign((0,S._)`${e}.items`,r)}function Bl(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,pt.schemaHasRulesButRef)(i,l))){o.block(()=>Jl(t,"$ref",l.all.$ref.definition));return}c.jtd||gy(t,e),o.block(()=>{for(let h of l.rules)d(h);d(l.post)});function d(h){(0,as.shouldUseGroup)(i,h)&&(h.type?(o.if((0,So.checkDataType)(h.type,s,c.strictNumbers)),Fl(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,So.reportTypeError)(t)),o.endIf()):Fl(t,h),a||o.if((0,S._)`${A.default.errors} === ${r||0}`))}}function Fl(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,ty.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,as.shouldUseRule)(r,i)&&Jl(t,i.keyword,i.definition,e.type)})}function gy(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(yy(t,e),t.opts.allowUnionTypes||_y(t,e),wy(t,t.dataTypes))}function yy(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Kl(t.dataTypes,n)||cs(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Sy(t,e)}}function _y(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&cs(t,"use allowUnionTypes to allow union type keyword")}function wy(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,as.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>by(e,s))&&cs(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function by(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Kl(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Sy(t,e){let n=[];for(let r of t.dataTypes)Kl(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function cs(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,pt.checkStrictMode)(t,e,t.opts.strictTypes)}var vo=class{constructor(e,n,r){if((0,kr.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,pt.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",Yl(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,kr.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,S.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,S.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,S._)`${n} !== undefined && (${(0,S.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?Er.reportExtraError:Er.reportError)(this,this.def.error,n)}$dataError(){(0,Er.reportError)(this,this.def.$dataError||Er.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Er.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=S.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=S.nil,n=S.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,S.or)((0,S._)`${o} === undefined`,n)),e!==S.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==S.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(r.length){if(!(n instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,S._)`${(0,So.checkDataTypes)(c,n,i.opts.strictNumbers,So.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${n})`}return S.nil}}subschema(e,n){let r=(0,ss.getSubschema)(this.it,e);(0,ss.extendSubschemaData)(r,this.it,e),(0,ss.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return cy(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=pt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=pt.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,S.Name)),!0}};Ct.KeywordCxt=vo;function Jl(t,e,n,r){let o=new vo(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,kr.funcKeywordCode)(o,n):"macro"in n?(0,kr.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,kr.funcKeywordCode)(o,n)}var vy=/^\/(?:[^~]|~0|~1)*$/,Ey=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Yl(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return A.default.rootData;if(t[0]==="/"){if(!vy.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=A.default.rootData}else{let u=Ey.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,S._)`${i}${(0,S.getProperty)((0,pt.unescapeJsonPointer)(u))}`,s=(0,S._)`${s} && ${i}`);return s;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Ct.getData=Yl});var Eo=_(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});var ls=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};us.default=ls});var Rr=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var ds=vr(),fs=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,ds.resolveUrl)(e,n,r),this.missingSchema=(0,ds.normalizeId)((0,ds.getFullPath)(e,this.missingRef))}};ms.default=fs});var $o=_(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.resolveSchema=Me.getCompilingSchema=Me.resolveRef=Me.compileSchema=Me.SchemaEnv=void 0;var He=x(),ky=Eo(),Qt=mt(),qe=vr(),Ql=N(),$y=$r(),xn=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,qe.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Me.SchemaEnv=xn;function hs(t){let e=Xl.call(this,t);if(e)return e;let n=(0,qe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new He.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:ky.default,code:(0,He._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let u={gen:s,allErrors:this.opts.allErrors,data:Qt.default.data,parentData:Qt.default.parentData,parentDataProperty:Qt.default.parentDataProperty,dataNames:[Qt.default.data],dataPathArr:[He.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,He.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:He.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,He._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,$y.validateFunctionCode)(u),s.optimize(this.opts.code.optimize);let d=s.toString();l=`${s.scopeRefs(Qt.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${Qt.default.self}`,`${Qt.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 He.Name?void 0:f,items:m instanceof He.Name?void 0:m,dynamicProps:f instanceof He.Name,dynamicItems:m instanceof He.Name},p.source&&(p.source.evaluated=(0,He.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)}}Me.compileSchema=hs;function Ry(t,e,n){var r;n=(0,qe.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Py.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 xn({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Ay.call(this,i)}Me.resolveRef=Ry;function Ay(t){return(0,qe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:hs.call(this,t)}function Xl(t){for(let e of this._compilations)if(Ty(e,t))return e}Me.getCompilingSchema=Xl;function Ty(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Py(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||ko.call(this,t,e)}function ko(t,e){let n=this.opts.uriResolver.parse(e),r=(0,qe._getFullPath)(this.opts.uriResolver,n),o=(0,qe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return ps.call(this,n,t);let i=(0,qe.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=ko.call(this,t,s);return typeof a?.schema!="object"?void 0:ps.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||hs.call(this,s),i===(0,qe.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,qe.resolveUrl)(this.opts.uriResolver,o,u)),new xn({schema:a,schemaId:c,root:t,baseId:o})}return ps.call(this,n,s)}}Me.resolveSchema=ko;var xy=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ps(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,Ql.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!xy.has(a)&&u&&(e=(0,qe.resolveUrl)(this.opts.uriResolver,e,u))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Ql.schemaHasRulesButRef)(n,this.RULES)){let a=(0,qe.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=ko.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new xn({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Zl=_((TA,Cy)=>{Cy.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 ys=_((PA,ru)=>{"use strict";var Iy=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),tu=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 gs(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 eu(t){return t.length=0,!0}function My(t,e,n){if(t.length){let r=gs(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Ny(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=My;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=eu}else{o.push(u);continue}}return o.length&&(a===eu?n.zone=o.join(""):s?r.push(o.join("")):r.push(gs(o))),n.address=r.join(""),n}function nu(t){if(Ly(t,":")<2)return{host:t,isIPV6:!1};let e=Ny(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 Ly(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function jy(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 Dy(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 By(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!tu(n)){let r=nu(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}ru.exports={nonSimpleDomain:Oy,recomposeAuthority:By,normalizeComponentEncoding:Dy,removeDotSegments:jy,isIPv4:tu,isUUID:Iy,normalizeIPv6:nu,stringArrayToHexStripped:gs}});var cu=_((xA,au)=>{"use strict";var{isUUID:Fy}=ys(),Uy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Hy=["http","https","ws","wss","urn","urn:uuid"];function qy(t){return Hy.indexOf(t)!==-1}function _s(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 ou(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function iu(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 Gy(t){return t.secure=_s(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Wy(t){if((t.port===(_s(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 Vy(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(Uy);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=ws(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function zy(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=ws(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 Ky(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!Fy(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Jy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var su={scheme:"http",domainHost:!0,parse:ou,serialize:iu},Yy={scheme:"https",domainHost:su.domainHost,parse:ou,serialize:iu},Ro={scheme:"ws",domainHost:!0,parse:Gy,serialize:Wy},Qy={scheme:"wss",domainHost:Ro.domainHost,parse:Ro.parse,serialize:Ro.serialize},Xy={scheme:"urn",parse:Vy,serialize:zy,skipNormalize:!0},Zy={scheme:"urn:uuid",parse:Ky,serialize:Jy,skipNormalize:!0},Ao={http:su,https:Yy,ws:Ro,wss:Qy,urn:Xy,"urn:uuid":Zy};Object.setPrototypeOf(Ao,null);function ws(t){return t&&(Ao[t]||Ao[t.toLowerCase()])||void 0}au.exports={wsIsSecure:_s,SCHEMES:Ao,isValidSchemeName:qy,getSchemeHandler:ws}});var du=_((CA,Po)=>{"use strict";var{normalizeIPv6:e_,removeDotSegments:Ar,recomposeAuthority:t_,normalizeComponentEncoding:To,isIPv4:n_,nonSimpleDomain:r_}=ys(),{SCHEMES:o_,getSchemeHandler:lu}=cu();function i_(t,e){return typeof t=="string"?t=tt(ht(t,e),e):typeof t=="object"&&(t=ht(tt(t,e),e)),t}function s_(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=uu(ht(t,r),ht(e,r),r,!0);return r.skipEscape=!0,tt(o,r)}function uu(t,e,n,r){let o={};return r||(t=ht(tt(t,n),n),e=ht(tt(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=Ar(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=Ar(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ar(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=Ar(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 a_(t,e,n){return typeof t=="string"?(t=unescape(t),t=tt(To(ht(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=tt(To(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=tt(To(ht(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=tt(To(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function tt(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=lu(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=t_(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=Ar(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 c_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ht(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(c_);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(n_(r.host)===!1){let c=e_(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=lu(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&r_(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 bs={SCHEMES:o_,normalize:i_,resolve:s_,resolveComponent:uu,equal:a_,serialize:tt,parse:ht};Po.exports=bs;Po.exports.default=bs;Po.exports.fastUri=bs});var mu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var fu=du();fu.code='require("ajv/dist/runtime/uri").default';Ss.default=fu});var Su=_(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=void 0;var l_=$r();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return l_.KeywordCxt}});var Cn=x();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Cn._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Cn.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Cn.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Cn.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Cn.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Cn.CodeGen}});var u_=Eo(),_u=Rr(),d_=Yi(),Tr=$o(),f_=x(),Pr=vr(),xo=Sr(),Es=N(),pu=Zl(),m_=mu(),wu=(t,e)=>new RegExp(t,e);wu.code="new RegExp";var p_=["removeAdditional","useDefaults","coerceTypes"],h_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g_={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."},y_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},hu=200;function __(t){var e,n,r,o,i,s,a,c,u,l,d,h,p,f,m,g,y,b,v,R,$,J,ee,ce,Qe;let ut=t.strict,cr=(e=t.code)===null||e===void 0?void 0:e.optimize,Xe=cr===!0||cr===void 0?1:cr||0,ie=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:wu,qt=(o=t.uriResolver)!==null&&o!==void 0?o:m_.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:ut)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ut)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ut)!==null&&l!==void 0?l:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:ut)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:ut)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Xe,regExp:ie}:{optimize:Xe,regExp:ie},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:hu,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:hu,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!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:(ee=t.validateFormats)!==null&&ee!==void 0?ee:!0,unicodeRegExp:(ce=t.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(Qe=t.int32range)!==null&&Qe!==void 0?Qe:!0,uriResolver:qt}}var xr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...__(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new f_.ValueScope({scope:{},prefixes:h_,es5:n,lines:r}),this.logger=k_(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,d_.getRules)(),gu.call(this,g_,e,"NOT SUPPORTED"),gu.call(this,y_,e,"DEPRECATED","warn"),this._metaOpts=v_.call(this),e.formats&&b_.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&S_.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),w_.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=pu;r==="id"&&(o={...pu},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 _u.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,Pr.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=yu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Tr.SchemaEnv({schema:{},schemaId:r});if(n=Tr.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=yu.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,Pr.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(R_.call(this,r,n),!n)return(0,Es.eachItem)(r,i=>vs.call(this,i)),this;T_.call(this,n);let o={...n,type:(0,xo.getJSONTypes)(n.type),schemaType:(0,xo.getJSONTypes)(n.schemaType)};return(0,Es.eachItem)(r,o.type.length===0?i=>vs.call(this,i,o):i=>o.type.forEach(s=>vs.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]=bu(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,Pr.normalizeId)(s||r);let u=Pr.getSchemaRefs.call(this,e,r);return c=new Tr.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):Tr.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{Tr.compileSchema.call(this,e)}finally{this.opts=n}}};xr.ValidationError=u_.default;xr.MissingRefError=_u.default;le.default=xr;function gu(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 yu(t){return t=(0,Pr.normalizeId)(t),this.schemas[t]||this.refs[t]}function w_(){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 b_(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function S_(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 v_(){let t={...this.opts};for(let e of p_)delete t[e];return t}var E_={log(){},warn(){},error(){}};function k_(t){if(t===!1)return E_;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 $_=/^[a-z_$][a-z0-9_$:-]*$/i;function R_(t,e){let{RULES:n}=this;if((0,Es.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!$_.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 vs(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,xo.getJSONTypes)(e.type),schemaType:(0,xo.getJSONTypes)(e.schemaType)}};e.before?A_.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 A_(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 T_(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=bu(e)),t.validateSchema=this.compile(e,!0))}var P_={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function bu(t){return{anyOf:[t,P_]}}});var vu=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var x_={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ks.default=x_});var Ru=_(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.callRef=Xt.getValidate=void 0;var C_=Rr(),Eu=Oe(),ve=x(),In=mt(),ku=$o(),Co=N(),I_={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=ku.resolveRef.call(c,u,o,n);if(l===void 0)throw new C_.default(r.opts.uriResolver,o,n);if(l instanceof ku.SchemaEnv)return h(l);return p(l);function d(){if(i===u)return Io(t,s,i,i.$async);let f=e.scopeValue("root",{ref:u});return Io(t,(0,ve._)`${f}.validate`,u,u.$async)}function h(f){let m=$u(t,f);Io(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,ve.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:ve.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function $u(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,ve._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Xt.getValidate=$u;function Io(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,u=c.passContext?In.default.this:ve.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,ve._)`await ${(0,Eu.callValidateCode)(t,e,u)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,ve._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Eu.callValidateCode)(t,e,u),()=>p(e),()=>h(e))}function h(f){let m=(0,ve._)`${f}.errors`;o.assign(In.default.vErrors,(0,ve._)`${In.default.vErrors} === null ? ${m} : ${In.default.vErrors}.concat(${m})`),o.assign(In.default.errors,(0,ve._)`${In.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=Co.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,ve._)`${f}.evaluated.props`);i.props=Co.mergeEvaluated.props(o,y,i.props,ve.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Co.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,ve._)`${f}.evaluated.items`);i.items=Co.mergeEvaluated.items(o,y,i.items,ve.Name)}}}Xt.callRef=Io;Xt.default=I_});var Au=_($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var O_=vu(),M_=Ru(),N_=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",O_.default,M_.default];$s.default=N_});var Tu=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var Oo=x(),It=Oo.operators,Mo={maximum:{okStr:"<=",ok:It.LTE,fail:It.GT},minimum:{okStr:">=",ok:It.GTE,fail:It.LT},exclusiveMaximum:{okStr:"<",ok:It.LT,fail:It.GTE},exclusiveMinimum:{okStr:">",ok:It.GT,fail:It.LTE}},L_={message:({keyword:t,schemaCode:e})=>(0,Oo.str)`must be ${Mo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Oo._)`{comparison: ${Mo[t].okStr}, limit: ${e}}`},j_={keyword:Object.keys(Mo),type:"number",schemaType:"number",$data:!0,error:L_,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Oo._)`${n} ${Mo[e].fail} ${r} || isNaN(${n})`)}};Rs.default=j_});var Pu=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Cr=x(),D_={message:({schemaCode:t})=>(0,Cr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Cr._)`{multipleOf: ${t}}`},B_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:D_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,Cr._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Cr._)`${s} !== parseInt(${s})`;t.fail$data((0,Cr._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};As.default=B_});var Cu=_(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});function xu(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}Ts.default=xu;xu.code='require("ajv/dist/runtime/ucs2length").default'});var Iu=_(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var Zt=x(),F_=N(),U_=Cu(),H_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Zt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Zt._)`{limit: ${t}}`},q_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:H_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Zt.operators.GT:Zt.operators.LT,s=o.opts.unicode===!1?(0,Zt._)`${n}.length`:(0,Zt._)`${(0,F_.useFunc)(t.gen,U_.default)}(${n})`;t.fail$data((0,Zt._)`${s} ${i} ${r}`)}};Ps.default=q_});var Ou=_(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var G_=Oe(),W_=N(),On=x(),V_={message:({schemaCode:t})=>(0,On.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,On._)`{pattern: ${t}}`},z_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:V_,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,On._)`new RegExp`:(0,W_.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,On._)`${u}(${i}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,On._)`!${l}`)}else{let c=(0,G_.usePattern)(t,o);t.fail$data((0,On._)`!${c}.test(${n})`)}}};xs.default=z_});var Mu=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var Ir=x(),K_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ir.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ir._)`{limit: ${t}}`},J_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:K_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ir.operators.GT:Ir.operators.LT;t.fail$data((0,Ir._)`Object.keys(${n}).length ${o} ${r}`)}};Cs.default=J_});var Nu=_(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var Or=Oe(),Mr=x(),Y_=N(),Q_={message:({params:{missingProperty:t}})=>(0,Mr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mr._)`{missingProperty: ${t}}`},X_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Q_,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,Y_.checkStrictMode)(s,y,s.opts.strictRequired)}}function u(){if(c||i)t.block$data(Mr.nil,d);else for(let p of n)(0,Or.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,Or.checkMissingProp)(t,n,p)),(0,Or.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",r,p=>{t.setParams({missingProperty:p}),e.if((0,Or.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function h(p,f){t.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(f,(0,Or.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Mr.not)(f),()=>{t.error(),e.break()})},Mr.nil)}}};Is.default=X_});var Lu=_(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var Nr=x(),Z_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Nr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Nr._)`{limit: ${t}}`},ew={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Z_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Nr.operators.GT:Nr.operators.LT;t.fail$data((0,Nr._)`${n}.length ${o} ${r}`)}};Os.default=ew});var No=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var ju=os();ju.code='require("ajv/dist/runtime/equal").default';Ms.default=ju});var Du=_(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Ns=Sr(),ue=x(),tw=N(),nw=No(),rw={message:({params:{i:t,j:e}})=>(0,ue.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ue._)`{i: ${t}, j: ${e}}`},ow={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rw,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,Ns.getSchemaTypes)(i.items):[];t.block$data(c,l,(0,ue._)`${s} === false`),t.ok(c);function l(){let f=e.let("i",(0,ue._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,ue._)`${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,Ns.checkDataTypes)(u,g,a.opts.strictNumbers,Ns.DataType.Wrong),b=e.const("indices",(0,ue._)`{}`);e.for((0,ue._)`;${f}--;`,()=>{e.let(g,(0,ue._)`${n}[${f}]`),e.if(y,(0,ue._)`continue`),u.length>1&&e.if((0,ue._)`typeof ${g} == "string"`,(0,ue._)`${g} += "_"`),e.if((0,ue._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(m,(0,ue._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,ue._)`${b}[${g}] = ${f}`)})}function p(f,m){let g=(0,tw.useFunc)(e,nw.default),y=e.name("outer");e.label(y).for((0,ue._)`;${f}--;`,()=>e.for((0,ue._)`${m} = ${f}; ${m}--;`,()=>e.if((0,ue._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Ls.default=ow});var Bu=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var js=x(),iw=N(),sw=No(),aw={message:"must be equal to constant",params:({schemaCode:t})=>(0,js._)`{allowedValue: ${t}}`},cw={keyword:"const",$data:!0,error:aw,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,js._)`!${(0,iw.useFunc)(e,sw.default)}(${n}, ${o})`):t.fail((0,js._)`${i} !== ${n}`)}};Ds.default=cw});var Fu=_(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var Lr=x(),lw=N(),uw=No(),dw={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Lr._)`{allowedValues: ${t}}`},fw={keyword:"enum",schemaType:"array",$data:!0,error:dw,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,lw.useFunc)(e,uw.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,Lr.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,Lr._)`${u()}(${n}, ${p})`,()=>e.assign(l,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,Lr._)`${u()}(${n}, ${p}[${f}])`:(0,Lr._)`${n} === ${m}`}}};Bs.default=fw});var Uu=_(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var mw=Tu(),pw=Pu(),hw=Iu(),gw=Ou(),yw=Mu(),_w=Nu(),ww=Lu(),bw=Du(),Sw=Bu(),vw=Fu(),Ew=[mw.default,pw.default,hw.default,gw.default,yw.default,_w.default,ww.default,bw.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Sw.default,vw.default];Fs.default=Ew});var Hs=_(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.validateAdditionalItems=void 0;var en=x(),Us=N(),kw={message:({params:{len:t}})=>(0,en.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,en._)`{limit: ${t}}`},$w={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:kw,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Us.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Hu(t,r)}};function Hu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,en._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,en._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Us.alwaysValidSchema)(s,r)){let u=n.var("valid",(0,en._)`${a} <= ${e.length}`);n.if((0,en.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:i,dataProp:l,dataPropType:Us.Type.Num},u),s.allErrors||n.if((0,en.not)(u),()=>n.break())})}}jr.validateAdditionalItems=Hu;jr.default=$w});var qs=_(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.validateTuple=void 0;var qu=x(),Lo=N(),Rw=Oe(),Aw={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Gu(t,"additionalItems",e);n.items=!0,!(0,Lo.alwaysValidSchema)(n,e)&&t.ok((0,Rw.validateArray)(t))}};function Gu(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=Lo.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,qu._)`${i}.length`);n.forEach((d,h)=>{(0,Lo.alwaysValidSchema)(a,d)||(r.if((0,qu._)`${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,Lo.checkStrictMode)(a,g,h.strictTuples)}}}Dr.validateTuple=Gu;Dr.default=Aw});var Wu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var Tw=qs(),Pw={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Tw.validateTuple)(t,"items")};Gs.default=Pw});var zu=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var Vu=x(),xw=N(),Cw=Oe(),Iw=Hs(),Ow={message:({params:{len:t}})=>(0,Vu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Vu._)`{limit: ${t}}`},Mw={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,xw.alwaysValidSchema)(r,e)&&(o?(0,Iw.validateAdditionalItems)(t,o):t.ok((0,Cw.validateArray)(t)))}};Ws.default=Mw});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Ne=x(),jo=N(),Nw={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}}`},Lw={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Nw,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,jo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,jo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,jo.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:jo.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)))}}};Vs.default=Lw});var Qu=_(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.validateSchemaDeps=nt.validatePropertyDeps=nt.error=void 0;var zs=x(),jw=N(),Br=Oe();nt.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,zs.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,zs._)`{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 Dw={keyword:"dependencies",type:"object",schemaType:"object",error:nt.error,code(t){let[e,n]=Bw(t);Ju(t,e),Yu(t,n)}};function Bw({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,Br.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,Br.checkReportMissingProp)(t,u)}):(n.if((0,zs._)`${c} && (${(0,Br.checkMissingProp)(t,a,i)})`),(0,Br.reportMissingProp)(t,i),n.else())}}nt.validatePropertyDeps=Ju;function Yu(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,jw.alwaysValidSchema)(i,e[a])||(n.if((0,Br.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))}nt.validateSchemaDeps=Yu;nt.default=Dw});var Zu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Xu=x(),Fw=N(),Uw={message:"property name must be valid",params:({params:t})=>(0,Xu._)`{propertyName: ${t.propertyName}}`},Hw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Uw,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,Fw.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,Xu.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Ks.default=Hw});var Ys=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Do=Oe(),Ge=x(),qw=mt(),Bo=N(),Gw={message:"must NOT have additional properties",params:({params:t})=>(0,Ge._)`{additionalProperty: ${t.additionalProperty}}`},Ww={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Gw,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,Bo.alwaysValidSchema)(s,n))return;let u=(0,Do.allSchemaProperties)(r.properties),l=(0,Do.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Ge._)`${i} === ${qw.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 b=(0,Bo.schemaRefOrVal)(s,r.properties,"properties");y=(0,Do.isOwnProperty)(e,b,g)}else u.length?y=(0,Ge.or)(...u.map(b=>(0,Ge._)`${g} === ${b}`)):y=Ge.nil;return l.length&&(y=(0,Ge.or)(y,...l.map(b=>(0,Ge._)`${(0,Do.usePattern)(t,b)}.test(${g})`))),(0,Ge.not)(y)}function p(g){e.code((0,Ge._)`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,Bo.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Ge.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Ge.not)(y),()=>e.break()))}}function m(g,y,b){let v={keyword:"additionalProperties",dataProp:g,dataPropType:Bo.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,y)}}};Js.default=Ww});var nd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Vw=$r(),ed=Oe(),Qs=N(),td=Ys(),zw={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&&td.default.code(new Vw.KeywordCxt(i,td.default,"additionalProperties"));let s=(0,ed.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Qs.mergeEvaluated.props(e,(0,Qs.toHash)(s),i.props));let a=s.filter(d=>!(0,Qs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,ed.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)}}};Xs.default=zw});var sd=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var rd=Oe(),Fo=x(),od=N(),id=N(),Kw={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,rd.allSchemaProperties)(n),c=a.filter(m=>(0,od.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 Fo.Name)&&(i.props=(0,id.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,od.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,Fo._)`${(0,rd.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:id.Type.Str},l),i.opts.unevaluated&&d!==!0?e.assign((0,Fo._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,Fo.not)(l),()=>e.break())})})}}};Zs.default=Kw});var ad=_(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var Jw=N(),Yw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,Jw.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"}};ea.default=Yw});var cd=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var Qw=Oe(),Xw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Qw.validateUnion,error:{message:"must match a schema in anyOf"}};ta.default=Xw});var ld=_(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});var Uo=x(),Zw=N(),eb={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Uo._)`{passingSchemas: ${t.passing}}`},tb={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:eb,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,Zw.alwaysValidSchema)(o,l)?e.var(c,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Uo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Uo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Uo.Name)})})}}};na.default=tb});var ud=_(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var nb=N(),rb={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,nb.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};ra.default=rb});var md=_(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});var Ho=x(),fd=N(),ob={message:({params:t})=>(0,Ho.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ho._)`{failingKeyword: ${t.ifClause}}`},ib={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ob,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,fd.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=dd(r,"then"),i=dd(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,Ho.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,Ho._)`${l}`):t.setParams({ifClause:l})}}}};function dd(t,e){let n=t.schema[e];return n!==void 0&&!(0,fd.alwaysValidSchema)(t,n)}oa.default=ib});var pd=_(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});var sb=N(),ab={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,sb.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};ia.default=ab});var hd=_(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});var cb=Hs(),lb=Wu(),ub=qs(),db=zu(),fb=Ku(),mb=Qu(),pb=Zu(),hb=Ys(),gb=nd(),yb=sd(),_b=ad(),wb=cd(),bb=ld(),Sb=ud(),vb=md(),Eb=pd();function kb(t=!1){let e=[_b.default,wb.default,bb.default,Sb.default,vb.default,Eb.default,pb.default,hb.default,mb.default,gb.default,yb.default];return t?e.push(lb.default,db.default):e.push(cb.default,ub.default),e.push(fb.default),e}sa.default=kb});var gd=_(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});var X=x(),$b={message:({schemaCode:t})=>(0,X.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,X._)`{format: ${t}}`},Rb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$b,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,X._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,X._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,X._)`${m}.type || "string"`).assign(y,(0,X._)`${m}.validate`),()=>n.assign(g,(0,X._)`"string"`).assign(y,m)),t.fail$data((0,X.or)(b(),v()));function b(){return c.strictSchema===!1?X.nil:(0,X._)`${s} && !${y}`}function v(){let R=l.$async?(0,X._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,X._)`${y}(${r})`,$=(0,X._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,X._)`${y} && ${y} !== true && ${g} === ${e} && !${$}`}}function p(){let f=d.formats[i];if(!f){b();return}if(f===!0)return;let[m,g,y]=v(f);m===e&&t.pass(R());function b(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function v($){let J=$ instanceof RegExp?(0,X.regexpCode)($):c.code.formats?(0,X._)`${c.code.formats}${(0,X.getProperty)(i)}`:void 0,ee=n.scopeValue("formats",{key:i,ref:$,code:J});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,X._)`${ee}.validate`]:["string",$,ee]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,X._)`await ${y}(${r})`}return typeof g=="function"?(0,X._)`${y}(${r})`:(0,X._)`${y}.test(${r})`}}}};aa.default=Rb});var yd=_(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});var Ab=gd(),Tb=[Ab.default];ca.default=Tb});var _d=_(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.contentVocabulary=Mn.metadataVocabulary=void 0;Mn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Mn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var bd=_(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});var Pb=Au(),xb=Uu(),Cb=hd(),Ib=yd(),wd=_d(),Ob=[Pb.default,xb.default,(0,Cb.default)(),Ib.default,wd.metadataVocabulary,wd.contentVocabulary];la.default=Ob});var vd=_(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.DiscrError=void 0;var Sd;(function(t){t.Tag="tag",t.Mapping="mapping"})(Sd||(qo.DiscrError=Sd={}))});var kd=_(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});var Nn=x(),ua=vd(),Ed=$o(),Mb=Rr(),Nb=N(),Lb={message:({params:{discrError:t,tagName:e}})=>t===ua.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Nn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},jb={keyword:"discriminator",type:"object",schemaType:"object",error:Lb,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,Nn._)`${n}${(0,Nn.getProperty)(a)}`);e.if((0,Nn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:ua.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,Nn._)`${u} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:ua.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,Nn.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,Nb.schemaHasRulesButRef)($,i.self.RULES)){let ee=$.$ref;if($=Ed.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,ee),$ instanceof Ed.SchemaEnv&&($=$.schema),$===void 0)throw new Mb.default(i.opts.uriResolver,i.baseId,ee)}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($)),b(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 b(R,$){if(R.const)v(R.const,$);else if(R.enum)for(let J of R.enum)v(J,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(R,$){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=$}}}};da.default=jb});var $d=_((wT,Db)=>{Db.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 Wo=_((z,fa)=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.MissingRefError=z.ValidationError=z.CodeGen=z.Name=z.nil=z.stringify=z.str=z._=z.KeywordCxt=z.Ajv=void 0;var Bb=Su(),Fb=bd(),Ub=kd(),Rd=$d(),Hb=["/properties"],Go="http://json-schema.org/draft-07/schema",Ln=class extends Bb.default{_addVocabularies(){super._addVocabularies(),Fb.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Ub.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Rd,Hb):Rd;this.addMetaSchema(e,Go,!1),this.refs["http://json-schema.org/schema"]=Go}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Go)?Go:void 0)}};z.Ajv=Ln;fa.exports=z=Ln;fa.exports.Ajv=Ln;Object.defineProperty(z,"__esModule",{value:!0});z.default=Ln;var qb=$r();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return qb.KeywordCxt}});var jn=x();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return jn._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return jn.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return jn.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return jn.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return jn.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return jn.CodeGen}});var Gb=Eo();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return Gb.default}});var Wb=Rr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return Wb.default}})});var Md=_(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.formatNames=ot.fastFormats=ot.fullFormats=void 0;function rt(t,e){return{validate:t,compare:e}}ot.fullFormats={date:rt(xd,ga),time:rt(pa(!0),ya),"date-time":rt(Ad(!0),Id),"iso-time":rt(pa(),Cd),"iso-date-time":rt(Ad(),Od),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Qb,"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:oS,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:Xb,int32:{type:"number",validate:tS},int64:{type:"number",validate:nS},float:{type:"number",validate:Pd},double:{type:"number",validate:Pd},password:!0,binary:!0};ot.fastFormats={...ot.fullFormats,date:rt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ga),time:rt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ya),"date-time":rt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Id),"iso-time":rt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Cd),"iso-date-time":rt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Od),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};ot.formatNames=Object.keys(ot.fullFormats);function Vb(t){return t%4===0&&(t%100!==0||t%400===0)}var zb=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Kb=[0,31,28,31,30,31,30,31,31,30,31,30,31];function xd(t){let e=zb.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&&Vb(n)?29:Kb[r])}function ga(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ma=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function pa(t){return function(n){let r=ma.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 ya(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 Cd(t,e){if(!(t&&e))return;let n=ma.exec(t),r=ma.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 ha=/t|\s/i;function Ad(t){let e=pa(t);return function(r){let o=r.split(ha);return o.length===2&&xd(o[0])&&e(o[1])}}function Id(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Od(t,e){if(!(t&&e))return;let[n,r]=t.split(ha),[o,i]=e.split(ha),s=ga(n,o);if(s!==void 0)return s||ya(r,i)}var Jb=/\/|:/,Yb=/^(?:[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 Qb(t){return Jb.test(t)&&Yb.test(t)}var Td=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Xb(t){return Td.lastIndex=0,Td.test(t)}var Zb=-(2**31),eS=2**31-1;function tS(t){return Number.isInteger(t)&&t<=eS&&t>=Zb}function nS(t){return Number.isInteger(t)}function Pd(){return!0}var rS=/[^\\]\\Z/;function oS(t){if(rS.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Nd=_(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.formatLimitDefinition=void 0;var iS=Wo(),We=x(),Ot=We.operators,Vo={formatMaximum:{okStr:"<=",ok:Ot.LTE,fail:Ot.GT},formatMinimum:{okStr:">=",ok:Ot.GTE,fail:Ot.LT},formatExclusiveMaximum:{okStr:"<",ok:Ot.LT,fail:Ot.GTE},formatExclusiveMinimum:{okStr:">",ok:Ot.GT,fail:Ot.LTE}},sS={message:({keyword:t,schemaCode:e})=>(0,We.str)`should be ${Vo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,We._)`{comparison: ${Vo[t].okStr}, limit: ${e}}`};Dn.formatLimitDefinition={keyword:Object.keys(Vo),type:"string",schemaType:"string",$data:!0,error:sS,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 iS.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,We._)`${h}[${c.schemaCode}]`);t.fail$data((0,We.or)((0,We._)`typeof ${p} != "object"`,(0,We._)`${p} instanceof RegExp`,(0,We._)`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,We._)`${s.code.formats}${(0,We.getProperty)(h)}`:void 0});t.fail$data(d(f))}function d(h){return(0,We._)`${h}.compare(${n}, ${r}) ${Vo[o].fail} 0`}},dependencies:["format"]};var aS=t=>(t.addKeyword(Dn.formatLimitDefinition),t);Dn.default=aS});var ba=_((Fr,Dd)=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});var Bn=Md(),cS=Nd(),_a=x(),Ld=new _a.Name("fullFormats"),lS=new _a.Name("fastFormats"),wa=(t,e={keywords:!0})=>{if(Array.isArray(e))return jd(t,e,Bn.fullFormats,Ld),t;let[n,r]=e.mode==="fast"?[Bn.fastFormats,lS]:[Bn.fullFormats,Ld],o=e.formats||Bn.formatNames;return jd(t,o,n,r),e.keywords&&(0,cS.default)(t),t};wa.get=(t,e="full")=>{let r=(e==="fast"?Bn.fastFormats:Bn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function jd(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,_a._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Dd.exports=Fr=wa;Object.defineProperty(Fr,"__esModule",{value:!0});Fr.default=wa});var yt=_((HT,zd)=>{"use strict";var Wd=["nodebuffer","arraybuffer","fragments"],Vd=typeof Blob<"u";Vd&&Wd.push("blob");zd.exports={BINARY_TYPES:Wd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Vd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ur=_((qT,zo)=>{"use strict";var{EMPTY_BUFFER:SS}=yt(),va=Buffer[Symbol.species];function vS(t,e){if(t.length===0)return SS;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 va(n.buffer,n.byteOffset,r):n}function Kd(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 ES(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ea(t){if(Ea.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new va(t):ArrayBuffer.isView(t)?e=new va(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ea.readOnly=!1),e}zo.exports={concat:vS,mask:Kd,toArrayBuffer:ES,toBuffer:Ea,unmask:Jd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ne("bufferutil");zo.exports.mask=function(e,n,r,o,i){i<48?Kd(e,n,r,o,i):t.mask(e,n,r,o,i)},zo.exports.unmask=function(e,n){e.length<32?Jd(e,n):t.unmask(e,n)}}catch{}});var Xd=_((GT,Qd)=>{"use strict";var Yd=Symbol("kDone"),ka=Symbol("kRun"),$a=class{constructor(e){this[Yd]=()=>{this.pending--,this[ka]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ka]()}[ka](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Yd])}}};Qd.exports=$a});var Gn=_((WT,nf)=>{"use strict";var Hr=ne("zlib"),Zd=Ur(),kS=Xd(),{kStatusCode:ef}=yt(),$S=Buffer[Symbol.species],RS=Buffer.from([0,0,255,255]),Jo=Symbol("permessage-deflate"),_t=Symbol("total-length"),Hn=Symbol("callback"),Mt=Symbol("buffers"),qn=Symbol("error"),Ko,Ra=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,!Ko){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ko=new kS(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[Hn];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){Ko.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Ko.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"?Hr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Hr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Jo]=this,this._inflate[_t]=0,this._inflate[Mt]=[],this._inflate.on("error",TS),this._inflate.on("data",tf)}this._inflate[Hn]=r,this._inflate.write(e),n&&this._inflate.write(RS),this._inflate.flush(()=>{let i=this._inflate[qn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Zd.concat(this._inflate[Mt],this._inflate[_t]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_t]=0,this._inflate[Mt]=[],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"?Hr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Hr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[_t]=0,this._deflate[Mt]=[],this._deflate.on("data",AS)}this._deflate[Hn]=r,this._deflate.write(e),this._deflate.flush(Hr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Zd.concat(this._deflate[Mt],this._deflate[_t]);n&&(i=new $S(i.buffer,i.byteOffset,i.length-4)),this._deflate[Hn]=null,this._deflate[_t]=0,this._deflate[Mt]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};nf.exports=Ra;function AS(t){this[Mt].push(t),this[_t]+=t.length}function tf(t){if(this[_t]+=t.length,this[Jo]._maxPayload<1||this[_t]<=this[Jo]._maxPayload){this[Mt].push(t);return}this[qn]=new RangeError("Max payload size exceeded"),this[qn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[qn][ef]=1009,this.removeListener("data",tf),this.reset()}function TS(t){if(this[Jo]._inflate=null,this[qn]){this[Hn](this[qn]);return}t[ef]=1007,this[Hn](t)}});var Wn=_((VT,Yo)=>{"use strict";var{isUtf8:rf}=ne("buffer"),{hasBlob:PS}=yt(),xS=[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 CS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Aa(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 IS(t){return PS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Yo.exports={isBlob:IS,isValidStatusCode:CS,isValidUTF8:Aa,tokenChars:xS};if(rf)Yo.exports.isValidUTF8=function(t){return t.length<24?Aa(t):rf(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ne("utf-8-validate");Yo.exports.isValidUTF8=function(e){return e.length<32?Aa(e):t(e)}}catch{}});var Ia=_((zT,df)=>{"use strict";var{Writable:OS}=ne("stream"),of=Gn(),{BINARY_TYPES:MS,EMPTY_BUFFER:sf,kStatusCode:NS,kWebSocket:LS}=yt(),{concat:Ta,toArrayBuffer:jS,unmask:DS}=Ur(),{isValidStatusCode:BS,isValidUTF8:af}=Wn(),Qo=Buffer[Symbol.species],Le=0,cf=1,lf=2,uf=3,Pa=4,xa=5,Xo=6,Ca=class extends OS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||MS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[LS]=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 Qo(r.buffer,r.byteOffset+e,r.length-e),new Qo(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 Qo(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 cf:this.getPayloadLength16(e);break;case lf:this.getPayloadLength64(e);break;case uf:this.getMask();break;case Pa:this.getData(e);break;case xa:case Xo: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[of.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=cf:this._payloadLength===127?this._state=lf: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=uf:this._state=Pa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Pa}getData(e){let n=sf;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]&&DS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=xa,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[of.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=Ta(r,n):this._binaryType==="arraybuffer"?o=jS(Ta(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Le):(this._state=Xo,setImmediate(()=>{this.emit("message",o,!0),this._state=Le,this.startLoop(e)}))}else{let o=Ta(r,n);if(!this._skipUTF8Validation&&!af(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===xa||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Le):(this._state=Xo,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,sf),this.end();else{let r=e.readUInt16BE(0);if(!BS(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Qo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!af(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=Xo,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[NS]=o,s}};df.exports=Ca});var Na=_((JT,pf)=>{"use strict";var{Duplex:KT}=ne("stream"),{randomFillSync:FS}=ne("crypto"),ff=Gn(),{EMPTY_BUFFER:US,kWebSocket:HS,NOOP:qS}=yt(),{isBlob:Vn,isValidStatusCode:GS}=Wn(),{mask:mf,toBuffer:on}=Ur(),je=Symbol("kByteLength"),WS=Buffer.alloc(4),Zo=8*1024,sn,zn=Zo,Ve=0,VS=1,zS=2,Oa=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=Ve,this.onerror=qS,this[HS]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||WS,n.generateMask?n.generateMask(r):(zn===Zo&&(sn===void 0&&(sn=Buffer.alloc(Zo)),FS(sn,0,Zo),zn=0),r[0]=sn[zn++],r[1]=sn[zn++],r[2]=sn[zn++],r[3]=sn[zn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[je]!==void 0?a=n[je]:(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?(mf(e,r,u,i,a),[u]):(mf(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,o){let i;if(e===void 0)i=US;else{if(typeof e!="number"||!GS(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={[je]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ve?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):Vn(e)?(o=e.size,i=!1):(e=on(e),o=e.length,i=on.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[je]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Vn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ve?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):Vn(e)?(o=e.size,i=!1):(e=on(e),o=e.length,i=on.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[je]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Vn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ve?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[ff.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Vn(e)?(a=e.size,c=!1):(e=on(e),a=e.length,c=on.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={[je]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Vn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Ve?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[je],this._state=zS,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ma,this,a,o);return}this._bufferedBytes-=r[je];let s=on(i);n?this.dispatch(s,n,r,o):(this._state=Ve,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(KS,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[ff.extensionName];this._bufferedBytes+=r[je],this._state=VS,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ma(this,c,o);return}this._bufferedBytes-=r[je],this._state=Ve,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===Ve&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][je],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][je],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)}};pf.exports=Oa;function Ma(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 KS(t,e,n){Ma(t,e,n),t.onerror(e)}});var Ef=_((YT,vf)=>{"use strict";var{kForOnEventAttribute:qr,kListener:La}=yt(),hf=Symbol("kCode"),gf=Symbol("kData"),yf=Symbol("kError"),_f=Symbol("kMessage"),wf=Symbol("kReason"),Kn=Symbol("kTarget"),bf=Symbol("kType"),Sf=Symbol("kWasClean"),wt=class{constructor(e){this[Kn]=null,this[bf]=e}get target(){return this[Kn]}get type(){return this[bf]}};Object.defineProperty(wt.prototype,"target",{enumerable:!0});Object.defineProperty(wt.prototype,"type",{enumerable:!0});var an=class extends wt{constructor(e,n={}){super(e),this[hf]=n.code===void 0?0:n.code,this[wf]=n.reason===void 0?"":n.reason,this[Sf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[hf]}get reason(){return this[wf]}get wasClean(){return this[Sf]}};Object.defineProperty(an.prototype,"code",{enumerable:!0});Object.defineProperty(an.prototype,"reason",{enumerable:!0});Object.defineProperty(an.prototype,"wasClean",{enumerable:!0});var Jn=class extends wt{constructor(e,n={}){super(e),this[yf]=n.error===void 0?null:n.error,this[_f]=n.message===void 0?"":n.message}get error(){return this[yf]}get message(){return this[_f]}};Object.defineProperty(Jn.prototype,"error",{enumerable:!0});Object.defineProperty(Jn.prototype,"message",{enumerable:!0});var Gr=class extends wt{constructor(e,n={}){super(e),this[gf]=n.data===void 0?null:n.data}get data(){return this[gf]}};Object.defineProperty(Gr.prototype,"data",{enumerable:!0});var JS={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[qr]&&o[La]===e&&!o[qr])return;let r;if(t==="message")r=function(i,s){let a=new Gr("message",{data:s?i:i.toString()});a[Kn]=this,ei(e,this,a)};else if(t==="close")r=function(i,s){let a=new an("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Kn]=this,ei(e,this,a)};else if(t==="error")r=function(i){let s=new Jn("error",{error:i,message:i.message});s[Kn]=this,ei(e,this,s)};else if(t==="open")r=function(){let i=new wt("open");i[Kn]=this,ei(e,this,i)};else return;r[qr]=!!n[qr],r[La]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[La]===e&&!n[qr]){this.removeListener(t,n);break}}};vf.exports={CloseEvent:an,ErrorEvent:Jn,Event:wt,EventTarget:JS,MessageEvent:Gr};function ei(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ti=_((QT,kf)=>{"use strict";var{tokenChars:Wr}=Wn();function it(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function YS(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&&Wr[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?(it(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&&Wr[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),it(n,t.slice(c,l),!0),u===44&&(it(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(Wr[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Wr[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&&Wr[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),it(n,a,p),u===44&&(it(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?it(e,h,n):(a===void 0?it(n,h,!0):r?it(n,a,h.replace(/\\/g,"")):it(n,a,h),it(e,s,n)),e}function QS(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(", ")}kf.exports={format:QS,parse:YS}});var ii=_((eP,Lf)=>{"use strict";var XS=ne("events"),ZS=ne("https"),ev=ne("http"),Af=ne("net"),tv=ne("tls"),{randomBytes:nv,createHash:rv}=ne("crypto"),{Duplex:XT,Readable:ZT}=ne("stream"),{URL:ja}=ne("url"),Nt=Gn(),ov=Ia(),iv=Na(),{isBlob:sv}=Wn(),{BINARY_TYPES:$f,CLOSE_TIMEOUT:av,EMPTY_BUFFER:ni,GUID:cv,kForOnEventAttribute:Da,kListener:lv,kStatusCode:uv,kWebSocket:se,NOOP:Tf}=yt(),{EventTarget:{addEventListener:dv,removeEventListener:fv}}=Ef(),{format:mv,parse:pv}=ti(),{toBuffer:hv}=Ur(),Pf=Symbol("kAborted"),Ba=[8,13],bt=["CONNECTING","OPEN","CLOSING","CLOSED"],gv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,K=class t extends XS{constructor(e,n,r){super(),this._binaryType=$f[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ni,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]),xf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$f.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 ov({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new iv(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[se]=this,i[se]=this,e[se]=this,o.on("conclude",wv),o.on("drain",bv),o.on("error",Sv),o.on("message",vv),o.on("ping",Ev),o.on("pong",kv),i.onerror=$v,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Of),e.on("data",oi),e.on("end",Mf),e.on("error",Nf),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[Nt.extensionName]&&this._extensions[Nt.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){Re(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())}),If(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){Fa(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ni,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){Fa(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ni,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){Fa(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Nt.extensionName]||(o.compress=!1),this._sender.send(e||ni,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Re(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:bt.indexOf("CONNECTING")});Object.defineProperty(K.prototype,"CONNECTING",{enumerable:!0,value:bt.indexOf("CONNECTING")});Object.defineProperty(K,"OPEN",{enumerable:!0,value:bt.indexOf("OPEN")});Object.defineProperty(K.prototype,"OPEN",{enumerable:!0,value:bt.indexOf("OPEN")});Object.defineProperty(K,"CLOSING",{enumerable:!0,value:bt.indexOf("CLOSING")});Object.defineProperty(K.prototype,"CLOSING",{enumerable:!0,value:bt.indexOf("CLOSING")});Object.defineProperty(K,"CLOSED",{enumerable:!0,value:bt.indexOf("CLOSED")});Object.defineProperty(K.prototype,"CLOSED",{enumerable:!0,value:bt.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[Da])return e[lv];return null},set(e){for(let n of this.listeners(t))if(n[Da]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Da]:!0})}})});K.prototype.addEventListener=dv;K.prototype.removeEventListener=fv;Lf.exports=K;function xf(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:av,protocolVersion:Ba[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,!Ba.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ba.join(", ")})`);let i;if(e instanceof ja)i=e;else try{i=new ja(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;ri(t,m);return}let u=s?443:80,l=nv(16).toString("base64"),d=s?ZS.request:ev.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?_v:yv),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 Nt({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=mv({[Nt.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!gv.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",()=>{Re(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[Pf]||(f=t._req=null,ri(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){Re(t,f,"Maximum redirects exceeded");return}f.abort();let b;try{b=new ja(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);ri(t,R);return}xf(t,b,n,r)}else t.emit("unexpected-response",f,m)||Re(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 b=m.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){Re(t,g,"Invalid Upgrade header");return}let v=rv("sha1").update(l+cv).digest("base64");if(m.headers["sec-websocket-accept"]!==v){Re(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"),$){Re(t,g,$);return}R&&(t._protocol=R);let J=m.headers["sec-websocket-extensions"];if(J!==void 0){if(!p){Re(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ee;try{ee=pv(J)}catch{Re(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ce=Object.keys(ee);if(ce.length!==1||ce[0]!==Nt.extensionName){Re(t,g,"Server indicated an extension that was not requested");return}try{p.accept(ee[Nt.extensionName])}catch{Re(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Nt.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 ri(t,e){t._readyState=K.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function yv(t){return t.path=t.socketPath,Af.connect(t)}function _v(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Af.isIP(t.host)?"":t.host),tv.connect(t)}function Re(t,e,n){t._readyState=K.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Re),e.setHeader?(e[Pf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ri,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Fa(t,e,n){if(e){let r=sv(e)?e.size:hv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${bt[t.readyState]})`);process.nextTick(n,r)}}function wv(t,e){let n=this[se];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[se]!==void 0&&(n._socket.removeListener("data",oi),process.nextTick(Cf,n._socket),t===1005?n.close():n.close(t,e))}function bv(){let t=this[se];t.isPaused||t._socket.resume()}function Sv(t){let e=this[se];e._socket[se]!==void 0&&(e._socket.removeListener("data",oi),process.nextTick(Cf,e._socket),e.close(t[uv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Rf(){this[se].emitClose()}function vv(t,e){this[se].emit("message",t,e)}function Ev(t){let e=this[se];e._autoPong&&e.pong(t,!this._isServer,Tf),e.emit("ping",t)}function kv(t){this[se].emit("pong",t)}function Cf(t){t.resume()}function $v(t){let e=this[se];e.readyState!==K.CLOSED&&(e.readyState===K.OPEN&&(e._readyState=K.CLOSING,If(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function If(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Of(){let t=this[se];if(this.removeListener("close",Of),this.removeListener("data",oi),this.removeListener("end",Mf),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[se]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Rf),t._receiver.on("finish",Rf))}function oi(t){this[se]._receiver.write(t)||this.pause()}function Mf(){let t=this[se];t._readyState=K.CLOSING,t._receiver.end(),this.end()}function Nf(){let t=this[se];this.removeListener("error",Nf),this.on("error",Tf),t&&(t._readyState=K.CLOSING,this.destroy())}});var Ff=_((nP,Bf)=>{"use strict";var tP=ii(),{Duplex:Rv}=ne("stream");function jf(t){t.emit("close")}function Av(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Df(t){this.removeListener("error",Df),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Tv(t,e){let n=!0,r=new Rv({...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(jf,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick(jf,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",Av),r.on("error",Df),r}Bf.exports=Tv});var Ua=_((rP,Uf)=>{"use strict";var{tokenChars:Pv}=Wn();function xv(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&&Pv[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}Uf.exports={parse:xv}});var Kf=_((iP,zf)=>{"use strict";var Cv=ne("events"),si=ne("http"),{Duplex:oP}=ne("stream"),{createHash:Iv}=ne("crypto"),Hf=ti(),cn=Gn(),Ov=Ua(),Mv=ii(),{CLOSE_TIMEOUT:Nv,GUID:Lv,kWebSocket:jv}=yt(),Dv=/^[+/0-9A-Za-z]{22}==$/,qf=0,Gf=1,Vf=2,Ha=class extends Cv{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Nv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Mv,...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=si.createServer((r,o)=>{let i=si.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=Bv(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=qf}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===Vf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Vr,this);return}if(e&&this.once("close",e),this._state!==Gf)if(this._state=Gf,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(Vr,this):process.nextTick(Vr,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Vr(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",Wf);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ln(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){ln(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Dv.test(i)){ln(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ln(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){zr(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=Ov.parse(c)}catch{ln(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 cn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Hf.parse(l);p[cn.extensionName]&&(h.accept(p[cn.extensionName]),d[cn.extensionName]=h)}catch{ln(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 zr(n,f||401,m,g);this.completeUpgrade(d,i,u,e,n,r,o)});return}if(!this.options.verifyClient(h))return zr(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[jv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>qf)return zr(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Iv("sha1").update(n+Lv).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[cn.extensionName]){let d=e[cn.extensionName].params,h=Hf.format({[cn.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",Wf),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(Vr,this)})),a(l,o)}};zf.exports=Ha;function Bv(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 Vr(t){t._state=Vf,t.emit("close")}function Wf(){this.destroy()}function zr(t,e,n,r){n=n||si.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} ${si.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 ln(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,ln),t.emit("wsClientError",s,n,e)}else zr(n,r,o,i)}});var Uc={"-v":"version","-h":"help"};function ah(t){return t.startsWith("--")?!0:Uc[t]!==void 0}function Hc(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||ah(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=Uc[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 Wc from"node:path";import Vc from"node:fs";import qc from"node:fs";import ch from"node:os";import Gc from"node:path";var lh=Gc.join(".aifight","runtime");function Q(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Gc.join(ch.homedir(),lh)}function Be(){let t=Q();if(qc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{qc.chmodSync(t,448)}catch{}}var $e=class extends Error{name="RuntimeFilesError";kind;filePath;constructor(e,n,r){super(r),this.kind=e,this.filePath=n}};function uh(){return Wc.join(Q(),"token")}function dh(){return Wc.join(Q(),"port")}function zc(){let t=uh(),e;try{e=Vc.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new $e("token_missing",t,`token file not found at ${t}; AIFight Bridge must be running`):new $e("token_corrupt",t,`failed to read token file at ${t}: ${r.message}`)}let n=e.trim();if(n.length===0)throw new $e("token_corrupt",t,`token file at ${t} is empty`);return n}function Kc(){let t=dh(),e;try{e=Vc.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new $e("port_missing",t,`port file not found at ${t}; AIFight Bridge must be running`):new $e("port_corrupt",t,`failed to read port file at ${t}: ${o.message}`)}let n=e.trim();if(n.length===0)throw new $e("port_corrupt",t,`port file at ${t} is empty`);if(!/^-?\d+$/.test(n))throw new $e("port_corrupt",t,`port file at ${t} is not a number: "${n}"`);let r=Number.parseInt(n,10);if(r<1||r>65535)throw new $e("port_corrupt",t,`port file at ${t} is out of range [1, 65535]: ${r}`);return r}var fh=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function mh(t){return typeof t=="string"&&fh.has(t)}function ph(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 mh(n.code)&&typeof n.message=="string"}var he=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}},hh="127.0.0.1",gh=1e4;function Jc(t){let e=t.host??hh,n=t.baseTimeoutMs??gh,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new he("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new he("runtime_files_corrupt",`corrupt runtime files: ${f.message}`,{cause:f})}function a(){if(o!==void 0&&i!==void 0)return{token:o,port:i};try{let f=t.tokenSource(),m=t.portSource();return o=f,i=m,{token:f,port:m}}catch(f){throw f instanceof $e?s(f):f}}function c(){let f=o,m=i;try{let g=t.tokenSource(),y=t.portSource();return o=g,i=y,{token:g,port:y,changed:g!==f||y!==m}}catch(g){throw g instanceof $e?s(g):g}}function u(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function l(f,m,g,y){let b={Authorization:`Bearer ${g}`},v;return m===void 0?v=void 0:(b["Content-Type"]="application/json",v=JSON.stringify(m)),{method:f,headers:b,body:v,signal:y}}async function d(f,m,g,y,b){let v=`http://${e}:${b}${m}`,R=new AbortController,$=setTimeout(()=>{R.abort()},n);try{let J;try{J=await r(v,l(f,g,y,R.signal))}catch(ce){throw u(ce)?new he("request_timeout",`request timed out after ${n}ms`,{cause:ce}):new he("daemon_unreachable",`AIFight Bridge not running: ${ce.message}`,{cause:ce})}let ee;try{ee=await J.text()}catch(ce){throw u(ce)?new he("request_timeout",`request timed out after ${n}ms`,{cause:ce}):new he("transport_unparseable",`failed to read response body (status ${J.status})`,{status:J.status,cause:ce})}if(ee.length===0)return{status:J.status,parsedBody:void 0,parseFailed:!1};try{return{status:J.status,parsedBody:JSON.parse(ee),parseFailed:!1}}catch{return{status:J.status,parsedBody:ee,parseFailed:!0}}}finally{clearTimeout($)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new he("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!ph(f.parsedBody))throw new he("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new he("server_error",m.error.message,{serverCode:m.error.code,status:f.status,body:m})}async function p(f,m,g){let y=a(),b=await d(f,m,g,y.token,y.port);if(b.status!==401)return h(b);let v=c();if(!v.changed)throw new he("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,v.token,v.port);if(R.status===401)throw new he("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 Yc(t,e={}){return Jc({tokenSource:zc,portSource:Kc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var re=["texas_holdem","liars_dice","coup"];function Fe(t){return re.includes(t)}var T=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 F(t,e,n,r){let o=t.positional.length;if(o<e)throw new T(`missing required positional argument${e===1?"":"s"}`,r);if(o>n){let i=t.positional.slice(n).join(" ");throw new T(`unexpected extra positional argument${o-n===1?"":"s"}: ${i}`,r)}}function ao(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
+ `}import lo from"node:fs";import ur from"node:path";import{fileURLToPath as yh}from"node:url";var Qc=["./schemas","../../../protocol/schema","../../protocol/schema"],co=null;function dr(t=_h()){if(co)return co;for(let e of Qc){let n=ur.resolve(t,e);if(Xc(n)&&Xc(ur.join(n,"messages")))return co=n,co}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Qc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function _h(){return ur.dirname(yh(import.meta.url))}function Xc(t){try{return lo.statSync(t).isDirectory()}catch{return!1}}var wh={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 Ai(){return Object.keys(wh)}function Gt(){let t=dr(),e=new Map;return el(t,n=>{if(!n.endsWith(".schema.json"))return;let r=lo.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function el(t,e){for(let n of lo.readdirSync(t,{withFileTypes:!0})){let r=ur.join(t,n.name);n.isDirectory()?el(r,e):n.isFile()&&e(r)}}var Zc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function Ti(t){let e=Zc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Zc).join(", ")}`);let n=dr(),r=ur.join(n,e),o=lo.readFileSync(r,"utf8");return JSON.parse(o)}var Bd=Ce(Wo(),1),Fd=Ce(ba(),1);var Fn=class extends Error{},gt=class extends Fn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},tn=class extends Fn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},nn=class extends Fn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var uS=3e4,rn="/api/agents/register",dS="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Un=null;function fS(){if(Un)return Un;let t=new Bd.default({strict:!1,allErrors:!0});(0,Fd.default)(t);let e=Gt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(dS);if(n)return Un=n,Un;let r=Ti("register_response");return Un=t.compile(r),Un}async function Sa(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??uS,r=t.baseUrl.replace(/\/+$/,"")+rn,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 gt(`POST ${rn} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new gt(`POST ${rn} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new gt(`POST ${rn} 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 tn(s.status,p,`POST ${rn} returned HTTP ${s.status}`)}if(u!==null)throw new nn([],`POST ${rn} returned 201 with non-JSON body: ${u.message}`);if(typeof c!="object"||c===null)throw new nn([],`POST ${rn} returned 201 with non-object body`);let l=fS();if(!l(c)){let p=(l.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new nn(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 PT from"better-sqlite3";var Ud=`-- 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 Hd=[{version:1,up:t=>{t.exec(Ud)}},{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,218 +64,225 @@ 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})+`
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}})+`
67
+ `)}}],OT=Hd[Hd.length-1].version;import{Entry as LT}from"@napi-rs/keyring";var qd="AIFIGHT_KEYCHAIN_V1:",Gd="AIFIGHT_CRYPTO_V1:";var BT=Buffer.byteLength(qd,"ascii"),FT=Buffer.byteLength(Gd,"ascii");var Fv=Ce(Ff(),1),Uv=Ce(ti(),1),Hv=Ce(Gn(),1),qv=Ce(Ia(),1),Gv=Ce(Na(),1),Wv=Ce(Ua(),1),qa=Ce(ii(),1),Vv=Ce(Kf(),1);var pe=class extends Error{},Lt=class extends pe{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},jt=class extends pe{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},un=class extends pe{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Dt=class extends pe{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},dn=class extends pe{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},fn=class extends pe{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Ae=class extends pe{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},st=class extends pe{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},St=class extends pe{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},vt=class extends pe{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var Jf=Ce(Wo(),1),Yf=Ce(ba(),1);var Wa=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),Va=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Qf="https://aifight.ai/protocol/v1/messages/";function zv(t){return`${Qf}client_${t}.schema.json`}function Kv(t){return`${Qf}server_${t}.schema.json`}var Ga=null;function Xf(){if(Ga)return Ga;let t=new Jf.default({strict:!1,allErrors:!0});(0,Yf.default)(t);for(let[e,n]of Gt())t.getSchema(e)||t.addSchema(n,e);return Ga=t,t}function Zf(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function em(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function tm(t){if(!em(t))throw new st("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new st("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(Va.has(e))throw new st(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!Wa.has(e))throw new st(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...Wa].join(", ")})`);let n=Xf(),r=zv(e),o=n.getSchema(r);if(!o)throw new st(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new st(e,Zf(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function za(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 Ae("<unknown>",[],`parseServerFrame: malformed JSON: ${u}`)}if(!em(n))throw new Ae("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Ae("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!Va.has(r))throw Wa.has(r)?new St(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new St(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...Va].join(", ")})`);let o=Xf(),i=Kv(r),s=o.getSchema(i);if(!s)throw new Ae(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Ae(r,Zf(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var Jv=1e4,Yv=25e3;function nm(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 Ka=class{#e;#t="connected";#n=null;#r=null;#i=null;#a=new Set;#o=new Set;#s=new Set;#u=!1;#d=null;#f=null;#c=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#l(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.#c&&(this.#c(),this.#c=null)});let o=r.pingIntervalMs??Yv;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.#i=()=>{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.#i,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onClose(e){return this.#s.add(e),()=>{this.#s.delete(e)}}#l(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=za(n)}catch(o){if(o instanceof Ae||o instanceof St)this.#p(o);else{let i=o instanceof Error?o.message:String(o);this.#p(new Ae("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#g(r)}#g(e){let n=[...this.#a];for(let r of n)this.#h(()=>r(e))}#p(e){let n=[...this.#o];for(let r of n)this.#h(()=>r(e))}#y(e){if(this.#u)return;this.#u=!0;let n=[...this.#s];for(let r of n)this.#h(()=>r(e))}#h(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new fn(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=tm(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#i&&(this.#r.removeEventListener("abort",this.#i),this.#r=null,this.#i=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#f&&await this.#f;return}this.#d="client",this.#t="closing",this.#_(),this.#f=new Promise(r=>{this.#c=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#c&&(this.#c(),this.#c=null)}await this.#f}}};async function Ja(t){let e=t.welcomeTimeoutMs??Jv;return t.signal?.aborted?Promise.reject(new vt(`createWSClient aborted before start: ${nm(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new qa.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(l){let d=l instanceof Error?l.message:String(l);r(new Lt(`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: ${nm(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",l=>{u(()=>{try{o.terminate()}catch{}r(new Lt(`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 jt(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;u(()=>r(new jt(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{u(()=>{try{o.terminate()}catch{}r(new un(`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=za(d)}catch(b){let v=[],R="first frame failed to parse";b instanceof Ae?(v=b.ajvErrors,R=b.messageType==="welcome"?`welcome failed schema validation: ${b.message}`:`first frame parse failure (${b.messageType}): ${b.message}`):b instanceof St?R=`first frame had unknown server message type '${b.messageType}': ${b.message}`:b instanceof Error&&(R=`first frame parse error: ${b.message}`),u(()=>{try{o.terminate()}catch{}r(new Dt(v,R))});return}if(h.type!=="welcome"){u(()=>{try{o.terminate()}catch{}r(new Dt([],`expected first frame to be 'welcome', got '${h.type}'`))});return}let p=h,f=p.data.server_protocol_version,m=b=>b.startsWith("v")?b.slice(1):b,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){u(()=>{try{o.terminate()}catch{}r(new dn(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}u(()=>{let b=new Ka(o,p,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(b)})})})}var Yn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},Qv=1e3,Xv=2,Zv=3e4,e0="full",t0=5*60*1e3,n0=15*60*1e3,r0=new Set([1001,1006,1011,1012]);function o0(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function i0(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 s0(t){return t.code>=4e3&&t.code<5e3?!1:r0.has(t.code)}function a0(t){if(t instanceof vt||t instanceof Dt||t instanceof dn)return!1;if(t instanceof Lt||t instanceof un)return!0;if(t instanceof jt){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function c0(t){return t>=n0?"error":t>=t0?"warning":"info"}var Ya=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#i=new Set;#a=new Set;#o=0;#s=0;#u=null;#d=null;#f=!1;#c=null;#l=!1;#g=null;#p=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new fn(`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.#i.add(e),()=>{this.#i.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#c={code:e,reason:n},this.#g&&this.#g("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#l||this.#m({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#u=e,this.#d=n,this.#y()}async#y(){if(this.#o=Date.now(),this.#e.signal?.aborted){this.#v("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#S("attempt-start",this.attempt);let e,n=!1;try{let a=await Ja({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.#s=0,this.#S("attempt-success",c),this.#f||(this.#f=!0,this.#u?.());let u=await this.#_(a);if(this.#w(),this.#t=null,this.#c){this.#m({kind:"caller-close",code:this.#c.code??u.code,closeReason:this.#c.reason??u.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#m({kind:"signal",cause:void 0});return}if(!s0(u)){let l=new Yn("fatal-close",void 0,`close code ${u.code} not in retry whitelist`);this.#m({kind:"fatal-close",code:u.code,closeReason:u.reason,cause:l});return}this.#s=1,this.state="backoff",this.#o=Date.now()}catch(a){if(n)throw a;if(a instanceof pe&&(e=a),!a0(a)){let c=a instanceof pe?a:void 0,u=a instanceof vt?"signal":"fatal-error",l=a instanceof Error?a.message:"non-retriable error";this.#v(u,c,l);return}this.#s++,this.state="backoff"}let r=o0(this.#s,this.#e.initialBackoffMs??Qv,this.#e.backoffFactor??Xv,this.#e.maxBackoffMs??Zv),o=i0(r,this.#e.jitter??e0),i=this.attempt===0?1:this.attempt;if(this.#S("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#s>=this.#e.maxAttempts){this.#v("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#h(o);if(s==="abort"){this.#m({kind:"signal",cause:void 0}),this.#f||(this.#f=!0,this.#d?.(new Yn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#m({kind:"caller-close",code:this.#c?.code??1e3,closeReason:this.#c?.reason,cause:void 0});return}}}#h(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#g=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.#g=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.#p.push(e.onMessage(n));for(let n of this.#r)this.#p.push(e.onError(n))}#w(){for(let e of this.#p)try{e()}catch{}this.#p.length=0}#S(e,n,r,o){let i=Date.now()-this.#o,s=e==="give-up"?"error":e==="attempt-failure"?c0(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{}}#v(e,n,r){let o=new Yn(e,n,r);this.#m({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#f||(this.#f=!0,this.#d?.(o))}#m(e){if(this.#l)return;this.#l=!0,this.state="closed",this.#w(),this.#t=null,this.#S("give-up",this.attempt,void 0,e.cause);let n=[...this.#i];for(let r of n)try{r(e)}catch{}}};async function Qa(t){let e=new Ya(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var l0=["check","call","fold","raise","allin"];function Xa(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 l0){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function ec(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=u0(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=d0(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 u0(t){let e=f0(t);if(!e)return;let n=Za(e,"min_quantity"),r=Za(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Za(e,"max_quantity")}}function d0(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 f0(t){return t!==null&&typeof t=="object"?t:void 0}function Za(t,e){let n=t[e];return typeof n=="number"?n:void 0}var m0=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],p0=["pass","challenge"],h0=["pass","block"],g0=["lose_card"],y0=["return_cards"];function tc(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 Kr(n,m0);case"challenge_action":case"challenge_block":return Kr(n,p0);case"block":return Kr(n,h0);case"lose_influence":return Kr(n,g0);case"exchange_return":return Kr(n,y0);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function Kr(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var _0=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function rc(t,e,n=500){let r=t.trim(),o=S0(r),i;try{i=JSON.parse(o)}catch{return mn("json_parse",r,n)}if(!ai(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&&!ai(c))return mn("missing_fields",r,n);let u=ai(c)?c:void 0;if(!w0.has(s))return mn("unknown_action_type",r,n);let l=e.find(d=>d.type===s);if(!l)return mn("action_not_legal",r,n);if(s==="raise"){let d=b0(l,u);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:mn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:l,summary:a}:{kind:"ok",action:l}}var w0=new Set(["fold","check","call","raise","allin"]);function b0(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ai(t.data)?t.data:void 0,o=nc(r,"amount"),i=nc(r,"min")??o,s=nc(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function S0(t){let e=t.match(_0);return e?e[1].trim():t}function ai(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function nc(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function mn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var v0=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function ic(t,e,n=500){let r=t.trim(),o=$0(r),i;try{i=JSON.parse(o)}catch{return pn("json_parse",r,n)}if(!ci(i))return pn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return pn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ci(c))return pn("missing_fields",r,n);let u=ci(c)?c:void 0;if(!E0.has(s))return pn("unknown_action_type",r,n);let l=e.find(d=>d.type===s);if(!l)return pn("action_not_legal",r,n);if(s==="bid"){let d=k0(l,u);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:pn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:l,summary:a}:{kind:"ok",action:l}}var E0=new Set(["bid","challenge"]);function k0(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=ci(t.data)?t.data:void 0,i=oc(o,"min_quantity"),s=oc(o,"min_face"),a=oc(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 $0(t){let e=t.match(v0);return e?e[1].trim():t}function ci(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function oc(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function pn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var R0=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,A0=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function sc(t,e,n=500){let r=t.trim(),o=P0(r),i;try{i=JSON.parse(o)}catch{return hn("json_parse",r,n)}if(!Qn(i))return hn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return hn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Qn(c))return hn("missing_fields",r,n);let u=Qn(c)?c:void 0;if(!A0.has(s))return hn("unknown_action_type",r,n);let l=e.filter(h=>h.type===s);if(l.length===0)return hn("action_not_legal",r,n);let d=T0(s,l,u);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:hn("data_validation",r,n)}function T0(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>rm(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>rm(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=>x0(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=C0(o.data,"return_indices");return i!==void 0&&I0(i,r)})}default:return e[0]}}function P0(t){let e=t.match(R0);return e?e[1].trim():t}function Qn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rm(t,e){if(!Qn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function x0(t,e){if(!Qn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function C0(t,e){if(!Qn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function I0(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 hn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var ae="0.1.0-alpha.8",um="v1.0.0";function dm(){let t=dr(),e=Gt(),n=Ai();return{ok:!0,runtimeVersion:ae,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function ac(t,e){return F(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:ae})+`
68
+ `):e.stdout(`${ae}
69
+ `),0}import Jr from"node:fs";import N0 from"node:path";var ze=class extends Error{name="RuntimeLocalUrlError"};function Xn(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 Yr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new ze("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new ze("runtime URL must use http:// or https://");if(!B0(r.hostname))throw new ze("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new ze("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new ze("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Bt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function lc(){return N0.join(Q(),"bridge.json")}function fm(){Jr.rmSync(lc(),{force:!0})}function gn(t){Be();let e=lc(),n=`${e}.tmp`;if(Jr.writeFileSync(n,JSON.stringify(t,null,2)+`
70
+ `,{mode:384}),Jr.renameSync(n,e),process.platform!=="win32")try{Jr.chmodSync(e,384)}catch{}}function U(){let t=lc(),e;try{e=Jr.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(!j0(n))throw new Error("bridge config is invalid; run connect again");return n}function Ft(t){return{...t,apiKey:cc(t.apiKey),...t.claimUrl!==void 0?{claimUrl:L0(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:cc(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:cc(t.runtimeLocalToken)}:{}}}function cc(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function L0(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 j0(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"&&D0(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 D0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Yr(t,e),!0}catch{return!1}}function B0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var F0="npm install -g @aifight/aifight@alpha";async function De(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${H0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return uc(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=q0(s);return a===null?uc(t.currentVersion,"version check returned invalid policy"):U0(t.currentVersion,a)}catch(i){let s=i?.name;return uc(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function U0(t,e){let n=mm(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=mm(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 uc(t,e){return{status:"unknown",currentVersion:t,message:e}}function H0(t){return t.replace(/\/+$/,"")}function q0(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:F0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function mm(t,e){let n=pm(t),r=pm(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 G0(n.prerelease,r.prerelease)}function pm(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 G0(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 W0=1500;async function hm(t,e){F(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??dm)()}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 V0(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 V0(t,e){try{let n=U(),r=await De({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Ft(n),runtime:await z0(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 z0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??Bt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),W0);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=K0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${J0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function K0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function J0(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 CE from"node:os";import{randomBytes as IE}from"node:crypto";import{execFile as Y0}from"node:child_process";import Te from"node:fs";import dc from"node:os";import Et from"node:path";import{promisify as Q0}from"node:util";var Ut="aifight.service",li="ai.aifight.service",Z=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},X0=Q0(Y0),Ke=async(t,e)=>{try{let{stdout:n,stderr:r}=await X0(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 fc(t={}){let e=await er(t),n=t.execFile??Ke;Z0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",at(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",at(t),e.unitPath]);let o=await mc(t);return{...e,linger:"not_needed",...o?{warning:o}:{}}}let r=yn(e.platform);if(await n("systemctl",[...r,"daemon-reload"]),await n("systemctl",[...r,"enable","--now",Ut]),e.platform==="linux-systemd-user"){let o=await nE(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await rE(e,t),new Z("service_install_failed",`failed to install ${Ut}: ${Zn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function ui(t={}){let e=await er(t),n=t.execFile??Ke;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",at(t),e.unitPath]).catch(()=>{}),Te.rmSync(e.unitPath,{force:!0}),e;let r=yn(e.platform);return await n("systemctl",[...r,"disable","--now",Ut]).catch(()=>{}),Te.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function wm(t={}){let e=await er(t),n=t.execFile??Ke;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",at(t),e.unitPath]).catch(()=>{}),await mc(t),e):(await n("systemctl",[...yn(e.platform),"start",Ut]),e)}async function bm(t={}){let e=await er(t),n=t.execFile??Ke;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",at(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...yn(e.platform),"stop",Ut]),e)}async function Zr(t={}){let e=await er(t),n=t.execFile??Ke;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",at(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",at(t),e.unitPath]),await mc(t),e):(await n("systemctl",[...yn(e.platform),"restart",Ut]),e)}async function kt(t={}){let e=await er(t),n=t.execFile??Ke;if(!Te.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${at(t)}/${li}`]),{...e,installed:!0,running:!0,detail:"running"}}catch(o){return{...e,installed:!0,running:!1,detail:Zn(o)}}try{let i=(await n("systemctl",[...yn(e.platform),"is-active",Ut])).stdout.trim()||"active";return{...e,installed:!0,running:i==="active",detail:i}}catch(o){return{...e,installed:!0,running:!1,detail:Zn(o)}}}async function er(t={}){let e=t.platform??process.platform,n=t.uid??process.getuid?.()??0,r=t.homeDir??dc.homedir(),o=t.runtimeHome??Q(),i=await oE(t),s=iE(t);if(e==="linux")return await gm("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??Et.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await gm("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??Et.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new Z("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function Z0(t){Te.mkdirSync(Et.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?tE(t):eE(t);aE(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function eE(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=${ym(t.nodeExec)} ${ym(t.aifightExec)} run`,_m("AIFIGHT_RUNTIME_HOME",t.runtimeHome),_m("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
+ `)}function tE(t){let e=Et.dirname(t.unitPath).includes("LaunchAgents")?Et.join(dc.homedir(),"Library","Logs","aifight"):Et.join(Et.dirname(t.unitPath),"logs");return Te.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>${li}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Qr(t.nodeExec)}</string>`,` <string>${Qr(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Qr(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Qr(Et.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Qr(Et.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
+ `)}function yn(t){return t==="linux-systemd-user"?["--user"]:[]}function at(t){return`gui/${t.uid??process.getuid?.()??0}`}async function mc(t){let e=t.execFile??Ke,n=`${at(t)}/${li}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${li} is loaded: ${Zn(r)}`}catch{throw r}}}async function nE(t){let e=t.username??dc.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??Ke;try{return await n("loginctl",["enable-linger",e]),{status:"enabled"}}catch(r){return{status:"failed",warning:`loginctl enable-linger ${e} failed: ${Zn(r)}`}}}async function rE(t,e){let n=e.execFile??Ke;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",at(e),t.unitPath]).catch(()=>{}),Te.rmSync(t.unitPath,{force:!0});return}let r=yn(t.platform);await n("systemctl",[...r,"disable","--now",Ut]).catch(()=>{}),Te.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function oE(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Xr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!sE(n))try{return Xr(n)}catch{}let r=t.execFile??Ke;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
+ `)[0];if(i)return Xr(i)}catch{}throw new Z("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 iE(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Xr(e);try{return Xr(process.execPath)}catch{throw new Z("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 Xr(t){let e=Te.realpathSync(t);return Te.accessSync(e,Te.constants.X_OK),e}function sE(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function gm(t,e,n){let r=n.execFile??Ke;try{await r(t,e)}catch(o){throw new Z("service_manager_unavailable",`${t} is not available or not usable on this system: ${Zn(o)}`,"AIFight will keep running in the foreground; use your own process manager if needed.")}}function ym(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function _m(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function aE(t,e,n){let r=`${t}.${process.pid}.tmp`;Te.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Te.chmodSync(r,n),Te.renameSync(r,t)}function Zn(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 Qr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var pc=["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 vm(t,e){F(t,1,1,pc);let n=t.positional[0],r=cE(t,"aifight-path");if(r!==void 0&&n!=="install")throw new T("--aifight-path is only supported with `aifight service install`",pc);try{switch(n){case"install":{U();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await fc(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
80
80
  `):(e.stdout(`aifight.service installed and started (${i.platform}).
81
81
  `),e.stdout(`unit: ${i.unitPath}
82
82
  `),i.warning&&e.stderr(`warning: ${i.warning}
83
- `)),0}case"status":{let o=await St(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
83
+ `)),0}case"status":{let o=await kt(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
84
84
  `):o.installed?(e.stdout(`aifight.service: ${o.running?"running":"stopped"} (${o.detail})
85
85
  `),e.stdout(`unit: ${o.unitPath}
86
86
  `)):(e.stdout(`aifight.service: not installed
87
87
  `),e.stdout(`run: aifight service install
88
- `)),0}case"start":{let o=await am(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
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}).
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}:{}}})+`
88
+ `)),0}case"start":{let o=await wm(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
89
+ `),0}case"stop":{let o=await bm(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}).
91
+ `),0}case"uninstall":{let o=await ui(e.bridgeService);return e.stdout(`aifight.service uninstalled (${o.platform}).
92
+ `),0}default:throw new T(`unknown service command '${n}'`,pc)}}catch(o){if(o instanceof T)throw o;if(o instanceof Z)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(`
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}).
97
+ `),1}}function cE(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function Em(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";let n=await lE(t);if(n?.installed&&n.running===!0){if(t.stdout(["aifight.service is already running.","AIFight just saved bridge credentials, so the service must reload them before the Dashboard can show the new Agent online.",""].join(`
98
+ `)),!(e.approvedLocalSetup===!0?!0:await Sm(t,"Restart aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting aifight.service now.
99
+ `);try{let i=await Zr(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 Z,i.message),a=i instanceof Z?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
- `)),!(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
- `);try{let o=await oc(t.bridgeService);return t.stdout(`aifight.service installed and started (${o.platform}).
104
+ `)),!(e.approvedLocalSetup===!0?!0:await Sm(t,"Install and start aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; installing aifight.service now.
105
+ `);try{let o=await fc(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 Z,o.message),s=o instanceof Z?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 lE(t){try{return await kt(t.bridgeService)}catch{return}}async function Sm(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}import{execFile as uE}from"node:child_process";import km from"node:fs";import $m from"node:path";var dE=3e4;function Pe(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split($m.delimiter))if(r)for(let o of n){let i=$m.join(r,`${t}${o}`);try{return km.accessSync(i,km.constants.X_OK),i}catch{}}}async function ct(t,e){let n=Pe(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};uE(n,e,{timeout:dE},(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 _n(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 di(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 tr(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 nr(t,e,n,r={}){let o=await fE(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: ${gE(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 tr(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
- `);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}
118
+ `);let a=await ct(o.command,o.args);return _n(t,o.manualCommand,a),e==="hermes"&&hE(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 fE(t){let e=await mE(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 mE(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 ct("systemctl",[...n,"is-active",r]);if(pE(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 pE(t){return t.code===0&&t.stdout.trim()==="active"}function hE(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
123
+ ${t.stderr}`)}function gE(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 wE}from"node:crypto";import rr from"node:fs";import bE from"node:os";import Am from"node:path";import eo from"node:fs";import yE from"node:path";function hc(){return yE.join(Q(),"runtime-setup.json")}function gc(){try{let t=eo.readFileSync(hc(),"utf8"),e=JSON.parse(t);return _E(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function yc(t){Be();let e=gc(),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=hc(),o=`${r}.tmp`;if(eo.writeFileSync(o,JSON.stringify(n,null,2)+`
124
+ `,{mode:384}),eo.renameSync(o,r),process.platform!=="win32")try{eo.chmodSync(r,384)}catch{}}function Rm(){eo.rmSync(hc(),{force:!0})}function _E(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var wc="gateway.http.endpoints.responses.enabled",Tm=4e3,SE=6e3,Pm=1e4;async function xm(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return vE(t);case"hermes":return EE(t);case"mock":return{}}}async function vE(t){let e=await or(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
- `)),!(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}).
129
+ `)),!(t.approvedLocalSetup===!0?!0:await di(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 l=await TE();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 or(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
- `),{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.
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 ${wc} true --strict-json`," openclaw config validate",""].join(`
135
+ `)),!Pe("openclaw"))return t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
136
136
 
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.
137
+ `),{};if(!(t.approvedLocalSetup===!0?!0:await di(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 xE(),o=await ct("openclaw",["config","set",wc,"true","--strict-json"]);if(_n(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
- `),{};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}
142
+ `),{};let i=await ct("openclaw",["config","validate"]);_n(t.env,"openclaw config validate",i),yc({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 bc(SE);let s=await or(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 nr(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 bc(Pm);let c=await or(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 EE(t){let e=await fi(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
- `),{};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.
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=${Im(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
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
- `),{};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.
156
+ `),{};if(!(t.approvedLocalSetup===!0?!0:await di(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=kE({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(yc({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 nr(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
- `),await fc(ym);let s=await ai(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
164
+ `),await bc(Pm);let s=await fi(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 or(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),Tm);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 fi(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await _c(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 _c(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 _c(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 _c(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),Tm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function kE(t){let e=process.env.HERMES_HOME??Am.join(bE.homedir(),".hermes");rr.mkdirSync(e,{recursive:!0,mode:448});let n=Am.join(e,".env"),r=rr.existsSync(n)?rr.readFileSync(n,"utf8"):"";if(r!==""){let u=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");rr.copyFileSync(n,`${n}.aifight-backup-${u}`)}let o=Cm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${wE(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:RE(t.runtimeLocalUrl),API_SERVER_PORT:String(Im(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=AE(r,Object.keys(s)),c=$E(r,s);if(rr.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{rr.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function $E(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 Cm(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 RE(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function Im(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function AE(t,e){let n={};for(let r of e){let o=Cm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function TE(){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 ct("openclaw",["config","get","gateway.auth.token"]);return r.code===0&&e(PE(r.stdout)),t}function PE(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 xE(){let t=await ct("openclaw",["config","get",wc]);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 bc(t){return new Promise(e=>setTimeout(e,t))}var OE="https://aifight.ai",Om=2,ME="approved-local-setup",wn=["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 Nm(t,e){F(t,0,1,wn);let n=FE();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[ME]===!0;if(t.jsonMode&&r)throw new T("--approved-local-setup cannot be combined with --json",wn);let o=await NE(t,e,r),i=DE(t,o),s=BE(process.env.AIFIGHT_BASE_URL??OE),a=to(t.flags,"runtime-model")??Bt(o),c=HE(to(t.flags,"runtime-url")??Xn(o),o),u=to(t.flags,"runtime-token");try{let l=await xm({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 Sa({baseUrl:s,request:{name:i,model:a,description:`AIFight Bridge agent (${o})`},fetchImpl:e.fetchImpl}),h={version:1,baseUrl:s,wsUrl:UE(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:Om,updatedAt:new Date().toISOString()};return gn(h),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:d.claimUrl,config:Ft(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(`Automatic ranked matches: ${bm} per day
176
+ `),e.stdout(`Runtime: ${Lm(h.runtimeType)} at ${h.runtimeLocalUrl}
177
+ `),e.stdout(`Automatic ranked matches: ${Om} 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 Em(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
-
193
- `),a.runtimeType;throw new O(["Could not safely auto-detect whether this machine is running OpenClaw or Hermes.",a.detail,"Rerun with an explicit runtime:"," aifight register openclaw --approved-local-setup"," aifight register hermes --approved-local-setup"].join(`
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)
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 tn){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 gt?new B("registration_failed",l.message):l}}function Lm(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function NE(t,e,n){let r=t.positional[0],o=to(t.flags,"runtime"),i=process.env.AIFIGHT_RUNTIME_TYPE,s=o??r??i;if(o!==void 0&&r!==void 0&&o!==r)throw new T("runtime argument and --runtime disagree",wn);if(s==="openclaw"||s==="hermes")return s;if(s===void 0){if(n){let a=await LE(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${Lm(a.runtimeType)} (${a.detail}).
193
+
194
+ `),a.runtimeType;throw new T(["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(`
195
+ `),wn)}return!t.jsonMode&&process.stdin.isTTY?jE(e):"openclaw"}throw new T(`runtime must be openclaw or hermes (got '${s}')`,wn)}async function LE(t){let[e,n]=await Promise.all([or(t,Xn("openclaw"),void 0,Bt("openclaw")),fi(t,Xn("hermes"),void 0,Bt("hermes"))]),r=Mm(e),o=Mm(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 Mm(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function jE(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 T(`runtime must be openclaw or hermes (got '${e.trim()}')`,wn)}function DE(t,e){let n=to(t.flags,"name");if(n!==void 0)return n;let r=CE.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${IE(3).toString("hex")}`.slice(0,50)}function BE(t){return t.replace(/\/+$/,"")}function FE(){try{return U()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}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 to(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function HE(t,e){try{return Yr(t,e)}catch(n){throw n instanceof ze?new T(n.message,wn):n}}var qE="https://aifight.ai";async function jm(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=GE(t.baseUrl??process.env.AIFIGHT_BASE_URL??qE),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 WE(o);throw new Error(u)}let i=await o.json(),s=VE(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:Xn(a),runtimeModel:Bt(a),updatedAt:c().toISOString()}}function GE(t){return t.replace(/\/+$/,"")}async function WE(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 VE(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 Fm=["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 Um(t,e){F(t,1,1,Fm);let n=t.positional[0],r=t.flags["runtime-url"],o=typeof r=="string"&&r.trim()!==""?Bm(r.trim(),"openclaw"):void 0,i=zE(),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 jm({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,...Dm(t.flags,"runtime-token","runtimeLocalToken"),...Dm(t.flags,"runtime-model","runtimeModel")},u=Bm(o??c.runtimeLocalUrl,c.runtimeType),l={...c,runtimeLocalUrl:u};return gn(l),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Ft(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 zE(){try{return U()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}function Dm(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function Bm(t,e){try{return Yr(t,e)}catch(n){throw n instanceof ze?new T(n.message,Fm):n}}var Sc=20,mi=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${Sc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${re.join(", ")}`].join(`
205
+ `);async function Gm(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new T(`unexpected extra positional arguments: ${i}`,mi)}let n=KE(),r=JE(t.positional,n),o=await De({baseUrl:n.baseUrl,currentVersion:ae,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 Yc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof he?new B(YE(i),QE(i),{hint:await XE(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 ${ZE(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 KE(){try{return U()}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 JE(t,e){if(t.length===0)return{game:qm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Hm(n);if(i!==null)return{game:qm(e.autoGames),count:i};if(Fe(n))return{game:n,count:1};throw new T(`unsupported game or count '${n}'`,mi)}let r=t[1];if(!Fe(n))throw new T(`unsupported game '${n}'`,mi);let o=Hm(r);if(o===null)throw new T(`N must be an integer between 1 and ${Sc}`,mi);return{game:n,count:o}}function Hm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>Sc?null:e}function qm(t){let e=(t??re).filter(Fe),n=e.length>0?e:re;return n[Math.floor(Math.random()*n.length)]}function YE(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 QE(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 XE(t){try{let e=await kt(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 Z))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function ZE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Ht from"node:path";import oe from"node:fs";import ek 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 Vm(){return Ht.join(Q(),"token")}function zm(){return Ht.join(Q(),"port")}function Ec(){return Ht.join(Q(),"pid")}function tk(){return Ht.join(Q(),"lock")}var Wm=0,nk=/^[0-9a-f]{64}$/;function kc(t,e,n){let r=Ht.dirname(t),o=Ht.basename(t);Wm+=1;let i=Ht.join(r,`${o}.${process.pid}.${Wm}.tmp`),s;try{if(s=oe.openSync(i,"w",n),oe.writeSync(s,e),oe.closeSync(s),s=void 0,process.platform!=="win32")try{oe.chmodSync(i,n)}catch{}oe.renameSync(i,t)}catch(a){if(s!==void 0)try{oe.closeSync(s)}catch{}try{oe.unlinkSync(i)}catch{}throw new _e("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Km(){return ek.randomBytes(32).toString("hex")}function Jm(t){let e=Vm();if(!nk.test(t))throw new _e("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);kc(e,t,384)}function Ym(t){let e=zm();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}`);kc(e,String(t),420)}function Qm(t){let e=Ec();if(!Number.isInteger(t)||t<1)throw new _e("write_failed",e,`pid must be a positive integer but received ${t}`);kc(e,String(t),420)}function $c(t){for(let e of[Vm(),zm(),Ec()])try{oe.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Xm(){let t=Q(),e;try{e=oe.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{oe.unlinkSync(Ht.join(t,n))}catch{}}var vc=new Set;function rk(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function ok(t){let e;try{e=oe.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 Zm(t){let e=tk(),n=Ec(),r=t?.processIsAlive??rk;if(vc.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=oe.openSync(e,oe.constants.O_WRONLY|oe.constants.O_CREAT|oe.constants.O_EXCL,384);if(oe.closeSync(i),process.platform!=="win32")try{oe.chmodSync(e,384)}catch{}return vc.add(e),ik(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=ok(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{oe.unlinkSync(e)}catch{}try{oe.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 ik(t){let e=!1;return{release(){if(!e){e=!0,vc.delete(t);try{oe.unlinkSync(t)}catch{}}}}}import*as ip from"node:http";import{Buffer as Tc}from"node:buffer";import*as sp from"node:crypto";var bn=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var ap="0.1.0-alpha.8",ep=`aifight-runtime/${ap}`,sk="127.0.0.1",ak=0,ck=1048576,lk=5e3,q=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 cp(t){return t.split("/").filter(e=>e.length>0)}function xe(t){let e=cp(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function uk(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 tp(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new q(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 q(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(u)}let a=Tc.concat(o).toString("utf8");if(a.length===0)throw new q(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new q(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function np(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new q(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 q(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function Rc(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function rp(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 q(400,"bad_request",n,{validation:e}):e==="invalid_state"?new q(503,"service_unavailable","scheduler stopped"):null}function op(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 dk(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 lp(t){let e=t.host??sk,n=t.port??ak,r=t.bodyLimitBytes??ck,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:xe("/v1/health"),handler:h},{method:"GET",pattern:xe("/v1/agents"),handler:y},{method:"GET",pattern:xe("/v1/agents/:name/status"),handler:b},{method:"POST",pattern:xe("/v1/agents/:name/join"),handler:v},{method:"POST",pattern:xe("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:xe("/v1/agents/:name/schedule"),handler:$},{method:"POST",pattern:xe("/v1/agents/:name/schedule"),handler:J},{method:"POST",pattern:xe("/v1/agents/:name/schedule/pause"),handler:ee},{method:"POST",pattern:xe("/v1/agents/:name/schedule/resume"),handler:ce},{method:"POST",pattern:xe("/v1/shutdown"),handler:ut},{method:"POST",pattern:xe("/v1/agents"),handler:p("M1-18")},{method:"DELETE",pattern:xe("/v1/agents/:name"),handler:p("M1-18")},{method:"POST",pattern:xe("/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=Tc.from(C,"utf8"),te=Tc.from(k,"utf8");return j.length!==te.length?{ok:!1,reason:"token_mismatch"}:sp.timingSafeEqual(j,te)?{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",ep),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:ap,uptimeMs:o.now()-i})}function p(w){return E=>{let C=E.url.pathname;throw new q(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 q(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",ep),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(op);l(w.res,200,{agents:E})}function b(w){let E=w.params.name,C;try{C=t.router.getAgent({name:E})}catch(j){throw Rc(j)?new q(404,"not_found",`agent '${E}' not found`):j}let k=C.snapshot();l(w.res,200,{agent:op(k)})}async function v(w){let E=w.params.name,C=await tp(w.req,r);np(C,["game"],"/v1/agents/:name/join");let k=C;if(typeof k.game!="string"||k.game.length===0)throw new q(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 q(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 q(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 q(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 q(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let te=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...te!==void 0?{oneShot:te}:{},...typeof j=="number"?{count:j}:{}})}catch(Y){throw Rc(Y)?new q(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 Rc(C)?new q(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=dk(C.snapshot());l(w.res,200,{schedule:k,snapshot:j})}async function J(w){let E=w.params.name,C=f(E),k=await tp(w.req,r),j;if(k===null)j=null;else{np(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let te=k;if(typeof te.enabled!="boolean")throw new q(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof te.timezone!="string")throw new q(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof te.days!="object"||te.days===null||Array.isArray(te.days))throw new q(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{C.setSchedule(j)}catch(te){let Y=rp(te);throw Y||te}a.set(E,j),g(w.res)}function ee(w){Qe(w,!1)}function ce(w){Qe(w,!0)}function Qe(w,E){let C=w.params.name,k=f(C),j=m(C);if(j===null){let Y=E?"resume":"pause";throw new q(400,"bad_request",`no schedule to ${Y}; POST /schedule first or configure initial schedule`)}let te={...j,enabled:E};try{k.setSchedule(te)}catch(Y){let so=rp(Y);throw so||Y}a.set(C,te),g(w.res)}function ut(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: ${Ac(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function cr(w,E){let C=o.now(),k=w.method??"GET",j=w.url??"/",te=`http://${w.headers.host??"localhost"}`,Y;try{Y=new URL(j,te)}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 so=cp(Y.pathname),lr=0;try{let ke=u(w);if(!ke.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${Y.pathname}: auth failed (${ke.reason})`,method:k,path:Y.pathname,reason:ke.reason}),new q(401,"unauthorized",`authentication required: ${ke.reason}`);let ki=s.map($t=>({route:$t,params:uk($t.pattern,so)})).filter($t=>$t.params!==null);if(ki.length===0)throw new q(404,"not_found","path not found");let $i=ki.find($t=>$t.route.method===k);if(!$i){let $t=ki.map(Ri=>Ri.route.method).filter((Ri,Zp,eh)=>eh.indexOf(Ri)===Zp).join(", ");throw E.headersSent||E.setHeader("Allow",$t),new q(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${Y.pathname}`,method:k,path:Y.pathname}),await $i.route.handler({req:w,res:E,url:Y,params:$i.params}),lr=E.statusCode}catch(ke){ke instanceof q?(d(E,ke.status,ke.code,ke.message,ke.details),lr=ke.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${k} ${Y.pathname}: ${Ac(ke)}`,method:k,path:Y.pathname,cause:ke}),d(E,500,"internal_error","internal server error"),lr=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${k} ${Y.pathname} -> ${lr} (${o.now()-C}ms)`,method:k,path:Y.pathname,status:lr,durationMs:o.now()-C})}}let Xe=ip.createServer((w,E)=>{cr(w,E).catch(C=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${Ac(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{}}})}),ie="pre-listen",qt=null,vn=null,io=null;function Yp(){return ie==="listening"?Promise.reject(new bn("invalid_state","server already listening")):ie==="closing"||ie==="closed"||ie==="bind-failed"?Promise.reject(new bn("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let C=k=>{ie="bind-failed",E(new bn("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Xe.once("error",C),Xe.listen({host:e,port:n},()=>{Xe.off("error",C);let k=Xe.address();if(typeof k=="string"||k===null){ie="bind-failed",E(new bn("bind_failed","unexpected listen address shape from server.address()"));return}qt=k.address,vn=k.port,ie="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${qt}:${vn}`,host:qt,port:vn}),w(vn)})})}function Qp(){return ie!=="listening"||qt===null||vn===null?null:{host:qt,port:vn}}function Xp(){return ie==="pre-listen"||ie==="bind-failed"?(ie="closed",Promise.resolve()):ie==="closed"?Promise.resolve():(ie==="closing"&&io||(ie="closing",io=new Promise(w=>{let E=!1,C=()=>{E||(E=!0,clearTimeout(j),ie="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Xe.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Xe)}catch{}C()},lk);j.unref(),Xe.close(()=>C())})),io)}return{listen:Yp,address:Qp,close:Xp}}function Ac(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 Pc(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 up(t,e){if(e.type==="start")return W(Pc(e));if(t.phase==="closed")return e.type==="stop"?W(t):Ye(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return fk(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return mk(t);case"command.confirm_match":return pk(t,e.confirmId);case"ws.message":return hk(t,e.message,e.now);case"decision.ready":return vk(t,e.action);case"decision.failed":return Ek(t,e.reason);case"reconnect.event":return Ak(t,e.event);case"reconnect.close":return Tk(t,e.info);case"stop":return W({...t,phase:"closed",transport:"closed"})}}function fk(t,e,n,r){if(!t.availableGames.includes(e))return Ye(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:no(n),...r===!0?{one_shot:!0}:{}};return W({...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 mk(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?Ye(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):W({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function pk(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?Ye(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):W({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function hk(t,e,n){switch(e.type){case"queue_joined":return gk(t,e);case"queue_left":return W({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return yk(t,e);case"match_cancelled":return _k(t,e);case"game_start":return wk(t,e,n);case"game_state":return bk(t,e);case"action_request":return Sk(t,e);case"game_over":return kk(t,e);case"error":return $k(t,e);case"event":return Rk(t,e);default:return Ye(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function gk(t,e){return W({...t,phase:"queuing",queue:{game:e.data.game,mode:no(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function yk(t,e){let n={game:e.data.game,mode:no(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?W({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):W({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[Je("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function _k(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:no(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:no(e.data.mode)}:n;return W({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[Je("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return W({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[Je("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function wk(t,e,n){return W({...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 bk(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ye(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):W({...t,phase:t.activeMatch?"in_match":t.phase},[Je("info","fsm.game_state","Received game state update")])}function Sk(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?Ye(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ye(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):W({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function vk(t,e){return t.phase!=="deciding"||!t.pendingAction?Ye(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):W({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function Ek(t,e){return t.phase!=="deciding"||!t.pendingAction?Ye(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):W(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function kk(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?Ye(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):W({...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 $k(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return W({...t,lastError:n},[Je("error","server.error",n)])}function Rk(t,e){return W(t,[Je("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function Ak(t,e){return e.type==="attempt-success"?W({...t,transport:"connected"}):e.type==="attempt-start"?W({...t,transport:"backoff"},[Je("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?W({...t,transport:"backoff"},[Je(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):W({...t,phase:"closed",transport:"closed"},[Je(e.severity,"reconnect.give_up","Reconnect gave up")])}function Tk(t,e){return W({...t,phase:"closed",transport:"closed"},[Je("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function W(t,e=[]){return{state:t,effects:e}}function Ye(t,e,n){return W(t,[Je("warning",e,n)])}function Je(t,e,n){return{type:"notify",level:t,code:e,message:n}}function no(t){return t&&t.length>0?t:"ranked"}var ir=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},ro=class extends ir{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},oo=class extends ir{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},hi=class extends ir{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},xc=class extends ir{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},gi=class{#e;#t=null;#n=null;#r=!1;#i=!1;#a=[];#o=new Set;#s=Promise.resolve();#u=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#i)throw new hi(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new ro(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??Qa,n;try{n=await e(this.#e.ws)}catch(r){throw new ro(`failed to start agent '${this.#e.name}': ${pi(r)}`,r)}if(n.welcome===null)throw new ro(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=Pc({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#k()}),this.#r=!0,this.#f(n),this.#m(),this.snapshot()}async stop(e="agent stop"){if(this.#i)return;this.#i=!0,this.#$();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#l({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#l({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#l({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#l({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.#i}}onState(e){return this.#o.add(e),()=>{this.#o.delete(e)}}#f(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#c(n.data);return}this.#e.onServerMessage?.(n),this.#l({type:"ws.message",message:n,now:this.#k()})}),e.onReconnect(n=>{this.#l({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#l({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#c(e){let n=Pk(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.#h({type:"runtime_status",data:xk(r,n)})}catch(r){this.#h({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:dp(`readiness check failed: ${pi(r)}`)}})}}#l(e){let n=this.#v(),r=up(n,e);this.#n=r.state,this.#m(),this.#g(r.effects)}#g(e){e.length!==0&&(this.#s=this.#s.then(()=>this.#p(e)).catch(n=>{this.#b({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${pi(n)}`,cause:n})}))}async#p(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#h(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#b({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.#b(e);return}}#h(e){let n=this.#S();try{n.send(e),this.#e.onClientMessage?.(e)}catch(r){this.#b({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${pi(r)}`,cause:new xc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#u;this.#d={token:n,matchId:e.matchId};let r=this.#v();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.#b({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#l({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#b({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#l({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 oo(`agent '${this.#e.name}' is not started`);if(this.#i||this.#n.phase==="closed")throw new hi(`agent '${this.#e.name}' is stopped`)}#S(){if(this.#t===null)throw new oo(`agent '${this.#e.name}' is not started`);return this.#t}#v(){if(this.#n===null)throw new oo(`agent '${this.#e.name}' is not started`);return this.#n}#m(){let e=this.snapshot();for(let n of[...this.#o])n(e)}#$(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#b({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#b(e){this.#e.onNotify?.(e)}#k(){return this.#e.now?.()??Date.now()}};function pi(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function Pk(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function xk(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=dp(n.detail)),n}function dp(t){return t.length>240?t.slice(0,240):t}import Ck from"node:crypto";import fp from"node:fs";import yi from"node:path";var mp=64*1024;function Sn(t,e,n={}){let r=yi.join(n.runtimeHome??Q(),"agents",Ik(t),"strategy"),o=yi.join(r,"games");return{root:r,global:yi.join(r,"global.md"),gamesDir:o,...e!==void 0?{game:yi.join(o,`${e}.md`)}:{}}}function hp(t,e,n={}){let r=Sn(t,e,n);return{sections:[pp("global",r.global),r.game!==void 0?pp("game",r.game,e):null].filter(i=>i!==null),paths:r}}function pp(t,e,n){let r;try{r=fp.statSync(e)}catch{return null}if(!r.isFile()||r.size<=0)return null;let o=fp.readFileSync(e),i=o.length>mp,a=(i?o.subarray(0,mp):o).toString("utf8").trim();return a===""?null:{scope:t,...n!==void 0?{game:n}:{},path:e,content:a,sha256:Ck.createHash("sha256").update(a).digest("hex"),bytes:Buffer.byteLength(a,"utf8"),mtimeMs:Math.trunc(r.mtimeMs),truncated:i}}function Ik(t){let e=t.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,128);return e.length>0?e:"unknown"}import Ok from"node:crypto";import lt from"node:fs";import Ee from"node:path";var Ic=class{#e;#t;constructor(e={}){this.#e=e.runtimeHome??Q(),this.#t=e.now??(()=>new Date)}recordServerMessage(e,n){let r=this.#t().toISOString(),o=Mk(n);if(n.type==="game_start"){let a=n;this.#n(e,a.data.match_id,{now:r,game:a.data.game,mode:Dk(a.data),playerId:a.data.your_player_id})}if(!o)return;let i=this.#n(e,o,{now:r});this.#a(i,"inbound.jsonl",{at:r,direction:"inbound",type:n.type,message:n});let s={...i,inbound_count:i.inbound_count+1,updated_at:r};if(n.type==="game_state"){let a=n;s={...s,player_id:s.player_id??_i(a.data.state)}}n.type==="game_over"&&(s=this.#r(e,s,n,r)),this.#o(s)}recordClientMessage(e,n){if(n.type!=="action"||!n.match_id)return;let r=this.#t().toISOString(),o=this.#n(e,n.match_id,{now:r});this.#a(o,"outbound.jsonl",{at:r,direction:"outbound",type:n.type,message:n}),this.#o({...o,outbound_count:o.outbound_count+1,final_action_count:o.final_action_count+1,updated_at:r})}recordDecision(e){let n=e.context.matchId,r=e.startedAt.toISOString(),o=e.completedAt.toISOString(),i=this.#n(e.config,n,{now:r,game:e.context.game,playerId:_i(e.context.actionRequest.data.state)}),s=Lk(e.traces);this.#i(i,s,o),this.#a(i,"decisions.jsonl",{at:o,kind:"decision",session_id:n,game:e.context.game??i.game??null,player_id:_i(e.context.actionRequest.data.state)??i.player_id??null,duration_ms:Math.max(0,e.completedAt.getTime()-e.startedAt.getTime()),action_request:Nk(e.context.actionRequest),traces:jk(e.traces),status:e.error===void 0?"ok":"error",...e.action!==void 0?{final_action:e.action}:{},...e.error!==void 0?{error:Vk(e.error)}:{}}),this.#o({...i,game:e.context.game??i.game,player_id:_i(e.context.actionRequest.data.state)??i.player_id,updated_at:o,decision_count:i.decision_count+1,strategy_hashes:Gk(i.strategy_hashes,s.map(a=>a.sha256))})}listSessions(){return this.#s().sort((e,n)=>n.updated_at.localeCompare(e.updated_at))}getSession(e){let n=this.#s(),r=n.find(o=>o.session_id===e||o.real_match_id===e);if(r)return r;if(e.length>=8){let o=n.filter(i=>i.session_id.startsWith(e)||i.real_match_id?.startsWith(e));if(o.length===1)return o[0]}return null}exportSession(e){let n=this.getSession(e);return n?{summary:Hk(n),path:n.path,inbound:Cc(Ee.join(n.path,"inbound.jsonl")),outbound:Cc(Ee.join(n.path,"outbound.jsonl")),decisions:Cc(Ee.join(n.path,"decisions.jsonl")),strategySnapshot:Mc(Ee.join(n.path,"strategy-snapshot.json"))??null}:null}#n(e,n,r){let o=this.#u(e.agentId,n);wp(o);let i=gp(Ee.join(o,"session.json"));if(i){let a={...i,agent_name:e.agentName,game:r.game??i.game,mode:r.mode??i.mode,player_id:r.playerId??i.player_id,updated_at:r.now};return this.#o(a),a}let s={version:1,agent_id:e.agentId,agent_name:e.agentName,session_id:n,status:"active",...r.game!==void 0?{game:r.game}:{},...r.mode!==void 0?{mode:r.mode}:{},...r.playerId!==void 0?{player_id:r.playerId}:{},started_at:r.now,updated_at:r.now,inbound_count:0,outbound_count:0,decision_count:0,final_action_count:0,strategy_hashes:[]};return this.#o(s),s}#r(e,n,r,o){return{...n,status:"completed",updated_at:o,ended_at:o,real_match_id:r.data.match_id,...r.data.replay_url!==void 0?{replay_url:Uk(e.baseUrl,r.data.replay_url)}:{},result_label:Bk(e.agentId,r)}}#i(e,n,r){if(n.length===0)return;let o=Ee.join(this.#u(e.agent_id,e.session_id),"strategy-snapshot.json"),s={...qk(o).sections};for(let a of n)s[a.sha256]={scope:a.scope,...a.game!==void 0?{game:a.game}:{},path:a.path,sha256:a.sha256,bytes:a.bytes,mtimeMs:a.mtimeMs,truncated:a.truncated===!0,content:a.content};yp(o,{version:1,updated_at:r,sections:s})}#a(e,n,r){let o=Ee.join(this.#u(e.agent_id,e.session_id),n);lt.appendFileSync(o,`${JSON.stringify(r)}
214
+ `,{mode:384}),Oc(o)}#o(e){yp(Ee.join(this.#u(e.agent_id,e.session_id),"session.json"),e)}#s(){let e=Ee.join(this.#e,"agents"),n;try{n=lt.readdirSync(e)}catch{return[]}let r=[];for(let o of n){let i=Ee.join(e,o,"sessions"),s;try{s=lt.readdirSync(i)}catch{continue}for(let a of s){let c=Ee.join(i,a),u=gp(Ee.join(c,"session.json"));u&&r.push({...u,path:c})}}return r}#u(e,n){return Ee.join(this.#e,"agents",_p(e),"sessions",_p(n))}};function wi(t={}){return t.runtimeHome===void 0&&Be(),new Ic(t)}function Mk(t){return t.type==="game_start"||t.type==="game_state"||t.type==="action_request"?t.data.match_id:t.type==="game_over"?t.data.session_id:null}function Nk(t){let e=t.data;return{match_id:e.match_id,timeout_ms:e.timeout_ms,legal_action_count:(e.legal_actions??[]).length,legal_actions:e.legal_actions??[],state_sha256:Wk(e.state),state:e.state,new_events_count:Array.isArray(e.new_events)?e.new_events.length:0,new_events:e.new_events}}function Lk(t){let e=[];for(let n of t)if(n.type==="decision_request")for(let r of n.strategy)e.push({scope:r.scope,...r.game!==void 0?{game:r.game}:{},path:r.path,content:r.content,sha256:r.sha256,bytes:r.bytes,mtimeMs:r.mtimeMs,...r.truncated===!0?{truncated:!0}:{}});return e}function jk(t){return t.map(e=>e.type!=="decision_request"?e:{...e,strategy:e.strategy.map(n=>({scope:n.scope,...n.game!==void 0?{game:n.game}:{},path:n.path,sha256:n.sha256,bytes:n.bytes,mtimeMs:n.mtimeMs,...n.truncated===!0?{truncated:!0}:{}}))})}function _i(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function Dk(t){if(!t||typeof t!="object")return;let e=t.mode;return typeof e=="string"?e:void 0}function Bk(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`${Fk(o+1)} place`}function Fk(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 Uk(t,e){try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function gp(t){let e=Mc(t);if(!e||typeof e!="object")return null;let n=e;return n.version!==1||typeof n.agent_id!="string"||typeof n.agent_name!="string"||typeof n.session_id!="string"||n.status!=="active"&&n.status!=="completed"?null:{version:1,agent_id:n.agent_id,agent_name:n.agent_name,session_id:n.session_id,status:n.status,...typeof n.game=="string"?{game:n.game}:{},...typeof n.mode=="string"?{mode:n.mode}:{},...typeof n.player_id=="string"?{player_id:n.player_id}:{},started_at:typeof n.started_at=="string"?n.started_at:"",updated_at:typeof n.updated_at=="string"?n.updated_at:"",...typeof n.ended_at=="string"?{ended_at:n.ended_at}:{},...typeof n.real_match_id=="string"?{real_match_id:n.real_match_id}:{},...typeof n.replay_url=="string"?{replay_url:n.replay_url}:{},...typeof n.result_label=="string"?{result_label:n.result_label}:{},inbound_count:typeof n.inbound_count=="number"?n.inbound_count:0,outbound_count:typeof n.outbound_count=="number"?n.outbound_count:0,decision_count:typeof n.decision_count=="number"?n.decision_count:0,final_action_count:typeof n.final_action_count=="number"?n.final_action_count:0,strategy_hashes:Array.isArray(n.strategy_hashes)?n.strategy_hashes.filter(r=>typeof r=="string"):[]}}function Hk(t){let{path:e,...n}=t;return n}function qk(t){let e=Mc(t);if(!e||typeof e!="object")return{sections:{}};let n=e.sections;return n&&typeof n=="object"&&!Array.isArray(n)?{sections:n}:{sections:{}}}function Mc(t){try{return JSON.parse(lt.readFileSync(t,"utf8"))}catch{return null}}function Cc(t){let e;try{e=lt.readFileSync(t,"utf8")}catch{return[]}let n=[];for(let r of e.split(`
215
+ `))if(r.trim()!=="")try{n.push(JSON.parse(r))}catch{n.push({parse_error:!0,raw:r})}return n}function yp(t,e){wp(Ee.dirname(t));let n=`${t}.${process.pid}.${Date.now()}.tmp`;lt.writeFileSync(n,`${JSON.stringify(e,null,2)}
216
+ `,{mode:384}),Oc(n),lt.renameSync(n,t),Oc(t)}function wp(t){if(lt.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{lt.chmodSync(t,448)}catch{}}function Oc(t){if(process.platform!=="win32")try{lt.chmodSync(t,384)}catch{}}function _p(t){let e=t.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,128);return e.length>0?e:"unknown"}function Gk(t,e){return[...new Set([...t,...e])].sort()}function Wk(t){return Ok.createHash("sha256").update(JSON.stringify(t)).digest("hex")}function Vk(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}import zk from"node:crypto";function bp(t,e={}){return{async decide(n){let r=Xk(n.game),o=n.actionRequest.data,i=o.legal_actions??[];if(i.length===0)throw new Error("action_request had no legal actions");let s={game:r,matchId:n.matchId,playerId:Zk(o.state),legalActions:i,publicState:o.state,timeoutMs:typeof o.timeout_ms=="number"?o.timeout_ms:0},a=t$(e,{game:r,matchId:n.matchId,playerId:s.playerId}),c={...s,...a!==void 0&&a.sections.length>0?{strategy:a}:{}};e.onTrace?.({type:"decision_request",matchId:n.matchId,game:r,...s.playerId!==void 0?{playerId:s.playerId}:{},legalActionCount:i.length,timeoutMs:s.timeoutMs,strategy:a?.sections.map(n$)??[]});let u;for(let d of[1,2])try{u=await t.decide(c),e.onTrace?.({type:"runtime_success",matchId:n.matchId,attempt:d,raw:r$(u)});break}catch(h){e.onTrace?.({type:"runtime_failure",matchId:n.matchId,attempt:d,error:vp(h)})}if(u===void 0){let d=bi(r,i,o.state);return e.onTrace?.({type:"final_action",matchId:n.matchId,source:"fallback",reason:"runtime_failure",action:d}),d}let l=Kk({game:r,raw:u,legalActions:i,publicState:o.state});return e.onTrace?.({type:"final_action",matchId:n.matchId,source:l.source,...l.reason!==void 0?{reason:l.reason}:{},action:l.action}),l.action}}}function Sp(){return{name:"mock",async decide(t){return bi(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function Kk(t){if(typeof t.raw!="string"){let n=Qk(t.raw,t.legalActions);return n?{action:n,source:"runtime"}:{action:bi(t.game,t.legalActions,t.publicState),source:"fallback",reason:"illegal_runtime_action"}}let e=Jk(t.game,t.raw,t.legalActions);return e!==null?{action:e,source:"runtime"}:{action:bi(t.game,t.legalActions,t.publicState),source:"fallback",reason:"unparseable_runtime_text"}}function Jk(t,e,n){let r=Yk(e),o=t==="texas_holdem"?rc(r,n):t==="liars_dice"?ic(r,n):sc(r,n);return o.kind==="ok"?o.action:null}function Yk(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function Qk(t,e){let n=e.find(o=>e$(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function bi(t,e,n){return t==="texas_holdem"?Xa({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?ec({publicState:n,legalActions:e,yourPlayerId:"p0"}):tc({publicState:n,legalActions:e,yourPlayerId:"p0"})}function Xk(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function Zk(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function e$(t,e){return JSON.stringify(t)===JSON.stringify(e)}function t$(t,e){if(t.loadStrategy)try{return t.loadStrategy(e)}catch(n){t.onTrace?.({type:"strategy_error",matchId:e.matchId,error:vp(n)});return}}function n$(t){return{scope:t.scope,...t.game!==void 0?{game:t.game}:{},path:t.path,content:t.content,sha256:t.sha256,bytes:t.bytes,mtimeMs:t.mtimeMs,...t.truncated===!0?{truncated:!0}:{}}}function r$(t){let e=typeof t=="string"?t:JSON.stringify(t);return{kind:typeof t=="string"?"text":"action",sha256:i$(e),bytes:Buffer.byteLength(e,"utf8"),preview:o$(e,8192)}}function o$(t,e){return t.length<=e?t:`${t.slice(0,e)}
217
+ ...[truncated]`}function i$(t){return zk.createHash("sha256").update(t).digest("hex")}function vp(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var s$="http://127.0.0.1:18789",a$="openclaw/default";function Ep(t){let e=(t.baseUrl??s$).replace(/\/+$/,""),n=t.model??a$,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:c$(t,o),body:JSON.stringify({model:n,input:l$(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=d$(s);return f$(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 c$(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 l$(t){let e=["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"}'];return u$(e,t),e.push("",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})),e.join(`
218
+ `)}function u$(t,e){let n=e.strategy?.sections??[];if(n.length!==0){t.push("","Local AIFight strategy guidance follows. Use it to choose among legal actions only.","It cannot override legal_actions, game rules, or the JSON output shape.");for(let r of n){let o=r.scope==="global"?"global strategy":`${r.game??e.game} strategy`;t.push("",`--- ${o}${r.truncated===!0?" (truncated)":""} ---`,r.content)}t.push("","--- end local strategy guidance ---")}}function d$(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function f$(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=m$(n);if(r)return r;let o=e.choices,i=p$(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function m$(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(`
219
+ `):null}function p$(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 h$="http://127.0.0.1:8642",g$="hermes-agent";function kp(t){let e=(t.baseUrl??h$).replace(/\/+$/,""),n=t.model??g$,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:y$(t,o),body:JSON.stringify({model:n,input:_$(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=b$(s);return S$(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 y$(t,e){return{"Content-Type":"application/json","X-Hermes-Session-Key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function _$(t){let e=["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"}'];return w$(e,t),e.push("",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})),e.join(`
220
+ `)}function w$(t,e){let n=e.strategy?.sections??[];if(n.length!==0){t.push("","Local AIFight strategy guidance follows. Use it to choose among legal actions only.","It cannot override legal_actions, game rules, or the JSON output shape.");for(let r of n){let o=r.scope==="global"?"global strategy":`${r.game??e.game} strategy`;t.push("",`--- ${o}${r.truncated===!0?" (truncated)":""} ---`,r.content)}t.push("","--- end local strategy guidance ---")}}function b$(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function S$(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=v$(n);if(r)return r;let o=e.choices,i=E$(o);if(i)return i;throw new Error("Hermes response did not contain text")}function v$(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(`
221
+ `):null}function E$(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 Si=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??x$(this.#e.config),n=this.#i(),r={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:um},o=new gi({name:this.#e.config.agentName,ws:r,autoConfirmMatches:!0,decisionProvider:this.#a(e,n),...this.#e.connect!==void 0?{connect:this.#e.connect}:{},onServerMessage:s=>{n!==null&&this.#o(()=>n.recordServerMessage(this.#e.config,s))},onClientMessage:s=>{n!==null&&this.#o(()=>n.recordClientMessage(this.#e.config,s))},onReadinessCheck:async s=>this.#d(e,s),onNotify:s=>{this.#r(s.level,s.code,s.message)},onResult:(s,a)=>{this.#r("info","bridge.match_complete",$$(this.#e.config,s,a.game)),this.#u()},onFallbackRequired:s=>{this.#r("warning","bridge.fallback_required",`No action sent for match ${s.actionRequest.data.match_id}; runtime decision failed`)}});this.#t=o;let i=await o.start();if(this.#r("info","bridge.connected",`Connected ${this.#e.config.agentName}`),this.#e.autoJoinGame){let s=this.#e.autoJoinOneShot===!0;o.joinQueue(this.#e.autoJoinGame,this.#e.autoJoinMode,{oneShot:s}),this.#r("info","bridge.queue_joined",s?`Joined ${this.#e.autoJoinGame} for one manual match`:`Joined ${this.#e.autoJoinGame} for daily automatic matching`)}return i}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.#s().joinQueue(e,n),this.#r("info","bridge.queue_joined",`Joined ${e} for ${n??"default"} matching`)}leaveQueue(){let e=this.#s();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.#s(),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})}#i(){if(this.#e.sessionStore===!1)return null;if(this.#e.sessionStore!==void 0)return this.#e.sessionStore;try{return wi()}catch(e){return this.#r("warning","bridge.session_store_unavailable",`Local match session ledger is unavailable: ${e instanceof Error?e.message:String(e)}`),null}}#a(e,n){return{decide:async r=>{let o=[],i=new Date,s=bp(e,{loadStrategy:({game:a})=>hp(this.#e.config.agentId,a),onTrace:a=>{o.push(a)}});try{let a=await s.decide(r);if(n!==null){let c=new Date;this.#o(()=>n.recordDecision({config:this.#e.config,context:r,startedAt:i,completedAt:c,traces:o,action:a}))}return a}catch(a){if(n!==null){let c=new Date;this.#o(()=>n.recordDecision({config:this.#e.config,context:r,startedAt:i,completedAt:c,traces:o,error:a}))}throw a}}}}#o(e){try{e()}catch(n){this.#r("warning","bridge.session_record_failed",`Could not update local match session ledger: ${n instanceof Error?n.message:String(n)}`)}}#s(){if(this.#t===null)throw new Error("bridge runner is not started");return this.#t}#u(){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#d(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 $$(t,e,n){let r=[`Match complete: ${P$(n)}`,`Result: ${R$(t.agentId,e)}`],o=T$(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(`
222
+ `)}function R$(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`${A$(o+1)} place`}function A$(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 T$(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function P$(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 x$(t){return t.runtimeType==="mock"?Sp():t.runtimeType==="openclaw"?Ep({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):kp({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}import{execFile as C$}from"node:child_process";import{promisify as I$}from"node:util";var O$="@aifight/aifight@alpha",M$=10*60*1e3,N$=6*60*60*1e3,L$=I$(C$),j$=async(t,e)=>{let{stdout:n,stderr:r}=await L$(t,[...e],{timeout:12e4,maxBuffer:524288});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}};function Rp(t){let e=!1,n=!1,r=null,o=t.intervalMs??N$,i=t.initialDelayMs??M$,s=c=>{e||(r=setTimeout(()=>{a()},c))},a=async()=>{if(e||n)return null;n=!0;try{return await D$(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 D$(t){let e=await De({baseUrl:t.baseUrl,currentVersion:ae,fetchImpl:t.fetchImpl});if(e.status==="current"||e.status==="unknown")return{status:e.status,update:e};let r=t.snapshot()?.state?.phase??null;if(!B$(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 Nc({execFile:t.execFile})}catch(o){let i=$p(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: ${$p(o)}`})}return{status:"updated",update:e}}async function Nc(t={}){await(t.execFile??j$)("npm",["install","-g",O$])}function B$(t){return t==="connected"||t==="queuing"}function $p(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
223
+ `)[0]:t instanceof Error?t.message:String(t)}var F$=["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(`
224
+ `);async function Tp(t,e){F(t,0,0,F$);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await z$(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(`
225
+ `)),!await J$(e,"Continue anyway? [y/N] ")))return 0;let r=U();return U$({config:r,env:e})}async function U$(t){let{config:e,env:n}=t,r=await De({baseUrl:e.baseUrl,currentVersion:ae,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
219
226
  `),n.stderr(`Run: aifight update --yes
220
227
  `),n.stderr(`Manual npm command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
221
228
  `),1;r.status==="update_recommended"&&(n.stdout(`[warn] bridge.update: ${r.message}
222
229
  `),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.
230
+ `)),Be(),Xm();let o=null,i=null,s=null,a=new Si({config:e,...H$(e),onLog:c=>{Ap(c,n)}});try{o=Zm(),Qm(process.pid);let c=Km();n.stdout(G$(e)),await a.start(),i=lp({tokenSource:()=>c,router:q$(e,a),onLog:l=>{n.onLog?.({code:`control.${l.code}`,message:l.message})}});let u=await i.listen();return Jm(c),Ym(u),process.env.AIFIGHT_SERVICE_RUN==="1"&&(s=Rp({baseUrl:e.baseUrl,fetchImpl:n.fetchImpl,snapshot:()=>a.snapshot(),execFile:n.bridgeService?.execFile,onLog:l=>Ap(l,n),onRestartRequired:()=>{n.stdout(`AIFight Bridge updated; stopping so aifight.service can restart with the new package.
224
231
  `),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(`
232
+ `),await K$(async()=>{s?.stop(),s=null,await i?.close(),i=null,await a.stop(),$c({onLog:l=>n.stderr(`warning: ${l}
233
+ `)}),o?.release(),o=null}),0}catch(c){throw s?.stop(),await i?.close().catch(()=>{}),await a.stop().catch(()=>{}),$c({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 H$(t){let e=(t.autoDailyLimit??0)>0?V$(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function q$(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(!Fe(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 G$(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: ${W$(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
234
  `)}
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}
235
+ `}function Ap(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
236
  `);return}if(t.code==="bridge.match_complete"){e.stdout(`
230
237
  ${t.message}
231
238
  `);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})+`
239
+ `;t.level==="error"?e.stderr(r):e.stdout(r)}function W$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function V$(t){let e=(t??re).filter(Fe),n=e.length>0?e:re;return n[Math.floor(Math.random()*n.length)]}async function z$(t){try{let e=await kt(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof Z,!1}}async function K$(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 J$(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 Y$="usage: aifight status",Q$=1500;async function Pp(t,e){F(t,0,0,Y$);let n=rR();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:ae})+`
233
240
  `):(e.stdout(`AIFight status
234
241
 
235
242
  `),e.stdout(`Bridge: not configured
236
- `),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})+`
243
+ `),e.stdout(`CLI version: ${ae}
244
+ `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Ft(n),o=await De({baseUrl:n.baseUrl,currentVersion:ae,fetchImpl:e.fetchImpl}),i=await X$(n,e.fetchImpl);return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:ae,update:o,platformAgentStatus:i,config:r})+`
238
245
  `),0):(e.stdout(`AIFight status
239
246
 
240
247
  `),e.stdout(`Agent: ${r.agentName}
241
- `),e.stdout(`Profile: ${Zk(i,n)}
248
+ `),e.stdout(`Profile: ${eR(i,n)}
242
249
  `),i.kind==="unavailable"&&e.stdout(`Profile check: ${i.message}
243
250
  `),e.stdout(`Bridge: configured
244
- `),e.stdout(`CLI version: ${se}
251
+ `),e.stdout(`CLI version: ${ae}
245
252
  `),e.stdout(`Update: ${o.message}
246
253
  `),(o.status==="update_recommended"||o.status==="unsupported")&&(e.stdout(`Update command: aifight update --yes
247
254
  `),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)}
255
+ `),e.stdout("The update command keeps local credentials and restarts `aifight.service` when it is installed.\n")),e.stdout(`Runtime: ${nR(r.runtimeType)} at ${r.runtimeLocalUrl}
256
+ `),e.stdout(`Automatic ranked matches: ${tR(r.autoDailyLimit)}
250
257
  `),e.stdout(`Games: ${r.autoGames?.join(", ")??"texas_holdem, liars_dice, coup"}
251
258
  `),e.stdout(`AIFight WebSocket: ${r.wsUrl}
252
259
  `),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})+`
260
+ `),0)}async function X$(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Q$);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=Z$(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 Z$(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 eR(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 tR(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function nR(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function rR(){try{return U()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var oR=["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(`
261
+ `),iR="https://aifight.ai",vi="@aifight/aifight@alpha";async function xp(t,e){F(t,0,0,oR);let n=t.flags.yes===!0,r=await De({baseUrl:sR(),currentVersion:ae,fetchImpl:e.fetchImpl});if(r.status==="current")return t.jsonMode?e.stdout(JSON.stringify({status:"current",update:r})+`
255
262
  `):(e.stdout(`${r.message}
256
263
  `),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}
264
+ `)),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
265
  `),r.policy!==void 0&&(e.stdout(`Latest: ${r.policy.latestVersion}
259
- `),e.stdout(`Update package: ${pi}
266
+ `),e.stdout(`Update package: ${vi}
260
267
  `))),!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)}
268
+ `),e.stderr("Run `aifight update --yes` after the human approves the local package update.\n"),1;if(!await lR(e,"Run npm update now? [y/N] "))return e.stdout(`Update skipped.
269
+ `),0}await aR(e,t.jsonMode);let o=await cR(e,t.jsonMode);return t.jsonMode&&e.stdout(JSON.stringify({status:"updated",package:vi,service:o})+`
270
+ `),0}function sR(){try{return U().baseUrl}catch{return process.env.AIFIGHT_BASE_URL?.replace(/\/+$/,"")??iR}}async function aR(t,e){e||t.stdout(`Updating AIFight CLI: npm install -g ${vi}
271
+ `);try{await Nc({execFile:t.bridgeService?.execFile})}catch(n){throw new B("update_failed",`npm update failed: ${Lc(n)}`,{hint:`Run manually: npm install -g ${vi}`})}e||t.stdout(`AIFight CLI package updated.
272
+ `)}async function cR(t,e){let n;try{n=await kt(t.bridgeService)}catch(r){return e||(t.stderr(`warning: could not inspect aifight.service: ${Lc(r)}
266
273
  `),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)}
274
+ `);try{await Zr(t.bridgeService)}catch(r){let o=r instanceof Z?r.hint:void 0;return e||(t.stderr(`warning: aifight.service restart failed: ${Lc(r)}
268
275
  `),o&&t.stderr(`${o}
269
276
  `),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
- `),{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})+`
277
+ `),{installed:!0,restarted:!0,running:!0,detail:"restarted"}}function Lc(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
278
+ `)[0]:t instanceof Error?t.message:String(t)}async function lR(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 jc=["usage: aifight set daily <N>"," aifight set game <game1,game2>",`supported games: ${re.join(", ")}`].join(`
279
+ `);async function Cp(t,e){F(t,2,2,jc);let n=t.positional[0];if(n==="daily")return uR(t.positional[1],t,e);if(n==="game")return fR(t.positional[1],t,e);throw new T(`unknown set target '${n}'`,"available: daily | game")}async function uR(t,e,n){if(!/^\d+$/.test(t))throw new T(`daily must be a non-negative integer (got '${t}')`,jc);let r=Number.parseInt(t,10),o=U();await dR(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return gn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
273
280
  `),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
281
  `):n.stdout(`Automatic ranked matches set to ${r} per day.
275
282
  `),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})+`
283
+ `),0)}async function dR(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 mR(o,`daily policy sync failed with HTTP ${o.status}`))}function fR(t,e,n){let r=t.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(r.length===0)throw new T("at least one game is required",jc);let o=new Set,i=[];for(let c of r){if(!Fe(c))throw new T(`unsupported game '${c}'`,`supported: ${re.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...U(),autoGames:i,updatedAt:new Date().toISOString()};return gn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
277
284
  `),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)+`
285
+ `),0)}async function mR(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 Ip="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function Op(t,e){F(t,1,1,Ip);let n=t.positional[0];if(n!=="texas_holdem"&&n!=="liars_dice"&&n!=="coup")throw new T(`challenge game must be texas_holdem, liars_dice, or coup (got '${n}')`,Ip);let r=U(),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 pR(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
286
  `),0):(e.stdout(`Friendly challenge created.
280
287
 
281
288
  `),e.stdout(`Game: ${n}
@@ -287,50 +294,92 @@ ${t.message}
287
294
 
288
295
  `),e.stdout(`This does not affect ratings or daily auto-play.
289
296
  `),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)+`
297
+ `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function pR(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 Dc="usage: aifight accept <challenge_url_or_token>";async function Mp(t,e){F(t,1,1,Dc);let n=hR(t.positional[0]),r=U(),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 yR(o,`challenge accept failed with HTTP ${o.status}`);throw new B("challenge_accept_failed",gR(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
291
298
  `),0):(e.stdout(`Friendly challenge accepted.
292
299
 
293
300
  `),i.match_id&&e.stdout(`Match: ${i.match_id}
294
301
  `),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.
308
- `);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(`
302
+ `),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 hR(t){let e=t.trim();if(e==="")throw new T("challenge token is required",Dc);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 T("invalid challenge URL or token",Dc)}function gR(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 yR(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 Ei from"node:fs";var Np="gateway.http.endpoints.responses.enabled",Lp=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],jp=["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(`
303
+ `);async function Dp(t,e){if(F(t,0,0,jp),t.jsonMode||!process.stdin.isTTY)throw new T("aifight uninstall requires an interactive terminal",jp);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(`
304
+ `));let n=wR();if(n!==void 0){let i=await bR(n,e.fetchImpl);e.stdout([`Local bridge identity: ${n.agentName} (${n.agentId})`,`Profile: ${i}`,""].join(`
305
+ `))}else e.stdout(`No local bridge credentials were found.
306
+
307
+ `);if(!await tr(e,"Continue with local uninstall? [y/N] "))return e.stdout(`Uninstall cancelled.
308
+ `),0;await vR(e),await ER(e);let o=await _R(e,n);return(n===void 0||o)&&Rm(),e.stdout(`AIFight local uninstall finished.
309
+
310
+ `),n!==void 0&&(e.stdout(`If local bridge credentials were kept, reinstalling the npm package can reuse this Agent.
311
+ `),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:
312
+ npm uninstall -g @aifight/aifight
313
+
314
+ `),0}async function _R(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(`
315
+ `)),!await tr(t,"Delete local bridge credentials too? [y/N] "))return t.stdout(`Kept local bridge credentials.
316
+ `),!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 SR()).trim()!==r?(t.stdout(`Confirmation did not match. Kept local bridge credentials.
317
+ `),!1):(fm(),t.stdout(`Local bridge credentials removed from this machine.
318
+ `),!0)}function wR(){try{return U()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}async function bR(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 SR(){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 vR(t){try{let e=await ui(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
319
+ `)}catch(e){let n=e instanceof Z||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
320
+ `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function ER(t){let e=gc();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
321
+ `);return}e.openclaw?.responsesEnabledByAIFight&&await kR(t),e.hermes&&await $R(t,e.hermes.envPath,e.hermes.previous)}async function kR(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(`
322
+ `)),!await tr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${Np} false --strict-json
323
+ `);return}if(!Pe("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
324
+ `);return}let n=await ct("openclaw",["config","set",Np,"false","--strict-json"]);if(_n(t,"openclaw config set",n),n.code!==0){t.stderr(`OpenClaw config restore failed. The bridge config was still removed.
325
+ `);return}let r=await ct("openclaw",["config","validate"]);_n(t,"openclaw config validate",r),await nr(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(`
326
+ `)),!await tr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
327
+ `);return}if(!Ei.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
328
+ `);return}let o=Ei.readFileSync(e,"utf8"),i=RR(o,n);if(Ei.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{Ei.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
329
+ `),await nr(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function RR(t,e){let n=new Set(Lp),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 Lp){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
311
330
  `).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
331
+ `)}var sr=["usage: aifight sessions list"," aifight sessions show <session_or_match_id>"," aifight sessions path <session_or_match_id>"," aifight sessions export <session_or_match_id>"].join(`
332
+ `);async function Up(t,e){let n=t.positional[0];if(!n)throw new T("missing sessions command",sr);let r=wi();if(n==="list"){F({...t,positional:t.positional.slice(1)},0,0,sr);let o=r.listSessions();return t.jsonMode?(e.stdout(JSON.stringify({sessions:o})+`
333
+ `),0):o.length===0?(e.stdout(`No local AIFight match sessions found yet.
334
+ `),0):(e.stdout(o.map(AR).join(`
335
+ `)+`
336
+ `),0)}if(n==="show"){let o=t.positional.slice(1);F({...t,positional:o},1,1,sr);let i=Bp(r,o[0]);return t.jsonMode?(e.stdout(JSON.stringify({session:i})+`
337
+ `),0):(e.stdout(TR(i)),0)}if(n==="path"){let o=t.positional.slice(1);F({...t,positional:o},1,1,sr);let i=Bp(r,o[0]);return t.jsonMode?e.stdout(JSON.stringify({path:i.path})+`
338
+ `):e.stdout(`${i.path}
339
+ `),0}if(n==="export"){let o=t.positional.slice(1);F({...t,positional:o},1,1,sr);let i=r.exportSession(o[0]);if(!i)throw new B("session_not_found",`local match session not found: ${o[0]}`);return e.stdout(JSON.stringify(i,null,2)+`
340
+ `),0}throw new T(`unknown sessions command '${n}'`,sr)}function Bp(t,e){let n=t.getSession(e);if(!n)throw new B("session_not_found",`local match session not found: ${e}`);return n}function AR(t){let e=t.game??"unknown_game",n=t.result_label??t.status,r=t.real_match_id?` match=${Fp(t.real_match_id)}`:"";return[Fp(t.session_id),e,n,`decisions=${t.decision_count}`,`updated=${t.updated_at}`,r.trim()].filter(Boolean).join(" ")}function TR(t){let e=[`Session: ${t.session_id}`,`Agent: ${t.agent_name} (${t.agent_id})`,`Status: ${t.status}`,`Game: ${t.game??"unknown"}`,`Started: ${t.started_at}`,`Updated: ${t.updated_at}`,`Decisions: ${t.decision_count}`,`Inbound messages: ${t.inbound_count}`,`Outbound actions: ${t.final_action_count}`,`Path: ${t.path}`];return t.real_match_id&&e.splice(1,0,`Match: ${t.real_match_id}`),t.result_label&&e.push(`Result: ${t.result_label}`),t.replay_url&&e.push(`Replay: ${t.replay_url}`),t.strategy_hashes.length>0&&e.push(`Strategy snapshots: ${t.strategy_hashes.length}`),`${e.join(`
341
+ `)}
342
+ `}function Fp(t){return t.length<=12?t:t.slice(0,12)}import ar from"node:fs";import Hp from"node:path";var PR=["usage: aifight strategy path [game]"," aifight strategy init [game]"," aifight strategy validate [game]",`supported games: ${re.join(", ")}`].join(`
343
+ `);async function Gp(t,e){F(t,1,2,PR);let n=t.positional[0],r=OR(t.positional[1]);if(n==="path")return xR(r,t,e);if(n==="init")return CR(r,t,e);if(n==="validate")return IR(r,t,e);throw new T(`unknown strategy command '${n}'`,"available: path | init | validate")}function xR(t,e,n){let r=U(),o=Sn(r.agentId,t),i=t===void 0?re.map(s=>({game:s,path:Sn(r.agentId,s).game})):[{game:t,path:o.game}];if(e.jsonMode)return n.stdout(JSON.stringify({agentId:r.agentId,root:o.root,global:o.global,gamesDir:o.gamesDir,games:i})+`
344
+ `),0;n.stdout(`Strategy root: ${o.root}
345
+ `),n.stdout(`Global strategy: ${o.global}
346
+ `),n.stdout(`Game strategy directory: ${o.gamesDir}
347
+ `);for(let s of i)n.stdout(`${s.game}: ${s.path}
348
+ `);return n.stdout(`Strategy files are Markdown/free-text .md files, not JSON config files.
349
+ `),n.stdout(`Missing or empty strategy files are skipped during matches.
350
+ `),0}function CR(t,e,n){let r=U(),o=Wp(r.agentId,t),i=0,s=0;for(let a of o){if(ar.mkdirSync(Hp.dirname(a.path),{recursive:!0,mode:448}),qp(Hp.dirname(a.path),448),ar.existsSync(a.path)){s+=1;continue}ar.writeFileSync(a.path,"",{mode:384}),qp(a.path,384),i+=1}if(e.jsonMode)return n.stdout(JSON.stringify({status:"ok",created:i,kept:s,files:o})+`
351
+ `),0;n.stdout(`Strategy files ready (${i} created, ${s} kept).
352
+ `);for(let a of o)n.stdout(`${Vp(a)}: ${a.path}
353
+ `);return n.stdout(`Edit these Markdown/free-text files with strategy guidance. Empty files are skipped during matches.
354
+ `),0}function IR(t,e,n){let r=U(),o=Wp(r.agentId,t).map(s=>MR(s)),i=o.flatMap(s=>s.warnings.map(a=>({path:s.path,warning:a})));if(e.jsonMode)return n.stdout(JSON.stringify({status:i.length===0?"ok":"warning",files:o,warnings:i})+`
355
+ `),i.length===0?0:1;for(let s of o){let a=Vp(s);if(!s.exists){n.stdout(`${a}: missing (${s.path})
356
+ `);continue}if(s.empty){n.stdout(`${a}: empty (${s.path})
357
+ `);continue}n.stdout(`${a}: ok, ${s.bytes} bytes${s.truncatedByBridge?" (Bridge will read the first 65536 bytes)":""}
358
+ `);for(let c of s.warnings)n.stdout(` warning: ${c}
359
+ `)}return i.length===0?0:1}function OR(t){if(t!==void 0){if(!Fe(t))throw new T(`unsupported game '${t}'`,`supported: ${re.join(", ")}`);return t}}function Wp(t,e){if(e!==void 0){let r=Sn(t,e);return[{scope:"global",path:r.global},{scope:"game",game:e,path:r.game}]}return[{scope:"global",path:Sn(t).global},...re.map(r=>{let o=Sn(t,r);return{scope:"game",game:r,path:o.game}})]}function MR(t){let e;try{e=ar.statSync(t.path)}catch{return{...t,exists:!1,bytes:0,empty:!0,truncatedByBridge:!1,warnings:[]}}if(!e.isFile())return{...t,exists:!0,bytes:0,empty:!0,truncatedByBridge:!1,warnings:["path exists but is not a regular file"]};let r=ar.readFileSync(t.path,"utf8").trim(),o=Buffer.byteLength(r,"utf8");return{...t,exists:!0,bytes:o,empty:r.length===0,truncatedByBridge:o>64*1024,warnings:NR(r)}}function NR(t){if(t.length===0)return[];let e=[],n=[[/\bsk-[A-Za-z0-9_-]{20,}\b/,"looks like an OpenAI-style API key"],[/\bsk-ant-[A-Za-z0-9_-]{20,}\b/,"looks like an Anthropic-style API key"],[/\bAIza[0-9A-Za-z_-]{20,}\b/,"looks like a Google API key"],[/\b[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{20,}\b/,"looks like a bot token"],[/\b(provider|api|secret|token|password)[_-]?(key|token|secret)?\s*[:=]\s*\S{12,}/i,"looks like a secret assignment"]];for(let[r,o]of n)r.test(t)&&!e.includes(o)&&e.push(o);return e}function Vp(t){return t.scope==="global"?"global":`game:${t.game}`}function qp(t,e){if(process.platform!=="win32")try{ar.chmodSync(t,e)}catch{}}async function Kp(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=LR(t)?t.slice(2):t.slice(),i=Hc(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 Jp(i.errors[0],n,s);if(i.flags.version===!0)return ac({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?Bc(n,s):BR(i.positional,n,s);if(i.positional.length===0)return Bc(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await jR(a,c,n)}catch(u){return FR(u,n,s)}}function LR(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 jR(t,e,n){switch(t){case"version":return ac(e,n);case"doctor":return hm(e,n);case"register":return Nm(e,n);case"connect":return Um(e,n);case"start":return Gm(e,n);case"run":return Tp(e,n);case"status":return Pp(e,n);case"update":return xp(e,n);case"service":return vm(e,n);case"sessions":return Up(e,n);case"strategy":return Gp(e,n);case"uninstall":return Dp(e,n);case"set":return Cp(e,n);case"challenge":return Op(e,n);case"accept":return Mp(e,n);default:throw new T(`unknown command '${t}'`)}}function zp(){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 sessions <command> Inspect local match session records"," aifight strategy <command> Show/init/validate local strategy files"," 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: ${re.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
360
+ `)}function Bc(t,e){return e?t.stdout(JSON.stringify({help:zp()})+`
361
+ `):t.stdout(zp()+`
362
+ `),0}function DR(t){switch(t[0]){case"version":return`Usage: aifight version
316
363
  Print the AIFight CLI version.`;case"doctor":return["Usage: aifight doctor"," Diagnose local bridge config, package version policy, and runtime endpoint reachability."].join(`
317
364
  `);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(`
319
- `);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(`
365
+ `);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(`
366
+ `);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: ${re.join(", ")}`].join(`
320
367
  `);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
368
  `);case"status":return["Usage: aifight status"," Show local bridge config with API key and runtime token redacted."].join(`
322
369
  `);case"update":return["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."," Updating does not require register, claim, or a new pairing code."].join(`
323
370
  `);case"service":return["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(`
371
+ `);case"sessions":return["Usage: aifight sessions list"," aifight sessions show <session_or_match_id>"," aifight sessions path <session_or_match_id>"," aifight sessions export <session_or_match_id>"," Inspect local per-match session records saved by the Bridge."," Records stay on this machine and include AIFight-visible match state, decisions, actions, and strategy snapshots."].join(`
372
+ `);case"strategy":return["Usage: aifight strategy path [game]"," aifight strategy init [game]"," aifight strategy validate [game]"," Show, create, or validate local Markdown/free-text strategy files."," Strategy files stay on this machine and are not JSON config files."," Missing or empty files are skipped during matches."].join(`
324
373
  `);case"uninstall":return["Usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This removes local credentials/config and aifight.service if installed."," It can also restore AIFight-recorded OpenClaw/Hermes setup changes with your approval."," It 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(`
325
- `);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(`
374
+ `);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: ${re.join(", ")}`].join(`
326
375
  `);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
376
  `);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})+`
377
+ `);default:return}}function BR(t,e,n){let r=DR(t);return r===void 0?Bc(e,n):(n?e.stdout(JSON.stringify({help:r})+`
329
378
  `):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}
379
+ `),0)}function Jp(t,e,n,r){return n?e.stderr(ao("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
331
380
  `),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}
381
+ `)),2}function FR(t,e,n){if(t instanceof T)return Jp(t.message,e,n,t.hint);if(t instanceof B)return n?e.stderr(ao(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
333
382
  `),t.hint!==void 0&&e.stderr(`${t.hint}
334
- `)),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}
383
+ `)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(ao("client_unexpected_error",r)):e.stderr(`aifight: unexpected error: ${r}
384
+ `),99}Kp(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
385
  `),process.exit(99)});