@lakutata/webrtc 3.1.5 → 3.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- export const sfuWorkerCode = "var S_=Object.create;var tl=Object.defineProperty;var w_=Object.getOwnPropertyDescriptor;var E_=Object.getOwnPropertyNames;var T_=Object.getPrototypeOf;var x_=Object.prototype.hasOwnProperty;var a=(r,e)=>tl(r,\"name\",{value:e,configurable:true});var R_=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var __=(r,e)=>{for(var t in e)tl(r,t,{get:e[t],enumerable:true})};var C_=(r,e,t,s)=>{if(e&&typeof e===\"object\"||typeof e===\"function\"){for(let n of E_(e))if(!x_.call(r,n)&&n!==t)tl(r,n,{get:()=>e[n],enumerable:!(s=w_(e,n))||s.enumerable})}return r};var Ye=(r,e,t)=>(t=r!=null?S_(T_(r)):{},C_(e||!r||!r.__esModule?tl(t,\"default\",{value:r,enumerable:true}):t,r));var Bn=R_(()=>{/*! *****************************************************************************\nCopyright (C) Microsoft. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */var zg;(function(r){(function(e){var t=typeof globalThis===\"object\"?globalThis:typeof global===\"object\"?global:typeof self===\"object\"?self:typeof this===\"object\"?this:c();var s=n(r);if(typeof t.Reflect!==\"undefined\"){s=n(t.Reflect,s)}e(s,t);if(typeof t.Reflect===\"undefined\"){t.Reflect=r}function n(l,u){return function(f,d){Object.defineProperty(l,f,{configurable:true,writable:true,value:d});if(u)u(f,d)}}a(n,\"makeExporter\");function i(){try{return Function(\"return this;\")()}catch(l){}}a(i,\"functionThis\");function o(){try{return(void 0,eval)(\"(function() { return this; })()\")}catch(l){}}a(o,\"indirectEvalThis\");function c(){return i()||o()}a(c,\"sloppyModeThis\")})(function(e,t){var s=Object.prototype.hasOwnProperty;var n=typeof Symbol===\"function\";var i=n&&typeof Symbol.toPrimitive!==\"undefined\"?Symbol.toPrimitive:\"@@toPrimitive\";var o=n&&typeof Symbol.iterator!==\"undefined\"?Symbol.iterator:\"@@iterator\";var c=typeof Object.create===\"function\";var l={__proto__:[]}instanceof Array;var u=!c&&!l;var f={create:c?function(){return Cd(Object.create(null))}:l?function(){return Cd({__proto__:null})}:function(){return Cd({})},has:u?function(E,R){return s.call(E,R)}:function(E,R){return R in E},get:u?function(E,R){return s.call(E,R)?E[R]:void 0}:function(E,R){return E[R]}};var d=Object.getPrototypeOf(Function);var h=typeof Map===\"function\"&&typeof Map.prototype.entries===\"function\"?Map:p_();var p=typeof Set===\"function\"&&typeof Set.prototype.entries===\"function\"?Set:m_();var m=typeof WeakMap===\"function\"?WeakMap:g_();var y=n?Symbol.for(\"@reflect-metadata:registry\"):void 0;var w=f_();var S=d_(w);function T(E,R,C,L){if(!z(C)){if(!Dg(E))throw new TypeError;if(!Ae(R))throw new TypeError;if(!Ae(L)&&!z(L)&&!Mn(L))throw new TypeError;if(Mn(L))L=void 0;C=ar(C);return xd(E,R,C,L)}else{if(!Dg(E))throw new TypeError;if(!Bg(R))throw new TypeError;return Qc(E,R)}}a(T,\"decorate\");e(\"decorate\",T);function _(E,R){function C(L,F){if(!Ae(L))throw new TypeError;if(!z(F)&&!l_(F))throw new TypeError;Oo(E,R,L,F)}a(C,\"decorator\");return C}a(_,\"metadata\");e(\"metadata\",_);function x(E,R,C,L){if(!Ae(C))throw new TypeError;if(!z(L))L=ar(L);return Oo(E,R,C,L)}a(x,\"defineMetadata\");e(\"defineMetadata\",x);function k(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return Ao(E,R,C)}a(k,\"hasMetadata\");e(\"hasMetadata\",k);function N(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return _t(E,R,C)}a(N,\"hasOwnMetadata\");e(\"hasOwnMetadata\",N);function A(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return Ns(E,R,C)}a(A,\"getMetadata\");e(\"getMetadata\",A);function B(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return Io(E,R,C)}a(B,\"getOwnMetadata\");e(\"getOwnMetadata\",B);function ee(E,R){if(!Ae(E))throw new TypeError;if(!z(R))R=ar(R);return el(E,R)}a(ee,\"getMetadataKeys\");e(\"getMetadataKeys\",ee);function fe(E,R){if(!Ae(E))throw new TypeError;if(!z(R))R=ar(R);return Ng(E,R)}a(fe,\"getOwnMetadataKeys\");e(\"getOwnMetadataKeys\",fe);function Rt(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);var L=ko(R,C,false);if(z(L))return false;return L.OrdinaryDeleteMetadata(E,R,C)}a(Rt,\"deleteMetadata\");e(\"deleteMetadata\",Rt);function Qc(E,R){for(var C=E.length-1;C>=0;--C){var L=E[C];var F=L(R);if(!z(F)&&!Mn(F)){if(!Bg(F))throw new TypeError;R=F}}return R}a(Qc,\"DecorateConstructor\");function xd(E,R,C,L){for(var F=E.length-1;F>=0;--F){var Ie=E[F];var De=Ie(R,C,L);if(!z(De)&&!Mn(De)){if(!Ae(De))throw new TypeError;L=De}}return L}a(xd,\"DecorateProperty\");function Ao(E,R,C){var L=_t(E,R,C);if(L)return true;var F=_d(R);if(!Mn(F))return Ao(E,F,C);return false}a(Ao,\"OrdinaryHasMetadata\");function _t(E,R,C){var L=ko(R,C,false);if(z(L))return false;return Mg(L.OrdinaryHasOwnMetadata(E,R,C))}a(_t,\"OrdinaryHasOwnMetadata\");function Ns(E,R,C){var L=_t(E,R,C);if(L)return Io(E,R,C);var F=_d(R);if(!Mn(F))return Ns(E,F,C);return void 0}a(Ns,\"OrdinaryGetMetadata\");function Io(E,R,C){var L=ko(R,C,false);if(z(L))return;return L.OrdinaryGetOwnMetadata(E,R,C)}a(Io,\"OrdinaryGetOwnMetadata\");function Oo(E,R,C,L){var F=ko(C,L,true);F.OrdinaryDefineOwnMetadata(E,R,C,L)}a(Oo,\"OrdinaryDefineOwnMetadata\");function el(E,R){var C=Ng(E,R);var L=_d(E);if(L===null)return C;var F=el(L,R);if(F.length<=0)return C;if(C.length<=0)return F;var Ie=new p;var De=[];for(var W=0,M=C;W<M.length;W++){var D=M[W];var U=Ie.has(D);if(!U){Ie.add(D);De.push(D)}}for(var j=0,J=F;j<J.length;j++){var D=J[j];var U=Ie.has(D);if(!U){Ie.add(D);De.push(D)}}return De}a(el,\"OrdinaryMetadataKeys\");function Ng(E,R){var C=ko(E,R,false);if(!C){return[]}return C.OrdinaryOwnMetadataKeys(E,R)}a(Ng,\"OrdinaryOwnMetadataKeys\");function Lg(E){if(E===null)return 1;switch(typeof E){case\"undefined\":return 0;case\"boolean\":return 2;case\"string\":return 3;case\"symbol\":return 4;case\"number\":return 5;case\"object\":return E===null?1:6;default:return 6}}a(Lg,\"Type\");function z(E){return E===void 0}a(z,\"IsUndefined\");function Mn(E){return E===null}a(Mn,\"IsNull\");function i_(E){return typeof E===\"symbol\"}a(i_,\"IsSymbol\");function Ae(E){return typeof E===\"object\"?E!==null:typeof E===\"function\"}a(Ae,\"IsObject\");function o_(E,R){switch(Lg(E)){case 0:return E;case 1:return E;case 2:return E;case 3:return E;case 4:return E;case 5:return E}var C=R===3?\"string\":R===5?\"number\":\"default\";var L=Ug(E,i);if(L!==void 0){var F=L.call(E,C);if(Ae(F))throw new TypeError;return F}return a_(E,C===\"default\"?\"number\":C)}a(o_,\"ToPrimitive\");function a_(E,R){if(R===\"string\"){var C=E.toString;if(Dn(C)){var L=C.call(E);if(!Ae(L))return L}var F=E.valueOf;if(Dn(F)){var L=F.call(E);if(!Ae(L))return L}}else{var F=E.valueOf;if(Dn(F)){var L=F.call(E);if(!Ae(L))return L}var Ie=E.toString;if(Dn(Ie)){var L=Ie.call(E);if(!Ae(L))return L}}throw new TypeError}a(a_,\"OrdinaryToPrimitive\");function Mg(E){return!!E}a(Mg,\"ToBoolean\");function c_(E){return\"\"+E}a(c_,\"ToString\");function ar(E){var R=o_(E,3);if(i_(R))return R;return c_(R)}a(ar,\"ToPropertyKey\");function Dg(E){return Array.isArray?Array.isArray(E):E instanceof Object?E instanceof Array:Object.prototype.toString.call(E)===\"[object Array]\"}a(Dg,\"IsArray\");function Dn(E){return typeof E===\"function\"}a(Dn,\"IsCallable\");function Bg(E){return typeof E===\"function\"}a(Bg,\"IsConstructor\");function l_(E){switch(Lg(E)){case 3:return true;case 4:return true;default:return false}}a(l_,\"IsPropertyKey\");function Rd(E,R){return E===R||E!==E&&R!==R}a(Rd,\"SameValueZero\");function Ug(E,R){var C=E[R];if(C===void 0||C===null)return void 0;if(!Dn(C))throw new TypeError;return C}a(Ug,\"GetMethod\");function jg(E){var R=Ug(E,o);if(!Dn(R))throw new TypeError;var C=R.call(E);if(!Ae(C))throw new TypeError;return C}a(jg,\"GetIterator\");function $g(E){return E.value}a($g,\"IteratorValue\");function Fg(E){var R=E.next();return R.done?false:R}a(Fg,\"IteratorStep\");function Hg(E){var R=E[\"return\"];if(R)R.call(E)}a(Hg,\"IteratorClose\");function _d(E){var R=Object.getPrototypeOf(E);if(typeof E!==\"function\"||E===d)return R;if(R!==d)return R;var C=E.prototype;var L=C&&Object.getPrototypeOf(C);if(L==null||L===Object.prototype)return R;var F=L.constructor;if(typeof F!==\"function\")return R;if(F===E)return R;return F}a(_d,\"OrdinaryGetPrototypeOf\");function u_(){var E;if(!z(y)&&typeof t.Reflect!==\"undefined\"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata===\"function\"){E=h_(t.Reflect)}var R;var C;var L;var F=new m;var Ie={registerProvider:De,getProvider:M,setProvider:U};return Ie;function De(j){if(!Object.isExtensible(Ie)){throw new Error(\"Cannot add provider to a frozen registry.\")}switch(true){case E===j:break;case z(R):R=j;break;case R===j:break;case z(C):C=j;break;case C===j:break;default:if(L===void 0)L=new p;L.add(j);break}}a(De,\"registerProvider\");function W(j,J){if(!z(R)){if(R.isProviderFor(j,J))return R;if(!z(C)){if(C.isProviderFor(j,J))return R;if(!z(L)){var be=jg(L);while(true){var Oe=Fg(be);if(!Oe){return void 0}var jt=$g(Oe);if(jt.isProviderFor(j,J)){Hg(be);return jt}}}}}if(!z(E)&&E.isProviderFor(j,J)){return E}return void 0}a(W,\"getProviderNoCache\");function M(j,J){var be=F.get(j);var Oe;if(!z(be)){Oe=be.get(J)}if(!z(Oe)){return Oe}Oe=W(j,J);if(!z(Oe)){if(z(be)){be=new h;F.set(j,be)}be.set(J,Oe)}return Oe}a(M,\"getProvider\");function D(j){if(z(j))throw new TypeError;return R===j||C===j||!z(L)&&L.has(j)}a(D,\"hasProvider\");function U(j,J,be){if(!D(be)){throw new Error(\"Metadata provider not registered.\")}var Oe=M(j,J);if(Oe!==be){if(!z(Oe)){return false}var jt=F.get(j);if(z(jt)){jt=new h;F.set(j,jt)}jt.set(J,be)}return true}a(U,\"setProvider\")}a(u_,\"CreateMetadataRegistry\");function f_(){var E;if(!z(y)&&Ae(t.Reflect)&&Object.isExtensible(t.Reflect)){E=t.Reflect[y]}if(z(E)){E=u_()}if(!z(y)&&Ae(t.Reflect)&&Object.isExtensible(t.Reflect)){Object.defineProperty(t.Reflect,y,{enumerable:false,configurable:false,writable:false,value:E})}return E}a(f_,\"GetOrCreateMetadataRegistry\");function d_(E){var R=new m;var C={isProviderFor:a(function(D,U){var j=R.get(D);if(z(j))return false;return j.has(U)},\"isProviderFor\"),OrdinaryDefineOwnMetadata:De,OrdinaryHasOwnMetadata:F,OrdinaryGetOwnMetadata:Ie,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:M};w.registerProvider(C);return C;function L(D,U,j){var J=R.get(D);var be=false;if(z(J)){if(!j)return void 0;J=new h;R.set(D,J);be=true}var Oe=J.get(U);if(z(Oe)){if(!j)return void 0;Oe=new h;J.set(U,Oe);if(!E.setProvider(D,U,C)){J.delete(U);if(be){R.delete(D)}throw new Error(\"Wrong provider for target.\")}}return Oe}a(L,\"GetOrCreateMetadataMap\");function F(D,U,j){var J=L(U,j,false);if(z(J))return false;return Mg(J.has(D))}a(F,\"OrdinaryHasOwnMetadata\");function Ie(D,U,j){var J=L(U,j,false);if(z(J))return void 0;return J.get(D)}a(Ie,\"OrdinaryGetOwnMetadata\");function De(D,U,j,J){var be=L(j,J,true);be.set(D,U)}a(De,\"OrdinaryDefineOwnMetadata\");function W(D,U){var j=[];var J=L(D,U,false);if(z(J))return j;var be=J.keys();var Oe=jg(be);var jt=0;while(true){var qg=Fg(Oe);if(!qg){j.length=jt;return j}var y_=$g(qg);try{j[jt]=y_}catch(b_){try{Hg(Oe)}finally{throw b_}}jt++}}a(W,\"OrdinaryOwnMetadataKeys\");function M(D,U,j){var J=L(U,j,false);if(z(J))return false;if(!J.delete(D))return false;if(J.size===0){var be=R.get(U);if(!z(be)){be.delete(j);if(be.size===0){R.delete(be)}}}return true}a(M,\"OrdinaryDeleteMetadata\")}a(d_,\"CreateMetadataProvider\");function h_(E){var R=E.defineMetadata,C=E.hasOwnMetadata,L=E.getOwnMetadata,F=E.getOwnMetadataKeys,Ie=E.deleteMetadata;var De=new m;var W={isProviderFor:a(function(M,D){var U=De.get(M);if(!z(U)&&U.has(D)){return true}if(F(M,D).length){if(z(U)){U=new p;De.set(M,U)}U.add(D);return true}return false},\"isProviderFor\"),OrdinaryDefineOwnMetadata:R,OrdinaryHasOwnMetadata:C,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:F,OrdinaryDeleteMetadata:Ie};return W}a(h_,\"CreateFallbackProvider\");function ko(E,R,C){var L=w.getProvider(E,R);if(!z(L)){return L}if(C){if(w.setProvider(E,R,S)){return S}throw new Error(\"Illegal state.\")}return void 0}a(ko,\"GetMetadataProvider\");function p_(){var E={};var R=[];var C=(function(){function W(M,D,U){this._index=0;this._keys=M;this._values=D;this._selector=U}a(W,\"MapIterator\");W.prototype[\"@@iterator\"]=function(){return this};W.prototype[o]=function(){return this};W.prototype.next=function(){var M=this._index;if(M>=0&&M<this._keys.length){var D=this._selector(this._keys[M],this._values[M]);if(M+1>=this._keys.length){this._index=-1;this._keys=R;this._values=R}else{this._index++}return{value:D,done:false}}return{value:void 0,done:true}};W.prototype.throw=function(M){if(this._index>=0){this._index=-1;this._keys=R;this._values=R}throw M};W.prototype.return=function(M){if(this._index>=0){this._index=-1;this._keys=R;this._values=R}return{value:M,done:true}};return W})();var L=(function(){function W(){this._keys=[];this._values=[];this._cacheKey=E;this._cacheIndex=-2}a(W,\"Map\");Object.defineProperty(W.prototype,\"size\",{get:a(function(){return this._keys.length},\"get\"),enumerable:true,configurable:true});W.prototype.has=function(M){return this._find(M,false)>=0};W.prototype.get=function(M){var D=this._find(M,false);return D>=0?this._values[D]:void 0};W.prototype.set=function(M,D){var U=this._find(M,true);this._values[U]=D;return this};W.prototype.delete=function(M){var D=this._find(M,false);if(D>=0){var U=this._keys.length;for(var j=D+1;j<U;j++){this._keys[j-1]=this._keys[j];this._values[j-1]=this._values[j]}this._keys.length--;this._values.length--;if(Rd(M,this._cacheKey)){this._cacheKey=E;this._cacheIndex=-2}return true}return false};W.prototype.clear=function(){this._keys.length=0;this._values.length=0;this._cacheKey=E;this._cacheIndex=-2};W.prototype.keys=function(){return new C(this._keys,this._values,F)};W.prototype.values=function(){return new C(this._keys,this._values,Ie)};W.prototype.entries=function(){return new C(this._keys,this._values,De)};W.prototype[\"@@iterator\"]=function(){return this.entries()};W.prototype[o]=function(){return this.entries()};W.prototype._find=function(M,D){if(!Rd(this._cacheKey,M)){this._cacheIndex=-1;for(var U=0;U<this._keys.length;U++){if(Rd(this._keys[U],M)){this._cacheIndex=U;break}}}if(this._cacheIndex<0&&D){this._cacheIndex=this._keys.length;this._keys.push(M);this._values.push(void 0)}return this._cacheIndex};return W})();return L;function F(W,M){return W}a(F,\"getKey\");function Ie(W,M){return M}a(Ie,\"getValue\");function De(W,M){return[W,M]}a(De,\"getEntry\")}a(p_,\"CreateMapPolyfill\");function m_(){var E=(function(){function R(){this._map=new h}a(R,\"Set\");Object.defineProperty(R.prototype,\"size\",{get:a(function(){return this._map.size},\"get\"),enumerable:true,configurable:true});R.prototype.has=function(C){return this._map.has(C)};R.prototype.add=function(C){return this._map.set(C,C),this};R.prototype.delete=function(C){return this._map.delete(C)};R.prototype.clear=function(){this._map.clear()};R.prototype.keys=function(){return this._map.keys()};R.prototype.values=function(){return this._map.keys()};R.prototype.entries=function(){return this._map.entries()};R.prototype[\"@@iterator\"]=function(){return this.keys()};R.prototype[o]=function(){return this.keys()};return R})();return E}a(m_,\"CreateSetPolyfill\");function g_(){var E=16;var R=f.create();var C=L();return(function(){function M(){this._key=L()}a(M,\"WeakMap\");M.prototype.has=function(D){var U=F(D,false);return U!==void 0?f.has(U,this._key):false};M.prototype.get=function(D){var U=F(D,false);return U!==void 0?f.get(U,this._key):void 0};M.prototype.set=function(D,U){var j=F(D,true);j[this._key]=U;return this};M.prototype.delete=function(D){var U=F(D,false);return U!==void 0?delete U[this._key]:false};M.prototype.clear=function(){this._key=L()};return M})();function L(){var M;do M=\"@@WeakMap@@\"+W();while(f.has(R,M));R[M]=true;return M}a(L,\"CreateUniqueKey\");function F(M,D){if(!s.call(M,C)){if(!D)return void 0;Object.defineProperty(M,C,{value:f.create()})}return M[C]}a(F,\"GetOrCreateWeakMapTable\");function Ie(M,D){for(var U=0;U<D;++U)M[U]=Math.random()*255|0;return M}a(Ie,\"FillRandomBytes\");function De(M){if(typeof Uint8Array===\"function\"){var D=new Uint8Array(M);if(typeof crypto!==\"undefined\"){crypto.getRandomValues(D)}else if(typeof msCrypto!==\"undefined\"){msCrypto.getRandomValues(D)}else{Ie(D,M)}return D}return Ie(new Array(M),M)}a(De,\"GenRandomBytes\");function W(){var M=De(E);M[6]=M[6]&79|64;M[8]=M[8]&191|128;var D=\"\";for(var U=0;U<E;++U){var j=M[U];if(U===4||U===6||U===8)D+=\"-\";if(j<16)D+=\"0\";D+=j.toString(16).toLowerCase()}return D}a(W,\"CreateUUID\")}a(g_,\"CreateWeakMapPolyfill\");function Cd(E){E.__=void 0;delete E.__;return E}a(Cd,\"MakeDictionary\")})})(zg||(zg={}))});var s_=require(\"node:util\");var Zc=require(\"node:worker_threads\");var Iz=Ye(Bn(),1);var Xg=require(\"node:util\");function v(r){return r}a(v,\"As\");var vd=class extends Error{static{a(this,\"Warning\")}get name(){return this.constructor.name}};function _r(r){return process.emit(\"warning\",new vd(r))}a(_r,\"throwWarning\");function Un(r){return process.env[r]}a(Un,\"variable\");function rl(r){const e=r?.trim().toLowerCase();return e===\"development\"||e===\"production\"?e:void 0}a(rl,\"modeOf\");function Gg(r){const e=rl(Un(\"MODE\"));if(e)return e;if(Un(\"MODE\")?.trim())_r(`The MODE environment variable \"${Un(\"MODE\")}\" is not a mode (development, production), it is ignored`);return rl(Un(\"NODE_ENV\"))??r??\"development\"}a(Gg,\"resolveMode\");function Ad(){return rl(Un(\"MODE\"))??rl(Un(\"NODE_ENV\"))??\"development\"}a(Ad,\"currentMode\");function v_(r){try{new Intl.DateTimeFormat(\"en-US\",{timeZone:r});return true}catch{return false}}a(v_,\"isTimezone\");function A_(r){const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!v_(r)){_r(`The passed time zone \"${r}\" is invalid, use the default time zone \"${e}\"`);return e}return r}a(A_,\"validateTimezone\");function Kg(r){process.env.appId=r.appId;process.env.appName=r.appName;const e=r.timezone===\"auto\"?Intl.DateTimeFormat().resolvedOptions().timeZone:r.timezone;process.env.TZ=A_(e);process.env.NODE_ENV=r.mode;process.env.MODE=r.mode;return Id()}a(Kg,\"setBasicInfo\");function jn(){return process.env.appId||\"Unknown\"}a(jn,\"getAppId\");function Qr(){return process.env.appName||\"Unknown\"}a(Qr,\"getAppName\");function Id(){return{appId:jn(),appName:Qr(),timezone:v(process.env.TZ),mode:Ad()}}a(Id,\"getBasicInfo\");var Wg=a(r=>r.replace(/&/g,\"&amp;\").replace(/\"/g,\"&quot;\").replace(/'/g,\"&#39;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\"),\"_htmlEscape\");function I_(r,...e){if(typeof r===\"string\"){return Wg(r)}let t=r[0];for(const[s,n]of e.entries()){t=t+Wg(String(n))+r[s+1]}return t}a(I_,\"htmlEscape\");var Od=class extends Error{static{a(this,\"MissingValueError\")}constructor(e){super(`Missing a value for ${e?`the placeholder: ${e}`:\"a placeholder\"}`);this.name=\"MissingValueError\";this.key=e}};function Vg(r,e,{ignoreMissing:t=false,transform:s=a(({value:n})=>n,\"transform\")}={}){if(typeof r!==\"string\"){throw new TypeError(`Expected a \\`string\\` in the first argument, got \\`${typeof r}\\``)}if(typeof e!==\"object\"){throw new TypeError(`Expected an \\`object\\` or \\`Array\\` in the second argument, got \\`${typeof e}\\``)}const n=a((l,u)=>{let f=e;for(const h of u.split(\".\")){f=f?f[h]:void 0}const d=s({value:f,key:u});if(d===void 0){if(t){return l}throw new Od(u)}return String(d)},\"replace\");const i=a(l=>(...u)=>I_(l(...u)),\"composeHtmlEscape\");const o=/{{(\\d+|[a-z$_][\\w\\-$]*?(?:\\.[\\w\\-$]*?)*?)}}/gi;if(o.test(r)){r=r.replace(o,i(n))}const c=/{(\\d+|[a-z$_][\\w\\-$]*?(?:\\.[\\w\\-$]*?)*?)}/gi;return r.replace(c,n)}a(Vg,\"templating\");function $t(...r){return void 0}a($t,\"DevNull\");var O_=\"sdifjoOc\";function k_(r,...e){if(!e.length)return r;let t=\"\";let s=0;let n=0;for(let i=0;i<r.length-1;i++){if(r[i]!==\"%\")continue;const o=r[++i];if(n<e.length&&O_.includes(o)){let c;try{c=o===\"c\"?\"\":(0,Xg.format)(`%${o}`,e[n])}catch{c=`%${o}`}t+=r.slice(s,i-1)+c;n++;s=i+1}else if(o===\"%\"){t+=r.slice(s,i);s=i+1}}return t+r.slice(s)}a(k_,\"format\");var P_=Symbol(\"EXCEPTION.PARAMS\");var Z=class extends Error{static{a(this,\"Exception\")}constructor(e,...t){super();this.appId=jn();this.appName=Qr();this.statusCode=500;if(t.length){const n=e;const i=t.length>1||typeof t[0]!==\"object\"||t[0]===null?t:t[0];Object.defineProperty(this,P_,{value:i,enumerable:false});try{this.message=Vg(n,i,{ignoreMissing:true})}catch(o){this.message=n;$t(o)}this.message=k_(this.message,...t)}else if(e){if(typeof e===\"string\"){this.message=e}else{this.message=v(e).message}}else{const n=this.name.replace(/([a-z\\d])([A-Z])/g,\"$1 $2\").replace(/([A-Z]+)([A-Z][a-z])/g,\"$1 $2\").split(/[\\s_-]+/).filter(i=>!!i).map(i=>/^[A-Z\\d]{2,}$/.test(i)?i:i.toLowerCase()).join(\" \");this.message=`${n.charAt(0).toUpperCase()}${n.slice(1)}`}let s=this.message;Object.defineProperty(this,\"message\",{configurable:true,enumerable:true,get:a(()=>s,\"get\"),set:a(n=>{s=n;v(this).errMsg=n},\"set\")});this.errMsg=s;this.err=this.name}get name(){return this.constructor.name}};var pB=Ye(Bn(),1);var Ub=require(\"node:util/types\");var Ls=class extends Error{static{a(this,\"AssertError\")}constructor(e,t){super(e||\"Unknown error\");this.name=\"AssertError\";if(typeof Error.captureStackTrace===\"function\")Error.captureStackTrace(this,t)}};function Po(...r){try{return JSON.stringify(...r)}catch(e){return\"[Cannot display object: \"+e.message+\"]\"}}a(Po,\"stringify\");function te(r,...e){if(r)return;if(e.length===1&&e[0]instanceof Error)throw e[0];const t=e.filter(s=>s!==\"\").map(s=>typeof s===\"string\"?s:s instanceof Error?s.message:Po(s));throw new Ls(t.join(\" \"),te)}a(te,\"assert\");function No(r,e={}){return e.symbols!==false?Reflect.ownKeys(r):Object.getOwnPropertyNames(r)}a(No,\"keys\");function ce(r){return Array.isArray(r)}a(ce,\"isArray\");function N_(r){if(r instanceof Set)return\"set\";if(r instanceof Map)return\"map\";return void 0}a(N_,\"iterables\");function et(r,e,t){if(e===false||e===null||e===void 0)return r;const s=typeof t===\"string\"?{separator:t}:t||{};const n=ce(e);te(!n||!s.separator,\"Separator option is not valid for array-based chain\");const i=ce(e)?e:e.split(s.separator||\".\");let o=r;for(let c=0;c<i.length;++c){let l=i[c];const u=s.iterables?N_(o):void 0;if(ce(o)||u===\"set\"){const f=Number(l);if(Number.isInteger(f))l=f<0?Number(o.length)+f:f}if(!o||typeof o===\"function\"&&s.functions===false||!u&&o[l]===void 0){te(!s.strict||c+1===i.length,\"Missing segment\",l,\"in reach path \",e);te(typeof o===\"object\"||s.functions===true||typeof o!==\"function\",\"Invalid segment\",l,\"in reach path \",e);o=s.default;break}if(!u){o=o[l]}else if(u===\"set\"){o=[...o][l]}else{o=o.get(l)}}return o}a(et,\"reach\");var K={array:Array.prototype,buffer:Buffer.prototype,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,url:URL.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype};var L_=new Map([[\"[object Error]\",K.error],[\"[object Map]\",K.map],[\"[object Promise]\",K.promise],[\"[object Set]\",K.set],[\"[object URL]\",K.url],[\"[object WeakMap]\",K.weakMap],[\"[object WeakSet]\",K.weakSet]]);function Ms(r){if(Array.isArray(r))return K.array;if(r instanceof Buffer)return K.buffer;if(r instanceof Date)return K.date;if(r instanceof RegExp)return K.regex;if(r instanceof Error)return K.error;const e=Object.prototype.toString.call(r);return L_.get(e)||K.generic}a(Ms,\"getInternalProto\");var Yg=new Set([K.set,K.map,K.weakSet,K.weakMap]);function G(r,e={},t=null){return kd(r,e,t)}a(G,\"clone\");function kd(r,e,t){if(typeof r!==\"object\"||r===null)return r;let s=kd;let n=t;if(e.shallow){if(e.shallow!==true)return M_(r,e);s=a(u=>u,\"cloner\")}else if(n){const u=n.get(r);if(u)return u}else{n=new Map}const i=Ms(r);switch(i){case K.buffer:return Buffer.from(r);case K.date:return new Date(r.getTime());case K.regex:return new RegExp(r);case K.url:return new URL(r)}const o=D_(r,i,e);if(o===r)return r;if(n)n.set(r,o);if(i===K.set){for(const u of r)o.add(s(u,e,n))}else if(i===K.map){for(const[u,f]of r)o.set(u,s(f,e,n))}const c=r;const l=o;for(const u of No(r,e)){if(u===\"__proto__\")continue;if(i===K.array&&u===\"length\"){o.length=r.length;continue}if(i===K.error&&u===\"stack\")continue;const f=Object.getOwnPropertyDescriptor(r,u);if(f){if(f.get||f.set){Object.defineProperty(o,u,f)}else if(f.enumerable){l[u]=s(c[u],e,n)}else{Object.defineProperty(o,u,{enumerable:false,writable:true,configurable:true,value:s(c[u],e,n)})}}else{Object.defineProperty(o,u,{enumerable:true,writable:true,configurable:true,value:s(c[u],e,n)})}}return o}a(kd,\"cloneValue\");function M_(r,e){const t=e.shallow;const s={...e,shallow:false};const n=new Map;for(const i of t){const o=et(r,i);if(typeof o===\"object\"||typeof o===\"function\")n.set(o,o)}return kd(r,s,n)}a(M_,\"cloneWithShallow\");function D_(r,e,t){if(t.prototype===false){if(Yg.has(e))return new e.constructor;return e===K.array?[]:{}}const s=Object.getPrototypeOf(r);if(s&&s.isImmutable)return r;if(e===K.array){const n=[];if(s!==e)Object.setPrototypeOf(n,s);return n}if(e===K.error&&s&&(s===e||Object.prototype.isPrototypeOf.call(Error,s.constructor))){const n=structuredClone(r);if(Object.getPrototypeOf(n)!==s)Object.setPrototypeOf(n,s);return n}if(Yg.has(e)){const n=new s.constructor;if(s!==e)Object.setPrototypeOf(n,s);return n}return Object.create(s)}a(D_,\"base\");function Ft(r,e,t){te(r&&typeof r===\"object\",\"Invalid target value: must be an object\");te(e===null||e===void 0||typeof e===\"object\",\"Invalid source value: must be null, undefined, or an object\");if(!e)return r;const s={nullOverride:true,mergeArrays:true,...t};if(ce(e)){te(ce(r),\"Cannot merge array onto an object\");if(!s.mergeArrays)r.length=0;for(let c=0;c<e.length;++c)r.push(G(e[c],{symbols:s.symbols}));return r}const n=r;const i=e;const o=No(e,s);for(let c=0;c<o.length;++c){const l=o[c];if(l===\"__proto__\"||!Object.prototype.propertyIsEnumerable.call(e,l))continue;const u=i[l];if(u&&typeof u===\"object\"){if(n[l]===u)continue;const f=n[l];if(!f||typeof f!==\"object\"||ce(f)!==ce(u)||u instanceof Date||Buffer.isBuffer(u)||u instanceof RegExp){n[l]=G(u,{symbols:s.symbols})}else{Ft(f,u,s)}}else{if(u!==null&&u!==void 0){n[l]=u}else if(s.nullOverride){n[l]=u}}}return r}a(Ft,\"merge\");function Pd(r,e,t={}){te(r&&typeof r===\"object\",\"Invalid defaults value: must be an object\");te(!e||e===true||typeof e===\"object\",\"Invalid source value: must be true, falsy or an object\");te(typeof t===\"object\",\"Invalid options: must be an object\");if(!e)return null;if(t.shallow)return B_(r,e,t);const s=G(r);if(e===true)return s;const n=t.nullOverride!==void 0?t.nullOverride:false;return Ft(s,e,{nullOverride:n,mergeArrays:false})}a(Pd,\"applyToDefaults\");function B_(r,e,t){const s=t.shallow;te(ce(s),\"Invalid keys\");const n=new Map;const i=e===true?null:new Set;for(const l of s){const u=ce(l)?l:l.split(\".\");const f=et(r,u);if(f&&typeof f===\"object\"){n.set(f,i&&et(e,u)||f)}else if(i){i.add(u)}}const o=G(r,{},n);if(!i)return o;for(const l of i)U_(o,e,l);const c=t.nullOverride!==void 0?t.nullOverride:false;return Ft(o,e,{nullOverride:c,mergeArrays:false})}a(B_,\"applyToDefaultsWithShallow\");function U_(r,e,t){let s=e;for(const o of t){if(!(o in s))return;const c=s[o];if(typeof c!==\"object\"||c===null)return;s=c}const n=s;let i=r;for(let o=0;o<t.length-1;++o){const c=t[o];if(typeof i[c]!==\"object\")i[c]={};i=i[c]}i[t[t.length-1]]=n}a(U_,\"reachCopy\");var Nd=Symbol(\"mismatched\");var Ld=class{static{a(this,\"SeenEntry\")}constructor(e,t){this.obj=e;this.ref=t}isSame(e,t){return this.obj===e&&this.ref===t}};function Ct(r,e,t){return!!es(r,e,{prototype:true,...t},[])}a(Ct,\"deepEqual\");function es(r,e,t,s){if(r===e)return r!==0||1/r===1/e;const n=typeof r;if(n!==typeof e)return false;if(r===null||e===null)return false;if(n===\"function\"){if(!t.deepFunction||sl(r)!==sl(e))return false}else if(n!==\"object\"){return r!==r&&e!==e}const i=r;const o=e;const c=j_(i,o,!!t.prototype);switch(c){case K.buffer:return Buffer.prototype.equals.call(r,e);case K.promise:return r===e;case K.regex:case K.url:return sl(r)===sl(e);case Nd:return false}for(let l=s.length-1;l>=0;--l){if(s[l].isSame(i,o))return true}s.push(new Ld(i,o));try{return!!F_(c,i,o,t,s)}finally{s.pop()}}a(es,\"isDeepEqual\");function sl(r){return r.toString()}a(sl,\"toStringOf\");function j_(r,e,t){if(t){if(Object.getPrototypeOf(r)!==Object.getPrototypeOf(e))return Nd;return Ms(r)}const s=Ms(r);if(s!==Ms(e))return Nd;return s}a(j_,\"getSharedType\");function Jg(r){const e=r.valueOf;if(e===void 0)return r;try{return e.call(r)}catch(t){return t}}a(Jg,\"valueOf\");function Lo(r,e){return Object.prototype.propertyIsEnumerable.call(r,e)}a(Lo,\"hasOwnEnumerableProperty\");function $_(r,e){for(const t of Set.prototype.values.call(r)){if(!Set.prototype.has.call(e,t))return false}return true}a($_,\"isSetSimpleEqual\");function F_(r,e,t,s,n){const i=e;const o=t;if(r===K.array){const d=e;const h=t;if(s.part){for(const p of d){for(const m of h){if(es(p,m,s,n))return true}}}else{if(d.length!==h.length)return false;for(let p=0;p<d.length;++p){if(!es(d[p],h[p],s,n))return false}return true}}else if(r===K.set){const d=e;const h=t;if(d.size!==h.size)return false;if(!$_(d,h)){const p=new Set(Set.prototype.values.call(h));for(const m of Set.prototype.values.call(d)){if(p.delete(m))continue;let y=false;for(const w of p){if(es(m,w,s,n)){p.delete(w);y=true;break}}if(!y)return false}}}else if(r===K.map){const d=e;const h=t;if(d.size!==h.size)return false;for(const[p,m]of Map.prototype.entries.call(d)){if(m===void 0&&!Map.prototype.has.call(h,p))return false;if(!es(m,Map.prototype.get.call(h,p),s,n))return false}}else if(r===K.error){if(e.name!==t.name||e.message!==t.message)return false}const c=Jg(e);const l=Jg(t);if((e!==c||t!==l)&&!es(c,l,s,n))return false;const u=Object.keys(e);if(!s.part&&u.length!==Object.keys(t).length&&!s.skip)return false;let f=0;for(const d of u){if(s.skip&&s.skip.includes(d)){if(o[d]===void 0)++f;continue}if(!Lo(t,d))return false;if(!es(i[d],o[d],s,n))return false}if(!s.part&&u.length-f!==Object.keys(t).length)return false;if(s.symbols!==false){const d=Object.getOwnPropertySymbols(e);const h=new Set(Object.getOwnPropertySymbols(t));for(const p of d){if(!s.skip?.includes(p)){if(Lo(e,p)){if(!Lo(t,p))return false;if(!es(i[p],o[p],s,n))return false}else if(Lo(t,p)){return false}}h.delete(p)}for(const p of h){if(Lo(t,p))return false}}return true}a(F_,\"isDeepEqualObj\");var H_=new Map([[38,\"&amp;\"],[60,\"&lt;\"],[62,\"&gt;\"],[34,\"&quot;\"],[160,\"&nbsp;\"],[162,\"&cent;\"],[163,\"&pound;\"],[164,\"&curren;\"],[169,\"&copy;\"],[174,\"&reg;\"]]);var q_=(()=>{const r=new Set;for(let e=32;e<123;++e){if(e>=97||e>=65&&e<=90||e>=48&&e<=57||e===32||e===46||e===44||e===45||e===58||e===95){r.add(e)}}return r})();function z_(r){const e=H_.get(r);if(e)return e;if(r>=256)return\"&#\"+r+\";\";const t=r.toString(16).padStart(2,\"0\");return`&#x${t};`}a(z_,\"escapeHtmlChar\");function Md(r){if(!r)return\"\";let e=\"\";for(let t=0;t<r.length;++t){const s=r.charCodeAt(t);e+=q_.has(s)?r[t]:z_(s)}return e}a(Md,\"escapeHtml\");function mt(r){return r.replace(/[\\^\\$\\.\\*\\+\\-\\?\\=\\!\\:\\|\\\\\\/\\(\\)\\[\\]\\{\\}\\,]/g,\"\\\\$&\")}a(mt,\"escapeRegex\");function ts(...r){}a(ts,\"ignore\");var rs=class extends Z{static{a(this,\"SchemaException\")}};var nl=class extends rs{static{a(this,\"SchemaDefinitionException\")}constructor(){super(...arguments);this.errno=\"E_SCHEMA_DEFINITION\"}};function $n(r,e,t){const s=new nl(r||\"Unknown error\");if(typeof Error.captureStackTrace===\"function\")Error.captureStackTrace(s,e);if(t!==void 0)s.cause=t;return s}a($n,\"definitionException\");function ss(r,e){r.message=e;if(r instanceof Z)r.errMsg=e}a(ss,\"setMessage\");function g(r,...e){if(r)return;if(e.length===1&&e[0]instanceof Error)throw e[0];const t=e.filter(s=>s!==\"\").map(s=>typeof s===\"string\"?s:s instanceof Error?s.message:Po(s));throw $n(t.join(\" \"),g)}a(g,\"assert\");function Fn(r){try{return r()}catch(e){if(e instanceof Ls)throw $n(e.message,Fn,e);throw e}}a(Fn,\"definition\");var gt={messages:void 0,template:void 0,schemas:void 0};var Dd;var Bd;var G_=/^(?:[-+]\\d{2})?(?:\\d{4}(?!\\d{2}\\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\\1(?:[12]\\d|0[1-9]|3[01]))?|W(?:[0-4]\\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[1-6])))(?![T]$|[T][\\d]+Z$)(?:[T\\s](?:(?:(?:[01]\\d|2[0-3])(?:(:?)[0-5]\\d)?|24\\:?00)(?:[.,]\\d+(?!:))?)(?:\\2[0-5]\\d(?:[.,]\\d+)?)?(?:[Z]|(?:[+-])(?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?)?$/;var ns=\"1.0.0\";var is={abortEarly:true,allowUnknown:false,artifacts:false,cache:true,context:null,convert:true,dateFormat:\"iso\",errors:{escapeHtml:false,label:\"path\",language:null,render:true,stack:false,wrap:{label:'\"',array:\"[]\"}},externals:true,messages:{},nonEnumerables:false,noDefaults:false,presence:\"optional\",skipFunctions:false,stripUnknown:false,warnings:false};var H={any:Symbol.for(\"@lakutata/validation/schema\"),arraySingle:Symbol(\"arraySingle\"),deepDefault:Symbol(\"deepDefault\"),errors:Symbol(\"errors\"),literal:Symbol(\"literal\"),override:Symbol(\"override\"),parent:Symbol(\"parent\"),prefs:Symbol(\"prefs\"),ref:Symbol(\"ref\"),template:Symbol(\"template\"),values:Symbol(\"values\")};function il(r,e){return r[e]}a(il,\"symbolOf\");function re(r,e,t=\"Options\"){g(r&&typeof r===\"object\"&&!ce(r),\"Options must be of type object\");const s=Object.keys(r).filter(n=>!e.includes(n));g(s.length===0,`${t} contain unknown keys: ${s}`)}a(re,\"assertOptions\");function Mo(r){Bd=Bd||gt.schemas();const e=Bd.preferences.validate(r);if(e.error)throw $n(String([e.error.details[0].message]),Mo)}a(Mo,\"checkPreferences\");function ot(r,e,t){const s=r;const n=e;switch(t){case\"=\":return r===e;case\">\":return s>n;case\"<\":return s<n;case\">=\":return s>=n;case\"<=\":return s<=n}}a(ot,\"compare\");function Ds(r,e){return r===void 0?e:r}a(Ds,\"defaultValue\");function ol(r){return G_.test(r)}a(ol,\"isIsoDate\");function Ud(r){return typeof r===\"number\"&&!isNaN(r)}a(Ud,\"isNumber\");function tt(r){if(!r)return false;return!!(il(r,H.ref)||il(r,H.template))}a(tt,\"isResolvable\");function oe(r,e={}){const t=r?il(r,H.any):void 0;if(!t)return false;g(e.legacy||t.version===ns,\"Cannot mix different versions of validation schemas\");return true}a(oe,\"isSchema\");function Zg(r){return!!il(r,H.values)}a(Zg,\"isValues\");function Cr(r){return Number.isSafeInteger(r)&&r>=0}a(Cr,\"limit\");function Ht(r,e){Dd=Dd||gt.messages;const t=r||{};const s=e||{};const n=Object.assign({},t,s);if(s.errors&&t.errors){n.errors=Object.assign({},t.errors,s.errors);n.errors.wrap=Object.assign({},t.errors.wrap,s.errors.wrap)}if(s.messages)n.messages=Dd.compile(s.messages,t.messages);delete n[H.prefs];return n}a(Ht,\"preferences\");function os(r,e,t={}){try{return r()}catch(s){const n=s;if(n.path!==void 0){n.path=e+\".\"+n.path}else{n.path=String(e)}if(t.append)ss(n,`${n.message} (${n.path})`);throw s}}a(os,\"tryWithPath\");function al(r,e,{assert:t,message:s}){if(oe(t)){const n=t.validate(r);if(!n.error)return;return n.error.message}else if(!t(r)){return e?`${e} ${s}`:s}}a(al,\"validateArg\");function Be(r,e){for(const t of r)g(!ce(t),\"Method no longer accepts array arguments:\",e)}a(Be,\"verifyFlat\");var jd=Symbol(\"annotations\");function Qg(r){if(!this._original||typeof this._original!==\"object\")return this.details[0].message;const e=r?\"\":\"\\x1B[31m\";const t=r?\"\":\"\\x1B[41m\";const s=r?\"\":\"\\x1B[0m\";const n=G(this._original);for(let c=this.details.length-1;c>=0;--c){const l=c+1;const u=this.details[c];const f=u.path;let d=n;for(let h=0;;++h){const p=f[h];if(oe(d))d=d.clone();if(h+1<f.length&&typeof d[p]!==\"string\"){d=d[p]}else{const m=d[jd]||{errors:{},missing:{}};d[jd]=m;const y=p||u.context?.key;if(d[p]!==void 0){m.errors[y]=m.errors[y]||[];m.errors[y].push(l)}else{m.missing[y]=l}break}}}const i={key:/_\\$key\\$_([, \\d]+)_\\$end\\$_\"/g,missing:/\"_\\$miss\\$_([^|]+)\\|(\\d+)_\\$end\\$_\": \"__missing__\"/g,arrayIndex:/\\s*\"_\\$idx\\$_([, \\d]+)_\\$end\\$_\",?\\n(.*)/g,specials:/\"\\[(NaN|Symbol.*|-?Infinity|function.*|\\(.*)]\"/g};let o=K_(n,2).replace(i.key,(c,l)=>`\" ${e}[${l}]${s}`).replace(i.missing,(c,l,u)=>`${t}\"${l}\"${s}${e} [${u}]: -- missing --${s}`).replace(i.arrayIndex,(c,l,u)=>`\n${u} ${e}[${l}]${s}`).replace(i.specials,(c,l)=>l);o=`${o}\n${e}`;for(let c=0;c<this.details.length;++c){const l=c+1;o=`${o}\n[${l}] ${this.details[c].message}`}o=o+s;return o}a(Qg,\"error\");function K_(r,e){return JSON.stringify(r,W_(),e)}a(K_,\"safeStringify\");function W_(){const r=[];const e=[];const t=a((s,n)=>{if(e[0]===n)return\"[Circular ~]\";return\"[Circular ~.\"+r.slice(0,e.indexOf(n)).join(\".\")+\"]\"},\"cycleReplacer\");return function(s,n){if(e.length>0){const i=e.indexOf(this);if(~i){e.length=i+1;r.length=i+1;r[i]=s}else{e.push(this);r.push(s)}if(~e.indexOf(n))n=t.call(this,s,n)}else{e.push(n)}if(n){const i=n[jd];if(i){if(ce(n)){const o=[];for(let c=0;c<n.length;++c){if(i.errors[c])o.push(`_$idx$_${i.errors[c].sort().join(\", \")}_$end$_`);o.push(n[c])}n=o}else{const o=n;for(const c in i.errors){o[`${c}_$key$_${i.errors[c].sort().join(\", \")}_$end$_`]=o[c];o[c]=void 0}for(const c in i.missing){o[`_$miss$_${c}|${i.missing[c]}_$end$_`]=\"__missing__\"}}return n}}if(n===Infinity||n===-Infinity||Number.isNaN(n)||typeof n===\"function\"||typeof n===\"symbol\"){return\"[\"+n.toString()+\"]\"}return n}}a(W_,\"serializer\");var qt=class r extends rs{static{a(this,\"SchemaValidationException\")}constructor(e,t,s){super(e);this.errno=\"E_SCHEMA_VALIDATION\";this.statusCode=400;if(this.message!==e){this.message=e;this.errMsg=e}this._original=s;this.details=t}annotate(e){return Qg.call(this,e)}static isError(e){return e instanceof r}};var V_=1e3;var X_=new Set([\"undefined\",\"boolean\",\"number\",\"string\"]);var $d=class{static{a(this,\"List\")}constructor(){this.tail=null;this.head=null}unshift(e){e.next=null;e.prev=this.head;if(this.head)this.head.next=e;this.head=e;if(!this.tail)this.tail=e;return e}first(e){if(e===this.head)return;this._remove(e);this.unshift(e)}pop(){return this._remove(this.tail)}_remove(e){const{next:t,prev:s}=e;t.prev=s;if(s)s.next=t;if(e===this.tail)this.tail=t;e.prev=null;e.next=null;return e}};var Fd=class{static{a(this,\"Cache\")}constructor(e={}){re(e,[\"max\"]);g(e.max===void 0||e.max&&e.max>0&&isFinite(e.max),\"Invalid max cache size\");this._max=e.max||V_;this._map=new Map;this._list=new $d}get length(){return this._map.size}set(e,t){if(e!==null&&!X_.has(typeof e))return;const s=e;let n=this._map.get(s);if(n){n.value=t;this._list.first(n);return}n=this._list.unshift({key:s,value:t,next:null,prev:null});this._map.set(s,n);this._compact()}get(e){const t=this._map.get(e);if(t){this._list.first(t);return G(t.value)}}_compact(){if(this._map.size>this._max){const e=this._list.pop();this._map.delete(e.key)}}};var cl={provision(r){return new Fd(r)}};var Hd;var qd={adjust:null,in:false,iterables:null,map:null,separator:\".\",type:\"value\"};var Do=class r{static{a(this,\"Ref\")}constructor(e){g(typeof e===\"object\",\"Invalid reference construction\");re(e,[\"adjust\",\"ancestor\",\"in\",\"iterables\",\"map\",\"path\",\"render\",\"separator\",\"type\",\"depth\",\"key\",\"root\",\"display\"]);g([false,void 0].includes(e.separator)||typeof e.separator===\"string\"&&e.separator.length===1,\"Invalid separator\");g(!e.adjust||typeof e.adjust===\"function\",\"options.adjust must be a function\");g(!e.map||ce(e.map),\"options.map must be an array\");g(!e.map||!e.adjust,\"Cannot set both map and adjust options\");Object.assign(this,qd,e);g(this.type===\"value\"||this.ancestor===void 0,\"Non-value references cannot reference ancestors\");if(ce(this.map))this.map=new Map(this.map);this.depth=this.path.length;this.key=this.path.length?this.path.join(this.separator):null;this.root=this.path[0];this.updateDisplay()}resolve(e,t,s,n,i={}){g(!this.in||i.in,\"Invalid in() reference usage\");if(this.type===\"global\")return this._resolve(s.context,t,i);if(this.type===\"local\")return this._resolve(n,t,i);if(!this.ancestor)return this._resolve(e,t,i);if(this.ancestor===\"root\")return this._resolve(t.ancestors[t.ancestors.length-1],t,i);g(this.ancestor<=t.ancestors.length,\"Invalid reference exceeds the schema root:\",this.display);return this._resolve(t.ancestors[this.ancestor-1],t,i)}_resolve(e,t,s){let n;if(this.type===\"value\"&&t.mainstay.shadow&&s.shadow!==false){n=t.mainstay.shadow.get(this.absolute(t))}if(n===void 0)n=et(e,this.path,{iterables:!!this.iterables,functions:true});if(this.adjust)n=this.adjust(n);if(this.map){const i=this.map.get(n);if(i!==void 0)n=i}if(t.mainstay)t.mainstay.tracer.resolve(t,this,n);return n}toString(){return this.display}absolute(e){return[...e.path.slice(0,-this.ancestor),...this.path]}clone(){return new r(this)}describe(){const e={path:this.path};if(this.type!==\"value\")e.type=this.type;if(this.separator!==\".\")e.separator=this.separator;if(this.type===\"value\"&&this.ancestor!==1)e.ancestor=this.ancestor;if(this.map)e.map=[...this.map];if(this.adjust!==null&&this.adjust!==void 0)e.adjust=this.adjust;if(this.iterables!==null&&this.iterables!==void 0)e.iterables=this.iterables;if(this.render!==null&&this.render!==void 0)e.render=this.render;if(this.in!==false)e.in=true;return{ref:e}}updateDisplay(){const e=this.key!==null?this.key:\"\";if(this.type!==\"value\"){this.display=`ref:${this.type}:${e}`;return}if(!this.separator){this.display=`ref:${e}`;return}if(!this.ancestor){this.display=`ref:${this.separator}${e}`;return}if(this.ancestor===\"root\"){this.display=`ref:root:${e}`;return}if(this.ancestor===1){this.display=`ref:${e||\"..\"}`;return}const t=new Array(this.ancestor+1).fill(this.separator).join(\"\");this.display=`ref:${t}${e||\"\"}`}};Object.defineProperty(Do.prototype,H.ref,{value:true,writable:true,enumerable:true,configurable:true});function Y_(r,e,t={}){r=r.trim();if(t){const s=t.global===void 0?\"$\":t.global;if(s!==e&&r.startsWith(s))return{key:r.slice(s.length),type:\"global\"};const n=t.local===void 0?\"#\":t.local;if(n!==e&&r.startsWith(n))return{key:r.slice(n.length),type:\"local\"};const i=t.root===void 0?\"/\":t.root;if(i!==e&&r.startsWith(i))return{key:r.slice(i.length),type:\"value\",root:true}}return{key:r,type:\"value\"}}a(Y_,\"context\");function J_(r,e){if(!e)return[1,0];if(r[0]!==e)return[1,0];if(r[1]!==e)return[0,1];let t=2;while(r[t]===e)++t;return[t-1,t]}a(J_,\"ancestor\");function as(r,e={}){g(typeof r===\"string\",\"Invalid reference key:\",r);re(e,[\"adjust\",\"ancestor\",\"in\",\"iterables\",\"map\",\"prefix\",\"render\",\"separator\"]);g(!e.prefix||typeof e.prefix===\"object\",\"options.prefix must be of type object\");const t=Object.assign({},qd,e);delete t.prefix;const s=t.separator;const n=Y_(r,s,e.prefix);t.type=n.type;let i=n.key;if(t.type===\"value\"){if(n.root){g(!s||i[0]!==s,\"Cannot specify relative path with root prefix\");t.ancestor=\"root\";if(!i)i=null}if(s&&s===i){i=null;t.ancestor=0}else{if(t.ancestor!==void 0){g(!s||!i||i[0]!==s,\"Cannot combine prefix with ancestor option\")}else{const[o,c]=J_(i,s);if(c){i=i.slice(c);if(i===\"\")i=null}t.ancestor=o}}}t.path=s?i===null?[]:i.split(s):[i];return new Do(t)}a(as,\"create\");function rt(r){return r?!!r[H.ref]:false}a(rt,\"isRef\");function ty(r,e={}){return as(r,{...e,in:true})}a(ty,\"inRef\");function zd(r){const e=Object.assign({},qd,r);if(e.type===\"value\"&&e.ancestor===void 0)e.ancestor=1;return new Do(e)}a(zd,\"build\");var ul=0;var Z_=1;var ll=class r{static{a(this,\"Manager\")}constructor(){this.refs=[]}register(e,t){if(!e)return;const s=t===void 0?Z_:t;if(ce(e)){for(const n of e)this.register(n,s);return}if(oe(e)){for(const n of e._refs.refs){if(n.ancestor-s>=0)this.refs.push({ancestor:n.ancestor-s,root:n.root})}return}if(rt(e)&&e.type===\"value\"&&e.ancestor-s>=0){this.refs.push({ancestor:e.ancestor-s,root:e.root})}Hd=Hd||gt.template;if(Hd.isTemplate(e))this.register(e.refs(),s)}get length(){return this.refs.length}clone(){const e=new r;e.refs=G(this.refs);return e}reset(){this.refs=[]}roots(){return this.refs.filter(e=>!e.ancestor).map(e=>e.root)}};function Kd(r,e,t={}){re(t,[\"appendPath\",\"override\"]);try{return Q_(r,e,t)}catch(s){if(t.appendPath&&s.path!==void 0)ss(s,`${s.message} (${s.path})`);throw s}}a(Kd,\"schema\");function Q_(r,e,t){g(e!==void 0,\"Invalid undefined schema\");if(Array.isArray(e)){g(e.length,\"Invalid empty array schema\");if(e.length===1)e=e[0]}const s=a((n,...i)=>{if(t.override!==false)return n.valid(r.override,...i);return n.valid(...i)},\"valid\");if(sy(e))return s(r,e);if(typeof e===\"function\")return r.custom(e);g(typeof e===\"object\",\"Invalid schema content:\",typeof e);if(tt(e))return s(r,e);if(oe(e))return e;if(Array.isArray(e)){for(const n of e){if(!sy(n))return r.alternatives().try(...e)}return s(r,...e)}if(e instanceof RegExp)return r.string().regex(e);if(e instanceof Date)return s(r.date(),e);g(Object.getPrototypeOf(e)===Object.getPrototypeOf({}),\"Schema can only contain plain objects\");return r.object().keys(e)}a(Q_,\"compileSchema\");function cr(r,e){return rt(r)?r:as(r,e)}a(cr,\"ref\");function fl(r,e,t={}){re(t,[\"legacy\"]);const s=e?e[H.any]:void 0;if(s){g(t.legacy||s.version===ns,\"Cannot mix different versions of validation schemas:\",s.version,ns);return e}if(typeof e!==\"object\"||!t.legacy)return ry(r,e);const n=Gd(e);if(!n)return ry(r,e);return n.compile(n.root,e)}a(fl,\"compile\");function ry(r,e){return Kd(r,e,{appendPath:true})}a(ry,\"compileRoot\");function Gd(r){if(typeof r!==\"object\")return null;if(Array.isArray(r)){for(const s of r){const n=Gd(s);if(n)return n}return null}const e=r;const t=e[H.any];if(t)return{root:e[t.root],compile:t.compile};g(Object.getPrototypeOf(r)===Object.getPrototypeOf({}),\"Schema can only contain plain objects\");for(const s in e){const n=Gd(e[s]);if(n)return n}return null}a(Gd,\"walk\");function sy(r){return r===null||[\"boolean\",\"string\",\"number\"].includes(typeof r)}a(sy,\"simple\");function dl(r,e,t){if(t===void 0){g(e&&typeof e===\"object\",\"Missing options\");t=e;e=as(\".\")}if(Array.isArray(t))t={switch:t};re(t,[\"is\",\"not\",\"then\",\"otherwise\",\"switch\",\"break\"]);if(oe(e)){g(t.is===void 0,'\"is\" can not be used with a schema condition');g(t.not===void 0,'\"not\" can not be used with a schema condition');g(t.switch===void 0,'\"switch\" can not be used with a schema condition');return ny(r,{is:e,then:t.then,otherwise:t.otherwise,break:t.break})}g(rt(e)||typeof e===\"string\",\"Invalid condition:\",e);g(t.not===void 0||t.is===void 0,'Cannot combine \"is\" with \"not\"');if(t.switch===void 0){let n=t;if(t.not!==void 0)n={is:t.not,then:t.otherwise,otherwise:t.then,break:t.break};let i=n.is!==void 0?r.$_compile(n.is):r.$_root.invalid(null,false,0,\"\").required();g(n.then!==void 0||n.otherwise!==void 0,'options must have at least one of \"then\", \"otherwise\", or \"switch\"');g(n.break===void 0||n.then===void 0||n.otherwise===void 0,\"Cannot specify then, otherwise, and break all together\");if(t.is!==void 0&&!rt(t.is)&&!oe(t.is))i=i.required();return ny(r,{ref:cr(e),is:i,then:n.then,otherwise:n.otherwise,break:n.break})}g(Array.isArray(t.switch),'\"switch\" must be an array');g(t.is===void 0,'Cannot combine \"switch\" with \"is\"');g(t.not===void 0,'Cannot combine \"switch\" with \"not\"');g(t.then===void 0,'Cannot combine \"switch\" with \"then\"');const s={ref:cr(e),switch:[],break:t.break};for(let n=0;n<t.switch.length;++n){const i=t.switch[n];const o=n===t.switch.length-1;re(i,o?[\"is\",\"then\",\"otherwise\"]:[\"is\",\"then\"]);g(i.is!==void 0,'Switch statement missing \"is\"');g(i.then!==void 0,'Switch statement missing \"then\"');const c={is:r.$_compile(i.is),then:r.$_compile(i.then)};if(!rt(i.is)&&!oe(i.is))c.is=c.is.required();if(o){g(t.otherwise===void 0||i.otherwise===void 0,'Cannot specify \"otherwise\" inside and outside a \"switch\"');const l=t.otherwise!==void 0?t.otherwise:i.otherwise;if(l!==void 0){g(s.break===void 0,\"Cannot specify both otherwise and break\");c.otherwise=r.$_compile(l)}}s.switch.push(c)}return s}a(dl,\"when\");function ny(r,e){for(const t of[\"then\",\"otherwise\"]){if(e[t]===void 0){delete e[t]}else{e[t]=r.$_compile(e[t])}}return e}a(ny,\"conditionOf\");var Wd=Symbol(\"settings\");var cy=Symbol(\"expression\");var iy=[\"!\",\"^\",\"*\",\"/\",\"%\",\"+\",\"-\",\"<\",\"<=\",\">\",\">=\",\"==\",\"!=\",\"&&\",\"||\",\"??\"];var oy=[\"!\",\"^\",\"*\",\"/\",\"%\",\"+\",\"-\",\"<\",\"=\",\">\",\"&\",\"|\",\"?\"];var eC=[[\"^\"],[\"*\",\"/\",\"%\"],[\"+\",\"-\"],[\"<\",\"<=\",\">\",\">=\"],[\"==\",\"!=\"],[\"&&\"],[\"||\",\"??\"]];var ay=[\"!\",\"n\"];var hl={'\"':'\"',\"`\":\"`\",\"'\":\"'\",\"[\":\"]\"};var tC=/^(?:[0-9]*(\\.[0-9]*)?){1}$/;var rC=/^[\\w\\$\\#\\.\\@\\:\\{\\}]+$/;var Bo=class r{static{a(this,\"Parser\")}constructor(e,t={}){this.single=null;this._parts=null;if(!t[Wd]&&t.constants){for(const s in t.constants){const n=t.constants[s];if(n!==null&&![\"boolean\",\"number\",\"string\"].includes(typeof n)){throw new Error(`Expression constant ${s} contains invalid ${typeof n} value type`)}}}this.settings=t[Wd]?t:{[Wd]:true,constants:{},functions:{},...t};this._parse(e)}_parse(e){let t=[];let s=\"\";let n=0;let i=false;const o=a(l=>{if(n)throw new Error(\"Expression missing closing parenthesis\");const u=t.length?t[t.length-1]:null;if(!i&&!s&&!l)return;if(u&&u.type===\"reference\"&&l===\")\"){t[t.length-1]={type:\"function\",value:this._subExpression(s,u.value)};s=\"\";return}if(l===\")\"){const f=new r(s,this.settings);t.push({type:\"segment\",value:f})}else if(i){if(i===\"]\"){t.push({type:\"reference\",value:s});s=\"\";return}t.push({type:\"literal\",value:s})}else if(oy.includes(s)){if(u&&u.type===\"operator\"&&iy.includes(u.value+s)){u.value+=s}else{t.push({type:\"operator\",value:s})}}else if(s.match(tC)){t.push({type:\"constant\",value:parseFloat(s)})}else if(this.settings.constants[s]!==void 0){t.push({type:\"constant\",value:this.settings.constants[s]})}else{if(!s.match(rC))throw new Error(`Expression contains invalid token: ${s}`);t.push({type:\"reference\",value:s})}s=\"\"},\"flush\");for(const l of e){if(i){if(l===i){o();i=false}else{s+=l}}else if(n){if(l===\"(\"){s+=l;++n}else if(l===\")\"){--n;if(!n){o(l)}else{s+=l}}else{s+=l}}else if(l in hl){i=hl[l]}else if(l===\"(\"){o();++n}else if(oy.includes(l)){o();s=l;o()}else if(l!==\" \"){s+=l}else{o()}}o();t=t.map((l,u)=>{if(l.type!==\"operator\"||l.value!==\"-\"||u&&t[u-1].type!==\"operator\")return l;return{type:\"operator\",value:\"n\"}});let c=false;for(const l of t){if(l.type===\"operator\"){if(ay.includes(l.value))continue;if(!c)throw new Error(\"Expression contains an operator in invalid position\");if(!iy.includes(l.value))throw new Error(`Expression contains an unknown operator ${l.value}`)}else if(c){throw new Error(\"Expression missing expected operator\")}c=!c}if(!c)throw new Error(\"Expression contains invalid trailing operator\");if(t.length===1&&[\"reference\",\"literal\",\"constant\"].includes(t[0].type)){this.single={type:t[0].type===\"reference\"?\"reference\":\"value\",value:t[0].value}}this._parts=t.map(l=>{if(l.type===\"operator\")return ay.includes(l.value)?l:l.value;if(l.type!==\"reference\")return l.value;if(this.settings.tokenRx&&!this.settings.tokenRx.test(l.value))throw new Error(`Expression contains invalid reference ${l.value}`);if(this.settings.reference)return this.settings.reference(l.value);return nC(l.value)})}_subExpression(e,t){const s=this.settings.functions[t];if(typeof s!==\"function\")throw new Error(`Expression contains unknown function ${t}`);const n=[];if(e){let o=\"\";let c=0;let l=false;const u=a(()=>{if(!o)throw new Error(`Expression contains function ${t} with invalid arguments ${e}`);n.push(o);o=\"\"},\"flush\");for(let f=0;f<e.length;++f){const d=e[f];if(l){o+=d;if(d===l)l=false}else if(d in hl&&!c){o+=d;l=hl[d]}else if(d===\",\"&&!c){u()}else{o+=d;if(d===\"(\"){++c}else if(d===\")\"){--c}}}u()}const i=n.map(o=>new r(o,this.settings));return function(o){const c=[];for(const l of i)c.push(l.evaluate(o));return s.call(o,...c)}}evaluate(e){const t=this._parts.slice();for(let s=t.length-2;s>=0;--s){const n=t[s];if(sC(n)){const i=t[s+1];t.splice(s+1,1);const o=pl(i,e);t[s]=iC(n.value,o)}}eC.forEach(s=>{for(let n=1;n<t.length-1;){if(s.includes(t[n])){const i=t[n];const o=pl(t[n-1],e);const c=pl(t[n+1],e);t.splice(n,2);const l=oC(i,o,c);t[n-1]=l===0?0:l}else{n+=2}}});return pl(t[0],e)}};Object.defineProperty(Bo.prototype,cy,{value:true,writable:true,enumerable:true,configurable:true});function sC(r){return!!r&&r.type===\"operator\"}a(sC,\"isPrefixOperator\");function nC(r){return function(e){return e&&e[r]!==void 0?e[r]:null}}a(nC,\"reference\");function pl(r,e){if(r===null)return null;if(typeof r===\"function\")return r(e);if(r[cy])return r.evaluate(e);return r}a(pl,\"evaluatePart\");function iC(r,e){if(r===\"!\")return e?false:true;const t=-e;if(t===0)return 0;return t}a(iC,\"single\");function Vd(r){return r!==null&&r!==void 0}a(Vd,\"exists\");function oC(r,e,t){if(r===\"??\")return Vd(e)?e:t;const s=e;const n=t;if(typeof e===\"string\"||typeof t===\"string\"){if(r===\"+\")return(Vd(e)?e:\"\")+(Vd(t)?t:\"\")}else{switch(r){case\"^\":return Math.pow(s,n);case\"*\":return s*n;case\"/\":return s/n;case\"%\":return s%n;case\"+\":return s+n;case\"-\":return s-n}}switch(r){case\"<\":return s<n;case\"<=\":return s<=n;case\">\":return s>n;case\">=\":return s>=n;case\"==\":return e===t;case\"!=\":return e!==t;case\"&&\":return e&&t;case\"||\":return e||t}return null}a(oC,\"calculate\");var vt=class{static{a(this,\"Report\")}constructor(e,t,s,n,i,o,c){this.code=e;this.flags=n;this.messages=i;this.path=o.path;this.prefs=c;this.state=o;this.value=t;this.message=null;this.template=null;this.local=s||{};this.local.label=Uo(this.flags,this.state,this.prefs,this.messages);if(this.value!==void 0&&!Object.prototype.hasOwnProperty.call(this.local,\"value\"))this.local.value=this.value;if(this.path.length){const l=this.path[this.path.length-1];if(typeof l!==\"object\")this.local.key=l}}_setTemplate(e){this.template=e;if(!this.flags.label&&this.path.length===0){const t=this._template(this.template,\"root\");if(t)this.local.label=t}}toString(){if(this.message)return this.message;const e=this.code;if(!this.prefs.errors.render)return this.code;const t=this._template(this.template)||this._template(this.prefs.messages)||this._template(this.messages);if(t===void 0)return`Error code \"${e}\" is not defined, your custom type is missing the correct messages definition`;this.message=t.render(this.value,this.state,this.prefs,this.local,{errors:this.prefs.errors,messages:[this.prefs.messages,this.messages]});if(!this.prefs.errors.label)this.message=this.message.replace(/^\"\" /,\"\").trim();return this.message}_template(e,t){return qn(this.value,e,t||this.code,this.state,this.prefs)}};function Xd(r){let e=\"\";for(const t of r){if(typeof t===\"object\")continue;if(typeof t===\"string\"){if(e)e+=\".\";e+=t}else{e+=`[${t}]`}}return e}a(Xd,\"path\");function qn(r,e,t,s,n){if(!e)return;if(se.isTemplate(e))return t!==\"root\"?e:null;let i=n.errors.language;if(tt(i))i=i.resolve(r,s,n,void 0);const o=e;if(i&&o[i]){const c=o[i];if(c[t]!==void 0)return c[t];if(c[\"*\"]!==void 0)return c[\"*\"]}if(!o[t])return o[\"*\"];return o[t]}a(qn,\"template\");function Uo(r,e,t,s){const n=t.errors;if(!n.label)return\"\";if(r.label)return r.label;let i=e.path;if(n.label===\"key\"&&e.path.length>1)i=e.path.slice(-1);const o=Xd(i);if(o)return o;return qn(null,t.messages,\"root\",e,t)||s&&qn(null,s,\"root\",e,t)||\"value\"}a(Uo,\"label\");function Yd(r,e,t){if(!r)return null;const{override:s,message:n,details:i}=lr(r);if(s)return s;if(t.errors.stack)return new qt(n,i,e);const o=Error.stackTraceLimit;Error.stackTraceLimit=0;const c=new qt(n,i,e);Error.stackTraceLimit=o;return c}a(Yd,\"process\");function lr(r,e={}){let t=[];const s=[];for(const n of r){if(n instanceof Error){if(e.override!==false)return{override:n};const o=n.toString();t.push(o);s.push({message:o,type:\"override\",context:{error:n}});continue}const i=n.toString();t.push(i);s.push({message:i,path:n.path.filter(o=>typeof o!==\"object\"),type:n.code,context:n.local})}if(t.length>1)t=[...new Set(t)];return{message:t.join(\". \"),details:s}}a(lr,\"detailsOf\");var aC=new Array(1e3).join(\"\\0\");var cC=new Array(1e3).join(\"\u0001\");var lC={date:Date.prototype.toDateString,iso:Date.prototype.toISOString,string:Date.prototype.toString,time:Date.prototype.toTimeString,utc:Date.prototype.toUTCString};var uC={true:true,false:false,null:null,second:1e3,minute:60*1e3,hour:60*60*1e3,day:24*60*60*1e3};var ly={if(r,e,t){return r?e:t},length(r){if(typeof r===\"string\")return r.length;if(!r||typeof r!==\"object\")return null;if(ce(r))return r.length;return Object.keys(r).length},msg(r){const[e,t,s,n,i]=this;const o=i.messages;if(!o)return\"\";const c=qn(e,o[0],r,t,s)||qn(e,o[1],r,t,s);if(!c)return\"\";return c.render(e,t,s,n,i)},number(r){if(typeof r===\"number\")return r;if(typeof r===\"string\")return parseFloat(r);if(typeof r===\"boolean\")return r?1:0;if(r instanceof Date)return r.getTime();return null}};function fC(r){return r.replace(/\\\\(\\{+)/g,(e,t)=>aC.slice(0,t.length)).replace(/\\\\(\\}+)/g,(e,t)=>cC.slice(0,t.length))}a(fC,\"encode\");function Jd(r){return r.replace(/\\u0000/g,\"{\").replace(/\\u0001/g,\"}\")}a(Jd,\"decode\");function dC(r){const e=[];let t=\"\";for(let s=0;s<r.length;++s){const n=r[s];if(n===\"{\"){let i=\"\";while(s+1<r.length&&r[s+1]===\"{\"){i+=\"{\";++s}e.push(t);t=i}else{t+=n}}e.push(t);return e}a(dC,\"split\");function Zd(r,e){if(!e)return r;if(e.length===1)return`${e}${r}${e}`;return`${e[0]}${r}${e[1]}`}a(Zd,\"wrap\");function Qd(r,e,t,s,n,i={}){const o=typeof r;const c=s&&s.errors&&s.errors.wrap||{};let l=false;if(rt(r)&&r.render){l=r.in;r=r.resolve(e,t,s,n,{in:r.in,...i})}if(r===null)return\"null\";if(o===\"string\")return Zd(r,i.arrayItems&&c.string);if(o===\"number\"||o===\"function\"||o===\"symbol\")return r.toString();if(o!==\"object\")return JSON.stringify(r);if(r instanceof Date)return se.date(r,s);if(r instanceof Map){const f=[];for(const[d,h]of r.entries())f.push(`${d.toString()} -> ${h.toString()}`);r=f}if(!ce(r))return r.toString();const u=[];for(const f of r)u.push(Qd(f,e,t,s,n,{arrayItems:true,...i}));return Zd(u.join(\", \"),!l&&c.array)}a(Qd,\"stringify\");var se=class r{static{a(this,\"Template\")}constructor(e,t){g(typeof e===\"string\",\"Template source must be a string\");g(!e.includes(\"\\0\")&&!e.includes(\"\u0001\"),\"Template source cannot contain reserved control characters\");this.source=e;this.rendered=e;this._template=null;if(t){const{functions:s,...n}=t;this._settings=Object.keys(n).length?G(n):void 0;this._functions=s;if(this._functions){g(Object.keys(this._functions).every(i=>typeof i===\"string\"),\"Functions keys must be strings\");g(Object.values(this._functions).every(i=>typeof i===\"function\"),\"Functions values must be functions\")}}else{this._settings=void 0;this._functions=void 0}this._parse()}_parse(){if(!this.source.includes(\"{\"))return;const e=fC(this.source);const t=dC(e);let s=false;const n=[];const i=t.shift();if(i)n.push(i);for(const o of t){const c=o[0]!==\"{\";const l=c?\"}\":\"}}\";const u=o.indexOf(l);if(u===-1||o[1]===\"{\"){n.push(`{${Jd(o)}`);continue}let f=o.slice(c?0:1,u);const d=f[0]===\":\";if(d)f=f.slice(1);const h=this._ref(Jd(f),{raw:c,wrapped:d});n.push(h);if(typeof h!==\"string\")s=true;const p=o.slice(u+l.length);if(p)n.push(Jd(p))}if(!s){this.rendered=n.join(\"\");return}this._template=n}static date(e,t){return lC[t.dateFormat].call(e)}describe(e={}){if(!this._settings&&e.compact)return this.source;const t={template:this.source};if(this._settings)t.options=this._settings;if(this._functions)t.functions=this._functions;return t}static build(e){return new r(e.template,e.options||e.functions?{...e.options,functions:e.functions}:void 0)}isDynamic(){return!!this._template}static isTemplate(e){return e?!!e[H.template]:false}refs(){if(!this._template)return;const e=[];for(const t of this._template){if(typeof t!==\"string\")e.push(...t.refs)}return e}resolve(e,t,s,n){if(this._template&&this._template.length===1)return this._part(this._template[0],[e,t,s,n,{}]);return this.render(e,t,s,n)}_part(e,t){if(e.ref)return e.ref.resolve(...t);return e.expression.evaluate(t)}render(e,t,s,n,i={}){if(!this.isDynamic())return this.rendered;const o=[];for(const c of this._template){if(typeof c===\"string\"){o.push(c)}else{const l=this._part(c,[e,t,s,n,i]);const u=Qd(l,e,t,s,n,i);if(u!==void 0){const f=c.raw||(i.errors&&i.errors.escapeHtml)===false?u:Md(u);o.push(Zd(f,c.wrapped&&s.errors.wrap.label))}}}return o.join(\"\")}_ref(e,{raw:t,wrapped:s}){const n=[];const i=a(c=>{const l=as(c,this._settings);n.push(l);return u=>{const f=l.resolve(...u);return f!==void 0?f:null}},\"reference\");let o;try{const c=this._functions?{...ly,...this._functions}:ly;o=new Bo(e,{reference:i,functions:c,constants:uC})}catch(c){throw $n(`Invalid template variable \"${e}\" fails due to: ${c.message}`,r.prototype._ref,c)}if(o.single){if(o.single.type===\"reference\"){const c=n[0];return{ref:c,raw:t,refs:n,wrapped:s||c.type===\"local\"&&c.key===\"label\"}}return Qd(o.single.value)}return{expression:o,raw:t,refs:n}}toString(){return this.source}};Object.defineProperty(se.prototype,H.template,{value:true,writable:true,enumerable:true,configurable:true});Object.defineProperty(se.prototype,\"isImmutable\",{value:true,writable:true,enumerable:true,configurable:true});gt.template=se;function jo(r,e){if(typeof r===\"string\"){g(!e,\"Cannot set single message string\");return new se(r)}if(se.isTemplate(r)){g(!e,\"Cannot set single message template\");return r}g(typeof r===\"object\"&&!ce(r),\"Invalid message options\");const t=e?G(e):{};for(const s in r){const n=r[s];if(s===\"root\"||se.isTemplate(n)){t[s]=n;continue}if(typeof n===\"string\"){t[s]=new se(n);continue}g(typeof n===\"object\"&&!ce(n),\"Invalid message for\",s);const i=s;t[i]=t[i]||{};const o=t[i];for(const c in n){const l=n[c];if(c===\"root\"||se.isTemplate(l)){o[c]=l;continue}g(typeof l===\"string\",\"Invalid message for\",c,\"in\",i);o[c]=new se(l)}}return t}a(jo,\"compile\");function uy(r){const e={};for(const t in r){const s=r[t];if(t===\"root\"){e.root=s;continue}if(se.isTemplate(s)){e[t]=s.describe({compact:true});continue}const n=t;const i={};e[n]=i;for(const o in s){const c=s[o];if(o===\"root\"){i.root=c;continue}i[o]=c.describe({compact:true})}}return e}a(uy,\"decompile\");function ml(r,e){if(!r)return jo(e);if(!e)return r;if(typeof e===\"string\")return new se(e);if(se.isTemplate(e))return e;const t=G(r);for(const s in e){const n=e[s];if(s===\"root\"||se.isTemplate(n)){t[s]=n;continue}if(typeof n===\"string\"){t[s]=new se(n);continue}g(typeof n===\"object\"&&!ce(n),\"Invalid message for\",s);const i=s;t[i]=t[i]||{};const o=t[i];for(const c in n){const l=n[c];if(c===\"root\"||se.isTemplate(l)){o[c]=l;continue}g(typeof l===\"string\",\"Invalid message for\",c,\"in\",i);o[c]=new se(l)}}return t}a(ml,\"merge\");gt.messages={compile:a((r,e)=>jo(r,e),\"compile\")};function yl(r,e){const t=Object.getPrototypeOf(r);const s=G(t);const n=r._assign(Object.create(s));const i=Object.assign({},e);delete i.base;const o=i;s._definition=o;const c=t._definition||{};o.messages=ml(c.messages,i.messages);o.properties=Object.assign({},c.properties,i.properties);n.type=i.type;o.flags=Object.assign({},c.flags,i.flags);const l=Object.assign({},c.terms);if(i.terms){for(const h in i.terms){const p=i.terms[h];g(n.$_terms[h]===void 0,\"Invalid term override for\",i.type,h);n.$_terms[h]=p.init;l[h]=p}}o.terms=l;if(!i.args)o.args=c.args;o.prepare=mC(i.prepare,c.prepare);if(i.coerce){if(typeof i.coerce===\"function\")i.coerce={method:i.coerce};if(i.coerce.from&&!Array.isArray(i.coerce.from))i.coerce={method:i.coerce.method,from:[].concat(i.coerce.from)}}o.coerce=pC(i.coerce,c.coerce);o.validate=yC(i.validate,c.validate);const u=Object.assign({},c.rules);if(i.rules){for(const h in i.rules){const p=i.rules[h];g(typeof p===\"object\",\"Invalid rule definition for\",i.type,h);let m=p.method;if(m===void 0){m=a(function(){return this.$_addRule(h)},\"method\")}if(m){g(!s[h],\"Rule conflict in\",i.type,h);s[h]=m}g(!u[h],\"Rule conflict in\",i.type,h);u[h]=p;if(p.alias){const y=[].concat(p.alias);for(const w of y)s[w]=p.method}if(p.args){const y=new Map;p.argsByName=y;p.args=p.args.map(w=>{if(typeof w===\"string\")w={name:w};g(!y.has(w.name),\"Duplicated argument name\",w.name);if(oe(w.assert))w.assert=w.assert.strict().label(w.name);y.set(w.name,w);return w})}}}o.rules=u;const f=Object.assign({},c.modifiers);if(i.modifiers){for(const h in i.modifiers){g(!s[h],\"Rule conflict in\",i.type,h);const p=i.modifiers[h];g(typeof p===\"function\",\"Invalid modifier definition for\",i.type,h);const m=a(function(y){return this.rule({[h]:y})},\"method\");s[h]=m;f[h]=p}}o.modifiers=f;if(i.overrides){s._super=t;n.$_super={};for(const h in i.overrides){const p=t[h];g(p,\"Cannot override missing\",h);i.overrides[h][H.parent]=p;n.$_super[h]=p.bind(n)}Object.assign(s,i.overrides)}o.cast=Object.assign({},c.cast,i.cast);const d=Object.assign({},c.manifest,i.manifest);d.build=hC(i.manifest&&i.manifest.build,c.manifest&&c.manifest.build);o.manifest=d;o.rebuild=gC(i.rebuild,c.rebuild);return n}a(yl,\"type\");function hC(r,e){if(!r||!e)return r||e;return function(t,s){return e(r(t,s),s)}}a(hC,\"build\");function pC(r,e){if(!r||!e)return r||e;return{from:r.from&&e.from?[...new Set([...r.from,...e.from])]:null,method(t,s){let n;if(!e.from||e.from.includes(typeof t)){n=e.method(t,s);if(n){if(n.errors||n.value===void 0)return n;t=n.value}}if(!r.from||r.from.includes(typeof t)){const i=r.method(t,s);if(i)return i}return n}}}a(pC,\"coerce\");function mC(r,e){if(!r||!e)return r||e;return function(t,s){const n=r(t,s);if(n){if(n.errors||n.value===void 0)return n;t=n.value}return e(t,s)||n}}a(mC,\"prepare\");function gC(r,e){if(!r||!e)return r||e;return function(t){e(t);r(t)}}a(gC,\"rebuild\");function yC(r,e){if(!r||!e)return r||e;return function(t,s){const n=e(t,s);if(n){if(n.errors&&(!Array.isArray(n.errors)||n.errors.length))return n;t=n.value}return r(t,s)||n}}a(yC,\"validate\");var eh;function rh(r){const e=r._definition;const t={type:r.type,flags:{},rules:[]};const s=t.flags;const n=t.rules;for(const i in r._flags){if(i[0]!==\"_\")s[i]=zn(r._flags[i])}if(!Object.keys(s).length)delete t.flags;if(r._preferences){const i=G(r._preferences,{shallow:[\"messages\"]});t.preferences=i;delete i[H.prefs];if(i.messages)i.messages=uy(i.messages)}if(r._valids)t.allow=r._valids.describe();if(r._invalids)t.invalid=r._invalids.describe();for(const i of r._rules){const o=e.rules[i.name];if(o.manifest===false)continue;const c={name:i.name};for(const l in e.modifiers){if(i[l]!==void 0)c[l]=zn(i[l])}if(i.args){const l={};c.args=l;for(const u in i.args){const f=i.args[u];if(u===\"options\"&&!Object.keys(f).length)continue;l[u]=zn(f,{assign:u})}if(!Object.keys(l).length)delete c.args}n.push(c)}if(!n.length)delete t.rules;for(const i in r.$_terms){if(i[0]===\"_\")continue;g(!t[i],\"Cannot describe schema due to internal name conflict with\",i);const o=r.$_terms[i];if(!o)continue;if(o instanceof Map){if(o.size)t[i]=[...o.entries()];continue}if(Zg(o)){t[i]=o.describe();continue}g(e.terms[i],\"Term\",i,\"missing configuration\");const c=e.terms[i].manifest;const l=typeof c===\"object\";const u=o;if(!u.length&&!l)continue;const f=[];for(const d of u)f.push(zn(d));if(l){const{from:d,to:h}=c.mapped;const p={};t[i]=p;for(const m of f)p[m[h]]=m[d];continue}if(c===\"single\"){g(f.length===1,\"Term\",i,\"contains more than one item\");t[i]=f[0];continue}t[i]=f}py(r.$_root,t);return t}a(rh,\"describe\");function zn(r,e={}){if(Array.isArray(r))return r.map(n=>zn(n));if(r===H.deepDefault)return{special:\"deep\"};if(typeof r!==\"object\"||r===null)return r;if(e.assign===\"options\")return G(r);if(Buffer&&Buffer.isBuffer(r))return{buffer:r.toString(\"binary\")};if(r instanceof Date)return r.toISOString();if(r instanceof Error)return r;if(r instanceof RegExp){if(e.assign===\"regex\")return r.toString();return{regex:r.toString()}}const t=r;if(t[H.literal])return{function:t.literal};if(typeof t.describe===\"function\"){const n=t.describe;if(e.assign===\"ref\")return n.call(r).ref;return n.call(r)}const s={};for(const n in t){const i=t[n];if(i===void 0)continue;s[n]=zn(i,{assign:n})}return s}a(zn,\"describeItem\");function sh(r,e){const t=new th(r);return t.parse(e)}a(sh,\"build\");var th=class{static{a(this,\"Builder\")}constructor(e){this.engine=e}parse(e){py(this.engine,e);let t=this.engine[e.type].call(this.engine)._bare();const s=t._definition;if(e.flags){for(const i in e.flags){const o=s.flags[i]&&s.flags[i].setter||i;g(typeof t[o]===\"function\",\"Invalid flag\",i,\"for type\",e.type);t=dy(t,o,this.build(e.flags[i]))}}if(e.preferences)t=t.preferences(this.build(e.preferences));if(e.allow)t=t.allow(...this.build(e.allow));if(e.invalid)t=t.invalid(...this.build(e.invalid));if(e.rules){for(const i of e.rules){g(typeof t[i.name]===\"function\",\"Invalid rule\",i.name,\"for type\",e.type);const o=[];if(i.args){const l={};for(const d in i.args)l[d]=this.build(i.args[d],{assign:d});const u=Object.keys(l);const f=s.rules[i.name].args;if(f){g(u.length<=f.length,\"Invalid number of arguments for\",e.type,i.name,\"(expected up to\",f.length,\", found\",u.length,\")\");for(const{name:d}of f)o.push(l[d])}else{g(u.length===1,\"Invalid number of arguments for\",e.type,i.name,\"(expected up to 1, found\",u.length,\")\");o.push(l[u[0]])}}t=dy(t,i.name,...o);const c={};for(const l in s.modifiers){if(i[l]!==void 0)c[l]=this.build(i[l])}if(Object.keys(c).length)t=t.rule(c)}}const n={};for(const i in e){if([\"allow\",\"flags\",\"invalid\",\"whens\",\"preferences\",\"rules\",\"type\"].includes(i))continue;g(s.terms[i],\"Term\",i,\"missing configuration\");const o=s.terms[i].manifest;if(o===\"schema\"){n[i]=e[i].map(c=>this.parse(c));continue}if(o===\"values\"){n[i]=e[i].map(c=>this.build(c));continue}if(o===\"single\"){n[i]=this.build(e[i]);continue}if(typeof o===\"object\"){const c={};n[i]=c;const l=e[i];for(const u in l){const f=l[u];c[u]=this.parse(f)}continue}n[i]=this.build(e[i])}if(e.whens)n.whens=e.whens.map(i=>this.build(i));t=s.manifest.build(t,n);t.$_temp.ruleset=false;return t}build(e,t={}){if(e===null)return null;if(Array.isArray(e))return e.map(i=>this.build(i));if(e instanceof Error)return e;if(t.assign===\"options\")return G(e);if(t.assign===\"regex\")return hy(e);if(t.assign===\"ref\")return zd(e);if(typeof e!==\"object\")return e;const s=e;if(Object.keys(s).length===1){if(s.buffer){g(Buffer,\"Buffers are not supported\");return Buffer&&Buffer.from(s.buffer,\"binary\")}if(s.function)return{[H.literal]:true,literal:s.function};if(s.override)return H.override;if(s.ref)return zd(s.ref);if(s.regex)return hy(s.regex);if(s.special){g([\"deep\"].includes(s.special),\"Unknown special value\",s.special);return H.deepDefault}if(s.value)return G(s.value)}if(s.type)return this.parse(s);if(s.template)return se.build(s);const n={};for(const i in s)n[i]=this.build(s[i],{assign:i});return n}};function dy(r,e,...t){return r[e].call(r,...t)}a(dy,\"call\");function hy(r){const e=r.lastIndexOf(\"/\");const t=r.slice(1,e);const s=r.slice(e+1);return new RegExp(t,s)}a(hy,\"regex\");function py(r,e){eh=eh||gt.schemas();r.assert(e,eh.description)}a(py,\"validate\");function nh(r=0){const e=Error.prepareStackTrace;Error.prepareStackTrace=(n,i)=>i;const t={};Error.captureStackTrace(t);const s=t.stack[r+1];Error.prepareStackTrace=e;return{filename:s.getFileName(),line:s.getLineNumber()}}a(nh,\"location\");var bC={error:1,pass:2,full:3};var SC={0:\"never used\",1:\"always error\",2:\"always pass\"};function ch(r){const e=a(function(){r._tracer=r._tracer||new oh;return r._tracer},\"trace\");r.trace=e;r.untrace=()=>{r._tracer=null}}a(ch,\"setup\");function lh(r){return r.$_setFlag(\"_tracerLocation\",nh(2))}a(lh,\"location\");var oh=class{static{a(this,\"Tracer\")}constructor(){this.name=\"lakutata\";this._schemas=new Map}_register(e){const t=this._schemas.get(e);if(t)return t.store;const s=new ah(e);const{filename:n,line:i}=e._flags._tracerLocation||nh(5);this._schemas.set(e,{filename:n,line:i,store:s});return s}_combine(e,t){for(const{store:s}of this._schemas.values())s._combine(e,t)}report(e){const t=[];for(const{filename:s,line:n,store:i}of this._schemas.values()){if(e&&e!==s)continue;const o=[];const c=[];for(const[l,u]of i._sources.entries()){if(TC(u.paths,c))continue;if(!u.entry){o.push({status:\"never reached\",paths:[...u.paths]});c.push(...u.paths);continue}for(const d of[\"valid\",\"invalid\"]){const h=l[`_${d}s`];if(!h)continue;const p=new Set(h._values);const m=new Set(h._refs);for(const{value:y,ref:w}of u[d]){p.delete(y);m.delete(w)}if(p.size||m.size){o.push({status:[...p,...[...m].map(y=>y.display)],rule:`${d}s`})}}const f=l._rules.map(d=>d.name);for(const d of[\"default\",\"failover\"]){if(l._flags[d]!==void 0)f.push(d)}for(const d of f){const h=SC[u.rule[d]||0];if(h){const p={rule:d,status:h};if(u.paths.size)p.paths=[...u.paths];o.push(p)}}}if(o.length){t.push({filename:s,line:n,missing:o,severity:\"error\",message:`Schema missing tests for ${o.map(wC).join(\", \")}`})}}return t.length?t:null}};var ah=class{static{a(this,\"Store\")}constructor(e){this.active=true;this._sources=new Map;this._combos=new Map;this._scan(e)}debug(e,t,s,n){e.mainstay.debug&&e.mainstay.debug.push({type:t,name:s,result:n,path:e.path})}entry(e,t){ih(t,{type:\"entry\"});this._record(e,s=>{s.entry=true})}filter(e,t,s,n){ih(t,{type:s,...n});this._record(e,i=>{i[s].add(n)})}log(e,t,s,n,i){ih(t,{type:s,name:n,result:i===\"full\"?\"pass\":i});this._record(e,o=>{o[s][n]=o[s][n]||0;o[s][n]|=bC[i]})}resolve(e,t,s){if(!e.mainstay.debug)return;const n={type:\"resolve\",ref:t.display,to:s,path:e.path};e.mainstay.debug.push(n)}value(e,t,s,n,i){if(!e.mainstay.debug||Ct(s,n))return;const o={type:\"value\",by:t,from:s,to:n,path:e.path};if(i)o.name=i;e.mainstay.debug.push(o)}_record(e,t){const s=this._sources.get(e);if(s){t(s);return}const n=this._combos.get(e);for(const i of n)this._record(i,t)}_scan(e,t){const s=t||[];let n=this._sources.get(e);if(!n){n={paths:new Set,entry:false,rule:{},valid:new Set,invalid:new Set};this._sources.set(e,n)}if(s.length)n.paths.add(s);const i=a((o,c)=>{const l=EC(o,c);this._scan(o,s.concat(l))},\"each\");e.$_modify({each:i,ref:false})}_combine(e,t){this._combos.set(e,t)}};function wC(r){const e=r.paths?Xd(r.paths[0])+(r.rule?\":\":\"\"):\"\";return`${e}${r.rule||\"\"} (${r.status})`}a(wC,\"message\");function EC(r,{source:e,name:t,path:s,key:n}){if(r._flags.id)return r._flags.id;if(n)return n;t=`@${t}`;if(e===\"terms\")return[t,s[Math.min(s.length-1,1)]];return t}a(EC,\"id\");function TC(r,e){for(const t of r){for(const s of e){if(Ct(t.slice(0,s.length),s))return true}}return false}a(TC,\"sub\");function ih(r,e){if(r.mainstay.debug){e.path=r.debug?[...r.path,r.debug]:r.path;r.mainstay.debug.push(e)}}a(ih,\"debug\");var bl=class r{static{a(this,\"Ids\")}constructor(){this._byId=new Map;this._byKey=new Map;this._schemaChain=false}clone(){const e=new r;e._byId=new Map(this._byId);e._byKey=new Map(this._byKey);e._schemaChain=this._schemaChain;return e}concat(e){if(e._schemaChain)this._schemaChain=true;for(const[t,s]of e._byId.entries()){g(!this._byKey.has(t),\"Schema id conflicts with existing key:\",t);this._byId.set(t,s)}for(const[t,s]of e._byKey.entries()){g(!this._byId.has(t),\"Schema key conflicts with existing id:\",t);this._byKey.set(t,s)}}fork(e,t,s){const n=this._collect(e);n.push({schema:s});const i=n.shift();let o={id:i.id,schema:t(i.schema)};g(oe(o.schema),\"adjuster function failed to return a schema\");for(const c of n)o={id:c.id,schema:xC(c.schema,o.id,o.schema)};return o.schema}labels(e,t=[]){const s=e[0];const n=this._get(s);if(!n)return[...t,...e].join(\".\");const i=e.slice(1);t=[...t,n.schema._flags.label||s];if(!i.length)return t.join(\".\");return n.schema._ids.labels(i,t)}reach(e,t=[]){const s=e[0];const n=this._get(s);g(n,\"Schema does not contain path\",[...t,...e].join(\".\"));const i=e.slice(1);if(!i.length)return n.schema;return n.schema._ids.reach(i,[...t,s])}register(e,{key:t}={}){if(!e||!oe(e))return;const s=e;if(s.$_property(\"schemaChain\")||s._ids._schemaChain)this._schemaChain=true;const n=s._flags.id;if(n){const i=this._byId.get(n);g(!i||i.schema===s,\"Cannot add different schemas with the same id:\",n);g(!this._byKey.has(n),\"Schema id conflicts with existing key:\",n);this._byId.set(n,{schema:s,id:n})}if(t){g(!this._byKey.has(t),\"Schema already contains key:\",t);g(!this._byId.has(t),\"Schema key conflicts with existing id:\",t);this._byKey.set(t,{schema:s,id:t})}}reset(){this._byId=new Map;this._byKey=new Map;this._schemaChain=false}_collect(e,t=[],s=[]){const n=e[0];const i=this._get(n);g(i,\"Schema does not contain path\",[...t,...e].join(\".\"));s=[i,...s];const o=e.slice(1);if(!o.length)return s;return i.schema._ids._collect(o,[...t,n],s)}_get(e){return this._byId.get(e)||this._byKey.get(e)}};function xC(r,e,t){const s=a((i,{key:o})=>{if(e===(i._flags.id||o))return t},\"each\");const n=uh(r,{each:s,ref:false});return n?n.$_mutateRebuild():r}a(xC,\"fork\");function uh(r,e){let t;for(const s in r._flags){if(s[0]===\"_\")continue;const n=$o(r._flags[s],{source:\"flags\",name:s},e);if(n!==void 0){t=t||r.clone();t._flags[s]=n}}for(let s=0;s<r._rules.length;++s){const n=r._rules[s];const i=$o(n.args,{source:\"rules\",name:n.name},e);if(i!==void 0){t=t||r.clone();const o=Object.assign({},n);o.args=i;t._rules[s]=o;const c=t._singleRules.get(n.name);if(c===n)t._singleRules.set(n.name,o)}}for(const s in r.$_terms){if(s[0]===\"_\")continue;const n=$o(r.$_terms[s],{source:\"terms\",name:s},e);if(n!==void 0){t=t||r.clone();t.$_terms[s]=n}}return t}a(uh,\"modifySchema\");function $o(r,e,t,s,n){const i=s||[];if(r===null||typeof r!==\"object\")return;let o;if(Array.isArray(r)){for(let l=0;l<r.length;++l){const u=e.source===\"terms\"&&e.name===\"keys\"&&r[l].key;const f=$o(r[l],e,t,[l,...i],u);if(f!==void 0){o=o||r.slice();o[l]=f}}return o}if(t.schema!==false&&oe(r)||t.ref!==false&&rt(r)){const l=t.each(r,{...e,path:i,key:n});if(l===r)return;return l}const c=r;for(const l in c){if(l[0]===\"_\")continue;const u=$o(c[l],e,t,[l,...i],n);if(u!==void 0){o=o||Object.assign({},c);o[l]=u}}return o}a($o,\"scan\");var yy=Symbol(\"value\");function by(r){if(oe(r))return{schema:r};return r}a(by,\"schemaEntry\");var fh=class{static{a(this,\"Shadow\")}constructor(){this._values=null}set(e,t,s){if(!e.length)return;if(s===\"strip\"&&typeof e[e.length-1]===\"number\")return;this._values=this._values||new Map;let n=this._values;for(let i=0;i<e.length;++i){const o=e[i];let c=n.get(o);if(!c){c=new Map;n.set(o,c)}n=c}n[yy]=t}get(e){const t=this.node(e);if(t)return t[yy]}node(e){if(!this._values)return;return et(this._values,e,{iterables:true})}override(e,t){if(!this._values)return;const s=e.slice(0,-1);const n=e[e.length-1];const i=et(this._values,s,{iterables:true});if(t){i.set(n,t);return}if(i)i.delete(n)}};var Sl=class r{static{a(this,\"State\")}constructor(e,t,s){this.path=e;this.ancestors=t;this.mainstay=s.mainstay;this.schemas=s.schemas;this.debug=null}localize(e,t=null,s=null){const n=new r(e,t,this);if(s&&n.schemas)n.schemas=[by(s),...n.schemas];return n}nest(e,t){const s=new r(this.path,this.ancestors,this);s.schemas=s.schemas&&[by(e),...s.schemas];s.debug=t;return s}shadow(e,t){this.mainstay.shadow=this.mainstay.shadow||new fh;this.mainstay.shadow.set(this.path,e,t)}snapshot(){if(this.mainstay.shadow)this._snapshot=G(this.mainstay.shadow.node(this.path));this.mainstay.snapshot()}restore(){if(this.mainstay.shadow){this.mainstay.shadow.override(this.path,this._snapshot);this._snapshot=void 0}this.mainstay.restore()}commit(){if(this.mainstay.shadow){this.mainstay.shadow.override(this.path,this._snapshot);this._snapshot=void 0}this.mainstay.commit()}};var xe=Symbol(\"fallback\");var le=Symbol(\"invalid\");var dh=Object.freeze({fastPathError:true});var _C=Symbol(\"unsupported\");var Sy=new Map([[\"any\",new Set],[\"string\",null],[\"number\",null],[\"boolean\",null],[\"date\",null],[\"object\",new Set([\"min\",\"max\",\"length\"])],[\"array\",new Set([\"items\",\"min\",\"max\",\"length\"])],[\"alternatives\",new Set]]);var CC=[\"empty\",\"cast\",\"result\",\"artifact\",\"_endedSwitch\",\"_hasPatternMatch\",\"single\",\"match\"];var vC=[\"whens\",\"externals\",\"renames\",\"dependencies\",\"_exclusions\",\"_requireds\"];var xy=new WeakSet;function Us(r){xy.add(r);return r}a(Us,\"pure\");function AC(r,e){return{original:void 0,prefs:e,schema:r,state:void 0,error:a(()=>dh,\"error\"),errorsArray:a(()=>{const t=[];t[H.errors]=true;return t},\"errorsArray\"),warn:a(()=>{throw _C},\"warn\"),message:a(()=>dh,\"message\")}}a(AC,\"fixedHelpers\");function IC(r){return!!r.errors&&(!Array.isArray(r.errors)||r.errors.length>0)}a(IC,\"hasErrors\");function OC(r){return r===dh||r instanceof vt||Array.isArray(r)&&!!r[H.errors]}a(OC,\"isRuleError\");function wy(r){return!r||r._refs.size===0}a(wy,\"withoutReferences\");function kC(r,e,t){const s=r._definition.rules[e.method];const n=s.validate;if(!n)return null;const i=e.args;return o=>{const c=n(o,t,i,e);return OC(c)?le:c}}a(kC,\"compileRule\");function PC(r,e){const t=r.$_terms;const s=t.keys;const n=t.patterns;const i=r.$_property(\"typeof\");if(!s&&!n){return m=>!m||typeof m!==i||Array.isArray(m)?le:m}const o=[];for(const m of s||[]){const y=Bs(m.schema,e);if(!y)return null;o.push({key:m.key,compiled:y})}const c=[];const l=Object.assign({},e,{abortEarly:true,_externals:false});for(const m of n||[]){if(m.matches)return null;const y=Bs(m.rule,e);if(!y)return null;if(m.regex){c.push({regex:m.regex,rule:y,fallthrough:!!m.fallthrough})}else{const w=Bs(m.schema,l);if(!w)return null;c.push({matcher:w,rule:y,fallthrough:!!m.fallthrough})}}const u=r._flags;const f=e.stripUnknown?e.stripUnknown===true?true:!!e.stripUnknown.objects:false;const d=!!(e.stripUnknown&&typeof u.unknown===\"undefined\"||e.skipFunctions);const h=!Ds(u.unknown,e.allowUnknown);const p=h&&!c.length?new Set(o.map(m=>m.key)):null;return m=>{if(!m||typeof m!==i||Array.isArray(m))return le;const y=Object.create(Object.getPrototypeOf(m));Object.assign(y,m);const w=new Set(Object.keys(y));if(p){for(const S of w){if(p.has(S))continue;if(d&&(f||typeof y[S]===\"function\"))continue;return le}}for(const{key:S,compiled:T}of o){const _=y[S];w.delete(S);const x=T(_);if(x===xe||x===le)return x;if(x===void 0&&_!==void 0){delete y[S]}else if(x!==void 0){y[S]=x}}if(w.size){for(const S of w){const T=y[S];for(const _ of c){if(_.regex){if(!_.regex.test(S))continue}else{const k=_.matcher(S);if(k===le)continue;if(k===xe)return xe}w.delete(S);const x=_.rule(T);if(x===xe||x===le)return x;y[S]=x;if(!_.fallthrough)break}}if(w.size){if(d){for(const S of w){if(f){delete y[S];w.delete(S)}else if(typeof y[S]===\"function\"){w.delete(S)}}}if(h&&w.size)return le}}return y}}a(PC,\"compileKeys\");function NC(r,e){const t=r.$_terms;const s=t.items;const n=t._inclusions;if(s.length>1||n.length!==s.length)return null;const i=n.length?Bs(n[0],e):null;if(n.length&&!i)return null;const o=[];for(const u of t.ordered){const f=Bs(u,e);if(!f)return null;o.push(f)}const c=!!r._flags.sparse;const l=!!(e.stripUnknown&&e.stripUnknown.arrays);return u=>{const f=u;let d=0;for(let h=0;h<f.length;++h){const p=f[h];if(!c&&p===void 0)return le;if(o.length){if(d<o.length){const m=o[d++](p);if(m===xe||m===le)return m;if(!c&&m===void 0)return le;f[h]=m;continue}else if(!s.length){return le}}if(i){const m=i(p);if(m===xe)return xe;if(m===le)return l?xe:le;if(!c&&m===void 0)return le;f[h]=m}}if(d<o.length)return xe;return f}}a(NC,\"compileItems\");function LC(r){if(!Sy.has(r.type))return false;if(r._cache||r._ids._schemaChain)return false;const e=r._flags;for(const n of CC){if(e[n]!==void 0)return false}if(typeof e.unknown===\"object\")return false;const t=r.$_terms;for(const n of vC){const i=t[n];if(i&&(!Array.isArray(i)||i.length))return false}if(!wy(r._valids)||!wy(r._invalids))return false;const s=Sy.get(r.type);for(const n of r._rules){if(n._resolve.length||n.warn)return false;if(n.name===\"custom\"){if(!xy.has(n.args.method))return false;continue}if(n.name===\"warning\")return false;if(s&&!s.has(n.name))return false}return true}a(LC,\"compilable\");function Bs(r,e){if(!LC(r))return null;const t=r._preferences?Ht(e,r._preferences):e;if(t.nonEnumerables||t.debug)return null;const s=r._definition;const n=r._flags;const i=AC(r,t);const o=t.convert?s.prepare:void 0;const c=t.convert?s.coerce:void 0;const l=n.presence||t.presence;const u=n.default!==void 0&&!t.noDefaults;const f=n.default===H.deepDefault;const d=r._valids;const h=r._invalids;const p=n.insensitive;const m=!!n.only;const y=!!t.convert;let w;if(r.type===\"object\"){w=PC(r,t);if(!w)return null}else if(r.type===\"alternatives\"){w=MC(r,t);if(!w)return null}else{const N=s.validate;w=N?A=>{const B=N(A,i);if(!B)return A;if(IC(B))return le;return B.value}:null}const S=[];for(const N of r._rules){const A=s.rules[N.method];if(A.convert&&y)continue;const B=r.type===\"array\"&&N.name===\"items\"?NC(r,t):kC(r,N,i);if(!B)return null;S.push(B)}const T=n.default;const _=a(()=>{if(!T)return T;if(typeof T===\"function\")return xe;if(typeof T!==\"object\")return T;if(T[H.literal])return T.literal;if(tt(T))return xe;return G(T)},\"defaulted\");const x=a(N=>N===void 0&&u?_():N,\"finalize\");const k=a(N=>{let A=N;if(o&&A!==void 0){const B=o(A,i);if(B){if(B.errors)return le;A=B.value}}if(c&&A!==void 0&&(!c.from||c.from.includes(typeof A))){const B=c.method(A,i);if(B){if(B.errors)return le;A=B.value}}if(A===void 0){if(l===\"forbidden\")return x(A);if(l===\"required\")return le;if(l===\"optional\")return f?xe:x(A)}else if(l===\"forbidden\"){return le}if(d){const B=d.get(A,null,t,p);if(B){if(y)A=B.value;return x(A)}if(m)return le}if(h&&h.get(A,null,t,p))return le;if(w){A=w(A);if(A===xe||A===le)return A}for(const B of S){A=B(A);if(A===xe||A===le)return A}return x(A)},\"node\");if(n.failover===void 0)return k;return N=>{const A=k(N);return A===le?xe:A}}a(Bs,\"compileSchema\");function MC(r,e){const t=[];for(const s of r.$_terms.matches){if(!s.schema)return null;const n=Bs(s.schema,e);if(!n)return null;t.push(n)}return s=>{for(const n of t){const i=n(s);if(i!==le)return i}return le}}a(MC,\"compileAlternatives\");var Ey=new WeakMap;function Ry(r,e){let t=Ey.get(r);if(!t){t=new WeakMap;Ey.set(r,t)}let s=t.get(e);if(s===void 0){const n=e.debug?null:Bs(r,e);s=n?DC(n):null;t.set(e,s)}return s}a(Ry,\"compiledFor\");function DC(r){return e=>{try{return r(e)}catch{return xe}}}a(DC,\"guarded\");function Ty(r){try{return Date.prototype.getTime.call(r)}catch{return void 0}}a(Ty,\"dateTime\");function hh(r,e,t,s=new Map){if(Object.is(r,e))return true;if(typeof r!==\"object\"||r===null||typeof e!==\"object\"||e===null)return false;if(r===t||e===t)return false;const n=s.get(r);if(n)return n===e;s.set(r,e);if(Object.getPrototypeOf(r)!==Object.getPrototypeOf(e))return false;if(Array.isArray(r)!==Array.isArray(e))return false;const i=Ty(r);const o=Ty(e);if(i!==void 0||o!==void 0)return i!==void 0&&o!==void 0&&Object.is(i,o);const c=Reflect.ownKeys(r);const l=Reflect.ownKeys(e);if(c.length!==l.length)return false;for(let u=0;u<l.length;++u){const f=l[u];if(c[u]!==f)return false;const d=Object.getOwnPropertyDescriptor(r,f);const h=Object.getOwnPropertyDescriptor(e,f);if(d.enumerable!==h.enumerable||d.configurable!==h.configurable||d.writable!==h.writable)return false;if(d.get!==h.get||d.set!==h.set)return false;if(\"value\"in d){const p=t!==null&&typeof t===\"object\"?t[f]:void 0;if(!hh(d.value,h.value,p,s))return false}}return true}a(hh,\"sameResult\");var ph=class{static{a(this,\"Mainstay\")}constructor(e,t,s){this.externals=[];this.warnings=[];this.tracer=e;this.debug=t;this.links=s;this.shadow=null;this.artifacts=null;this._snapshots=[]}snapshot(){this._snapshots.push({externals:this.externals.slice(),warnings:this.warnings.slice()})}restore(){const e=this._snapshots.pop();this.externals=e.externals;this.warnings=e.warnings}commit(){this._snapshots.pop()}};function mh(r,e,t){let s=is;if(t){g(t.warnings===void 0,\"Cannot override warnings preference in synchronous validation\");g(t.artifacts===void 0,\"Cannot override artifacts preference in synchronous validation\");s=Ly(t)}const n=Py(r,e,s);if(n!==xe&&n!==le&&Gn===\"on\")return{value:n};const i=Oy(r,e,s);if(Gn===\"verify\")Ny(r,n,i);g(!i.mainstay.externals.length,\"Schema with external rules must use validateAsync()\");const o={value:i.value};if(i.error)o.error=i.error;if(i.mainstay.warnings.length)o.warning=lr(i.mainstay.warnings);if(i.mainstay.debug)o.debug=i.mainstay.debug;if(i.mainstay.artifacts)o.artifacts=i.mainstay.artifacts;return o}a(mh,\"entry\");async function gh(r,e,t){let s=is;if(t)s=Ly(t);const n=Py(r,e,s);if(n!==xe&&n!==le&&Gn===\"on\"){if(!s.warnings&&!s.debug&&!s.artifacts)return n;return{value:n}}const i=Oy(r,e,s);if(Gn===\"verify\")Ny(r,n,i);const o=i.mainstay;if(i.error){if(o.debug)i.error.debug=o.debug;throw i.error}if(o.externals.length){let l=i.value;const u=[];for(const f of o.externals){const d=f.state.path;const h=f.schema.type===\"link\"?o.links.get(f.schema):null;let p=l;let m;let y;const w=d.length?[l]:[];const S=d.length?et(r,d):r;if(d.length){m=d[d.length-1];let T=l;for(const _ of d.slice(0,-1)){T=T[_];w.unshift(T)}y=w[0];p=y[m]}try{const T=a((x,k)=>(h||f.schema).$_createError(x,p,k,f.state,s),\"createError\");const _=await f.method(p,{schema:f.schema,linked:h,state:f.state,prefs:t,original:S,error:T,errorsArray:My,warn:a((x,k)=>{o.warnings.push((h||f.schema).$_createError(x,p,k,f.state,s))},\"warn\"),message:a((x,k)=>(h||f.schema).$_createError(\"external\",p,k,f.state,s,{messages:x}),\"message\")});if(_===void 0||_===p)continue;if(_ instanceof vt){o.tracer.log(f.schema,f.state,\"rule\",\"external\",\"error\");u.push(_);if(s.abortEarly)break;continue}if(Array.isArray(_)&&_[H.errors]){o.tracer.log(f.schema,f.state,\"rule\",\"external\",\"error\");u.push(..._);if(s.abortEarly)break;continue}if(y){o.tracer.value(f.state,\"rule\",p,_,\"external\");y[m]=_}else{o.tracer.value(f.state,\"rule\",l,_,\"external\");l=_}}catch(T){if(s.errors.label)ss(T,`${T.message} (${f.label})`);throw T}}i.value=l;if(u.length){i.error=Yd(u,r,s);if(o.debug)i.error.debug=o.debug;throw i.error}}if(!s.warnings&&!s.debug&&!s.artifacts)return i.value;const c={value:i.value};if(o.warnings.length)c.warning=lr(o.warnings);if(o.debug)c.debug=o.debug;if(o.artifacts)c.artifacts=o.artifacts;return c}a(gh,\"entryAsync\");function Iy(r,e){if(e.isAsync())return gh(r,e);return mh(r,e)}a(Iy,\"standard\");function Oy(r,e,t){const{tracer:s,cleanup:n}=BC(e,t);const i=t.debug?[]:null;const o=e._ids._schemaChain?new Map:null;const c=new ph(s,i,o);const l=e._ids._schemaChain?[{schema:e}]:null;const u=new Sl([],[],{mainstay:c,schemas:l});const f=wl(r,e,u,t);if(n)e.$_root.untrace();const d=Yd(f.errors,r,t);return{value:f.value,error:d,mainstay:c}}a(Oy,\"validateEntry\");function BC(r,e){if(r.$_root._tracer)return{tracer:r.$_root._tracer._register(r)};if(e.debug){g(r.$_root.trace,\"Debug mode not supported\");return{tracer:r.$_root.trace()._register(r),cleanup:true}}return{tracer:qC}}a(BC,\"tracerOf\");function wl(r,e,t,s,n={}){if(e.$_terms.whens)e=e._generate(r,t,s).schema;if(e._preferences)s=$C(e,s);if(e._cache&&s.cache){const d=e._cache.get(r);t.mainstay.tracer.debug(t,\"validate\",\"cached\",!!d);if(d)return d}const i=a((d,h,p)=>e.$_createError(d,r,h,p||t,s),\"createError\");const o={original:r,prefs:s,schema:e,state:t,error:i,errorsArray:My,warn:a((d,h,p)=>{t.mainstay.warnings.push(i(d,h,p))},\"warn\"),message:a((d,h)=>e.$_createError(\"custom\",r,h,t,s,{messages:d}),\"message\")};t.mainstay.tracer.entry(e,t);const c=e._definition;if(c.prepare&&r!==void 0&&s.convert){const d=c.prepare(r,o);if(d){t.mainstay.tracer.value(t,\"prepare\",r,d.value);if(d.errors)return at(d.value,[].concat(d.errors),o);r=d.value}}if(c.coerce&&r!==void 0&&s.convert&&(!c.coerce.from||c.coerce.from.includes(typeof r))){const d=c.coerce.method(r,o);if(d){t.mainstay.tracer.value(t,\"coerced\",r,d.value);if(d.errors)return at(d.value,[].concat(d.errors),o);r=d.value}}const l=e._flags.empty;if(l&&l.$_match(HC(r,e),t.nest(l),is)){t.mainstay.tracer.value(t,\"empty\",r,void 0);r=void 0}const u=n.presence||e._flags.presence||(e._flags._endedSwitch?null:s.presence);if(r===void 0){if(u===\"forbidden\")return at(r,null,o);if(u===\"required\")return at(r,[e.$_createError(\"any.required\",r,null,t,s)],o);if(u===\"optional\"){if(e._flags.default!==H.deepDefault)return at(r,null,o);t.mainstay.tracer.value(t,\"default\",r,{});r={}}}else if(u===\"forbidden\"){return at(r,[e.$_createError(\"any.unknown\",r,null,t,s)],o)}const f=[];if(e._valids){const d=e._valids.get(r,t,s,e._flags.insensitive);if(d){if(s.convert){t.mainstay.tracer.value(t,\"valids\",r,d.value);r=d.value}t.mainstay.tracer.filter(e,t,\"valid\",d);return at(r,null,o)}if(e._flags.only){const h=e.$_createError(\"any.only\",r,{valids:e._valids.values({display:true})},t,s);if(s.abortEarly)return at(r,[h],o);f.push(h)}}if(e._invalids){const d=e._invalids.get(r,t,s,e._flags.insensitive);if(d){t.mainstay.tracer.filter(e,t,\"invalid\",d);const h=e.$_createError(\"any.invalid\",r,{invalids:e._invalids.values({display:true})},t,s);if(s.abortEarly)return at(r,[h],o);f.push(h)}}if(c.validate){const d=c.validate(r,o);if(d){t.mainstay.tracer.value(t,\"base\",r,d.value);r=d.value;if(d.errors){if(!Array.isArray(d.errors)){f.push(d.errors);return at(r,f,o)}if(d.errors.length){f.push(...d.errors);return at(r,f,o)}}}}if(!e._rules.length)return at(r,f,o);return UC(r,f,o)}a(wl,\"validate\");function UC(r,e,t){const{schema:s,state:n,prefs:i}=t;for(const o of s._rules){const c=s._definition.rules[o.method];if(c.convert&&i.convert){n.mainstay.tracer.log(s,n,\"rule\",o.name,\"full\");continue}let l;let u=o.args;if(o._resolve.length){u=Object.assign({},u);for(const d of o._resolve){const h=c.argsByName.get(d);const p=u[d].resolve(r,n,i);const m=h.normalize?h.normalize(p):p;const y=al(m,void 0,h);if(y){l=s.$_createError(\"any.ref\",p,{arg:d,ref:u[d],reason:y},n,i);break}u[d]=m}}l=l||c.validate(r,t,u,o);const f=jC(l,o);if(f.errors){n.mainstay.tracer.log(s,n,\"rule\",o.name,\"error\");if(o.warn){n.mainstay.warnings.push(...f.errors);continue}if(i.abortEarly)return at(r,f.errors,t);e.push(...f.errors)}else{n.mainstay.tracer.log(s,n,\"rule\",o.name,\"pass\");n.mainstay.tracer.value(n,\"rule\",r,f.value,o.name);r=f.value}}return at(r,e,t)}a(UC,\"rules\");function jC(r,e){if(r instanceof vt){_y(r,e);return{errors:[r],value:null}}if(Array.isArray(r)&&r[H.errors]){r.forEach(t=>_y(t,e));return{errors:r,value:null}}return{errors:null,value:r}}a(jC,\"ruleResult\");function _y(r,e){if(e.message)r._setTemplate(e.message);return r}a(_y,\"error\");function at(r,e,t){e=e||[];const{schema:s,state:n,prefs:i}=t;if(e.length){const l=Ay(\"failover\",void 0,e,t);if(l!==void 0){n.mainstay.tracer.value(n,\"failover\",r,l);r=l;e=[]}}const o=s._flags.error;if(e.length&&o){if(typeof o===\"function\"){const l=o(e);e=Array.isArray(l)?l:[l];for(const u of e)g(u instanceof Error||u instanceof vt,\"error() must return an Error object\")}else{e=[o]}}if(r===void 0){const l=Ay(\"default\",r,e,t);n.mainstay.tracer.value(n,\"default\",r,l);r=l}if(s._flags.cast&&r!==void 0){const l=s._definition.cast[s._flags.cast];if(l.from(r)){const u=l.to(r,t);n.mainstay.tracer.value(n,\"cast\",r,u,s._flags.cast);r=u}}if(s.$_terms.externals&&i.externals&&i._externals!==false){for(const{method:l}of s.$_terms.externals)n.mainstay.externals.push({method:l,schema:s,state:n,label:Uo(s._flags,n,i,void 0)})}const c={value:r,errors:e.length?e:null};if(s._flags.result){c.value=s._flags.result===\"strip\"?void 0:t.original;n.mainstay.tracer.value(n,s._flags.result,r,c.value);n.shadow(r,s._flags.result)}if(s._cache&&i.cache!==false&&!s._refs.length)s._cache.set(t.original,c);if(r!==void 0&&!c.errors&&s._flags.artifact!==void 0){n.mainstay.artifacts=n.mainstay.artifacts||new Map;if(!n.mainstay.artifacts.has(s._flags.artifact))n.mainstay.artifacts.set(s._flags.artifact,[]);n.mainstay.artifacts.get(s._flags.artifact).push(n.path)}return c}a(at,\"finalize\");var Cy=new WeakMap;function $C(r,e){const t=r._preferences;const s=e===is;if(s&&t[H.prefs])return t[H.prefs];let n=Cy.get(t);const i=n&&n.get(e);if(i)return i;const o=Ht(e,t);if(s){t[H.prefs]=o}else{if(!n){n=new WeakMap;Cy.set(t,n)}n.set(e,o)}return o}a($C,\"prefsOf\");var vy=new WeakMap;var ky=new WeakSet([is]);var Gn=\"on\";function Py(r,e,t){if(Gn===\"off\"||e.$_root._tracer)return xe;if(Gn===\"on\"&&!ky.has(t))return xe;const s=Ry(e,t);return s?s(r):xe}a(Py,\"fastPath\");function Ny(r,e,t){if(e===xe)return;if(e===le){if(!t.error)throw new Error(\"Validation fast path mismatch: invalid for the fast path, valid for the interpreter\");return}if(t.error||!hh(e,t.value,r))throw new Error(`Validation fast path mismatch: ${t.error?t.error.message:\"different value\"}`)}a(Ny,\"verifyFastPath\");function FC(r){if(!Object.isFrozen(r)||Object.getOwnPropertySymbols(r).length)return false;for(const e of Object.keys(r)){const t=r[e];if(t!==null&&typeof t===\"object\"||typeof t===\"function\")return false}return true}a(FC,\"isImmutableOptions\");function Ly(r){const e=vy.get(r);if(e)return e;const t=Ht(is,r);if(FC(r)){vy.set(r,t);ky.add(t)}return t}a(Ly,\"entrySettings\");function Ay(r,e,t,s){const{schema:n,state:i,prefs:o}=s;const c=n._flags[r];if(o.noDefaults||c===void 0)return e;i.mainstay.tracer.log(n,i,\"rule\",r,\"full\");if(!c)return c;if(typeof c===\"function\"){const l=c.length?[G(i.ancestors[0]),s]:[];try{return c(...l)}catch(u){t.push(n.$_createError(`any.${r}`,null,{error:u},i,o));return}}if(typeof c!==\"object\")return c;if(c[H.literal])return c.literal;if(tt(c))return c.resolve(e,i,o);return G(c)}a(Ay,\"defaultValue\");function HC(r,e){if(typeof r!==\"string\")return r;const t=e.$_getRule(\"trim\");if(!t||!t.args.enabled)return r;return r.trim()}a(HC,\"trim\");var qC={active:false,debug:ts,entry:ts,filter:ts,log:ts,resolve:ts,value:ts};function My(){const r=[];r[H.errors]=true;return r}a(My,\"errorsArray\");function GC(r){const e=new Map;if(r){for(const t of r){if(typeof t===\"string\")e.set(t.toLowerCase(),t)}}return e}a(GC,\"lowercases\");var zt=class r{static{a(this,\"Values\")}constructor(e,t){this._values=new Set(e);this._refs=new Set(t);this._lowercase=GC(e);this._override=false}get length(){return this._values.size+this._refs.size}add(e,t){if(tt(e)){if(!this._refs.has(e)){this._refs.add(e);if(t)t.register(e)}return}if(!this.has(e,null,null,false)){this._values.add(e);if(typeof e===\"string\")this._lowercase.set(e.toLowerCase(),e)}}static merge(e,t,s){const n=e||new r;if(t){if(t._override)return t.clone();for(const i of[...t._values,...t._refs])n.add(i)}if(s){for(const i of[...s._values,...s._refs])n.remove(i)}return n.length?n:null}remove(e){if(tt(e)){this._refs.delete(e);return}this._values.delete(e);if(typeof e===\"string\")this._lowercase.delete(e.toLowerCase())}has(e,t,s,n){return!!this.get(e,t,s,n)}get(e,t,s,n){if(!this.length)return false;if(this._values.has(e))return{value:e};if(typeof e===\"string\"&&e&&n){const i=this._lowercase.get(e.toLowerCase());if(i)return{value:i}}if(!this._refs.size&&typeof e!==\"object\")return false;if(typeof e===\"object\"){for(const i of this._values){if(Ct(i,e))return{value:i}}}if(t){for(const i of this._refs){const o=i.resolve(e,t,s,null,{in:true});if(o===void 0)continue;const c=!i.in||typeof o!==\"object\"?[o]:ce(o)?o:Object.keys(o);for(const l of c){if(typeof l!==typeof e)continue;if(n&&e&&typeof e===\"string\"){if(l.toLowerCase()===e.toLowerCase())return{value:l,ref:i}}else{if(Ct(l,e))return{value:l,ref:i}}}}}return false}override(){this._override=true}values(e){if(e&&e.display){const t=[];for(const s of[...this._values,...this._refs]){if(s!==void 0)t.push(s)}return t}return Array.from([...this._values,...this._refs])}clone(){const e=new r(this._values,this._refs);e._override=this._override;return e}slice(){return this.clone()}concat(e){g(!e._override,\"Cannot concat override set of values\");const t=new r([...this._values,...e._values],[...this._refs,...e._refs]);t._override=this._override;return t}describe(){const e=[];if(this._override)e.push({override:true});for(const t of this._values.values())e.push(t&&typeof t===\"object\"?{value:t}:t);for(const t of this._refs.values())e.push(t.describe());return e}};Object.defineProperty(zt.prototype,H.values,{value:true,writable:true,enumerable:true,configurable:true});var Dy=new WeakMap;function KC(r){let e=Dy.get(r);if(!e){e=Object.assign({},r);e.abortEarly=true;e._externals=false;Dy.set(r,e)}return e}a(KC,\"matchPreferences\");var js=class{static{a(this,\"Base\")}constructor(e){this.type=e;this.$_root=null;this._definition={};this._reset()}_reset(){this._ids=new bl;this._preferences=null;this._refs=new ll;this._cache=null;this._valids=null;this._invalids=null;this._flags={};this._rules=[];this._singleRules=new Map;this.$_terms={};this.$_temp={ruleset:null,whens:{}}}describe(){g(typeof rh===\"function\",\"Manifest functionality disabled\");return rh(this)}allow(...e){Be(e,\"allow\");return this._values(e,\"_valids\")}alter(e){g(e&&typeof e===\"object\"&&!Array.isArray(e),\"Invalid targets argument\");g(!this._inRuleset(),\"Cannot set alterations inside a ruleset\");const t=this.clone();t.$_terms.alterations=t.$_terms.alterations||[];for(const s in e){const n=e[s];g(typeof n===\"function\",\"Alteration adjuster for\",s,\"must be a function\");t.$_terms.alterations.push({target:s,adjuster:n})}t.$_temp.ruleset=false;return t}artifact(e){g(e!==void 0,\"Artifact cannot be undefined\");g(!this._cache,\"Cannot set an artifact with a rule cache\");return this.$_setFlag(\"artifact\",e)}cast(e){g(e===false||typeof e===\"string\",\"Invalid to value\");g(e===false||this._definition.cast[e],\"Type\",this.type,\"does not support casting to\",e);return this.$_setFlag(\"cast\",e===false?void 0:e)}default(e,t){return this._default(\"default\",e,t)}description(e){g(e&&typeof e===\"string\",\"Description must be a non-empty string\");return this.$_setFlag(\"description\",e)}empty(e){const t=this.clone();if(e!==void 0)e=t.$_compile(e,{override:false});return t.$_setFlag(\"empty\",e,{clone:false})}error(e){g(e,\"Missing error\");g(e instanceof Error||typeof e===\"function\",\"Must provide a valid Error object or a function\");return this.$_setFlag(\"error\",e)}example(e,t={}){g(e!==void 0,\"Missing example\");re(t,[\"override\"]);return this._inner(\"examples\",e,{single:true,override:t.override})}external(e,t){if(typeof e===\"object\"){g(!t,\"Cannot combine options with description\");t=e.description;e=e.method}g(typeof e===\"function\",\"Method must be a function\");g(t===void 0||t&&typeof t===\"string\",\"Description must be a non-empty string\");return this._inner(\"externals\",{method:e,description:t},{single:true})}failover(e,t){return this._default(\"failover\",e,t)}forbidden(){return this.presence(\"forbidden\")}id(e){if(!e)return this.$_setFlag(\"id\",void 0);g(typeof e===\"string\",\"id must be a non-empty string\");g(/^[^\\.]+$/.test(e),\"id cannot contain period character\");return this.$_setFlag(\"id\",e)}invalid(...e){return this._values(e,\"_invalids\")}label(e){g(e&&typeof e===\"string\",\"Label name must be a non-empty string\");return this.$_setFlag(\"label\",e)}meta(e){g(e!==void 0,\"Meta cannot be undefined\");return this._inner(\"metas\",e,{single:true})}note(...e){g(e.length,\"Missing notes\");for(const t of e)g(t&&typeof t===\"string\",\"Notes must be non-empty strings\");return this._inner(\"notes\",e)}only(e=true){g(typeof e===\"boolean\",\"Invalid mode:\",e);return this.$_setFlag(\"only\",e)}optional(){return this.presence(\"optional\")}prefs(e){g(e,\"Missing preferences\");g(e.context===void 0,\"Cannot override context\");g(e.externals===void 0,\"Cannot override externals\");g(e.warnings===void 0,\"Cannot override warnings\");g(e.debug===void 0,\"Cannot override debug\");Mo(e);const t=this.clone();t._preferences=Ht(t._preferences,e);return t}presence(e){g([\"optional\",\"required\",\"forbidden\"].includes(e),\"Unknown presence mode\",e);return this.$_setFlag(\"presence\",e)}raw(e=true){return this.$_setFlag(\"result\",e?\"raw\":void 0)}result(e){g([\"raw\",\"strip\"].includes(e),\"Unknown result mode\",e);return this.$_setFlag(\"result\",e)}required(){return this.presence(\"required\")}strict(e){const t=this.clone();const s=e===void 0?false:!e;t._preferences=Ht(t._preferences,{convert:s});return t}strip(e=true){return this.$_setFlag(\"result\",e?\"strip\":void 0)}tag(...e){g(e.length,\"Missing tags\");for(const t of e)g(t&&typeof t===\"string\",\"Tags must be non-empty strings\");return this._inner(\"tags\",e)}unit(e){g(e&&typeof e===\"string\",\"Unit name must be a non-empty string\");return this.$_setFlag(\"unit\",e)}valid(...e){Be(e,\"valid\");const t=this.allow(...e);t.$_setFlag(\"only\",!!t._valids,{clone:false});return t}when(e,t){const s=this.clone();if(!s.$_terms.whens)s.$_terms.whens=[];const n=dl(s,e,t);if(![\"any\",\"link\"].includes(s.type)){const i=n.is?[n]:n.switch;for(const o of i){g(!o.then||o.then.type===\"any\"||o.then.type===s.type,\"Cannot combine\",s.type,\"with\",o.then&&o.then.type);g(!o.otherwise||o.otherwise.type===\"any\"||o.otherwise.type===s.type,\"Cannot combine\",s.type,\"with\",o.otherwise&&o.otherwise.type)}}s.$_terms.whens.push(n);return s.$_mutateRebuild()}cache(e){g(!this._inRuleset(),\"Cannot set caching inside a ruleset\");g(!this._cache,\"Cannot override schema cache\");g(this._flags.artifact===void 0,\"Cannot cache a rule with an artifact\");const t=this.clone();t._cache=e||cl.provision();t.$_temp.ruleset=false;return t}clone(){const e=Object.create(Object.getPrototypeOf(this));return this._assign(e)}concat(e){g(oe(e),\"Invalid schema object\");g(this.type===\"any\"||e.type===\"any\"||e.type===this.type,\"Cannot merge type\",this.type,\"with another type:\",e.type);g(!this._inRuleset(),\"Cannot concatenate onto a schema with open ruleset\");g(!e._inRuleset(),\"Cannot concatenate a schema with open ruleset\");let t=this.clone();if(this.type===\"any\"&&e.type!==\"any\"){const s=e.clone();for(const n of Object.keys(t)){if(n!==\"type\")s[n]=t[n]}t=s}t._ids.concat(e._ids);t._refs.register(e,ul);t._preferences=t._preferences?Ht(t._preferences,e._preferences):e._preferences;t._valids=zt.merge(t._valids,e._valids,e._invalids);t._invalids=zt.merge(t._invalids,e._invalids,e._valids);for(const s of e._singleRules.keys()){if(t._singleRules.has(s)){t._rules=t._rules.filter(n=>n.keep||n.name!==s);t._singleRules.delete(s)}}for(const s of e._rules){if(!e._definition.rules[s.method].multi)t._singleRules.set(s.name,s);t._rules.push(s)}if(t._flags.empty&&e._flags.empty){t._flags.empty=t._flags.empty.concat(e._flags.empty);const s=Object.assign({},e._flags);delete s.empty;Ft(t._flags,s)}else if(e._flags.empty){t._flags.empty=e._flags.empty;const s=Object.assign({},e._flags);delete s.empty;Ft(t._flags,s)}else{Ft(t._flags,e._flags)}for(const s in e.$_terms){const n=e.$_terms[s];if(!n){if(!t.$_terms[s])t.$_terms[s]=n;continue}if(!t.$_terms[s]){t.$_terms[s]=n.slice();continue}t.$_terms[s]=t.$_terms[s].concat(n)}if(this.$_root._tracer)this.$_root._tracer._combine(t,[this,e]);return t.$_mutateRebuild()}extend(e){g(!e.base,\"Cannot extend type with another base\");return yl(this,e)}extract(e){e=Array.isArray(e)?e:e.split(\".\");return this._ids.reach(e)}fork(e,t){g(!this._inRuleset(),\"Cannot fork inside a ruleset\");let s=this;for(let n of[].concat(e)){n=Array.isArray(n)?n:n.split(\".\");s=s._ids.fork(n,t,s)}s.$_temp.ruleset=false;return s}isAsync(){if(this.$_terms.externals?.length)return true;if(this.$_terms.whens){for(const e of this.$_terms.whens){if(e.then?.isAsync())return true;if(e.otherwise?.isAsync())return true;if(e.switch){for(const t of e.switch){if(t.then?.isAsync())return true;if(t.otherwise?.isAsync())return true}}}}return false}rule(e){const t=this._definition;re(e,Object.keys(t.modifiers));g(this.$_temp.ruleset!==false,\"Cannot apply rules to empty ruleset or the last rule added does not support rule properties\");const s=this.$_temp.ruleset===null?this._rules.length-1:this.$_temp.ruleset;g(s>=0&&s<this._rules.length,\"Cannot apply rules to empty ruleset\");const n=this.clone();for(let i=s;i<n._rules.length;++i){const o=n._rules[i];const c=G(o);for(const l in e){t.modifiers[l](c,e[l]);g(c.name===o.name,\"Cannot change rule name\")}n._rules[i]=c;if(n._singleRules.get(c.name)===o)n._singleRules.set(c.name,c)}n.$_temp.ruleset=false;return n.$_mutateRebuild()}get ruleset(){g(!this._inRuleset(),\"Cannot start a new ruleset without closing the previous one\");const e=this.clone();e.$_temp.ruleset=e._rules.length;return e}get $(){return this.ruleset}tailor(e){e=[].concat(e);g(!this._inRuleset(),\"Cannot tailor inside a ruleset\");let t=this;if(this.$_terms.alterations){for(const{target:s,adjuster:n}of this.$_terms.alterations){if(e.includes(s)){t=n(t);g(oe(t),\"Alteration adjuster for\",s,\"failed to return a schema object\")}}}t=t.$_modify({each:a(s=>s.tailor(e),\"each\"),ref:false});t.$_temp.ruleset=false;return t.$_mutateRebuild()}tracer(){return lh?lh(this):this}validate(e,t){return mh(e,this,t)}validateAsync(e,t){return gh(e,this,t)}$_addRule(e){if(typeof e===\"string\")e={name:e};g(e&&typeof e===\"object\",\"Invalid options\");g(e.name&&typeof e.name===\"string\",\"Invalid rule name\");for(const o in e)g(o[0]!==\"_\",\"Cannot set private rule properties\");const t=Object.assign({},e);t._resolve=[];t.method=t.method||t.name;const s=this._definition.rules[t.method];const n=t.args;g(s,\"Unknown rule\",t.method);const i=this.clone();if(n){g(Object.keys(n).length===1||Object.keys(n).length===this._definition.rules[t.name].args.length,\"Invalid rule definition for\",this.type,t.name);for(const o in n){let c=n[o];if(s.argsByName){const l=s.argsByName.get(o);if(l.ref&&tt(c)){t._resolve.push(o);i.$_mutateRegister(c)}else{if(l.normalize){c=l.normalize(c);n[o]=c}if(l.assert){const u=al(c,o,l);g(!u,u,\"or reference\")}}}if(c===void 0){delete n[o];continue}n[o]=c}}if(!s.multi){i._ruleRemove(t.name,{clone:false});i._singleRules.set(t.name,t)}if(i.$_temp.ruleset===false)i.$_temp.ruleset=null;if(s.priority){i._rules.unshift(t)}else{i._rules.push(t)}return i}$_compile(e,t){return Kd(this.$_root,e,t)}$_createError(e,t,s,n,i,o={}){const c=o.flags!==false?this._flags:{};const l=o.messages?ml(this._definition.messages,o.messages):this._definition.messages;return new vt(e,t,s,c,l,n,i)}$_getFlag(e){return this._flags[e]}$_getRule(e){return this._singleRules.get(e)}$_mapLabels(e){e=Array.isArray(e)?e:e.split(\".\");return this._ids.labels(e)}$_match(e,t,s,n){s=KC(s);t.snapshot();const i=!wl(e,this,t,s,n).errors;t.restore();return i}$_modify(e){re(e,[\"each\",\"once\",\"ref\",\"schema\"]);return uh(this,e)||this}$_mutateRebuild(){g(!this._inRuleset(),\"Cannot add this rule inside a ruleset\");this._refs.reset();this._ids.reset();const e=a((t,{source:s,name:n,key:i})=>{const o=this._definition[s];const c=o[n]&&o[n].register;if(c!==false)this.$_mutateRegister(t,{family:c,key:i})},\"each\");this.$_modify({each:e});if(this._definition.rebuild)this._definition.rebuild(this);this.$_temp.ruleset=false;return this}$_mutateRegister(e,{family:t,key:s}={}){this._refs.register(e,t);this._ids.register(e,{key:s||void 0})}$_property(e){return this._definition.properties[e]}$_reach(e){return this._ids.reach(e)}$_rootReferences(){return this._refs.roots()}$_setFlag(e,t,s={}){g(e[0]===\"_\"||!this._inRuleset(),\"Cannot set flag inside a ruleset\");const n=this._definition.flags[e]||{};if(Ct(t,n.default))t=void 0;if(Ct(t,this._flags[e]))return this;const i=s.clone!==false?this.clone():this;if(t!==void 0){i._flags[e]=t;i.$_mutateRegister(t)}else{delete i._flags[e]}if(e[0]!==\"_\")i.$_temp.ruleset=false;return i}$_parent(e,...t){const s=this[e];return s[H.parent].call(this,...t)}$_validate(e,t,s){return wl(e,this,t,s)}_assign(e){const t=e;t.type=this.type;t.$_root=this.$_root;t.$_temp=Object.assign({},this.$_temp);t.$_temp.whens={};t._ids=this._ids.clone();t._preferences=this._preferences;t._valids=this._valids&&this._valids.clone();t._invalids=this._invalids&&this._invalids.clone();t._rules=this._rules.slice();t._singleRules=G(this._singleRules,{shallow:true});t._refs=this._refs.clone();t._flags=Object.assign({},this._flags);t._cache=null;t.$_terms={};for(const s in this.$_terms)t.$_terms[s]=this.$_terms[s]?this.$_terms[s].slice():null;t.$_super={};for(const s in this.$_super)t.$_super[s]=this._super[s].bind(t);return e}_bare(){const e=this.clone();e._reset();const t=e._definition.terms;for(const s in t){const n=t[s];e.$_terms[s]=n.init}return e.$_mutateRebuild()}_default(e,t,s={}){re(s,\"literal\");g(t!==void 0,\"Missing\",e,\"value\");g(typeof t===\"function\"||!s.literal,\"Only function value supports literal option\");if(typeof t===\"function\"&&s.literal){t={[H.literal]:true,literal:t}}const n=this.$_setFlag(e,t);return n}_generate(e,t,s){if(!this.$_terms.whens)return{schema:this};const n=[];const i=[];const o=this.$_terms.whens;for(let u=0;u<o.length;++u){const f=o[u];if(f.concat){n.push(f.concat);i.push(`${u}.concat`);continue}const d=f.ref?f.ref.resolve(e,t,s,void 0):e;const h=f.is?[f]:f.switch;const p=i.length;for(let m=0;m<h.length;++m){const{is:y,then:w,otherwise:S}=h[m];const T=`${u}${f.switch?\".\"+m:\"\"}`;if(y.$_match(d,t.nest(y,`${T}.is`),s)){if(w){const _=t.localize([...t.path,`${T}.then`],t.ancestors,t.schemas);const{schema:x,id:k}=w._generate(e,_,s);n.push(x);i.push(`${T}.then${k?`(${k})`:\"\"}`);break}}else if(S){const _=t.localize([...t.path,`${T}.otherwise`],t.ancestors,t.schemas);const{schema:x,id:k}=S._generate(e,_,s);n.push(x);i.push(`${T}.otherwise${k?`(${k})`:\"\"}`);break}}if(f.break&&i.length>p)break}const c=i.join(\", \");t.mainstay.tracer.debug(t,\"rule\",\"when\",c);if(!c)return{schema:this};if(!t.mainstay.tracer.active&&this.$_temp.whens[c])return{schema:this.$_temp.whens[c],id:c};let l=this;if(this._definition.generate)l=this._definition.generate(this,e,t,s);for(const u of n)l=l.concat(u);if(this.$_root._tracer)this.$_root._tracer._combine(l,[this,...n]);this.$_temp.whens[c]=l;return{schema:l,id:c}}_inner(e,t,s={}){g(!this._inRuleset(),`Cannot set ${e} inside a ruleset`);const n=this.clone();if(!n.$_terms[e]||s.override)n.$_terms[e]=[];const i=n.$_terms[e];if(s.single){i.push(t)}else{i.push(...t)}n.$_temp.ruleset=false;return n}_inRuleset(){return this.$_temp.ruleset!==null&&this.$_temp.ruleset!==false}_ruleRemove(e,t={}){if(!this._singleRules.has(e))return this;const s=t.clone!==false?this.clone():this;s._singleRules.delete(e);const n=[];for(let i=0;i<s._rules.length;++i){const o=s._rules[i];if(o.name===e&&!o.keep){if(s._inRuleset()&&i<s.$_temp.ruleset)--s.$_temp.ruleset;continue}n.push(o)}s._rules=n;return s}_values(e,t){Be(e,t.slice(1,-1));const s=this.clone();const n=e[0]===H.override;if(n)e=e.slice(1);if(!s[t]&&e.length){s[t]=new zt}else if(n){s[t]=e.length?new zt:null;s.$_mutateRebuild()}if(!s[t])return s;const i=s[t];if(n)i.override();for(const o of e){g(o!==void 0,\"Cannot call allow/valid/invalid with undefined\");g(o!==H.override,\"Override must be the first value\");const c=t===\"_invalids\"?\"_valids\":\"_invalids\";const l=s[c];if(l){l.remove(o);if(!l.length){g(t===\"_valids\"||!s._flags.only,\"Setting invalid value\",o,\"leaves schema rejecting all values due to previous valid rule\");s[c]=null}}i.add(o,s._refs)}return s}get\"~standard\"(){const e=a(s=>{let n;if(qt.isError(s)){n=s.details.map(({message:i,path:o})=>({message:i,path:o}))}else{n=[{message:s.message}]}return{issues:n}},\"mapToStandardError\");const t=a(s=>({value:s}),\"mapToStandardValue\");return{version:1,vendor:\"lakutata\",validate:a(s=>{const n=Iy(s,this);if(n instanceof Promise)return n.then(t,e);if(!n.error)return t(n.value);return e(n.error)},\"validate\")}}};Object.defineProperty(js.prototype,H.any,{value:{version:ns,compile:fl,root:\"$_root\"},writable:true,enumerable:true,configurable:true});Object.defineProperty(js.prototype,\"isImmutable\",{value:true,writable:true,enumerable:true,configurable:true});for(const[r,e]of[[\"deny\",\"invalid\"],[\"disallow\",\"invalid\"],[\"equal\",\"valid\"],[\"exist\",\"required\"],[\"not\",\"invalid\"],[\"options\",\"prefs\"],[\"preferences\",\"prefs\"]]){Object.defineProperty(js.prototype,r,{value:js.prototype[e],writable:true,enumerable:true,configurable:true})}var WC=new js;var By=WC;function VC(r,e,t){return r[e].call(r,t)}a(VC,\"callBuild\");var XC=By.extend({type:\"any\",flags:{only:{default:false}},terms:{alterations:{init:null},examples:{init:null},externals:{init:null},metas:{init:[]},notes:{init:[]},shared:{init:null},tags:{init:[]},whens:{init:null}},rules:{allOf:{method(...r){if(r.length===1&&Array.isArray(r[0]))r=r[0];g(r.length>0,\"Missing schemas\");const e=r.map((s,n)=>os(()=>this.$_compile(s),n,{append:true}));const t=this.$_addRule({name:\"allOf\",args:{schemas:e}});for(const s of e)t.$_mutateRegister(s);return t},validate(r,{state:e,prefs:t,errorsArray:s},{schemas:n}){for(let i=0;i<n.length;++i){const o=n[i];const c=o.$_validate(r,e.nest(o,`allOf.${i}`),t);if(c.errors){const l=s();l.push(...c.errors);return l}}return r},args:[\"schemas\"],multi:true},custom:{method(r,e){g(typeof r===\"function\",\"Method must be a function\");g(e===void 0||e&&typeof e===\"string\",\"Description must be a non-empty string\");return this.$_addRule({name:\"custom\",args:{method:r,description:e}})},validate(r,e,{method:t}){try{return t(r,e)}catch(s){return e.error(\"any.custom\",{error:s})}},args:[\"method\",\"description\"],multi:true},messages:{method(r){return this.prefs({messages:r})}},shared:{method(r){g(oe(r)&&r._flags.id,\"Schema must be a schema with an id\");const e=this.clone();e.$_terms.shared=e.$_terms.shared||[];e.$_terms.shared.push(r);e.$_mutateRegister(r);return e}},warning:{method(r,e){g(r&&typeof r===\"string\",\"Invalid warning code\");return this.$_addRule({name:\"warning\",args:{code:r,local:e},warn:true})},validate(r,e,{code:t,local:s}){return e.error(t,s)},args:[\"code\",\"local\"],multi:true}},modifiers:{keep(r,e=true){r.keep=e},message(r,e){r.message=jo(e)},warn(r,e=true){r.warn=e}},manifest:{build(r,e){for(const t in e){const s=e[t];if([\"examples\",\"externals\",\"metas\",\"notes\",\"tags\"].includes(t)){for(const n of s)r=VC(r,t.slice(0,-1),n);continue}if(t===\"alterations\"){const n={};for(const{target:i,adjuster:o}of s)n[i]=o;r=r.alter(n);continue}if(t===\"whens\"){for(const n of s){const{ref:i,is:o,not:c,then:l,otherwise:u,concat:f}=n;if(f){r=r.concat(f)}else if(i){r=r.when(i,{is:o,not:c,then:l,otherwise:u,switch:n.switch,break:n.break})}else{r=r.when(o,{then:l,otherwise:u,break:n.break})}}continue}if(t===\"shared\"){for(const n of s)r=r.shared(n)}}return r}},messages:{\"any.custom\":\"{{#label}} failed custom validation because {{#error.message}}\",\"any.default\":\"{{#label}} threw an error when running default method\",\"any.failover\":\"{{#label}} threw an error when running failover method\",\"any.invalid\":\"{{#label}} contains an invalid value\",\"any.only\":'{{#label}} must be {if(#valids.length == 1, \"\", \"one of \")}{{#valids}}',\"any.ref\":\"{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}\",\"any.required\":\"{{#label}} is required\",\"any.unknown\":\"{{#label}} is not allowed\"}});var _e=XC;var YC=_e.extend({type:\"alternatives\",flags:{match:{default:\"any\"}},terms:{matches:{init:[],register:ul}},args(r,...e){if(e.length===1){if(Array.isArray(e[0])){return r.try(...e[0])}}return r.try(...e)},validate(r,e){const{schema:t,error:s,state:n,prefs:i}=e;if(t._flags.match===\"none\"){for(let c=0;c<t.$_terms.matches.length;++c){const l=t.$_terms.matches[c];if(l.schema.$_match(r,n.nest(l.schema,`match.${c}`),i))return{errors:s(\"alternatives.none\")}}return{value:r}}if(t._flags.match){const c=[];const l=[];for(let d=0;d<t.$_terms.matches.length;++d){const h=t.$_terms.matches[d];const p=n.nest(h.schema,`match.${d}`);p.snapshot();const m=h.schema.$_validate(r,p,i);if(!m.errors){c.push(m.value);p.commit()}else{l.push(m.errors);p.restore()}}if(c.length===0){const d={details:l.map(h=>lr(h,{override:false}))};return{errors:s(\"alternatives.any\",d)}}if(t._flags.match===\"one\"){return c.length===1?{value:c[0]}:{errors:s(\"alternatives.one\")}}if(c.length!==t.$_terms.matches.length){const d={details:l.map(h=>lr(h,{override:false}))};return{errors:s(\"alternatives.all\",d)}}const u=a(d=>{return d.$_terms.matches.some(h=>{return h.schema.type===\"object\"||h.schema.type===\"alternatives\"&&u(h.schema)})},\"isAnyObj\");const f=c.every(d=>d!==null&&typeof d===\"object\"&&!Array.isArray(d));return u(t)&&f?{value:c.reduce((d,h)=>Ft(d,h,{mergeArrays:false}),Object.create(Object.getPrototypeOf(c[0])))}:{value:c[c.length-1]}}const o=[];for(let c=0;c<t.$_terms.matches.length;++c){const l=t.$_terms.matches[c];if(l.schema){const d=n.nest(l.schema,`match.${c}`);d.snapshot();const h=l.schema.$_validate(r,d,i);if(!h.errors){d.commit();return h}d.restore();o.push({schema:l.schema,reports:h.errors});continue}const u=l.ref?l.ref.resolve(r,n,i,void 0):r;const f=l.is?[l]:l.switch;for(let d=0;d<f.length;++d){const h=f[d];const{is:p,then:m,otherwise:y}=h;const w=`match.${c}${l.switch?\".\"+d:\"\"}`;if(!p.$_match(u,n.nest(p,`${w}.is`),i)){if(y){return y.$_validate(r,n.nest(y,`${w}.otherwise`),i)}}else if(m){return m.$_validate(r,n.nest(m,`${w}.then`),i)}}}return JC(o,e)},rules:{conditional:{method(r,e){g(!this._flags._endedSwitch,\"Unreachable condition\");g(!this._flags.match,\"Cannot combine match mode\",this._flags.match,\"with conditional rule\");g(e.break===void 0,\"Cannot use break option with alternatives conditional\");const t=this.clone();const s=dl(t,r,e);const n=s.is?[s]:s.switch;for(const i of n){if(i.then&&i.otherwise){t.$_setFlag(\"_endedSwitch\",true,{clone:false});break}}t.$_terms.matches.push(s);return t.$_mutateRebuild()}},match:{method(r){g([\"any\",\"one\",\"all\",\"none\"].includes(r),\"Invalid alternatives match mode\",r);if(r!==\"any\"){for(const e of this.$_terms.matches){g(e.schema,\"Cannot combine match mode\",r,\"with conditional rules\")}}return this.$_setFlag(\"match\",r)}},try:{method(...r){g(r.length,\"Missing alternative schemas\");Be(r,\"try\");g(!this._flags._endedSwitch,\"Unreachable condition\");const e=this.clone();for(const t of r){e.$_terms.matches.push({schema:e.$_compile(t)})}return e.$_mutateRebuild()}}},overrides:{label(r){const e=this.$_parent(\"label\",r);const t=a((s,n)=>{return n.path[0]!==\"is\"&&typeof s._flags.label!==\"string\"?s.label(r):void 0},\"each\");return e.$_modify({each:t,ref:false})},isAsync(){if(this.$_terms.externals?.length){return true}for(const r of this.$_terms.matches){if(r.schema?.isAsync()){return true}if(r.then?.isAsync()){return true}if(r.otherwise?.isAsync()){return true}}return false}},rebuild(r){const e=a(t=>{if(oe(t)&&t.type===\"array\"){r.$_setFlag(\"_arrayItems\",true,{clone:false})}},\"each\");r.$_modify({each:e})},manifest:{build(r,e){if(e.matches){for(const t of e.matches){const{schema:s,ref:n,is:i,not:o,then:c,otherwise:l}=t;if(s){r=r.try(s)}else if(n){r=r.conditional(n,{is:i,then:c,not:o,otherwise:l,switch:t.switch})}else{r=r.conditional(i,{then:c,otherwise:l})}}}return r}},messages:{\"alternatives.all\":\"{{#label}} does not match all of the required types\",\"alternatives.any\":\"{{#label}} does not match any of the allowed types\",\"alternatives.match\":\"{{#label}} does not match any of the allowed types\",\"alternatives.none\":\"{{#label}} matches a type which is not allowed\",\"alternatives.one\":\"{{#label}} matches more than one allowed type\",\"alternatives.types\":\"{{#label}} must be one of {{#types}}\"}});var Uy=YC;function JC(r,{error:e,state:t}){if(!r.length){return{errors:e(\"alternatives.any\")}}if(r.length===1){return{errors:r[0].reports}}const s=new Set;const n=[];for(const{reports:i,schema:o}of r){if(i.length>1){return yh(r,e)}const c=i[0];if(c instanceof vt===false){return yh(r,e)}if(c.state.path.length!==t.path.length){n.push({type:o.type,report:c});continue}if(c.code===\"any.only\"){for(const f of c.local.valids){s.add(f)}continue}const[l,u]=c.code.split(\".\");if(u!==\"base\"){n.push({type:o.type,report:c})}else if(c.code===\"object.base\"){s.add(c.local.type)}else{s.add(l)}}if(!n.length){return{errors:e(\"alternatives.types\",{types:[...s]})}}if(n.length===1){return{errors:n[0].report}}return yh(r,e)}a(JC,\"reportErrors\");function yh(r,e){const t=[];for(const s of r){t.push(...s.reports)}return{errors:e(\"alternatives.match\",lr(t,{override:false}))}}a(yh,\"unmatched\");var ZC=_e.extend({type:\"array\",flags:{single:{default:false},sparse:{default:false}},terms:{items:{init:[],manifest:\"schema\"},ordered:{init:[],manifest:\"schema\"},_exclusions:{init:[]},_inclusions:{init:[]},_requireds:{init:[]}},coerce:{from:\"object\",method(r,{schema:e,state:t,prefs:s}){if(!Array.isArray(r))return;const n=e.$_getRule(\"sort\");if(!n)return;return jy(e,r,n.args.options,t,s)}},validate(r,{schema:e,error:t}){if(!Array.isArray(r)){if(e._flags.single){const s=[r];s[H.arraySingle]=true;return{value:s}}return{errors:t(\"array.base\")}}if(!e.$_getRule(\"items\")&&!e.$_terms.externals){return}return{value:r.slice()}},rules:{has:{method(r,e={}){r=this.$_compile(r,{appendPath:true});re(e,[\"min\",\"max\"]);g(e.min===void 0||Number.isSafeInteger(e.min)&&e.min>=0,\"min must be a non-negative integer\");g(e.max===void 0||Number.isSafeInteger(e.max)&&e.max>=0,\"max must be a non-negative integer\");g(e.max===void 0||(e.min??1)<=e.max,\"min must not be greater than max\");const t=this.$_addRule({name:\"has\",args:{schema:r,options:e}});t.$_mutateRegister(r);return t},validate(r,{state:e,prefs:t,error:s},{schema:n,options:i}){const o=r;const c=n;const l=[o,...e.ancestors];const{min:u=1,max:f}=i;if(u!==1||f!==void 0){let h=0;for(let p=0;p<o.length;++p){const m=e.localize([...e.path,p],l,c);if(c.$_match(o[p],m,t))++h}if(h<u)return s(\"array.hasMin\",{min:u,count:h});if(f!==void 0&&h>f)return s(\"array.hasMax\",{max:f,count:h});return o}for(let h=0;h<o.length;++h){const p=e.localize([...e.path,h],l,c);if(c.$_match(o[h],p,t))return o}const d=c._flags.label;if(d)return s(\"array.hasKnown\",{patternLabel:d});return s(\"array.hasUnknown\",null)},args:[\"schema\",\"options\"],multi:true},items:{method(...r){Be(r,\"items\");const e=this.$_addRule(\"items\");for(let t=0;t<r.length;++t){const s=os(()=>this.$_compile(r[t]),t,{append:true});e.$_terms.items.push(s)}return e.$_mutateRebuild()},validate(r,{schema:e,error:t,state:s,prefs:n,errorsArray:i}){const o=r;const c=e.$_terms._requireds.slice();const l=e.$_terms.ordered.slice();const u=[...e.$_terms._inclusions,...c];const f=!o[H.arraySingle];delete o[H.arraySingle];const d=i();let h=o.length;for(let p=0;p<h;++p){const m=o[p];let y=false;let w=false;const S=f?p:new Number(p);const T=[...s.path,S];if(!e._flags.sparse&&m===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));if(n.abortEarly)return d;l.shift();continue}const _=[o,...s.ancestors];for(const A of e.$_terms._exclusions){if(!A.$_match(m,s.localize(T,_,A),n,{presence:\"ignore\"})){continue}d.push(t(\"array.excludes\",{pos:p,value:m},s.localize(T)));if(n.abortEarly)return d;y=true;l.shift();break}if(y)continue;if(e.$_terms.ordered.length){if(l.length){const A=l.shift();const B=A.$_validate(m,s.localize(T,_,A),n);if(!B.errors){if(A._flags.result===\"strip\"){Fo(o,p);--p;--h}else if(!e._flags.sparse&&B.value===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));if(n.abortEarly)return d;continue}else{o[p]=B.value}}else{d.push(...B.errors);if(n.abortEarly)return d}continue}else if(!e.$_terms.items.length){d.push(t(\"array.orderedLength\",{pos:p,limit:e.$_terms.ordered.length}));if(n.abortEarly)return d;break}}const x=[];let k=c.length;for(let A=0;A<k;++A){const B=s.localize(T,_,c[A]);B.snapshot();const ee=c[A].$_validate(m,B,n);x[A]=ee;if(!ee.errors){B.commit();o[p]=ee.value;w=true;Fo(c,A);if(!e._flags.sparse&&ee.value===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));if(n.abortEarly)return d}break}B.restore()}if(w)continue;const N=n.stripUnknown&&!!n.stripUnknown.arrays||false;k=u.length;for(const A of u){let B;const ee=c.indexOf(A);if(ee!==-1){B=x[ee]}else{const fe=s.localize(T,_,A);fe.snapshot();B=A.$_validate(m,fe,n);if(!B.errors){fe.commit();if(A._flags.result===\"strip\"){Fo(o,p);--p;--h}else if(!e._flags.sparse&&B.value===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));y=true}else{o[p]=B.value}w=true;break}fe.restore()}if(k===1){if(N){Fo(o,p);--p;--h;w=true;break}d.push(...B.errors);if(n.abortEarly)return d;y=true;break}}if(y)continue;if((e.$_terms._inclusions.length||e.$_terms._requireds.length)&&!w){if(N){Fo(o,p);--p;--h;continue}d.push(t(\"array.includes\",{pos:p,value:m},s.localize(T)));if(n.abortEarly)return d}}if(c.length)Hy(e,d,c,o,s,n);if(l.length){QC(e,d,l,o,s,n);if(!d.length)e0(l,o,s,n)}return d.length?d:o},priority:true,manifest:false},length:{method(r){return this.$_addRule({name:\"length\",args:{limit:r},operator:\"=\"})},validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(r.length,t,n))return r;return e.error(\"array.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"}]},max:{method(r){return this.$_addRule({name:\"max\",method:\"length\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"length\",args:{limit:r},operator:\">=\"})}},ordered:{method(...r){Be(r,\"ordered\");const e=this.$_addRule(\"items\");for(let t=0;t<r.length;++t){const s=os(()=>this.$_compile(r[t]),t,{append:true});bh(s,e);e.$_mutateRegister(s);e.$_terms.ordered.push(s)}return e.$_mutateRebuild()}},single:{method(r){const e=r===void 0?true:!!r;g(!e||!this._flags._arrayItems,\"Cannot specify single rule when array has array items\");return this.$_setFlag(\"single\",e)}},sort:{method(r={}){re(r,[\"by\",\"order\"]);const e={order:r.order||\"ascending\"};if(r.by){e.by=cr(r.by,{ancestor:0});g(!e.by.ancestor,\"Cannot sort by ancestor\")}return this.$_addRule({name:\"sort\",args:{options:e}})},validate(r,{error:e,state:t,prefs:s,schema:n},i){const o=r;const c=i.options;const{value:l,errors:u}=jy(n,o,c,t,s);if(u)return u;for(let f=0;f<o.length;++f){if(o[f]!==l[f]){return e(\"array.sort\",{order:c.order,by:c.by?c.by.key:\"value\"})}}return o},convert:true},sparse:{method(r){const e=r===void 0?true:!!r;if(this._flags.sparse===e)return this;const t=e?this.clone():this.$_addRule(\"items\");return t.$_setFlag(\"sparse\",e,{clone:false})}},unique:{method(r,e={}){g(!r||typeof r===\"function\"||typeof r===\"string\",\"comparator must be a function or a string\");re(e,[\"ignoreUndefined\",\"separator\"]);const t={name:\"unique\",args:{options:e,comparator:r}};if(r){if(typeof r===\"string\"){const s=Ds(e.separator,\".\");t.path=s?r.split(s):[r]}else{t.comparator=r}}return this.$_addRule(t)},validate(r,{state:e,error:t},{comparator:s,options:n},i){const o=r;const c=i.comparator;const l=i.path;const u={string:Object.create(null),number:Object.create(null),undefined:Object.create(null),boolean:Object.create(null),bigint:Object.create(null),object:new Map,function:new Map,custom:new Map};const f=c||Ct;const d=n.ignoreUndefined;for(let h=0;h<o.length;++h){const p=l?et(o[h],l):o[h];const m=c?u.custom:u[typeof p];g(m,\"Failed to find unique map container for type\",typeof p);if(m instanceof Map){const y=m.entries();let w;while(!(w=y.next()).done){if(f(w.value[0],p)){const S=e.localize([...e.path,h],[o,...e.ancestors]);const T={pos:h,value:o[h],dupePos:w.value[1],dupeValue:o[w.value[1]]};if(l)T.path=s;return t(\"array.unique\",T,S)}}m.set(p,h)}else{if((!d||p!==void 0)&&m[p]!==void 0){const y={pos:h,value:o[h],dupePos:m[p],dupeValue:o[m[p]]};if(l)y.path=s;const w=e.localize([...e.path,h],[o,...e.ancestors]);return t(\"array.unique\",y,w)}m[p]=h}}return o},args:[\"comparator\",\"options\"],multi:true}},overrides:{isAsync(){if(this.$_terms.externals?.length)return true;for(const r of this.$_terms.items){if(r.isAsync())return true}for(const r of this.$_terms.ordered){if(r.isAsync())return true}return false}},cast:{set:{from:Array.isArray,to(r){return new Set(r)}}},rebuild(r){r.$_terms._inclusions=[];r.$_terms._exclusions=[];r.$_terms._requireds=[];for(const e of r.$_terms.items){bh(e,r);if(e._flags.presence===\"required\"){r.$_terms._requireds.push(e)}else if(e._flags.presence===\"forbidden\"){r.$_terms._exclusions.push(e)}else{r.$_terms._inclusions.push(e)}}for(const e of r.$_terms.ordered)bh(e,r)},manifest:{build(r,e){if(e.items)r=r.items(...e.items);if(e.ordered)r=r.ordered(...e.ordered);return r}},messages:{\"array.base\":\"{{#label}} must be an array\",\"array.excludes\":\"{{#label}} contains an excluded value\",\"array.hasKnown\":\"{{#label}} does not contain at least one required match for type {:#patternLabel}\",\"array.hasMax\":\"{{#label}} must contain at most {{#max}} required matches\",\"array.hasMin\":\"{{#label}} must contain at least {{#min}} required matches\",\"array.hasUnknown\":\"{{#label}} does not contain at least one required match\",\"array.includes\":\"{{#label}} does not match any of the allowed types\",\"array.includesRequiredBoth\":\"{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)\",\"array.includesRequiredKnowns\":\"{{#label}} does not contain {{#knownMisses}}\",\"array.includesRequiredUnknowns\":\"{{#label}} does not contain {{#unknownMisses}} required value(s)\",\"array.length\":\"{{#label}} must contain {{#limit}} items\",\"array.max\":\"{{#label}} must contain less than or equal to {{#limit}} items\",\"array.min\":\"{{#label}} must contain at least {{#limit}} items\",\"array.orderedLength\":\"{{#label}} must contain at most {{#limit}} items\",\"array.sort\":\"{{#label}} must be sorted in {#order} order by {{#by}}\",\"array.sort.mismatching\":\"{{#label}} cannot be sorted due to mismatching types\",\"array.sort.unsupported\":\"{{#label}} cannot be sorted due to unsupported type {#type}\",\"array.sparse\":\"{{#label}} must not be a sparse array item\",\"array.unique\":\"{{#label}} contains a duplicate value\"}});var Fy=ZC;function Hy(r,e,t,s,n,i){const o=[];let c=0;for(const l of t){const u=l._flags.label;if(u){o.push(u)}else{++c}}if(o.length){if(c){e.push(r.$_createError(\"array.includesRequiredBoth\",s,{knownMisses:o,unknownMisses:c},n,i))}else{e.push(r.$_createError(\"array.includesRequiredKnowns\",s,{knownMisses:o},n,i))}}else{e.push(r.$_createError(\"array.includesRequiredUnknowns\",s,{unknownMisses:c},n,i))}}a(Hy,\"fillMissedErrors\");function QC(r,e,t,s,n,i){const o=[];for(const c of t){if(c._flags.presence===\"required\")o.push(c)}if(o.length)Hy(r,e,o,s,n,i)}a(QC,\"fillOrderedErrors\");function e0(r,e,t,s){const n=[];let i=true;for(let o=r.length-1;o>=0;--o){const c=r[o];const l=[e,...t.ancestors];const u=c.$_validate(void 0,t.localize(t.path,l,c),s).value;if(i){if(u===void 0)continue;i=false}n.unshift(u)}if(n.length)e.push(...n)}a(e0,\"fillDefault\");function Fo(r,e){let t=e;while(t<r.length)r[t++]=r[t];--r.length}a(Fo,\"fastSplice\");function bh(r,e){if(r.type===\"array\"||r._flags._arrayItems){g(!e._flags.single,\"Cannot specify array item with single rule enabled\");e.$_setFlag(\"_arrayItems\",true,{clone:false})}}a(bh,\"validateSingle\");function jy(r,e,t,s,n){const i=t.order===\"ascending\"?1:-1;const o=-1*i;const c=i;const l=a((u,f)=>{let d=$y(u,f,o,c);if(d!==null)return d;if(t.by){u=t.by.resolve(u,s,n,void 0);f=t.by.resolve(f,s,n,void 0)}d=$y(u,f,o,c);if(d!==null)return d;const h=typeof u;if(h!==typeof f)throw r.$_createError(\"array.sort.mismatching\",e,null,s,n);if(h!==\"number\"&&h!==\"string\"){throw r.$_createError(\"array.sort.unsupported\",e,{type:h},s,n)}if(h===\"number\")return(u-f)*i;return u<f?o:c},\"sort\");try{return{value:e.slice().sort(l)}}catch(u){return{errors:u}}}a(jy,\"sortArray\");function $y(r,e,t,s){if(r===e)return 0;if(r===void 0)return 1;if(e===void 0)return-1;if(r===null)return s;if(e===null)return t;return null}a($y,\"compareNulls\");function qy(r){return typeof r===\"boolean\"}a(qy,\"isBool\");var t0=_e.extend({type:\"boolean\",flags:{sensitive:{default:false}},terms:{falsy:{init:null,manifest:\"values\"},truthy:{init:null,manifest:\"values\"}},coerce(r,{schema:e}){if(typeof r===\"boolean\")return;if(typeof r===\"string\"){const t=r.trim();const s=e._flags.sensitive?t:t.toLowerCase();r=s===\"true\"?true:s===\"false\"?false:r}if(typeof r!==\"boolean\"){r=e.$_terms.truthy&&e.$_terms.truthy.has(r,null,null,!e._flags.sensitive)||(e.$_terms.falsy&&e.$_terms.falsy.has(r,null,null,!e._flags.sensitive)?false:r)}return{value:r}},validate(r,{error:e}){if(typeof r!==\"boolean\")return{value:r,errors:e(\"boolean.base\")}},rules:{truthy:{method(...r){Be(r,\"truthy\");const e=this.clone();e.$_terms.truthy=e.$_terms.truthy||new zt;for(let t=0;t<r.length;++t){const s=r[t];g(s!==void 0,\"Cannot call truthy with undefined\");e.$_terms.truthy.add(s)}return e}},falsy:{method(...r){Be(r,\"falsy\");const e=this.clone();e.$_terms.falsy=e.$_terms.falsy||new zt;for(let t=0;t<r.length;++t){const s=r[t];g(s!==void 0,\"Cannot call falsy with undefined\");e.$_terms.falsy.add(s)}return e}},sensitive:{method(r=true){return this.$_setFlag(\"sensitive\",r)}}},cast:{number:{from:qy,to(r){return r?1:0}},string:{from:qy,to(r){return r?\"true\":\"false\"}}},manifest:{build(r,e){if(e.truthy)r=r.truthy(...e.truthy);if(e.falsy)r=r.falsy(...e.falsy);return r}},messages:{\"boolean.base\":\"{{#label}} must be a boolean\"}});var zy=t0;function Gy(r){return r instanceof Date}a(Gy,\"isDate\");var r0=_e.extend({type:\"date\",coerce:{from:[\"number\",\"string\"],method(r,{schema:e}){return{value:Ky(r,e._flags.format)||r}}},validate(r,{schema:e,error:t,prefs:s}){if(r instanceof Date&&!isNaN(r.getTime())){return}const n=e._flags.format;if(!s.convert||!n||typeof r!==\"string\"){return{value:r,errors:t(\"date.base\")}}return{value:r,errors:t(\"date.format\",{format:n})}},rules:{compare:{method:false,validate(r,e,{date:t},{name:s,operator:n,args:i}){const o=t===\"now\"?Date.now():t.getTime();if(ot(r.getTime(),o,n))return r;return e.error(\"date.\"+s,{limit:i.date,value:r})},args:[{name:\"date\",ref:true,normalize:a(r=>{return r===\"now\"?r:Ky(r)},\"normalize\"),assert:a(r=>r!==null,\"assert\"),message:\"must have a valid date format\"}]},format:{method(r){g([\"iso\",\"javascript\",\"unix\"].includes(r),\"Unknown date format\",r);return this.$_setFlag(\"format\",r)}},greater:{method(r){return this.$_addRule({name:\"greater\",method:\"compare\",args:{date:r},operator:\">\"})}},iso:{method(){return this.format(\"iso\")}},less:{method(r){return this.$_addRule({name:\"less\",method:\"compare\",args:{date:r},operator:\"<\"})}},max:{method(r){return this.$_addRule({name:\"max\",method:\"compare\",args:{date:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"compare\",args:{date:r},operator:\">=\"})}},timestamp:{method(r=\"javascript\"){g([\"javascript\",\"unix\"].includes(r),'\"type\" must be one of \"javascript, unix\"');return this.format(r)}}},cast:{number:{from:Gy,to(r){return r.getTime()}},string:{from:Gy,to(r,{prefs:e}){return se.date(r,e)}}},messages:{\"date.base\":\"{{#label}} must be a valid date\",\"date.format\":'{{#label}} must be in {msg(\"date.format.\" + #format) || #format} format',\"date.greater\":\"{{#label}} must be greater than {{:#limit}}\",\"date.less\":\"{{#label}} must be less than {{:#limit}}\",\"date.max\":\"{{#label}} must be less than or equal to {{:#limit}}\",\"date.min\":\"{{#label}} must be greater than or equal to {{:#limit}}\",\"date.format.iso\":\"ISO 8601 date\",\"date.format.javascript\":\"timestamp or number of milliseconds\",\"date.format.unix\":\"timestamp or number of seconds\"}});var Wy=r0;function Ky(r,e){if(r instanceof Date)return r;if(typeof r!==\"string\"&&(isNaN(r)||!isFinite(r))){return null}if(/^\\s*$/.test(r))return null;if(e===\"iso\"){if(!ol(r))return null;return El(r.toString())}const t=r;if(typeof r===\"string\"&&/^[+-]?\\d+(\\.\\d+)?$/.test(r)){r=parseFloat(r)}if(e){if(e===\"javascript\")return El(1*r);if(e===\"unix\")return El(1e3*r);if(typeof t===\"string\")return null}return El(r)}a(Ky,\"parse\");function El(r){const e=new Date(r);if(!isNaN(e.getTime()))return e;return null}a(El,\"date\");function Tl(r){return[].concat(r)}a(Tl,\"toArray\");function s0(r,e){return r.sort===e.sort?0:r.sort<e.sort?-1:1}a(s0,\"mergeSort\");var xl=class{static{a(this,\"Sorter\")}constructor(){this.nodes=[];this._items=[]}add(e,t){const s=t??{};const n=Tl(s.before??[]);const i=Tl(s.after??[]);const o=s.group??\"?\";const c=s.sort??0;te(!n.includes(o),`Item cannot come before itself: ${o}`);te(!n.includes(\"?\"),\"Item cannot come before unassociated items\");te(!i.includes(o),`Item cannot come after itself: ${o}`);te(!i.includes(\"?\"),\"Item cannot come after unassociated items\");for(const l of Tl(e)){this._items.push({seq:this._items.length,sort:c,before:n,after:i,group:o,node:l})}if(!s.manual){const l=this._sort();te(l,\"item\",o!==\"?\"?`added into group ${o}`:\"\",\"created a dependencies error\")}return this.nodes}merge(e){for(const s of Tl(e)){if(s){for(const n of s._items)this._items.push({...n})}}this._items.sort(s0);for(let s=0;s<this._items.length;++s)this._items[s].seq=s;const t=this._sort();te(t,\"merge created a dependencies error\");return this.nodes}sort(){const e=this._sort();te(e,\"sort created a dependencies error\");return this.nodes}_sort(){const e={};const t=Object.create(null);const s=Object.create(null);for(const u of this._items){const f=u.seq;const d=u.group;s[d]=s[d]??[];s[d].push(f);e[f]=u.before;for(const h of u.after){t[h]=t[h]??[];t[h].push(f)}}const n={};for(const u in e){const f=[];for(const d of e[u]){s[d]=s[d]??[];f.push(...s[d])}n[u]=f}for(const u in t){if(s[u]){for(const f of s[u])n[f].push(...t[u])}}const i={};for(const u in n){for(const f of n[u]){i[f]=i[f]??[];i[f].push(u)}}const o={};const c=[];for(let u=0;u<this._items.length;++u){let f=u;if(i[u]){f=null;for(let d=0;d<this._items.length;++d){if(o[d]===true)continue;if(!i[d])i[d]=[];const h=i[d].length;let p=0;for(let m=0;m<h;++m){if(o[i[d][m]])++p}if(p===h){f=d;break}}}if(f!==null){o[f]=true;c.push(f)}}if(c.length!==this._items.length)return false;const l={};for(const u of this._items)l[u.seq]=u;this._items=[];this.nodes=[];for(const u of c){const f=l[u];this.nodes.push(f.node);this._items.push(f)}return true}};var i0={alias:false,multiple:false,override:false};var o0=_e.extend({type:\"_keys\",properties:{typeof:\"object\"},flags:{unknown:{default:void 0}},terms:{dependencies:{init:null},keys:{init:null,manifest:{mapped:{from:\"schema\",to:\"key\"}}},patterns:{init:null},renames:{init:null}},args(r,e){return r.keys(e)},validate(r,{schema:e,error:t,state:s,prefs:n}){if(!r||typeof r!==e.$_property(\"typeof\")||Array.isArray(r)){return{value:r,errors:t(\"object.base\",{type:e.$_property(\"typeof\")})}}if(!e.$_terms.renames&&!e.$_terms.dependencies&&!e.$_terms.keys&&!e.$_terms.patterns&&!e.$_terms.externals&&typeof e._flags.unknown!==\"object\"){return}const i=a0(r,n);const o=[];if(e.$_terms.renames&&!l0(e,i,s,n,o)){return{value:i,errors:o}}if(!e.$_terms.keys&&!e.$_terms.patterns&&!e.$_terms.dependencies&&typeof e._flags.unknown!==\"object\"){return{value:i,errors:o}}const c=new Set(Object.keys(i));if(e.$_terms.keys){const l=[i,...s.ancestors];for(const u of e.$_terms.keys){const f=u.key;const d=i[f];c.delete(f);const h=s.localize([...s.path,f],l,u);const p=u.schema.$_validate(d,h,n);if(p.errors){if(n.abortEarly)return{value:i,errors:p.errors};if(p.value!==void 0)i[f]=p.value;o.push(...p.errors)}else if(u.schema._flags.result===\"strip\"||p.value===void 0&&d!==void 0){delete i[f]}else if(p.value!==void 0){i[f]=p.value}}}if(c.size||e._flags._hasPatternMatch){const l=u0(e,i,c,o,s,n);if(l)return l}if(e.$_terms.dependencies){for(const l of e.$_terms.dependencies){if(l.key!==null&&fs(l.options)(l.key.resolve(i,s,n,null,{shadow:false}))===false){continue}const u=c0[l.rel](e,l,i,s,n);if(u){const f=e.$_createError(u.code,i,u.context,s,n);if(n.abortEarly)return{value:i,errors:f};o.push(f)}}}return{value:i,errors:o}},rules:{and:{method(...r){Be(r,\"and\");return us(this,\"and\",null,r)}},append:{method(r){if(r===null||r===void 0||Object.keys(r).length===0){return this}return this.keys(r)}},assert:{method(r,e,t){if(!se.isTemplate(r))r=cr(r);g(t===void 0||typeof t===\"string\",\"Message must be a string\");e=this.$_compile(e,{appendPath:true});const s=this.$_addRule({name:\"assert\",args:{subject:r,schema:e,message:t}});s.$_mutateRegister(r);s.$_mutateRegister(e);return s},validate(r,{error:e,prefs:t,state:s},{subject:n,schema:i,message:o}){const c=n.resolve(r,s,t);const l=rt(n)?n.absolute(s):[];if(i.$_match(c,s.localize(l,[r,...s.ancestors],i),t))return r;return e(\"object.assert\",{subject:n,message:o})},args:[\"subject\",\"schema\",\"message\"],multi:true},instance:{method(r,e){g(typeof r===\"function\",\"constructor must be a function\");e=e||r.name;return this.$_addRule({name:\"instance\",args:{constructor:r,name:e}})},validate(r,e,{constructor:t,name:s}){if(r instanceof t)return r;return e.error(\"object.instance\",{type:s,value:r})},args:[\"constructor\",\"name\"]},keyNames:{method(r){r=this.$_compile(r);const e=this.$_addRule({name:\"keyNames\",args:{schema:r}});e.$_mutateRegister(r);return e},validate(r,{state:e,prefs:t,error:s},{schema:n}){const i=n;const o=[r,...e.ancestors];for(const c of Object.keys(r)){const l=e.localize([...e.path,c],o,i);if(!i.$_match(c,l,t))return s(\"object.keyNames\",{name:c})}return r},args:[\"schema\"]},keys:{method(r){g(r===void 0||typeof r===\"object\",\"Object schema must be a valid object\");g(!oe(r),\"Object schema cannot be a schema object\");const e=this.clone();if(!r){e.$_terms.keys=null}else if(!Object.keys(r).length){e.$_terms.keys=new Ho}else{e.$_terms.keys=e.$_terms.keys?e.$_terms.keys.filter(t=>!Object.hasOwn(r,t.key)):new Ho;for(const t in r){os(()=>e.$_terms.keys.push({key:t,schema:this.$_compile(r[t])}),t)}}return e.$_mutateRebuild()}},length:{method(r){return this.$_addRule({name:\"length\",args:{limit:r},operator:\"=\"})},validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(Object.keys(r).length,t,n))return r;return e.error(\"object.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"}]},max:{method(r){return this.$_addRule({name:\"max\",method:\"length\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"length\",args:{limit:r},operator:\">=\"})}},nand:{method(...r){Be(r,\"nand\");return us(this,\"nand\",null,r)}},or:{method(...r){Be(r,\"or\");return us(this,\"or\",null,r)}},oxor:{method(...r){return us(this,\"oxor\",null,r)}},pattern:{method(r,e,t={}){const s=r instanceof RegExp;if(!s)r=this.$_compile(r,{appendPath:true});g(e!==void 0,\"Invalid rule\");re(t,[\"fallthrough\",\"matches\"]);if(s)g(!r.flags.includes(\"g\")&&!r.flags.includes(\"y\"),\"pattern should not use global or sticky mode\");e=this.$_compile(e,{appendPath:true});const n=this.clone();n.$_terms.patterns=n.$_terms.patterns||[];const i={[s?\"regex\":\"schema\"]:r,rule:e};if(t.matches){i.matches=this.$_compile(t.matches);if(i.matches.type!==\"array\")i.matches=i.matches.$_root.array().items(i.matches);n.$_mutateRegister(i.matches);n.$_setFlag(\"_hasPatternMatch\",true,{clone:false})}if(t.fallthrough)i.fallthrough=true;n.$_terms.patterns.push(i);n.$_mutateRegister(e);return n}},ref:{method(){return this.$_addRule(\"ref\")},validate(r,e){if(rt(r))return r;return e.error(\"object.refType\",{value:r})}},regex:{method(){return this.$_addRule(\"regex\")},validate(r,e){if(r instanceof RegExp)return r;return e.error(\"object.regex\",{value:r})}},rename:{method(r,e,t={}){g(typeof r===\"string\"||r instanceof RegExp,\"Rename missing the from argument\");g(typeof e===\"string\"||e instanceof se,\"Invalid rename to argument\");g(e!==r,\"Cannot rename key to same name:\",r);re(t,[\"alias\",\"ignoreUndefined\",\"override\",\"multiple\"]);const s=this.clone();s.$_terms.renames=s.$_terms.renames||[];for(const n of s.$_terms.renames)g(n.from!==r,\"Cannot rename the same key multiple times\");if(e instanceof se)s.$_mutateRegister(e);s.$_terms.renames.push({from:r,to:e,options:Pd(i0,t)});return s}},schema:{method(r=\"any\"){return this.$_addRule({name:\"schema\",args:{type:r}})},validate(r,e,{type:t}){if(oe(r)&&(t===\"any\"||r.type===t)){return r}return e.error(\"object.schema\",{type:t})}},unknown:{method(r){if(r===void 0||r===null||typeof r===\"boolean\")return this.$_setFlag(\"unknown\",r!==false);const e=this.clone();const t=e.$_compile(r);e.$_mutateRegister(t);return e.$_setFlag(\"unknown\",t,{clone:false})}},with:{method(r,e,t={}){return us(this,\"with\",r,e,t)}},without:{method(r,e,t={}){return us(this,\"without\",r,e,t)}},xor:{method(...r){Be(r,\"xor\");return us(this,\"xor\",null,r)}}},overrides:{default(r,e){if(r===void 0)r=H.deepDefault;return this.$_parent(\"default\",r,e)},isAsync(){if(this.$_terms.externals?.length)return true;if(typeof this._flags.unknown===\"object\"&&this._flags.unknown.isAsync())return true;if(this.$_terms.keys?.length){for(const r of this.$_terms.keys){if(r.schema.isAsync())return true}}if(this.$_terms.patterns?.length){for(const r of this.$_terms.patterns){if(r.rule.isAsync())return true}}return false}},rebuild(r){if(r.$_terms.keys){const e=new xl;for(const t of r.$_terms.keys){os(()=>Fn(()=>e.add(t,{after:t.schema.$_rootReferences(),group:t.key})),t.key)}r.$_terms.keys=new Ho(...e.nodes)}},manifest:{build(r,e){if(e.keys)r=r.keys(e.keys);if(e.dependencies){for(const{rel:t,key:s=null,peers:n,options:i}of e.dependencies)r=us(r,t,s,n,i)}if(e.patterns){for(const{regex:t,schema:s,rule:n,fallthrough:i,matches:o}of e.patterns)r=r.pattern(t||s,n,{fallthrough:i,matches:o})}if(e.renames){for(const{from:t,to:s,options:n}of e.renames)r=r.rename(t,s,n)}return r}},messages:{\"object.and\":\"{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}\",\"object.assert\":'{{#label}} is invalid because {if(#subject.key, `\"` + #subject.key + `\" failed to ` + (#message || \"pass the assertion test\"), #message || \"the assertion failed\")}',\"object.base\":\"{{#label}} must be of type {{#type}}\",\"object.instance\":\"{{#label}} must be an instance of {{:#type}}\",\"object.keyNames\":'{{#label}} has a key name \"{{#name}}\" which is not allowed',\"object.length\":'{{#label}} must have {{#limit}} key{if(#limit == 1, \"\", \"s\")}',\"object.max\":'{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, \"\", \"s\")}',\"object.min\":'{{#label}} must have at least {{#limit}} key{if(#limit == 1, \"\", \"s\")}',\"object.missing\":\"{{#label}} must contain at least one of {{#peersWithLabels}}\",\"object.nand\":\"{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}\",\"object.oxor\":\"{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}\",\"object.pattern.match\":\"{{#label}} keys failed to match pattern requirements\",\"object.refType\":\"{{#label}} must be a reference\",\"object.regex\":\"{{#label}} must be a RegExp object\",\"object.rename.multiple\":\"{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}\",\"object.rename.override\":\"{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists\",\"object.schema\":\"{{#label}} must be a schema of {{#type}} type\",\"object.unknown\":\"{{#label}} is not allowed\",\"object.with\":\"{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}\",\"object.without\":\"{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}\",\"object.xor\":\"{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}\"}});var Rl=o0;function a0(r,e){if(typeof r===\"object\"){if(e.nonEnumerables)return G(r,{shallow:true});const n=Object.create(Object.getPrototypeOf(r));Object.assign(n,r);return n}const t=r;const s=a(function(...n){return t.apply(this,n)},\"clone\");s.prototype=G(t.prototype);Object.defineProperty(s,\"name\",{value:t.name,writable:false});Object.defineProperty(s,\"length\",{value:t.length,writable:false});Object.assign(s,r);return s}a(a0,\"clone\");function us(r,e,t,s,n){g(t===null||typeof t===\"string\",e,\"key must be a strings\");if(!n)n=s.length>1&&typeof s[s.length-1]===\"object\"?s.pop():{};re(n,[\"separator\",\"isPresent\"]);s=[].concat(s);const i=Ds(n.separator,\".\");const o=[];for(const l of s){g(typeof l===\"string\",e,\"peers must be strings\");o.push(cr(l,{separator:i,ancestor:0,prefix:false}))}if(t!==null)t=cr(t,{separator:i,ancestor:0,prefix:false});const c=r.clone();c.$_terms.dependencies=c.$_terms.dependencies||[];c.$_terms.dependencies.push(new Sh(e,t,o,s,n));return c}a(us,\"dependency\");var c0={and(r,e,t,s,n){const i=[];const o=[];const c=e.peers.length;const l=fs(e.options);for(const u of e.peers){if(l(u.resolve(t,s,n,null,{shadow:false}))===false){i.push(u.key)}else{o.push(u.key)}}if(i.length!==c&&o.length!==c){return{code:\"object.and\",context:{present:o,presentWithLabels:yt(r,o),missing:i,missingWithLabels:yt(r,i)}}}},nand(r,e,t,s,n){const i=[];const o=fs(e.options);for(const u of e.peers){if(o(u.resolve(t,s,n,null,{shadow:false})))i.push(u.key)}if(i.length!==e.peers.length)return;const c=e.paths[0];const l=e.paths.slice(1);return{code:\"object.nand\",context:{main:c,mainWithLabel:yt(r,c),peers:l,peersWithLabels:yt(r,l)}}},or(r,e,t,s,n){const i=fs(e.options);for(const o of e.peers){if(i(o.resolve(t,s,n,null,{shadow:false})))return}return{code:\"object.missing\",context:{peers:e.paths,peersWithLabels:yt(r,e.paths)}}},oxor(r,e,t,s,n){const i=[];const o=fs(e.options);for(const l of e.peers){if(o(l.resolve(t,s,n,null,{shadow:false})))i.push(l.key)}if(!i.length||i.length===1){return}const c={peers:e.paths,peersWithLabels:yt(r,e.paths)};c.present=i;c.presentWithLabels=yt(r,i);return{code:\"object.oxor\",context:c}},with(r,e,t,s,n){const i=fs(e.options);for(const o of e.peers){if(i(o.resolve(t,s,n,null,{shadow:false}))===false){return{code:\"object.with\",context:{main:e.key.key,mainWithLabel:yt(r,e.key.key),peer:o.key,peerWithLabel:yt(r,o.key)}}}}},without(r,e,t,s,n){const i=fs(e.options);for(const o of e.peers){if(i(o.resolve(t,s,n,null,{shadow:false}))){return{code:\"object.without\",context:{main:e.key.key,mainWithLabel:yt(r,e.key.key),peer:o.key,peerWithLabel:yt(r,o.key)}}}}},xor(r,e,t,s,n){const i=[];const o=fs(e.options);for(const l of e.peers){if(o(l.resolve(t,s,n,null,{shadow:false})))i.push(l.key)}if(i.length===1)return;const c={peers:e.paths,peersWithLabels:yt(r,e.paths)};if(i.length===0)return{code:\"object.missing\",context:c};c.present=i;c.presentWithLabels=yt(r,i);return{code:\"object.xor\",context:c}}};function yt(r,e){if(Array.isArray(e))return e.map(t=>r.$_mapLabels(t));return r.$_mapLabels(e)}a(yt,\"keysToLabels\");function fs(r){return typeof r.isPresent===\"function\"?r.isPresent:e=>e!==void 0}a(fs,\"isPresent\");function l0(r,e,t,s,n){const i={};for(const o of r.$_terms.renames){const c=[];const l=typeof o.from!==\"string\";if(!l){if(Object.prototype.hasOwnProperty.call(e,o.from)&&(e[o.from]!==void 0||!o.options.ignoreUndefined)){c.push(o)}}else{for(const u in e){if(e[u]===void 0&&o.options.ignoreUndefined){continue}if(u===o.to)continue;const f=o.from.exec(u);if(!f)continue;c.push({from:u,to:o.to,match:f})}}for(const u of c){const f=u.from;let d=u.to;if(d instanceof se)d=d.render(e,t,s,u.match);if(f===d)continue;if(!o.options.multiple&&i[d]){n.push(r.$_createError(\"object.rename.multiple\",e,{from:f,to:d,pattern:l},t,s));if(s.abortEarly)return false}if(Object.prototype.hasOwnProperty.call(e,d)&&!o.options.override&&!i[d]){n.push(r.$_createError(\"object.rename.override\",e,{from:f,to:d,pattern:l},t,s));if(s.abortEarly)return false}if(e[f]===void 0){delete e[d]}else{e[d]=e[f]}i[d]=true;if(!o.options.alias)delete e[f]}}return true}a(l0,\"rename\");function u0(r,e,t,s,n,i){if(r.$_terms.patterns){let l=false;const u=r.$_terms.patterns.map(d=>{if(d.matches){l=true;return[]}});const f=[e,...n.ancestors];for(const d of t){const h=e[d];const p=[...n.path,d];for(let m=0;m<r.$_terms.patterns.length;++m){const y=r.$_terms.patterns[m];if(y.regex){const T=y.regex.test(d);n.mainstay.tracer.debug(n,\"rule\",`pattern.${m}`,T?\"pass\":\"error\");if(!T)continue}else{if(!y.schema.$_match(d,n.nest(y.schema,`pattern.${m}`),i))continue}t.delete(d);const w=n.localize(p,f,{schema:y.rule,key:d});const S=y.rule.$_validate(h,w,i);if(S.errors){if(i.abortEarly)return{value:e,errors:S.errors};s.push(...S.errors)}if(y.matches)u[m].push(d);e[d]=S.value;if(!y.fallthrough)break}}if(l){for(let d=0;d<u.length;++d){const h=u[d];if(!h)continue;const p=r.$_terms.patterns[d].matches;const m=n.localize(n.path,f,p);const y=p.$_validate(h,m,i);if(y.errors){const w=lr(y.errors,{override:false});w.matches=h;const S=r.$_createError(\"object.pattern.match\",e,w,n,i);if(i.abortEarly)return{value:e,errors:S};s.push(S)}}}}const o=r._flags.unknown;if(typeof o===\"object\"){const l=[e,...n.ancestors];for(const u of t){const f=n.localize([...n.path,u],l,{schema:o,key:u});const d=o.$_validate(e[u],f,i);if(d.errors){if(i.abortEarly)return{value:e,errors:d.errors};s.push(...d.errors)}e[u]=d.value}return}if(!t.size||!r.$_terms.keys&&!r.$_terms.patterns){return}if(i.stripUnknown&&typeof r._flags.unknown===\"undefined\"||i.skipFunctions){const l=i.stripUnknown?i.stripUnknown===true?true:!!i.stripUnknown.objects:false;for(const u of t){if(l){delete e[u];t.delete(u)}else if(typeof e[u]===\"function\"){t.delete(u)}}}const c=!Ds(r._flags.unknown,i.allowUnknown);if(c){for(const l of t){const u=n.localize([...n.path,l],[]);const f=r.$_createError(\"object.unknown\",e[l],{child:l},u,i,{flags:false});if(i.abortEarly)return{value:e,errors:f};s.push(f)}}}a(u0,\"unknown\");var Sh=class{static{a(this,\"Dependency\")}constructor(e,t,s,n,i){this.rel=e;this.key=t;this.peers=s;this.paths=n;this.options=i}describe(){const e={rel:this.rel,peers:this.paths};if(this.key!==null)e.key=this.key.key;if(this.peers[0].separator!==\".\")e.options={...e.options,separator:this.peers[0].separator};if(this.options.isPresent)e.options={...e.options,isPresent:this.options.isPresent};return e}};var Ho=class extends Array{static{a(this,\"Keys\")}concat(e){const t=this.slice();const s=new Map;for(let n=0;n<t.length;++n)s.set(t[n].key,n);for(const n of e){const i=n.key;const o=s.get(i);if(o!==void 0){t[o]={key:i,schema:t[o].schema.concat(n.schema)}}else{t.push(n)}}return t}};var f0=Rl.extend({type:\"function\",properties:{typeof:\"function\"},rules:{arity:{method(r){g(Number.isSafeInteger(r)&&r>=0,\"n must be a positive integer\");return this.$_addRule({name:\"arity\",args:{n:r}})},validate(r,e,{n:t}){if(r.length===t)return r;return e.error(\"function.arity\",{n:t})}},class:{method(){return this.$_addRule(\"class\")},validate(r,e){if(/^\\s*class\\s/.test(r.toString()))return r;return e.error(\"function.class\",{value:r})}},minArity:{method(r){g(Number.isSafeInteger(r)&&r>0,\"n must be a strict positive integer\");return this.$_addRule({name:\"minArity\",args:{n:r}})},validate(r,e,{n:t}){if(r.length>=t)return r;return e.error(\"function.minArity\",{n:t})}},maxArity:{method(r){g(Number.isSafeInteger(r)&&r>=0,\"n must be a positive integer\");return this.$_addRule({name:\"maxArity\",args:{n:r}})},validate(r,e,{n:t}){if(r.length<=t)return r;return e.error(\"function.maxArity\",{n:t})}}},messages:{\"function.arity\":\"{{#label}} must have an arity of {{#n}}\",\"function.class\":\"{{#label}} must be a class\",\"function.maxArity\":\"{{#label}} must have an arity lesser or equal to {{#n}}\",\"function.minArity\":\"{{#label}} must have an arity greater or equal to {{#n}}\"}});var Vy=f0;var d0=_e.extend({type:\"link\",properties:{schemaChain:true},terms:{link:{init:null,manifest:\"single\",register:false}},args(r,e){return r.ref(e)},validate(r,{schema:e,state:t,prefs:s}){g(e.$_terms.link,\"Uninitialized link schema\");const n=Xy(e,r,t,s);const i=e.$_terms.link[0].ref;return n.$_validate(r,t.nest(n,`link:${i.display}:${n.type}`),s)},generate(r,e,t,s){return Xy(r,e,t,s)},rules:{ref:{method(r){g(!this.$_terms.link,\"Cannot reinitialize schema\");const e=cr(r);g(e.type===\"value\"||e.type===\"local\",\"Invalid reference type:\",e.type);g(e.type===\"local\"||e.ancestor===\"root\"||e.ancestor>0,\"Link cannot reference itself\");const t=this.clone();t.$_terms.link=[{ref:e}];return t}},relative:{method(r=true){return this.$_setFlag(\"relative\",r)}}},overrides:{concat(r){g(this.$_terms.link,\"Uninitialized link schema\");g(oe(r),\"Invalid schema object\");g(r.type!==\"link\",\"Cannot merge type link with another link\");const e=this.clone();if(!e.$_terms.whens){e.$_terms.whens=[]}e.$_terms.whens.push({concat:r});return e.$_mutateRebuild()}},manifest:{build(r,e){g(e.link,\"Invalid link description missing link\");return r.ref(e.link)}}});var Yy=d0;function Xy(r,e,t,s){const n=t.mainstay.links;let i=n.get(r);if(i){return i._generate(e,t,s).schema}const o=r.$_terms.link[0].ref;const{perspective:c,path:l}=h0(o,t);wh(c,\"which is outside of schema boundaries\",o,r,t,s);try{i=l.length?c.$_reach(l):c}catch{wh(false,\"to non-existing schema\",o,r,t,s)}wh(i.type!==\"link\",\"which is another link\",o,r,t,s);if(!r._flags.relative){n.set(r,i)}return i._generate(e,t,s).schema}a(Xy,\"generate\");function h0(r,e){const t=e.schemas;if(r.type===\"local\"){for(const{schema:s,key:n}of t){const i=s;const o=i._flags.id||n;if(o===r.path[0]){return{perspective:i,path:r.path.slice(1)}}if(i.$_terms.shared){for(const c of i.$_terms.shared){if(c._flags.id===r.path[0]){return{perspective:c,path:r.path.slice(1)}}}}}return{perspective:null,path:null}}if(r.ancestor===\"root\"){return{perspective:t[t.length-1].schema,path:r.path}}return{perspective:t[r.ancestor]&&t[r.ancestor].schema,path:r.path}}a(h0,\"perspectiveOf\");function wh(r,e,t,s,n,i){if(r){return}g(false,`\"${Uo(s._flags,n,i,void 0)}\" contains link reference \"${t.display}\" ${e}`)}a(wh,\"assertLink\");var At=Object.freeze({int8:[-128,127],uint8:[0,255],int16:[-32768,32767],uint16:[0,65535],int32:[-2147483648,2147483647],uint32:[0,4294967295],int64:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],uint64:[0,Number.MAX_SAFE_INTEGER]});var Gt=34028234663852886e22;function ds(r){const[e,t]=At[r];return{method(){return this.$_addRule(r)},validate(s,n){if(!Number.isInteger(s))return n.error(\"number.integer\");if(s<e||s>t)return n.error(`number.${r}`,{min:e,max:t});return s}}}a(ds,\"integerRule\");var p0=/^\\s*[+-]?(?:(?:\\d+(?:\\.\\d*)?)|(?:\\.\\d+))(?:e([+-]?\\d+))?\\s*$/i;var m0=/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;var g0=/[eE][+-]?\\d+$/;var y0=/^[+-]?(0*)?/;var b0=/\\./;var S0=/0+$/;function Jy(r){const e=r.toString();const t=e.indexOf(\".\");const s=e.indexOf(\"e\");return(t<0?0:(s<0?e.length:s)-t-1)+(s<0?0:Math.max(0,-parseInt(e.slice(s+1))))}a(Jy,\"decimalPlaces\");var w0=_e.extend({type:\"number\",flags:{unsafe:{default:false}},coerce:{from:\"string\",method(r,{schema:e,error:t}){let s=r;const n=s.match(p0);if(!n)return;s=s.trim();const i={value:parseFloat(s)};if(i.value===0)i.value=0;if(!e._flags.unsafe){if(s.match(/e/i)){if(Zy(s)!==Zy(String(i.value))){i.errors=t(\"number.unsafe\");return i}}else{const o=i.value.toString();if(o.match(/e/i))return i;if(o!==E0(s)){i.errors=t(\"number.unsafe\");return i}}}return i}},validate(r,{schema:e,error:t,prefs:s}){if(r===Infinity||r===-Infinity){return{value:r,errors:t(\"number.infinity\")}}if(!Ud(r))return{value:r,errors:t(\"number.base\")};const n={value:r};if(s.convert){const i=e.$_getRule(\"precision\");if(i){const o=Math.pow(10,i.args.limit);n.value=Math.round(n.value*o)/o}}if(n.value===0)n.value=0;if(!e._flags.unsafe&&(r>Number.MAX_SAFE_INTEGER||r<Number.MIN_SAFE_INTEGER)){n.errors=t(\"number.unsafe\")}return n},rules:{compare:{method:false,validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(r,t,n))return r;return e.error(\"number.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Ud,message:\"must be a number\"}]},double:{method(){return this.unsafe().$_addRule(\"double\")},validate(r){return r}},float:{method(){return this.unsafe().$_addRule(\"float\")},validate(r,e){if(Math.abs(r)<=Gt)return r;return e.error(\"number.float\",{min:-Gt,max:Gt})}},greater:{method(r){return this.$_addRule({name:\"greater\",method:\"compare\",args:{limit:r},operator:\">\"})}},int8:ds(\"int8\"),int16:ds(\"int16\"),int32:ds(\"int32\"),int64:ds(\"int64\"),integer:{method(){return this.$_addRule(\"integer\")},validate(r,e){if(Math.trunc(r)-r===0)return r;return e.error(\"number.integer\")}},less:{method(r){return this.$_addRule({name:\"less\",method:\"compare\",args:{limit:r},operator:\"<\"})}},max:{method(r){return this.$_addRule({name:\"max\",method:\"compare\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"compare\",args:{limit:r},operator:\">=\"})}},multiple:{method(r){const e=typeof r===\"number\"?Jy(r):null;const t=Math.pow(10,e);return this.$_addRule({name:\"multiple\",args:{base:r,baseDecimalPlace:e,pfactor:t}})},validate(r,e,{base:t,baseDecimalPlace:s,pfactor:n},i){const o=Jy(r);if(o>s){return e.error(\"number.multiple\",{multiple:i.args.base,value:r})}return Math.round(n*r)%Math.round(n*t)===0?r:e.error(\"number.multiple\",{multiple:i.args.base,value:r})},args:[{name:\"base\",ref:true,assert:a(r=>typeof r===\"number\"&&isFinite(r)&&r>0,\"assert\"),message:\"must be a positive number\"},\"baseDecimalPlace\",\"pfactor\"],multi:true},negative:{method(){return this.sign(\"negative\")}},port:{method(){return this.$_addRule(\"port\")},validate(r,e){if(Number.isSafeInteger(r)&&r>=0&&r<=65535){return r}return e.error(\"number.port\")}},positive:{method(){return this.sign(\"positive\")}},precision:{method(r){g(Number.isSafeInteger(r),\"limit must be an integer\");return this.$_addRule({name:\"precision\",args:{limit:r}})},validate(r,e,{limit:t}){const s=r.toString().match(m0);const n=Math.max((s[1]?s[1].length:0)-(s[2]?parseInt(s[2],10):0),0);if(n<=t)return r;return e.error(\"number.precision\",{limit:t,value:r})},convert:true},sign:{method(r){g([\"negative\",\"positive\"].includes(r),\"Invalid sign\",r);return this.$_addRule({name:\"sign\",args:{sign:r}})},validate(r,e,{sign:t}){if(t===\"negative\"&&r<0||t===\"positive\"&&r>0){return r}return e.error(`number.${t}`)}},uint8:ds(\"uint8\"),uint16:ds(\"uint16\"),uint32:ds(\"uint32\"),uint64:ds(\"uint64\"),unsafe:{method(r=true){g(typeof r===\"boolean\",\"enabled must be a boolean\");return this.$_setFlag(\"unsafe\",r)}}},cast:{string:{from:a(r=>typeof r===\"number\",\"from\"),to(r){return r.toString()}}},messages:{\"number.base\":\"{{#label}} must be a number\",\"number.float\":\"{{#label}} must be a valid Float value (between {{#min}} and {{#max}})\",\"number.greater\":\"{{#label}} must be greater than {{#limit}}\",\"number.infinity\":\"{{#label}} cannot be infinity\",\"number.int8\":\"{{#label}} must be a valid Int8 value (between -128 and 127)\",\"number.int16\":\"{{#label}} must be a valid Int16 value (between -32768 and 32767)\",\"number.int32\":\"{{#label}} must be a valid Int32 value (between -2147483648 and 2147483647)\",\"number.int64\":\"{{#label}} must be a valid Int64 value (between -9007199254740991 and 9007199254740991, the safe integers of JavaScript)\",\"number.integer\":\"{{#label}} must be an integer\",\"number.less\":\"{{#label}} must be less than {{#limit}}\",\"number.max\":\"{{#label}} must be less than or equal to {{#limit}}\",\"number.min\":\"{{#label}} must be greater than or equal to {{#limit}}\",\"number.multiple\":\"{{#label}} must be a multiple of {{#multiple}}\",\"number.negative\":\"{{#label}} must be a negative number\",\"number.port\":\"{{#label}} must be a valid port\",\"number.positive\":\"{{#label}} must be a positive number\",\"number.precision\":\"{{#label}} must have no more than {{#limit}} decimal places\",\"number.uint8\":\"{{#label}} must be a valid UInt8 value (between 0 and 255)\",\"number.uint16\":\"{{#label}} must be a valid UInt16 value (between 0 and 65535)\",\"number.uint32\":\"{{#label}} must be a valid UInt32 value (between 0 and 4294967295)\",\"number.uint64\":\"{{#label}} must be a valid UInt64 value (between 0 and 9007199254740991, the safe integers of JavaScript)\",\"number.unsafe\":\"{{#label}} must be a safe number\"}});var Qy=w0;function Zy(r){return r.replace(g0,\"\").replace(b0,\"\").replace(S0,\"\").replace(y0,\"\")}a(Zy,\"extractSignificantDigits\");function E0(r){r=r.replace(/^\\+/,\"\").replace(/\\.0*$/,\"\").replace(/^(-?)\\.([^\\.]*)$/,\"$10.$2\").replace(/^(-?)0+([0-9])/,\"$1$2\");if(r.includes(\".\")&&r.endsWith(\"0\")){r=r.replace(/0+$/,\"\")}if(r===\"-0\")return\"0\";return r}a(E0,\"normalizeDecimal\");var T0=Rl.extend({type:\"object\",cast:{map:{from:a(r=>r&&typeof r===\"object\",\"from\"),to(r){return new Map(Object.entries(r))}}}});var eb=T0;var rb=Ye(require(\"node:url\"),1);var tb={EMPTY_STRING:\"Address must be a non-empty string\",FORBIDDEN_UNICODE:\"Address contains forbidden Unicode characters\",MULTIPLE_AT_CHAR:\"Address cannot contain more than one @ character\",MISSING_AT_CHAR:\"Address must contain one @ character\",EMPTY_LOCAL:\"Address local part cannot be empty\",ADDRESS_TOO_LONG:\"Address too long\",LOCAL_TOO_LONG:\"Address local part too long\",EMPTY_LOCAL_SEGMENT:\"Address local part contains empty dot-separated segment\",INVALID_LOCAL_CHARS:\"Address local part contains invalid character\",DOMAIN_NON_EMPTY_STRING:\"Domain must be a non-empty string\",DOMAIN_TOO_LONG:\"Domain too long\",DOMAIN_INVALID_UNICODE_CHARS:\"Domain contains forbidden Unicode characters\",DOMAIN_INVALID_CHARS:\"Domain contains invalid character\",DOMAIN_INVALID_TLDS_CHARS:\"Domain contains invalid tld character\",DOMAIN_SEGMENTS_COUNT:\"Domain lacks the minimum required number of segments\",DOMAIN_SEGMENTS_COUNT_MAX:\"Domain contains too many segments\",DOMAIN_FORBIDDEN_TLDS:\"Domain uses forbidden TLD\",DOMAIN_EMPTY_SEGMENT:\"Domain contains empty dot-separated segment\",DOMAIN_LONG_SEGMENT:\"Domain contains dot-separated segment that is too long\"};function we(r){return{code:r,error:tb[r]}}a(we,\"errorCode\");var x0=2;var R0=/[^\\x00-\\x7f]/;var _0=/[\\x00-\\x20@\\:\\/\\\\#!\\$&\\'\\(\\)\\*\\+,;=\\?]/;var C0=/^[a-zA-Z](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/;var v0=/^[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/;var A0=/^[a-zA-Z0-9_](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/;var I0=rb.URL||URL;function O0(r){return!!r.allow}a(O0,\"isTldsAllow\");function Eh(r,e={}){if(!r){return we(\"DOMAIN_NON_EMPTY_STRING\")}if(typeof r!==\"string\"){throw new Error(\"Invalid input: domain must be a string\")}if(r.length>256){return we(\"DOMAIN_TOO_LONG\")}const t=!R0.test(r);if(!t){if(e.allowUnicode===false){return we(\"DOMAIN_INVALID_UNICODE_CHARS\")}r=r.normalize(\"NFC\")}if(_0.test(r)){return we(\"DOMAIN_INVALID_CHARS\")}r=k0(r);if(e.allowFullyQualified&&r[r.length-1]===\".\"){r=r.slice(0,-1)}const s=e.minDomainSegments||x0;const n=r.split(\".\");if(n.length<s){return we(\"DOMAIN_SEGMENTS_COUNT\")}if(e.maxDomainSegments){if(n.length>e.maxDomainSegments){return we(\"DOMAIN_SEGMENTS_COUNT_MAX\")}}const i=e.tlds;if(i){const o=n[n.length-1].toLowerCase();if(O0(i)){if(!i.allow.has(o)){return we(\"DOMAIN_FORBIDDEN_TLDS\")}}else if(i.deny.has(o)){return we(\"DOMAIN_FORBIDDEN_TLDS\")}}for(let o=0;o<n.length;++o){const c=n[o];if(!c.length){return we(\"DOMAIN_EMPTY_SEGMENT\")}if(c.length>63){return we(\"DOMAIN_LONG_SEGMENT\")}if(o<n.length-1){if(e.allowUnderscore){if(!A0.test(c)){return we(\"DOMAIN_INVALID_CHARS\")}}else{if(!v0.test(c)){return we(\"DOMAIN_INVALID_CHARS\")}}}else{if(!C0.test(c)){return we(\"DOMAIN_INVALID_TLDS_CHARS\")}}}return null}a(Eh,\"analyzeDomain\");function qo(r,e){return!Eh(r,e)}a(qo,\"isDomainValid\");function k0(r){if(r.includes(\"%\")){r=r.replace(/%/g,\"%25\")}try{return new I0(`http://${r}`).host}catch(e){return r}}a(k0,\"punycode\");var nb=Ye(require(\"node:util\"),1);var P0=/[^\\x00-\\x7f]/;var ib=new(nb.TextEncoder||TextEncoder);function zo(r,e){return!N0(r,e)}a(zo,\"isEmailValid\");function N0(r,e={}){if(typeof r!==\"string\"){throw new Error(\"Invalid input: email must be a string\")}if(!r){return we(\"EMPTY_STRING\")}const t=!P0.test(r);if(!t){if(e.allowUnicode===false){return we(\"FORBIDDEN_UNICODE\")}r=r.normalize(\"NFC\")}const s=r.split(\"@\");if(s.length!==2){return s.length>2?we(\"MULTIPLE_AT_CHAR\"):we(\"MISSING_AT_CHAR\")}const[n,i]=s;if(!n){return we(\"EMPTY_LOCAL\")}if(!e.ignoreLength){if(r.length>254){return we(\"ADDRESS_TOO_LONG\")}if(ib.encode(n).length>64){return we(\"LOCAL_TOO_LONG\")}}return L0(n,t)||Eh(i,e)}a(N0,\"validateEmail\");function L0(r,e){const t=r.split(\".\");for(const s of t){if(!s.length){return we(\"EMPTY_LOCAL_SEGMENT\")}if(e){if(!sb.test(s)){return we(\"INVALID_LOCAL_CHARS\")}continue}for(const n of s){if(sb.test(n)){continue}const i=M0(n);if(!D0.test(i)){return we(\"INVALID_LOCAL_CHARS\")}}}return null}a(L0,\"validateLocal\");function M0(r){return Array.from(ib.encode(r),e=>String.fromCharCode(e)).join(\"\")}a(M0,\"toBinary\");var sb=/^[\\w!#\\$%&'\\*\\+\\-/=\\?\\^`\\{\\|\\}~]+$/;var D0=new RegExp([\"(?:[\\\\xc2-\\\\xdf][\\\\x80-\\\\xbf])\",\"(?:\\\\xe0[\\\\xa0-\\\\xbf][\\\\x80-\\\\xbf])|(?:[\\\\xe1-\\\\xec][\\\\x80-\\\\xbf]{2})|(?:\\\\xed[\\\\x80-\\\\x9f][\\\\x80-\\\\xbf])|(?:[\\\\xee-\\\\xef][\\\\x80-\\\\xbf]{2})\",\"(?:\\\\xf0[\\\\x90-\\\\xbf][\\\\x80-\\\\xbf]{2})|(?:[\\\\xf1-\\\\xf3][\\\\x80-\\\\xbf]{3})|(?:\\\\xf4[\\\\x80-\\\\x8f][\\\\x80-\\\\xbf]{2})\"].join(\"|\"));function B0(){const r={};const e=\"\\\\dA-Fa-f\";const t=\"[\"+e+\"]\";const s=\"\\\\w-\\\\.~\";const n=\"!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=\";const i=\"%\"+e;const o=s+i+n+\":@\";const c=\"[\"+o+\"]\";const l=\"(?:0{0,2}\\\\d|0?[1-9]\\\\d|1\\\\d\\\\d|2[0-4]\\\\d|25[0-5])\";r.ipv4address=\"(?:\"+l+\"\\\\.){3}\"+l;const u=t+\"{1,4}\";const f=\"(?:\"+u+\":\"+u+\"|\"+r.ipv4address+\")\";const d=\"(?:\"+u+\":){6}\"+f;const h=\"::(?:\"+u+\":){5}\"+f;const p=\"(?:\"+u+\")?::(?:\"+u+\":){4}\"+f;const m=\"(?:(?:\"+u+\":){0,1}\"+u+\")?::(?:\"+u+\":){3}\"+f;const y=\"(?:(?:\"+u+\":){0,2}\"+u+\")?::(?:\"+u+\":){2}\"+f;const w=\"(?:(?:\"+u+\":){0,3}\"+u+\")?::\"+u+\":\"+f;const S=\"(?:(?:\"+u+\":){0,4}\"+u+\")?::\"+f;const T=\"(?:(?:\"+u+\":){0,5}\"+u+\")?::\"+u;const _=\"(?:(?:\"+u+\":){0,6}\"+u+\")?::\";r.ipv4Cidr=\"(?:\\\\d|[1-2]\\\\d|3[0-2])\";r.ipv6Cidr=\"(?:0{0,2}\\\\d|0?[1-9]\\\\d|1[01]\\\\d|12[0-8])\";r.ipv6address=\"(?:\"+d+\"|\"+h+\"|\"+p+\"|\"+m+\"|\"+y+\"|\"+w+\"|\"+S+\"|\"+T+\"|\"+_+\")\";r.ipvFuture=\"v\"+t+\"+\\\\.[\"+s+n+\":]+\";r.scheme=\"[a-zA-Z][a-zA-Z\\\\d+-\\\\.]*\";r.schemeRegex=new RegExp(r.scheme);const x=\"[\"+s+i+n+\":]*\";const k=\"\\\\[(?:\"+r.ipv6address+\"|\"+r.ipvFuture+\")\\\\]\";const N=\"[\"+s+i+n+\"]{1,255}\";const A=\"(?:\"+k+\"|\"+r.ipv4address+\"|\"+N+\")\";const B=\"\\\\d*\";const ee=\"(?:\"+x+\"@)?\"+A+\"(?::\"+B+\")?\";const fe=\"(?:\"+x+\"@)?(\"+A+\")(?::\"+B+\")?\";const Rt=c+\"*\";const Qc=c+\"+\";const xd=\"[\"+s+i+n+\"@]+\";const Ao=\"\";const _t=\"(?:\\\\/\"+Rt+\")*\";const Ns=\"\\\\/(?:\"+Qc+_t+\")?\";const Io=Qc+_t;const Oo=xd+_t;const el=\"(?:\\\\/\\\\/\\\\/\"+Rt+_t+\")\";r.hierPart=\"(?:(?:\\\\/\\\\/\"+ee+_t+\")|\"+Ns+\"|\"+Io+\"|\"+el+\")\";r.hierPartCapture=\"(?:(?:\\\\/\\\\/\"+fe+_t+\")|\"+Ns+\"|\"+Io+\")\";r.relativeRef=\"(?:(?:\\\\/\\\\/\"+ee+_t+\")|\"+Ns+\"|\"+Oo+\"|\"+Ao+\")\";r.relativeRefCapture=\"(?:(?:\\\\/\\\\/\"+fe+_t+\")|\"+Ns+\"|\"+Oo+\"|\"+Ao+\")\";r.query=\"[\"+o+\"\\\\/\\\\?]*(?=#|$)\";r.queryWithSquareBrackets=\"[\"+o+\"\\\\[\\\\]\\\\/\\\\?]*(?=#|$)\";r.fragment=\"[\"+o+\"\\\\/\\\\?]*\";return r}a(B0,\"generate\");var Kn=B0();var Wn={v4Cidr:Kn.ipv4Cidr,v6Cidr:Kn.ipv6Cidr,ipv4:Kn.ipv4address,ipv6:Kn.ipv6address,ipvfuture:Kn.ipvFuture};function ab(r){const e=Kn;const t=r.allowQuerySquareBrackets?e.queryWithSquareBrackets:e.query;const s=\"(?:\\\\?\"+t+\")?(?:#\"+e.fragment+\")?\";const n=r.domain?e.relativeRefCapture:e.relativeRef;if(r.relativeOnly){return ob(n+s)}let i=\"\";if(r.scheme){te(r.scheme instanceof RegExp||typeof r.scheme===\"string\"||Array.isArray(r.scheme),\"scheme must be a RegExp, String, or Array\");const u=[].concat(r.scheme);te(u.length>=1,\"scheme must have at least 1 scheme specified\");const f=[];for(let d=0;d<u.length;++d){const h=u[d];te(h instanceof RegExp||typeof h===\"string\",\"scheme at position \"+d+\" must be a RegExp or String\");if(h instanceof RegExp){f.push(h.source.toString())}else{te(e.schemeRegex.test(h),\"scheme at position \"+d+\" must be a valid scheme\");f.push(mt(h))}}i=f.join(\"|\")}const o=i?\"(?:\"+i+\")\":e.scheme;const c=\"(?:\"+o+\":\"+(r.domain?e.hierPartCapture:e.hierPart)+\")\";const l=r.allowRelative?\"(?:\"+c+\"|\"+n+\")\":c;return ob(l+s,i)}a(ab,\"createRegex\");function ob(r,e=null){r=`(?=.)(?!https?:/(?:$|[^/]))(?!https?:///)(?!https?:[^/])${r}`;return{raw:r,regex:new RegExp(`^${r}$`),scheme:e}}a(ob,\"wrap\");var U0=ab({});function Vn(r={}){if(r.scheme||r.allowRelative||r.relativeOnly||r.allowQuerySquareBrackets||r.domain){return ab(r)}return U0}a(Vn,\"uriRegex\");function Xn(r={}){const e=r.cidr||\"optional\";te([\"required\",\"optional\",\"forbidden\"].includes(e),\"options.cidr must be one of required, optional, forbidden\");te(r.version===void 0||typeof r.version===\"string\"||Array.isArray(r.version),\"options.version must be a string or an array of string\");let t=r.version||[\"ipv4\",\"ipv6\",\"ipvfuture\"];if(!Array.isArray(t)){t=[t]}te(t.length>=1,\"options.version must have at least 1 version specified\");for(const o of t){te(typeof o===\"string\"&&o===o.toLowerCase(),\"Invalid options.version value\");te([\"ipv4\",\"ipv6\",\"ipvfuture\"].includes(o),\"options.version contains unknown version \"+o+\" - must be one of ipv4, ipv6, ipvfuture\")}t=Array.from(new Set(t));const s=t.map(o=>{if(e===\"forbidden\"){return Wn[o]}const c=`\\\\/${o===\"ipv4\"?Wn.v4Cidr:Wn.v6Cidr}`;if(e===\"required\"){return`${Wn[o]}${c}`}return`${Wn[o]}(?:${c})?`});const n=`(?:${s.join(\"|\")})`;const i=new RegExp(`^${n}$`);return{cidr:e,versions:t,regex:i,raw:n}}a(Xn,\"ipRegex\");var j0=/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;var $0=[0,31,28,31,30,31,30,31,31,30,31,30,31];var F0=/^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i;var H0=/^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/;var q0=/^(?=.{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;var z0=/^(?:(?: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)$/;var G0=Xn({version:[\"ipv6\"],cidr:\"forbidden\"}).regex;var K0=Vn().regex;var W0=Vn({allowRelative:true}).regex;var V0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var X0=/^(?:\\/(?:[^~/]|~0|~1)*)*$/;var Y0=/^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;var J0=/^(?:[^\\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;var Z0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Q0(r){return r%4===0&&(r%100!==0||r%400===0)}a(Q0,\"isLeapYear\");function cb(r){const e=j0.exec(r);if(!e)return false;const t=+e[1];const s=+e[2];const n=+e[3];return s>=1&&s<=12&&n>=1&&n<=(s===2&&Q0(t)?29:$0[s])}a(cb,\"isDate\");function lb(r){const e=F0.exec(r);if(!e)return false;const t=+e[1];const s=+e[2];const n=+e[3];const i=e[4];if(!i)return false;const o=e[5]===\"-\"?-1:1;const c=+(e[6]||0);const l=+(e[7]||0);if(c>23||l>59)return false;if(t<=23&&s<=59&&n<60)return true;const u=s-l*o;const f=t-c*o-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&n<61}a(lb,\"isTime\");var Yn=Object.freeze({\"date\":cb,\"time\":lb,\"date-time\":a(r=>{const e=r.split(/t|\\s/i);return e.length===2&&cb(e[0])&&lb(e[1])},\"date-time\"),\"duration\":a(r=>H0.test(r),\"duration\"),\"email\":a(r=>zo(r,{allowUnicode:false}),\"email\"),\"idn-email\":a(r=>zo(r),\"idn-email\"),\"hostname\":a(r=>q0.test(r),\"hostname\"),\"ipv4\":a(r=>z0.test(r),\"ipv4\"),\"ipv6\":a(r=>G0.test(r),\"ipv6\"),\"uri\":a(r=>K0.test(r),\"uri\"),\"uri-reference\":a(r=>r===\"\"||W0.test(r),\"uri-reference\"),\"uri-template\":a(r=>J0.test(r),\"uri-template\"),\"uuid\":a(r=>V0.test(r),\"uuid\"),\"regex\":a(r=>{try{new RegExp(r,\"u\");return true}catch{return false}},\"regex\"),\"json-pointer\":a(r=>X0.test(r),\"json-pointer\"),\"relative-json-pointer\":a(r=>Y0.test(r),\"relative-json-pointer\"),\"byte\":a(r=>Z0.test(r),\"byte\")});var ub=[\"AAA\",\"AARP\",\"ABB\",\"ABBOTT\",\"ABBVIE\",\"ABC\",\"ABLE\",\"ABOGADO\",\"ABUDHABI\",\"AC\",\"ACADEMY\",\"ACCENTURE\",\"ACCOUNTANT\",\"ACCOUNTANTS\",\"ACO\",\"ACTOR\",\"AD\",\"ADS\",\"ADULT\",\"AE\",\"AEG\",\"AERO\",\"AETNA\",\"AF\",\"AFL\",\"AFRICA\",\"AG\",\"AGAKHAN\",\"AGENCY\",\"AI\",\"AIG\",\"AIRBUS\",\"AIRFORCE\",\"AIRTEL\",\"AKDN\",\"AL\",\"ALIBABA\",\"ALIPAY\",\"ALLFINANZ\",\"ALLSTATE\",\"ALLY\",\"ALSACE\",\"ALSTOM\",\"AM\",\"AMAZON\",\"AMERICANEXPRESS\",\"AMERICANFAMILY\",\"AMEX\",\"AMFAM\",\"AMICA\",\"AMSTERDAM\",\"ANALYTICS\",\"ANDROID\",\"ANQUAN\",\"ANZ\",\"AO\",\"AOL\",\"APARTMENTS\",\"APP\",\"APPLE\",\"AQ\",\"AQUARELLE\",\"AR\",\"ARAB\",\"ARAMCO\",\"ARCHI\",\"ARMY\",\"ARPA\",\"ART\",\"ARTE\",\"AS\",\"ASDA\",\"ASIA\",\"ASSOCIATES\",\"AT\",\"ATHLETA\",\"ATTORNEY\",\"AU\",\"AUCTION\",\"AUDI\",\"AUDIBLE\",\"AUDIO\",\"AUSPOST\",\"AUTHOR\",\"AUTO\",\"AUTOS\",\"AW\",\"AWS\",\"AX\",\"AXA\",\"AZ\",\"AZURE\",\"BA\",\"BABY\",\"BAIDU\",\"BANAMEX\",\"BAND\",\"BANK\",\"BAR\",\"BARCELONA\",\"BARCLAYCARD\",\"BARCLAYS\",\"BAREFOOT\",\"BARGAINS\",\"BASEBALL\",\"BASKETBALL\",\"BAUHAUS\",\"BAYERN\",\"BB\",\"BBC\",\"BBT\",\"BBVA\",\"BCG\",\"BCN\",\"BD\",\"BE\",\"BEATS\",\"BEAUTY\",\"BEER\",\"BERLIN\",\"BEST\",\"BESTBUY\",\"BET\",\"BF\",\"BG\",\"BH\",\"BHARTI\",\"BI\",\"BIBLE\",\"BID\",\"BIKE\",\"BING\",\"BINGO\",\"BIO\",\"BIZ\",\"BJ\",\"BLACK\",\"BLACKFRIDAY\",\"BLOCKBUSTER\",\"BLOG\",\"BLOOMBERG\",\"BLUE\",\"BM\",\"BMS\",\"BMW\",\"BN\",\"BNPPARIBAS\",\"BO\",\"BOATS\",\"BOEHRINGER\",\"BOFA\",\"BOM\",\"BOND\",\"BOO\",\"BOOK\",\"BOOKING\",\"BOSCH\",\"BOSTIK\",\"BOSTON\",\"BOT\",\"BOUTIQUE\",\"BOX\",\"BR\",\"BRADESCO\",\"BRIDGESTONE\",\"BROADWAY\",\"BROKER\",\"BROTHER\",\"BRUSSELS\",\"BS\",\"BT\",\"BUILD\",\"BUILDERS\",\"BUSINESS\",\"BUY\",\"BUZZ\",\"BV\",\"BW\",\"BY\",\"BZ\",\"BZH\",\"CA\",\"CAB\",\"CAFE\",\"CAL\",\"CALL\",\"CALVINKLEIN\",\"CAM\",\"CAMERA\",\"CAMP\",\"CANON\",\"CAPETOWN\",\"CAPITAL\",\"CAPITALONE\",\"CAR\",\"CARAVAN\",\"CARDS\",\"CARE\",\"CAREER\",\"CAREERS\",\"CARS\",\"CASA\",\"CASE\",\"CASH\",\"CASINO\",\"CAT\",\"CATERING\",\"CATHOLIC\",\"CBA\",\"CBN\",\"CBRE\",\"CC\",\"CD\",\"CENTER\",\"CEO\",\"CERN\",\"CF\",\"CFA\",\"CFD\",\"CG\",\"CH\",\"CHANEL\",\"CHANNEL\",\"CHARITY\",\"CHASE\",\"CHAT\",\"CHEAP\",\"CHINTAI\",\"CHRISTMAS\",\"CHROME\",\"CHURCH\",\"CI\",\"CIPRIANI\",\"CIRCLE\",\"CISCO\",\"CITADEL\",\"CITI\",\"CITIC\",\"CITY\",\"CK\",\"CL\",\"CLAIMS\",\"CLEANING\",\"CLICK\",\"CLINIC\",\"CLINIQUE\",\"CLOTHING\",\"CLOUD\",\"CLUB\",\"CLUBMED\",\"CM\",\"CN\",\"CO\",\"COACH\",\"CODES\",\"COFFEE\",\"COLLEGE\",\"COLOGNE\",\"COM\",\"COMMBANK\",\"COMMUNITY\",\"COMPANY\",\"COMPARE\",\"COMPUTER\",\"COMSEC\",\"CONDOS\",\"CONSTRUCTION\",\"CONSULTING\",\"CONTACT\",\"CONTRACTORS\",\"COOKING\",\"COOL\",\"COOP\",\"CORSICA\",\"COUNTRY\",\"COUPON\",\"COUPONS\",\"COURSES\",\"CPA\",\"CR\",\"CREDIT\",\"CREDITCARD\",\"CREDITUNION\",\"CRICKET\",\"CROWN\",\"CRS\",\"CRUISE\",\"CRUISES\",\"CU\",\"CUISINELLA\",\"CV\",\"CW\",\"CX\",\"CY\",\"CYMRU\",\"CYOU\",\"CZ\",\"DAD\",\"DANCE\",\"DATA\",\"DATE\",\"DATING\",\"DATSUN\",\"DAY\",\"DCLK\",\"DDS\",\"DE\",\"DEAL\",\"DEALER\",\"DEALS\",\"DEGREE\",\"DELIVERY\",\"DELL\",\"DELOITTE\",\"DELTA\",\"DEMOCRAT\",\"DENTAL\",\"DENTIST\",\"DESI\",\"DESIGN\",\"DEV\",\"DHL\",\"DIAMONDS\",\"DIET\",\"DIGITAL\",\"DIRECT\",\"DIRECTORY\",\"DISCOUNT\",\"DISCOVER\",\"DISH\",\"DIY\",\"DJ\",\"DK\",\"DM\",\"DNP\",\"DO\",\"DOCS\",\"DOCTOR\",\"DOG\",\"DOMAINS\",\"DOT\",\"DOWNLOAD\",\"DRIVE\",\"DTV\",\"DUBAI\",\"DUPONT\",\"DURBAN\",\"DVAG\",\"DVR\",\"DZ\",\"EARTH\",\"EAT\",\"EC\",\"ECO\",\"EDEKA\",\"EDU\",\"EDUCATION\",\"EE\",\"EG\",\"EMAIL\",\"EMERCK\",\"ENERGY\",\"ENGINEER\",\"ENGINEERING\",\"ENTERPRISES\",\"EPSON\",\"EQUIPMENT\",\"ER\",\"ERICSSON\",\"ERNI\",\"ES\",\"ESQ\",\"ESTATE\",\"ET\",\"EU\",\"EUROVISION\",\"EUS\",\"EVENTS\",\"EXCHANGE\",\"EXPERT\",\"EXPOSED\",\"EXPRESS\",\"EXTRASPACE\",\"FAGE\",\"FAIL\",\"FAIRWINDS\",\"FAITH\",\"FAMILY\",\"FAN\",\"FANS\",\"FARM\",\"FARMERS\",\"FASHION\",\"FAST\",\"FEDEX\",\"FEEDBACK\",\"FERRARI\",\"FERRERO\",\"FI\",\"FIDELITY\",\"FIDO\",\"FILM\",\"FINAL\",\"FINANCE\",\"FINANCIAL\",\"FIRE\",\"FIRESTONE\",\"FIRMDALE\",\"FISH\",\"FISHING\",\"FIT\",\"FITNESS\",\"FJ\",\"FK\",\"FLICKR\",\"FLIGHTS\",\"FLIR\",\"FLORIST\",\"FLOWERS\",\"FLY\",\"FM\",\"FO\",\"FOO\",\"FOOD\",\"FOOTBALL\",\"FORD\",\"FOREX\",\"FORSALE\",\"FORUM\",\"FOUNDATION\",\"FOX\",\"FR\",\"FREE\",\"FRESENIUS\",\"FRL\",\"FROGANS\",\"FRONTIER\",\"FTR\",\"FUJITSU\",\"FUN\",\"FUND\",\"FURNITURE\",\"FUTBOL\",\"FYI\",\"GA\",\"GAL\",\"GALLERY\",\"GALLO\",\"GALLUP\",\"GAME\",\"GAMES\",\"GAP\",\"GARDEN\",\"GAY\",\"GB\",\"GBIZ\",\"GD\",\"GDN\",\"GE\",\"GEA\",\"GENT\",\"GENTING\",\"GEORGE\",\"GF\",\"GG\",\"GGEE\",\"GH\",\"GI\",\"GIFT\",\"GIFTS\",\"GIVES\",\"GIVING\",\"GL\",\"GLASS\",\"GLE\",\"GLOBAL\",\"GLOBO\",\"GM\",\"GMAIL\",\"GMBH\",\"GMO\",\"GMX\",\"GN\",\"GODADDY\",\"GOLD\",\"GOLDPOINT\",\"GOLF\",\"GOO\",\"GOODYEAR\",\"GOOG\",\"GOOGLE\",\"GOP\",\"GOT\",\"GOV\",\"GP\",\"GQ\",\"GR\",\"GRAINGER\",\"GRAPHICS\",\"GRATIS\",\"GREEN\",\"GRIPE\",\"GROCERY\",\"GROUP\",\"GS\",\"GT\",\"GU\",\"GUCCI\",\"GUGE\",\"GUIDE\",\"GUITARS\",\"GURU\",\"GW\",\"GY\",\"HAIR\",\"HAMBURG\",\"HANGOUT\",\"HAUS\",\"HBO\",\"HDFC\",\"HDFCBANK\",\"HEALTH\",\"HEALTHCARE\",\"HELP\",\"HELSINKI\",\"HERE\",\"HERMES\",\"HIPHOP\",\"HISAMITSU\",\"HITACHI\",\"HIV\",\"HK\",\"HKT\",\"HM\",\"HN\",\"HOCKEY\",\"HOLDINGS\",\"HOLIDAY\",\"HOMEDEPOT\",\"HOMEGOODS\",\"HOMES\",\"HOMESENSE\",\"HONDA\",\"HORSE\",\"HOSPITAL\",\"HOST\",\"HOSTING\",\"HOT\",\"HOTELS\",\"HOTMAIL\",\"HOUSE\",\"HOW\",\"HR\",\"HSBC\",\"HT\",\"HU\",\"HUGHES\",\"HYATT\",\"HYUNDAI\",\"IBM\",\"ICBC\",\"ICE\",\"ICU\",\"ID\",\"IE\",\"IEEE\",\"IFM\",\"IKANO\",\"IL\",\"IM\",\"IMAMAT\",\"IMDB\",\"IMMO\",\"IMMOBILIEN\",\"IN\",\"INC\",\"INDUSTRIES\",\"INFINITI\",\"INFO\",\"ING\",\"INK\",\"INSTITUTE\",\"INSURANCE\",\"INSURE\",\"INT\",\"INTERNATIONAL\",\"INTUIT\",\"INVESTMENTS\",\"IO\",\"IPIRANGA\",\"IQ\",\"IR\",\"IRISH\",\"IS\",\"ISMAILI\",\"IST\",\"ISTANBUL\",\"IT\",\"ITAU\",\"ITV\",\"JAGUAR\",\"JAVA\",\"JCB\",\"JE\",\"JEEP\",\"JETZT\",\"JEWELRY\",\"JIO\",\"JLL\",\"JM\",\"JMP\",\"JNJ\",\"JO\",\"JOBS\",\"JOBURG\",\"JOT\",\"JOY\",\"JP\",\"JPMORGAN\",\"JPRS\",\"JUEGOS\",\"JUNIPER\",\"KAUFEN\",\"KDDI\",\"KE\",\"KERRYHOTELS\",\"KERRYPROPERTIES\",\"KFH\",\"KG\",\"KH\",\"KI\",\"KIA\",\"KIDS\",\"KIM\",\"KINDLE\",\"KITCHEN\",\"KIWI\",\"KM\",\"KN\",\"KOELN\",\"KOMATSU\",\"KOSHER\",\"KP\",\"KPMG\",\"KPN\",\"KR\",\"KRD\",\"KRED\",\"KUOKGROUP\",\"KW\",\"KY\",\"KYOTO\",\"KZ\",\"LA\",\"LACAIXA\",\"LAMBORGHINI\",\"LAMER\",\"LAND\",\"LANDROVER\",\"LANXESS\",\"LASALLE\",\"LAT\",\"LATINO\",\"LATROBE\",\"LAW\",\"LAWYER\",\"LB\",\"LC\",\"LDS\",\"LEASE\",\"LECLERC\",\"LEFRAK\",\"LEGAL\",\"LEGO\",\"LEXUS\",\"LGBT\",\"LI\",\"LIDL\",\"LIFE\",\"LIFEINSURANCE\",\"LIFESTYLE\",\"LIGHTING\",\"LIKE\",\"LILLY\",\"LIMITED\",\"LIMO\",\"LINCOLN\",\"LINK\",\"LIVE\",\"LIVING\",\"LK\",\"LLC\",\"LLP\",\"LOAN\",\"LOANS\",\"LOCKER\",\"LOCUS\",\"LOL\",\"LONDON\",\"LOTTE\",\"LOTTO\",\"LOVE\",\"LPL\",\"LPLFINANCIAL\",\"LR\",\"LS\",\"LT\",\"LTD\",\"LTDA\",\"LU\",\"LUNDBECK\",\"LUXE\",\"LUXURY\",\"LV\",\"LY\",\"MA\",\"MADRID\",\"MAIF\",\"MAISON\",\"MAKEUP\",\"MAN\",\"MANAGEMENT\",\"MANGO\",\"MAP\",\"MARKET\",\"MARKETING\",\"MARKETS\",\"MARRIOTT\",\"MARSHALLS\",\"MATTEL\",\"MBA\",\"MC\",\"MCKINSEY\",\"MD\",\"ME\",\"MED\",\"MEDIA\",\"MEET\",\"MELBOURNE\",\"MEME\",\"MEMORIAL\",\"MEN\",\"MENU\",\"MERCKMSD\",\"MG\",\"MH\",\"MIAMI\",\"MICROSOFT\",\"MIL\",\"MINI\",\"MINT\",\"MIT\",\"MITSUBISHI\",\"MK\",\"ML\",\"MLB\",\"MLS\",\"MM\",\"MMA\",\"MN\",\"MO\",\"MOBI\",\"MOBILE\",\"MODA\",\"MOE\",\"MOI\",\"MOM\",\"MONASH\",\"MONEY\",\"MONSTER\",\"MORMON\",\"MORTGAGE\",\"MOSCOW\",\"MOTO\",\"MOTORCYCLES\",\"MOV\",\"MOVIE\",\"MP\",\"MQ\",\"MR\",\"MS\",\"MSD\",\"MT\",\"MTN\",\"MTR\",\"MU\",\"MUSEUM\",\"MUSIC\",\"MV\",\"MW\",\"MX\",\"MY\",\"MZ\",\"NA\",\"NAB\",\"NAGOYA\",\"NAME\",\"NAVY\",\"NBA\",\"NC\",\"NE\",\"NEC\",\"NET\",\"NETBANK\",\"NETFLIX\",\"NETWORK\",\"NEUSTAR\",\"NEW\",\"NEWS\",\"NEXT\",\"NEXTDIRECT\",\"NEXUS\",\"NF\",\"NFL\",\"NG\",\"NGO\",\"NHK\",\"NI\",\"NICO\",\"NIKE\",\"NIKON\",\"NINJA\",\"NISSAN\",\"NISSAY\",\"NL\",\"NO\",\"NOKIA\",\"NORTON\",\"NOW\",\"NOWRUZ\",\"NOWTV\",\"NP\",\"NR\",\"NRA\",\"NRW\",\"NTT\",\"NU\",\"NYC\",\"NZ\",\"OBI\",\"OBSERVER\",\"OFFICE\",\"OKINAWA\",\"OLAYAN\",\"OLAYANGROUP\",\"OLLO\",\"OM\",\"OMEGA\",\"ONE\",\"ONG\",\"ONL\",\"ONLINE\",\"OOO\",\"OPEN\",\"ORACLE\",\"ORANGE\",\"ORG\",\"ORGANIC\",\"ORIGINS\",\"OSAKA\",\"OTSUKA\",\"OTT\",\"OVH\",\"PA\",\"PAGE\",\"PANASONIC\",\"PARIS\",\"PARS\",\"PARTNERS\",\"PARTS\",\"PARTY\",\"PAY\",\"PCCW\",\"PE\",\"PET\",\"PF\",\"PFIZER\",\"PG\",\"PH\",\"PHARMACY\",\"PHD\",\"PHILIPS\",\"PHONE\",\"PHOTO\",\"PHOTOGRAPHY\",\"PHOTOS\",\"PHYSIO\",\"PICS\",\"PICTET\",\"PICTURES\",\"PID\",\"PIN\",\"PING\",\"PINK\",\"PIONEER\",\"PIZZA\",\"PK\",\"PL\",\"PLACE\",\"PLAY\",\"PLAYSTATION\",\"PLUMBING\",\"PLUS\",\"PM\",\"PN\",\"PNC\",\"POHL\",\"POKER\",\"POLITIE\",\"PORN\",\"POST\",\"PR\",\"PRAXI\",\"PRESS\",\"PRIME\",\"PRO\",\"PROD\",\"PRODUCTIONS\",\"PROF\",\"PROGRESSIVE\",\"PROMO\",\"PROPERTIES\",\"PROPERTY\",\"PROTECTION\",\"PRU\",\"PRUDENTIAL\",\"PS\",\"PT\",\"PUB\",\"PW\",\"PWC\",\"PY\",\"QA\",\"QPON\",\"QUEBEC\",\"QUEST\",\"RACING\",\"RADIO\",\"RE\",\"READ\",\"REALESTATE\",\"REALTOR\",\"REALTY\",\"RECIPES\",\"RED\",\"REDUMBRELLA\",\"REHAB\",\"REISE\",\"REISEN\",\"REIT\",\"RELIANCE\",\"REN\",\"RENT\",\"RENTALS\",\"REPAIR\",\"REPORT\",\"REPUBLICAN\",\"REST\",\"RESTAURANT\",\"REVIEW\",\"REVIEWS\",\"REXROTH\",\"RICH\",\"RICHARDLI\",\"RICOH\",\"RIL\",\"RIO\",\"RIP\",\"RO\",\"ROCKS\",\"RODEO\",\"ROGERS\",\"ROOM\",\"RS\",\"RSVP\",\"RU\",\"RUGBY\",\"RUHR\",\"RUN\",\"RW\",\"RWE\",\"RYUKYU\",\"SA\",\"SAARLAND\",\"SAFE\",\"SAFETY\",\"SAKURA\",\"SALE\",\"SALON\",\"SAMSCLUB\",\"SAMSUNG\",\"SANDVIK\",\"SANDVIKCOROMANT\",\"SANOFI\",\"SAP\",\"SARL\",\"SAS\",\"SAVE\",\"SAXO\",\"SB\",\"SBI\",\"SBS\",\"SC\",\"SCB\",\"SCHAEFFLER\",\"SCHMIDT\",\"SCHOLARSHIPS\",\"SCHOOL\",\"SCHULE\",\"SCHWARZ\",\"SCIENCE\",\"SCOT\",\"SD\",\"SE\",\"SEARCH\",\"SEAT\",\"SECURE\",\"SECURITY\",\"SEEK\",\"SELECT\",\"SENER\",\"SERVICES\",\"SEVEN\",\"SEW\",\"SEX\",\"SEXY\",\"SFR\",\"SG\",\"SH\",\"SHANGRILA\",\"SHARP\",\"SHELL\",\"SHIA\",\"SHIKSHA\",\"SHOES\",\"SHOP\",\"SHOPPING\",\"SHOUJI\",\"SHOW\",\"SI\",\"SILK\",\"SINA\",\"SINGLES\",\"SITE\",\"SJ\",\"SK\",\"SKI\",\"SKIN\",\"SKY\",\"SKYPE\",\"SL\",\"SLING\",\"SM\",\"SMART\",\"SMILE\",\"SN\",\"SNCF\",\"SO\",\"SOCCER\",\"SOCIAL\",\"SOFTBANK\",\"SOFTWARE\",\"SOHU\",\"SOLAR\",\"SOLUTIONS\",\"SONG\",\"SONY\",\"SOY\",\"SPA\",\"SPACE\",\"SPORT\",\"SPOT\",\"SR\",\"SRL\",\"SS\",\"ST\",\"STADA\",\"STAPLES\",\"STAR\",\"STATEBANK\",\"STATEFARM\",\"STC\",\"STCGROUP\",\"STOCKHOLM\",\"STORAGE\",\"STORE\",\"STREAM\",\"STUDIO\",\"STUDY\",\"STYLE\",\"SU\",\"SUCKS\",\"SUPPLIES\",\"SUPPLY\",\"SUPPORT\",\"SURF\",\"SURGERY\",\"SUZUKI\",\"SV\",\"SWATCH\",\"SWISS\",\"SX\",\"SY\",\"SYDNEY\",\"SYSTEMS\",\"SZ\",\"TAB\",\"TAIPEI\",\"TALK\",\"TAOBAO\",\"TARGET\",\"TATAMOTORS\",\"TATAR\",\"TATTOO\",\"TAX\",\"TAXI\",\"TC\",\"TCI\",\"TD\",\"TDK\",\"TEAM\",\"TECH\",\"TECHNOLOGY\",\"TEL\",\"TEMASEK\",\"TENNIS\",\"TEVA\",\"TF\",\"TG\",\"TH\",\"THD\",\"THEATER\",\"THEATRE\",\"TIAA\",\"TICKETS\",\"TIENDA\",\"TIPS\",\"TIRES\",\"TIROL\",\"TJ\",\"TJMAXX\",\"TJX\",\"TK\",\"TKMAXX\",\"TL\",\"TM\",\"TMALL\",\"TN\",\"TO\",\"TODAY\",\"TOKYO\",\"TOOLS\",\"TOP\",\"TORAY\",\"TOSHIBA\",\"TOTAL\",\"TOURS\",\"TOWN\",\"TOYOTA\",\"TOYS\",\"TR\",\"TRADE\",\"TRADING\",\"TRAINING\",\"TRAVEL\",\"TRAVELERS\",\"TRAVELERSINSURANCE\",\"TRUST\",\"TRV\",\"TT\",\"TUBE\",\"TUI\",\"TUNES\",\"TUSHU\",\"TV\",\"TVS\",\"TW\",\"TZ\",\"UA\",\"UBANK\",\"UBS\",\"UG\",\"UK\",\"UNICOM\",\"UNIVERSITY\",\"UNO\",\"UOL\",\"UPS\",\"US\",\"UY\",\"UZ\",\"VA\",\"VACATIONS\",\"VANA\",\"VANGUARD\",\"VC\",\"VE\",\"VEGAS\",\"VENTURES\",\"VERISIGN\",\"VERSICHERUNG\",\"VET\",\"VG\",\"VI\",\"VIAJES\",\"VIDEO\",\"VIG\",\"VIKING\",\"VILLAS\",\"VIN\",\"VIP\",\"VIRGIN\",\"VISA\",\"VISION\",\"VIVA\",\"VIVO\",\"VLAANDEREN\",\"VN\",\"VODKA\",\"VOLVO\",\"VOTE\",\"VOTING\",\"VOTO\",\"VOYAGE\",\"VU\",\"WALES\",\"WALMART\",\"WALTER\",\"WANG\",\"WANGGOU\",\"WATCH\",\"WATCHES\",\"WEATHER\",\"WEATHERCHANNEL\",\"WEBCAM\",\"WEBER\",\"WEBSITE\",\"WED\",\"WEDDING\",\"WEIBO\",\"WEIR\",\"WF\",\"WHOSWHO\",\"WIEN\",\"WIKI\",\"WILLIAMHILL\",\"WIN\",\"WINDOWS\",\"WINE\",\"WINNERS\",\"WME\",\"WOLTERSKLUWER\",\"WOODSIDE\",\"WORK\",\"WORKS\",\"WORLD\",\"WOW\",\"WS\",\"WTC\",\"WTF\",\"XBOX\",\"XEROX\",\"XIHUAN\",\"XIN\",\"XN--11B4C3D\",\"XN--1CK2E1B\",\"XN--1QQW23A\",\"XN--2SCRJ9C\",\"XN--30RR7Y\",\"XN--3BST00M\",\"XN--3DS443G\",\"XN--3E0B707E\",\"XN--3HCRJ9C\",\"XN--3PXU8K\",\"XN--42C2D9A\",\"XN--45BR5CYL\",\"XN--45BRJ9C\",\"XN--45Q11C\",\"XN--4DBRK0CE\",\"XN--4GBRIM\",\"XN--54B7FTA0CC\",\"XN--55QW42G\",\"XN--55QX5D\",\"XN--5SU34J936BGSG\",\"XN--5TZM5G\",\"XN--6FRZ82G\",\"XN--6QQ986B3XL\",\"XN--80ADXHKS\",\"XN--80AO21A\",\"XN--80AQECDR1A\",\"XN--80ASEHDB\",\"XN--80ASWG\",\"XN--8Y0A063A\",\"XN--90A3AC\",\"XN--90AE\",\"XN--90AIS\",\"XN--9DBQ2A\",\"XN--9ET52U\",\"XN--9KRT00A\",\"XN--B4W605FERD\",\"XN--BCK1B9A5DRE4C\",\"XN--C1AVG\",\"XN--C2BR7G\",\"XN--CCK2B3B\",\"XN--CCKWCXETD\",\"XN--CG4BKI\",\"XN--CLCHC0EA0B2G2A9GCD\",\"XN--CZR694B\",\"XN--CZRS0T\",\"XN--CZRU2D\",\"XN--D1ACJ3B\",\"XN--D1ALF\",\"XN--E1A4C\",\"XN--ECKVDTC9D\",\"XN--EFVY88H\",\"XN--FCT429K\",\"XN--FHBEI\",\"XN--FIQ228C5HS\",\"XN--FIQ64B\",\"XN--FIQS8S\",\"XN--FIQZ9S\",\"XN--FJQ720A\",\"XN--FLW351E\",\"XN--FPCRJ9C3D\",\"XN--FZC2C9E2C\",\"XN--FZYS8D69UVGM\",\"XN--G2XX48C\",\"XN--GCKR3F0F\",\"XN--GECRJ9C\",\"XN--GK3AT1E\",\"XN--H2BREG3EVE\",\"XN--H2BRJ9C\",\"XN--H2BRJ9C8C\",\"XN--HXT814E\",\"XN--I1B6B1A6A2E\",\"XN--IMR513N\",\"XN--IO0A7I\",\"XN--J1AEF\",\"XN--J1AMH\",\"XN--J6W193G\",\"XN--JLQ480N2RG\",\"XN--JVR189M\",\"XN--KCRX77D1X4A\",\"XN--KPRW13D\",\"XN--KPRY57D\",\"XN--KPUT3I\",\"XN--L1ACC\",\"XN--LGBBAT1AD8J\",\"XN--MGB9AWBF\",\"XN--MGBA3A3EJT\",\"XN--MGBA3A4F16A\",\"XN--MGBA7C0BBN0A\",\"XN--MGBAAM7A8H\",\"XN--MGBAB2BD\",\"XN--MGBAH1A3HJKRD\",\"XN--MGBAI9AZGQP6J\",\"XN--MGBAYH7GPA\",\"XN--MGBBH1A\",\"XN--MGBBH1A71E\",\"XN--MGBC0A9AZCG\",\"XN--MGBCA7DZDO\",\"XN--MGBCPQ6GPA1A\",\"XN--MGBERP4A5D4AR\",\"XN--MGBGU82A\",\"XN--MGBI4ECEXP\",\"XN--MGBPL2FH\",\"XN--MGBT3DHD\",\"XN--MGBTX2B\",\"XN--MGBX4CD0AB\",\"XN--MIX891F\",\"XN--MK1BU44C\",\"XN--MXTQ1M\",\"XN--NGBC5AZD\",\"XN--NGBE9E0A\",\"XN--NGBRX\",\"XN--NODE\",\"XN--NQV7F\",\"XN--NQV7FS00EMA\",\"XN--NYQY26A\",\"XN--O3CW4H\",\"XN--OGBPF8FL\",\"XN--OTU796D\",\"XN--P1ACF\",\"XN--P1AI\",\"XN--PGBS0DH\",\"XN--PSSY2U\",\"XN--Q7CE6A\",\"XN--Q9JYB4C\",\"XN--QCKA1PMC\",\"XN--QXA6A\",\"XN--QXAM\",\"XN--RHQV96G\",\"XN--ROVU88B\",\"XN--RVC1E0AM3E\",\"XN--S9BRJ9C\",\"XN--SES554G\",\"XN--T60B56A\",\"XN--TCKWE\",\"XN--TIQ49XQYJ\",\"XN--UNUP4Y\",\"XN--VERMGENSBERATER-CTB\",\"XN--VERMGENSBERATUNG-PWB\",\"XN--VHQUV\",\"XN--VUQ861B\",\"XN--W4R85EL8FHU5DNRA\",\"XN--W4RS40L\",\"XN--WGBH1C\",\"XN--WGBL6A\",\"XN--XHQ521B\",\"XN--XKC2AL3HYE2A\",\"XN--XKC2DL3A5EE0H\",\"XN--Y9A3AQ\",\"XN--YFRO4I67O\",\"XN--YGBI2AMMX\",\"XN--ZFR164B\",\"XXX\",\"XYZ\",\"YACHTS\",\"YAHOO\",\"YAMAXUN\",\"YANDEX\",\"YE\",\"YODOBASHI\",\"YOGA\",\"YOKOHAMA\",\"YOU\",\"YOUTUBE\",\"YT\",\"YUN\",\"ZA\",\"ZAPPOS\",\"ZARA\",\"ZERO\",\"ZIP\",\"ZM\",\"ZONE\",\"ZUERICH\",\"ZW\"];var Th=new Set(ub.map(r=>r.toLowerCase()));var Go=Th instanceof Set?{tlds:{allow:Th,deny:null}}:false;var fb={true:{true:/^(?:[\\w\\-]{2}[\\w\\-]{2})*(?:[\\w\\-]{2}==|[\\w\\-]{3}=)?$/,false:/^(?:[A-Za-z0-9+\\/]{2}[A-Za-z0-9+\\/]{2})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/},false:{true:/^(?:[\\w\\-]{2}[\\w\\-]{2})*(?:[\\w\\-]{2}(==)?|[\\w\\-]{3}=?)?$/,false:/^(?:[A-Za-z0-9+\\/]{2}[A-Za-z0-9+\\/]{2})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?$/}};var tv=/^data:[\\w+.-]+\\/[\\w+.-]+;((charset=[\\w-]+|base64),)?(.*)$/;var xh={withPrefix:/^0x[0-9a-f]+$/i,withOptionalPrefix:/^(?:0x)?[0-9a-f]+$/i,withoutPrefix:/^[0-9a-f]+$/i};var rv=Xn({cidr:\"forbidden\"}).regex;var sv=/^P(?!$)(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?$/;var _l={\"{\":\"}\",\"[\":\"]\",\"(\":\")\",\"\":\"\"};var db={uuidv1:\"1\",uuidv2:\"2\",uuidv3:\"3\",uuidv4:\"4\",uuidv5:\"5\",uuidv6:\"6\",uuidv7:\"7\",uuidv8:\"8\"};var nv=new Set([void 0,true,false,\"-\",\":\"]);var hb=[\"NFC\",\"NFD\",\"NFKC\",\"NFKD\"];var iv=_e.extend({type:\"string\",flags:{insensitive:{default:false},truncate:{default:false}},terms:{replacements:{init:null}},coerce:{from:\"string\",method(r,{schema:e,state:t,prefs:s}){const n=e.$_getRule(\"normalize\");if(n){r=r.normalize(n.args.form)}const i=e.$_getRule(\"case\");if(i){r=i.args.direction===\"upper\"?r.toLocaleUpperCase():r.toLocaleLowerCase()}const o=e.$_getRule(\"trim\");if(o&&o.args.enabled){r=r.trim()}if(e.$_terms.replacements){for(const l of e.$_terms.replacements){r=r.replace(l.pattern,l.replacement)}}const c=e.$_getRule(\"hex\");if(c&&c.args.options.byteAligned&&r.length%2!==0){r=`0${r}`}if(e.$_getRule(\"isoDate\")){const l=mb(r);if(l){r=l}}if(e._flags.truncate){const l=e.$_getRule(\"max\");if(l){let u=l.args.limit;if(tt(u)){u=u.resolve(r,t,s);if(!Cr(u)){return{value:r,errors:e.$_createError(\"any.ref\",u,{ref:l.args.limit,arg:\"limit\",reason:\"must be a positive integer\"},t,s)}}}r=av(r,u)}}return{value:r}}},validate(r,{schema:e,error:t}){if(typeof r!==\"string\"){return{value:r,errors:t(\"string.base\")}}if(r===\"\"){const s=e.$_getRule(\"min\");if(s&&s.args.limit===0){return}return{value:r,errors:t(\"string.empty\")}}},rules:{alphanum:{method(){return this.$_addRule(\"alphanum\")},validate(r,e){if(/^[a-zA-Z0-9]+$/.test(r)){return r}return e.error(\"string.alphanum\")}},base64:{method(r={}){re(r,[\"paddingRequired\",\"urlSafe\"]);r={urlSafe:false,paddingRequired:true,...r};g(typeof r.paddingRequired===\"boolean\",\"paddingRequired must be boolean\");g(typeof r.urlSafe===\"boolean\",\"urlSafe must be boolean\");return this.$_addRule({name:\"base64\",args:{options:r}})},validate(r,e,{options:t}){const s=fb[t.paddingRequired][t.urlSafe];if(s.test(r)){return r}return e.error(\"string.base64\")}},case:{method(r){g([\"lower\",\"upper\"].includes(r),\"Invalid case:\",r);return this.$_addRule({name:\"case\",args:{direction:r}})},validate(r,e,{direction:t}){if(t===\"lower\"&&r===r.toLocaleLowerCase()||t===\"upper\"&&r===r.toLocaleUpperCase()){return r}return e.error(`string.${t}case`)},convert:true},creditCard:{method(){return this.$_addRule(\"creditCard\")},validate(r,e){let t=r.length;let s=0;let n=1;while(t--){const i=r.charAt(t)*n;s=s+(i-(i>9)*9);n=n^3}if(s>0&&s%10===0){return r}return e.error(\"string.creditCard\")}},dataUri:{method(r={}){re(r,[\"paddingRequired\"]);r={paddingRequired:true,...r};g(typeof r.paddingRequired===\"boolean\",\"paddingRequired must be boolean\");return this.$_addRule({name:\"dataUri\",args:{options:r}})},validate(r,e,{options:t}){const s=r.match(tv);if(s){if(!s[2]){return r}if(s[2]!==\"base64\"){return r}const n=fb[t.paddingRequired].false;if(n.test(s[3])){return r}}return e.error(\"string.dataUri\")}},domain:{method(r){if(r){re(r,[\"allowFullyQualified\",\"allowUnicode\",\"allowUnderscore\",\"maxDomainSegments\",\"minDomainSegments\",\"tlds\"])}const e=Rh(r);return this.$_addRule({name:\"domain\",args:{options:r},address:e})},validate(r,e,t,{address:s}){if(qo(r,s)){return r}return e.error(\"string.domain\")}},email:{method(r={}){re(r,[\"allowFullyQualified\",\"allowUnicode\",\"ignoreLength\",\"maxDomainSegments\",\"minDomainSegments\",\"multiple\",\"separator\",\"tlds\"]);g(r.multiple===void 0||typeof r.multiple===\"boolean\",\"multiple option must be an boolean\");const e=Rh(r);const t=new RegExp(`\\\\s*[${r.separator?mt(r.separator):\",\"}]\\\\s*`);return this.$_addRule({name:\"email\",args:{options:r},regex:t,address:e})},validate(r,e,{options:t},{regex:s,address:n}){const i=t.multiple?r.split(s):[r];const o=[];for(const c of i){if(!zo(c,n)){o.push(c)}}if(!o.length){return r}return e.error(\"string.email\",{value:r,invalids:o})}},format:{method(r){g(typeof r===\"string\"&&Object.prototype.hasOwnProperty.call(Yn,r),\"Unknown format\",r);return this.$_addRule({name:\"format\",args:{name:r}})},validate(r,e,{name:t}){if(Yn[t](r))return r;return e.error(\"string.format\",{format:t})},args:[\"name\"]},guid:{alias:\"uuid\",method(r={}){re(r,[\"version\",\"separator\",\"wrapper\"]);g(r.wrapper===void 0||typeof r.wrapper===\"boolean\"||typeof r.wrapper===\"string\"&&typeof _l[r.wrapper]===\"string\",`\"wrapper\" must be true, false, or one of \"${Object.keys(_l).filter(Boolean).join('\", \"')}\"`);let e=\"\";if(r.version){const o=[].concat(r.version);g(o.length>=1,\"version must have at least 1 valid version specified\");const c=new Set;for(let l=0;l<o.length;++l){const u=o[l];g(typeof u===\"string\",\"version at position \"+l+\" must be a string\");const f=db[u.toLowerCase()];g(f,\"version at position \"+l+\" must be one of \"+Object.keys(db).join(\", \"));g(!c.has(f),\"version at position \"+l+\" must not be a duplicate\");e+=f;c.add(f)}}g(nv.has(r.separator),'separator must be one of true, false, \"-\", or \":\"');const t=r.separator===void 0?\"[:-]?\":r.separator===true?\"[:-]\":r.separator===false?\"[]?\":`\\\\${r.separator}`;let s;let n;if(r.wrapper===void 0){s=\"[\\\\[{\\\\(]?\";n=\"[\\\\]}\\\\)]?\"}else if(r.wrapper===true){s=\"[\\\\[{\\\\(]\";n=\"[\\\\]}\\\\)]\"}else if(r.wrapper===false){s=\"\";n=\"\"}else{s=mt(r.wrapper);n=mt(_l[r.wrapper])}const i=new RegExp(`^(${s})[0-9A-F]{8}(${t})[0-9A-F]{4}\\\\2?[${e||\"0-9A-F\"}][0-9A-F]{3}\\\\2?[${e?\"89AB\":\"0-9A-F\"}][0-9A-F]{3}\\\\2?[0-9A-F]{12}(${n})$`,\"i\");return this.$_addRule({name:\"guid\",args:{options:r},regex:i})},validate(r,e,t,{regex:s}){const n=s.exec(r);if(!n){return e.error(\"string.guid\")}const i=n[1];const o=n[n.length-1];if((i||o)&&_l[i]!==o){return e.error(\"string.guid\")}return r}},hex:{method(r={}){re(r,[\"byteAligned\",\"prefix\"]);r={byteAligned:false,prefix:false,...r};g(typeof r.byteAligned===\"boolean\",\"byteAligned must be boolean\");g(typeof r.prefix===\"boolean\"||r.prefix===\"optional\",'prefix must be boolean or \"optional\"');return this.$_addRule({name:\"hex\",args:{options:r}})},validate(r,e,{options:t}){const s=t.prefix===\"optional\"?xh.withOptionalPrefix:t.prefix===true?xh.withPrefix:xh.withoutPrefix;if(!s.test(r)){return e.error(\"string.hex\")}if(t.byteAligned&&r.length%2!==0){return e.error(\"string.hexAlign\")}return r}},hostname:{method(){return this.$_addRule(\"hostname\")},validate(r,e){if(qo(r,{minDomainSegments:1})||rv.test(r)){return r}return e.error(\"string.hostname\")}},insensitive:{method(){return this.$_setFlag(\"insensitive\",true)}},ip:{method(r={}){re(r,[\"cidr\",\"version\"]);const{cidr:e,versions:t,regex:s}=Fn(()=>Xn(r));const n=r.version?t:void 0;return this.$_addRule({name:\"ip\",args:{options:{cidr:e,version:n}},regex:s})},validate(r,e,{options:t},{regex:s}){if(s.test(r)){return r}if(t.version){return e.error(\"string.ipVersion\",{value:r,cidr:t.cidr,version:t.version})}return e.error(\"string.ip\",{value:r,cidr:t.cidr})}},isoDate:{method(){return this.$_addRule(\"isoDate\")},validate(r,{error:e}){if(mb(r)){return r}return e(\"string.isoDate\")}},isoDuration:{method(){return this.$_addRule(\"isoDuration\")},validate(r,e){if(sv.test(r)){return r}return e.error(\"string.isoDuration\")}},length:{method(r,e){return _h(this,\"length\",r,\"=\",e)},validate(r,e,{limit:t,encoding:s},{name:n,operator:i,args:o}){let c;if(s){c=Buffer&&Buffer.byteLength(r,s)}else{const l=r.length;const u=ot(Math.ceil(l/2),t,i);c=u===ot(l,t,i)?l:ov(r)}if(ot(c,t,i)){return r}return e.error(\"string.\"+n,{limit:o.limit,value:r,encoding:s})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"},\"encoding\"]},lowercase:{method(){return this.case(\"lower\")}},max:{method(r,e){return _h(this,\"max\",r,\"<=\",e)},args:[\"limit\",\"encoding\"]},min:{method(r,e){return _h(this,\"min\",r,\">=\",e)},args:[\"limit\",\"encoding\"]},normalize:{method(r=\"NFC\"){g(hb.includes(r),\"normalization form must be one of \"+hb.join(\", \"));return this.$_addRule({name:\"normalize\",args:{form:r}})},validate(r,{error:e},{form:t}){if(r===r.normalize(t)){return r}return e(\"string.normalize\",{value:r,form:t})},convert:true},pattern:{alias:\"regex\",method(r,e={}){g(r instanceof RegExp,\"regex must be a RegExp\");g(!r.flags.includes(\"g\")&&!r.flags.includes(\"y\"),\"regex should not use global or sticky mode\");if(typeof e===\"string\"){e={name:e}}re(e,[\"invert\",\"name\"]);const t=[\"string.pattern\",e.invert?\".invert\":\"\",e.name?\".name\":\".base\"].join(\"\");return this.$_addRule({name:\"pattern\",args:{regex:r,options:e},errorCode:t})},validate(r,e,{regex:t,options:s},{errorCode:n}){const i=t.test(r);if(i^s.invert){return r}return e.error(n,{name:s.name,regex:t,value:r})},args:[\"regex\",\"options\"],multi:true},replace:{method(r,e){if(typeof r===\"string\"){r=new RegExp(mt(r),\"g\")}g(r instanceof RegExp,\"pattern must be a RegExp\");g(typeof e===\"string\",\"replacement must be a String\");const t=this.clone();if(!t.$_terms.replacements){t.$_terms.replacements=[]}t.$_terms.replacements.push({pattern:r,replacement:e});return t}},token:{method(){return this.$_addRule(\"token\")},validate(r,e){if(/^\\w+$/.test(r)){return r}return e.error(\"string.token\")}},trim:{method(r=true){g(typeof r===\"boolean\",\"enabled must be a boolean\");return this.$_addRule({name:\"trim\",args:{enabled:r}})},validate(r,e,{enabled:t}){if(!t||r===r.trim()){return r}return e.error(\"string.trim\")},convert:true},truncate:{method(r=true){g(typeof r===\"boolean\",\"enabled must be a boolean\");return this.$_setFlag(\"truncate\",r)}},uppercase:{method(){return this.case(\"upper\")}},uri:{method(r={}){re(r,[\"allowRelative\",\"allowQuerySquareBrackets\",\"domain\",\"relativeOnly\",\"scheme\",\"encodeUri\"]);if(r.domain){re(r.domain,[\"allowFullyQualified\",\"allowUnicode\",\"maxDomainSegments\",\"minDomainSegments\",\"tlds\"])}const{regex:e,scheme:t}=Fn(()=>Vn(r));const s=r.domain?Rh(r.domain):null;return this.$_addRule({name:\"uri\",args:{options:r},regex:e,domain:s,scheme:t})},validate(r,e,{options:t},{regex:s,domain:n,scheme:i}){if([\"http:/\",\"https:/\"].includes(r)){return e.error(\"string.uri\")}let o=s.exec(r);if(!o&&e.prefs.convert&&t.encodeUri){const c=encodeURI(r);o=s.exec(c);if(o){r=c}}if(o){const c=o[1]||o[2];if(n&&(!t.allowRelative||c)&&!qo(c,n)){return e.error(\"string.domain\",{value:c})}return r}if(t.relativeOnly){return e.error(\"string.uriRelativeOnly\")}if(t.scheme){return e.error(\"string.uriCustomScheme\",{scheme:i,value:r})}return e.error(\"string.uri\")}}},manifest:{build(r,e){if(e.replacements){for(const{pattern:t,replacement:s}of e.replacements){r=r.replace(t,s)}}return r}},messages:{\"string.alphanum\":\"{{#label}} must only contain alpha-numeric characters\",\"string.base\":\"{{#label}} must be a string\",\"string.base64\":\"{{#label}} must be a valid base64 string\",\"string.creditCard\":\"{{#label}} must be a credit card\",\"string.dataUri\":\"{{#label}} must be a valid dataUri string\",\"string.domain\":\"{{#label}} must contain a valid domain name\",\"string.email\":\"{{#label}} must be a valid email\",\"string.empty\":\"{{#label}} is not allowed to be empty\",\"string.format\":\"{{#label}} must be a valid {{#format}}\",\"string.guid\":\"{{#label}} must be a valid GUID\",\"string.hex\":\"{{#label}} must only contain hexadecimal characters\",\"string.hexAlign\":\"{{#label}} hex decoded representation must be byte aligned\",\"string.hostname\":\"{{#label}} must be a valid hostname\",\"string.ip\":\"{{#label}} must be a valid ip address with a {{#cidr}} CIDR\",\"string.ipVersion\":\"{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR\",\"string.isoDate\":\"{{#label}} must be in iso format\",\"string.isoDuration\":\"{{#label}} must be a valid ISO 8601 duration\",\"string.length\":\"{{#label}} length must be {{#limit}} characters long\",\"string.lowercase\":\"{{#label}} must only contain lowercase characters\",\"string.max\":\"{{#label}} length must be less than or equal to {{#limit}} characters long\",\"string.min\":\"{{#label}} length must be at least {{#limit}} characters long\",\"string.normalize\":\"{{#label}} must be unicode normalized in the {{#form}} form\",\"string.token\":\"{{#label}} must only contain alpha-numeric and underscore characters\",\"string.pattern.base\":\"{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}\",\"string.pattern.name\":\"{{#label}} with value {:[.]} fails to match the {{#name}} pattern\",\"string.pattern.invert.base\":\"{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}\",\"string.pattern.invert.name\":\"{{#label}} with value {:[.]} matches the inverted {{#name}} pattern\",\"string.trim\":\"{{#label}} must not have leading or trailing whitespace\",\"string.uri\":\"{{#label}} must be a valid uri\",\"string.uriCustomScheme\":\"{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern\",\"string.uriRelativeOnly\":\"{{#label}} must be a valid relative uri\",\"string.uppercase\":\"{{#label}} must only contain uppercase characters\"}});var gb=iv;function Rh(r){if(!r){return Go||r}g(r.minDomainSegments===void 0||Number.isSafeInteger(r.minDomainSegments)&&r.minDomainSegments>0,\"minDomainSegments must be a positive integer\");g(r.maxDomainSegments===void 0||Number.isSafeInteger(r.maxDomainSegments)&&r.maxDomainSegments>0,\"maxDomainSegments must be a positive integer\");if(r.tlds===false){return r}if(r.tlds===true||r.tlds===void 0){g(Go,\"Built-in TLD list disabled\");return Object.assign({},r,Go)}g(typeof r.tlds===\"object\",\"tlds must be true, false, or an object\");const e=r.tlds.deny;if(e){if(Array.isArray(e)){r=Object.assign({},r,{tlds:{deny:new Set(e)}})}g(r.tlds.deny instanceof Set,\"tlds.deny must be an array, Set, or boolean\");g(!r.tlds.allow,\"Cannot specify both tlds.allow and tlds.deny lists\");pb(r.tlds.deny,\"tlds.deny\");return r}const t=r.tlds.allow;if(!t){return{...r,tlds:false}}if(t===true){g(Go,\"Built-in TLD list disabled\");return Object.assign({},r,Go)}if(Array.isArray(t)){r=Object.assign({},r,{tlds:{allow:new Set(t)}})}g(r.tlds.allow instanceof Set,\"tlds.allow must be an array, Set, or boolean\");pb(r.tlds.allow,\"tlds.allow\");return r}a(Rh,\"addressOptions\");function pb(r,e){for(const t of r){g(qo(t,{minDomainSegments:1,maxDomainSegments:1}),`${e} must contain valid top level domain names`)}}a(pb,\"validateTlds\");function mb(r){if(!ol(r)){return null}if(/.*T.*[+-]\\d\\d$/.test(r)){r+=\"00\"}const e=new Date(r);if(isNaN(e.getTime())){return null}return e.toISOString()}a(mb,\"isoDate\");function ov(r){let e=r.length;for(let t=0;t<r.length-1;++t){const s=r.charCodeAt(t);if(s>=55296&&s<=56319){const n=r.charCodeAt(t+1);if(n>=56320&&n<=57343){--e;++t}}}return e}a(ov,\"codePointLength\");function av(r,e){if(r.length<=e)return r;let t=0;for(let s=0;s<e&&t<r.length;++s){const n=r.charCodeAt(t);const i=r.charCodeAt(t+1);t+=n>=55296&&n<=56319&&i>=56320&&i<=57343?2:1}return r.slice(0,t)}a(av,\"codePointSlice\");function _h(r,e,t,s,n){g(!n||Buffer&&Buffer.isEncoding(n),\"Invalid encoding:\",n);return r.$_addRule({name:e,method:\"length\",args:{limit:t,encoding:n},operator:s})}a(_h,\"length\");var Ch=class r extends Map{static{a(this,\"SymbolMap\")}slice(){return new r(this)}};var cv=_e.extend({type:\"symbol\",terms:{map:{init:new Ch}},coerce:{method(r,{schema:e,error:t}){const s=e.$_terms.map.get(r);if(s)r=s;if(!e._flags.only||typeof r===\"symbol\"){return{value:r}}return{value:r,errors:t(\"symbol.map\",{map:e.$_terms.map})}}},validate(r,{error:e}){if(typeof r!==\"symbol\")return{value:r,errors:e(\"symbol.base\")}},rules:{map:{method(r){if(r&&!r[Symbol.iterator]&&typeof r===\"object\"){r=Object.entries(r)}g(r&&r[Symbol.iterator],\"Iterable must be an iterable or object\");const e=this.clone();const t=[];for(const s of r){g(s&&s[Symbol.iterator],\"Entry must be an iterable\");const[n,i]=s;g(typeof n!==\"object\"&&typeof n!==\"function\"&&typeof n!==\"symbol\",\"Key must not be of type object, function, or Symbol\");g(typeof i===\"symbol\",\"Value must be a Symbol\");e.$_terms.map.set(n,i);t.push(i)}return e.valid(...t)}}},manifest:{build(r,e){if(e.map)r=r.map(e.map);return r}},messages:{\"symbol.base\":\"{{#label}} must be a symbol\",\"symbol.map\":\"{{#label}} must be one of {{#map}}\"}});var yb=cv;var lv=_e.extend({type:\"binary\",coerce:{from:[\"string\",\"object\"],method(r,{schema:e}){if(typeof r===\"string\"||r!==null&&r.type===\"Buffer\"){try{return{value:Buffer.from(r,e._flags.encoding)}}catch{}}}},validate(r,{error:e}){if(!Buffer.isBuffer(r))return{value:r,errors:e(\"binary.base\")}},rules:{encoding:{method(r){g(Buffer.isEncoding(r),\"Invalid encoding:\",r);return this.$_setFlag(\"encoding\",r)}},length:{method(r){return this.$_addRule({name:\"length\",method:\"length\",args:{limit:r},operator:\"=\"})},validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(r.length,t,n))return r;return e.error(\"binary.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"}]},max:{method(r){return this.$_addRule({name:\"max\",method:\"length\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"length\",args:{limit:r},operator:\">=\"})}}},cast:{string:{from:a(r=>Buffer.isBuffer(r),\"from\"),to(r){return r.toString()}}},messages:{\"binary.base\":\"{{#label}} must be a buffer or a string\",\"binary.length\":\"{{#label}} must be {{#limit}} bytes\",\"binary.max\":\"{{#label}} must be less than or equal to {{#limit}} bytes\",\"binary.min\":\"{{#label}} must be at least {{#limit}} bytes\"}});var bb=lv;var Ko={};var Sb=false;function Cl(){if(!Sb){Sb=true;uv()}return Ko}a(Cl,\"getSchemas\");function uv(){const r=b.string().min(1).max(2).allow(false);Ko.preferences=b.object({allowUnknown:b.boolean(),abortEarly:b.boolean(),artifacts:b.boolean(),cache:b.boolean(),context:b.object(),convert:b.boolean(),dateFormat:b.valid(\"date\",\"iso\",\"string\",\"time\",\"utc\"),debug:b.boolean(),errors:{escapeHtml:b.boolean(),label:b.valid(\"path\",\"key\",false),language:[b.string(),b.object().ref()],render:b.boolean(),stack:b.boolean(),wrap:{label:r,array:r,string:r}},externals:b.boolean(),messages:b.object(),noDefaults:b.boolean(),nonEnumerables:b.boolean(),presence:b.valid(\"required\",\"optional\",\"forbidden\"),skipFunctions:b.boolean(),stripUnknown:b.object({arrays:b.boolean(),objects:b.boolean()}).or(\"arrays\",\"objects\").allow(true,false),warnings:b.boolean()}).strict();const e=/^[a-zA-Z0-9]\\w*$/;const t=b.object({alias:b.array().items(b.string().pattern(e)).single(),args:b.array().items(b.string(),b.object({name:b.string().pattern(e).required(),ref:b.boolean(),assert:b.alternatives([b.function(),b.object().schema()]).conditional(\"ref\",{is:true,then:b.required()}),normalize:b.function(),message:b.string().when(\"assert\",{is:b.function(),then:b.required()})})),convert:b.boolean(),manifest:b.boolean(),method:b.function().allow(false),multi:b.boolean(),validate:b.function()});Ko.extension=b.object({type:b.alternatives([b.string(),b.object().regex()]).required(),args:b.function(),cast:b.object().pattern(e,b.object({from:b.function().maxArity(1).required(),to:b.function().minArity(1).maxArity(2).required()})),base:b.object().schema().when(\"type\",{is:b.object().regex(),then:b.forbidden()}),coerce:[b.function().maxArity(3),b.object({method:b.function().maxArity(3).required(),from:b.array().items(b.string()).single()})],flags:b.object().pattern(e,b.object({setter:b.string(),default:b.any()})),manifest:{build:b.function().arity(2)},messages:[b.object(),b.string()],modifiers:b.object().pattern(e,b.function().minArity(1).maxArity(2)),overrides:b.object().pattern(e,b.function()),prepare:b.function().maxArity(3),rebuild:b.function().arity(1),rules:b.object().pattern(e,t),terms:b.object().pattern(e,b.object({init:b.array().allow(null).required(),manifest:b.object().pattern(/.+/,[b.valid(\"schema\",\"single\"),b.object({mapped:b.object({from:b.string().required(),to:b.string().required()}).required()})])})),validate:b.function().maxArity(3)}).strict();Ko.extensions=b.array().items(b.object(),b.function().arity(1)).strict();const s={buffer:b.object({buffer:b.string()}),func:b.object({function:b.function().required(),options:{literal:true}}),override:b.object({override:true}),ref:b.object({ref:b.object({type:b.valid(\"value\",\"global\",\"local\"),path:b.array().required(),separator:b.string().length(1).allow(false),ancestor:b.number().min(0).integer().allow(\"root\"),map:b.array().items(b.array().length(2)).min(1),adjust:b.function(),iterables:b.boolean(),in:b.boolean(),render:b.boolean()}).required()}),regex:b.object({regex:b.string().min(3)}),special:b.object({special:b.valid(\"deep\").required()}),template:b.object({template:b.string().required(),options:b.object()}),value:b.object({value:b.alternatives([b.object(),b.array()]).required()})};s.entity=b.alternatives([b.array().items(b.link(\"...\")),b.boolean(),b.function(),b.number(),b.string(),s.buffer,s.func,s.ref,s.regex,s.special,s.template,s.value,b.link(\"/\")]);s.values=b.array().items(null,b.boolean(),b.function(),b.number().allow(Infinity,-Infinity),b.string().allow(\"\"),b.symbol(),s.buffer,s.func,s.override,s.ref,s.regex,s.template,s.value);s.messages=b.object().pattern(/.+/,[b.string(),s.template,b.object().pattern(/.+/,[b.string(),s.template])]);Ko.description=b.object({type:b.string().required(),flags:b.object({cast:b.string(),default:b.any(),description:b.string(),empty:b.link(\"/\"),failover:s.entity,id:b.string(),label:b.string(),only:true,presence:[\"optional\",\"required\",\"forbidden\"],result:[\"raw\",\"strip\"],strip:b.boolean(),unit:b.string()}).unknown(),preferences:{allowUnknown:b.boolean(),abortEarly:b.boolean(),artifacts:b.boolean(),cache:b.boolean(),convert:b.boolean(),dateFormat:[\"date\",\"iso\",\"string\",\"time\",\"utc\"],errors:{escapeHtml:b.boolean(),label:[\"path\",\"key\"],language:[b.string(),s.ref],wrap:{label:r,array:r}},externals:b.boolean(),messages:s.messages,noDefaults:b.boolean(),nonEnumerables:b.boolean(),presence:[\"required\",\"optional\",\"forbidden\"],skipFunctions:b.boolean(),stripUnknown:b.object({arrays:b.boolean(),objects:b.boolean()}).or(\"arrays\",\"objects\").allow(true,false),warnings:b.boolean()},allow:s.values,invalid:s.values,rules:b.array().min(1).items({name:b.string().required(),args:b.object().min(1),keep:b.boolean(),message:[b.string(),s.messages],warn:b.boolean()}),keys:b.object().pattern(/.*/,b.link(\"/\")),link:s.ref}).pattern(/^[a-z]\\w*$/,b.any())}a(uv,\"build\");gt.schemas=Cl;var vl;var vh={alternatives:Uy,any:_e,array:Fy,boolean:zy,date:Wy,function:Vy,link:Yy,number:Qy,object:eb,string:gb,symbol:yb};var Ah={alt:\"alternatives\",bool:\"boolean\",func:\"function\"};if(Buffer)vh.binary=bb;function fv(){const r={_types:new Set(Object.keys(vh))};for(const e of r._types){r[e]=function(...t){g(!t.length||[\"alternatives\",\"link\",\"object\"].includes(e),\"The\",e,\"type does not allow arguments\");return Ih(this,vh[e],t)}}for(const e of[\"allow\",\"custom\",\"disallow\",\"equal\",\"exist\",\"forbidden\",\"invalid\",\"not\",\"only\",\"optional\",\"options\",\"prefs\",\"preferences\",\"required\",\"strip\",\"valid\",\"when\"]){r[e]=function(...t){const s=this.any();return s[e].call(s,...t)}}Object.assign(r,dv);for(const e in Ah){const t=Ah[e];r[e]=r[t]}r.x=r.expression;if(ch)ch(r);return r}a(fv,\"createRoot\");var dv={ValidationError:qt,version:ns,cache:cl,assert(r,e,...t){wb(r,e,true,t)},attempt(r,e,...t){return wb(r,e,false,t)},build(r){g(typeof sh===\"function\",\"Manifest functionality disabled\");return sh(this,r)},checkPreferences(r){Mo(r)},compile(r,e){return fl(this,r,e)},defaults(r){g(typeof r===\"function\",\"modifier must be a function\");const e=Object.assign({},this);for(const t of e._types){const s=r(e[t].call(e));g(oe(s),\"modifier must return a valid schema object\");e[t]=function(...n){return Ih(this,s,n)}}return e},expression(r,e){return new se(r,e)},extend(...r){Be(r,\"extend\");vl=vl||Cl();g(r.length,\"You need to provide at least one extension\");this.assert(r,vl.extensions);const e=Object.assign({},this);e._types=new Set(e._types);for(let t of r){if(typeof t===\"function\")t=t(e);this.assert(t,vl.extension);const s=hv(t,e);for(const n of s){g(e[n.type]===void 0||e._types.has(n.type),\"Cannot override name\",n.type);const i=n.base||this.any();const o=yl(i,n);e._types.add(n.type);e[n.type]=function(...c){return Ih(this,o,c)}}}return e},isError:qt.isError,isExpression:se.isTemplate,isRef:rt,isSchema:oe,in(r,e){return ty(r,e)},override:H.override,ref(r,e){return as(r,e)},types(){const r={};for(const e of this._types)r[e]=this[e].call(this);for(const e in Ah)r[e]=this[e].call(this);return r}};function wb(r,e,t,s){const n=s[0]instanceof Error||typeof s[0]===\"string\"?s[0]:null;const i=n!==null?s[1]:s[0];const o=e.validate(r,Ht({errors:{stack:true}},i||{}));let c=o.error;if(!c)return o.value;if(n instanceof Error)throw n;const l=t&&typeof c.annotate===\"function\"?c.annotate():c.message;if(c instanceof qt===false)c=G(c);ss(c,n?`${n} ${l}`:l);throw c}a(wb,\"assertValue\");function Ih(r,e,t){g(r,\"Must be invoked on a validation root.\");e.$_root=r;if(!e._definition.args||!t.length)return e;return e._definition.args(e,...t)}a(Ih,\"generate\");function hv(r,e){if(typeof r.type===\"string\")return[r];const t=[];for(const s of e._types){if(r.type.test(s)){const n=Object.assign({},r);n.type=s;n.base=e[s].call(e);t.push(n)}}return t}a(hv,\"expandExtension\");var pv=fv();var b=pv;var Jn=a(r=>typeof r===\"bigint\",\"isBigint\");var mv=a(r=>({type:\"bigint\",messages:{\"bigint.base\":\"{{#label}} must be a bigint\",\"bigint.greater\":\"{{#label}} must be greater than {{#limit}}\",\"bigint.less\":\"{{#label}} must be less than {{#limit}}\",\"bigint.max\":\"{{#label}} must be less than or equal to {{#limit}}\",\"bigint.min\":\"{{#label}} must be greater than or equal to {{#limit}}\",\"bigint.multiple\":\"{{#label}} must be a multiple of {{#base}}\",\"bigint.negative\":\"{{#label}} must be a negative number\",\"bigint.port\":\"{{#label}} must be a valid port\",\"bigint.positive\":\"{{#label}} must be a positive number\"},coerce(e){if(typeof e===\"string\"||typeof e===\"number\"&&Number.isInteger(e)){try{return{value:BigInt(e)}}catch{}}return{value:e}},validate(e,t){if(!Jn(e))return{value:e,errors:t.error(\"bigint.base\")}},rules:{greater:{method(e){return this.$_addRule({name:\"greater\",args:{limit:e}})},validate(e,t,{limit:s}){return e>s?e:t.error(\"bigint.greater\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},less:{method(e){return this.$_addRule({name:\"less\",args:{limit:e}})},validate(e,t,{limit:s}){return e<s?e:t.error(\"bigint.less\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},max:{method(e){return this.$_addRule({name:\"max\",args:{limit:e}})},validate(e,t,{limit:s}){return e<=s?e:t.error(\"bigint.max\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},min:{method(e){return this.$_addRule({name:\"min\",args:{limit:e}})},validate(e,t,{limit:s}){return e>=s?e:t.error(\"bigint.min\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},multiple:{method(e){return this.$_addRule({name:\"multiple\",args:{base:e}})},validate(e,t,{base:s}){return e%s===0n?e:t.error(\"bigint.multiple\",{base:s.toString()})},args:[{name:\"base\",ref:true,assert:a(e=>Jn(e)&&e>0n,\"assert\"),message:\"must be a positive bigint\"}],multi:true},negative:{method(){return this.$_addRule({name:\"negative\"})},validate(e,t){return e<0n?e:t.error(\"bigint.negative\")}},port:{method(){return this.$_addRule({name:\"port\"})},validate(e,t){return e>=0n&&e<=65535n?e:t.error(\"bigint.port\")}},positive:{method(){return this.$_addRule({name:\"positive\"})},validate(e,t){return e>0n?e:t.error(\"bigint.positive\")}},sign:{method(e){return this.$_addRule({name:\"sign\",args:{sign:e}})},validate(e,t,{sign:s}){return s===\"negative\"&&e<0n||s===\"positive\"&&e>0n?e:t.error(`bigint.${s}`)},args:[{name:\"sign\",assert:a(e=>[\"negative\",\"positive\"].includes(e),\"assert\"),message:'must be \"negative\" or \"positive\"'}]}}}),\"bigintExtension\");var Eb=a(r=>{return r.extend(mv)},\"extendBigInt\");var Tb=require(\"node:async_hooks\");var gv=new Tb.AsyncLocalStorage;function Oh(){return gv.getStore()}a(Oh,\"currentValidationLanguage\");var ur=class extends Z{static{a(this,\"InvalidValueException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_VALUE\";this.statusCode=400}};function hs(r,e){r.cause=e;return r}a(hs,\"withCause\");var Wo=Object.freeze({abortEarly:true,cache:false,allowUnknown:true,stripUnknown:true,convert:true});var xb={next:new Map};var kh=0;var yv=1e3;function Ph(r){if(Object.getOwnPropertySymbols(r).length)return{...Wo,...r};let e=xb;for(const t of Object.keys(r)){const s=r[t];if(s!==null&&typeof s===\"object\"||typeof s===\"function\"||Object.is(s,-0))return{...Wo,...r};let n=e.next.get(t);if(!n){n=new Map;e.next.set(t,n)}let i=n.get(s);if(!i){i={next:new Map};n.set(s,i)}e=i}if(!e.merged){if(kh>=yv){xb={next:new Map};kh=0}e.merged=Object.freeze({...Wo,...r});kh++}return e.merged}a(Ph,\"mergeOptions\");var Rb=new WeakMap;function _b(r,e){if(!b.isSchema(r))return b.object({[e]:r});let t=Rb.get(r);if(!t){t=new Map;Rb.set(r,t)}let s=t.get(e);if(!s){s=b.object({[e]:r});t.set(e,s)}return s}a(_b,\"targetSchema\");var Nh=class{static{a(this,\"ValidateMethods\")}isSchema(e){return b.isSchema(e)}isValid(e,t,s={}){try{this.validate(e,t,s);return true}catch(n){return false}}async isValidAsync(e,t,s={}){try{await this.validateAsync(e,t,s);return true}catch(n){return false}}validate(e,t,s={}){try{return this.validateIn(e,t,s)}catch(n){const i=Cb(s);if(!i)throw n;return this.validateIn(e,t,{...s,errors:{...v(s).errors,language:i}})}}validateIn(e,t,s){s=Ph(s);let n;let i;if(s.targetName){const o=_b(t,s.targetName).validate({[s.targetName]:e},v(s));n=o.error;i=v(o.value)[s.targetName]}else{const o=v(t).validate(e,v(s));n=o.error;i=v(o.value)}if(n)throw hs(new ur(n.message),n);return i}async validateAsync(e,t,s={}){try{return await this.validateAsyncIn(e,t,s)}catch(n){const i=Cb(s);if(!i)throw n;return await this.validateAsyncIn(e,t,{...s,errors:{...v(s).errors,language:i}})}}async validateAsyncIn(e,t,s){s=Ph(s);try{if(s.targetName){const n=v(await _b(t,s.targetName).validateAsync({[s.targetName]:e},v(Ph({...s,artifacts:false}))));return n[s.targetName]}else{return v(await v(t).validateAsync(e,v(s)))}}catch(n){throw hs(new ur(n.message),n)}}};function Cb(r){const e=Oh();return e&&!v(r).errors?.language?e:void 0}a(Cb,\"inLanguage\");var Ce=v(Eb(b));var $s=new Nh;var bv={\"{\":\"}\",\"(\":\")\",\"[\":\"]\"};function Sv(r){if(typeof r!==\"string\"||r===\"\")return false;let e;while(e=/(\\\\).|([@?!+*]\\(.*\\))/g.exec(r)){if(e[2])return true;r=r.slice(e.index+e[0].length)}return false}a(Sv,\"isExtglob\");function wv(r){if(r[0]===\"!\")return true;let e=0;let t=-2;let s=-2;let n=-2;let i=-2;let o=-2;while(e<r.length){if(r[e]===\"*\")return true;if(r[e+1]===\"?\"&&/[\\].+)]/.test(r[e]))return true;if(s!==-1&&r[e]===\"[\"&&r[e+1]!==\"]\"){if(s<e)s=r.indexOf(\"]\",e);if(s>e){if(o===-1||o>s)return true;o=r.indexOf(\"\\\\\",e);if(o===-1||o>s)return true}}if(n!==-1&&r[e]===\"{\"&&r[e+1]!==\"}\"){n=r.indexOf(\"}\",e);if(n>e){o=r.indexOf(\"\\\\\",e);if(o===-1||o>n)return true}}if(i!==-1&&r[e]===\"(\"&&r[e+1]===\"?\"&&/[:!=]/.test(r[e+2])&&r[e+3]!==\")\"){i=r.indexOf(\")\",e);if(i>e){o=r.indexOf(\"\\\\\",e);if(o===-1||o>i)return true}}if(t!==-1&&r[e]===\"(\"&&r[e+1]!==\"|\"){if(t<e)t=r.indexOf(\"|\",e);if(t!==-1&&r[t+1]!==\")\"){i=r.indexOf(\")\",t);if(i>t){o=r.indexOf(\"\\\\\",t);if(o===-1||o>i)return true}}}if(r[e]===\"\\\\\"){const c=r[e+1];e+=2;const l=bv[c];if(l){const u=r.indexOf(l,e);if(u!==-1)e=u+1}if(r[e]===\"!\")return true}else{e++}}return false}a(wv,\"strictCheck\");function vb(r){if(typeof r!==\"string\"||r===\"\")return false;if(Sv(r))return true;if(r.replace(/\\\\./g,\"\").includes(\"?\"))return true;return wv(r)}a(vb,\"isGlobString\");var Ev=[\"a\",\"abbr\",\"address\",\"area\",\"article\",\"aside\",\"audio\",\"b\",\"base\",\"bdi\",\"bdo\",\"blockquote\",\"body\",\"br\",\"button\",\"canvas\",\"caption\",\"cite\",\"code\",\"col\",\"colgroup\",\"data\",\"datalist\",\"dd\",\"del\",\"details\",\"dfn\",\"dialog\",\"div\",\"dl\",\"dt\",\"em\",\"embed\",\"fieldset\",\"figcaption\",\"figure\",\"footer\",\"form\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"head\",\"header\",\"hgroup\",\"hr\",\"html\",\"i\",\"iframe\",\"img\",\"input\",\"ins\",\"kbd\",\"label\",\"legend\",\"li\",\"link\",\"main\",\"map\",\"mark\",\"math\",\"menu\",\"meta\",\"meter\",\"nav\",\"noscript\",\"object\",\"ol\",\"optgroup\",\"option\",\"output\",\"p\",\"picture\",\"pre\",\"progress\",\"q\",\"rp\",\"rt\",\"ruby\",\"s\",\"samp\",\"script\",\"search\",\"section\",\"select\",\"selectedcontent\",\"slot\",\"small\",\"source\",\"span\",\"strong\",\"style\",\"sub\",\"summary\",\"sup\",\"svg\",\"table\",\"tbody\",\"td\",\"template\",\"textarea\",\"tfoot\",\"th\",\"thead\",\"time\",\"title\",\"tr\",\"track\",\"u\",\"ul\",\"var\",\"video\",\"wbr\"];var Tv=/\\s?<!doctype html>|(<html\\b[^>]*>|<body\\b[^>]*>|<x-[^>]+>)+/i;var xv=new RegExp(Ev.map(r=>`<${r}\\\\b[^>]*>`).join(\"|\"),\"i\");function Ab(r){if(typeof r!==\"string\")return false;const e=r.trim().slice(0,1e3);return Tv.test(e)||xv.test(e)}a(Ab,\"isHTML\");var Pb=\":A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";var Rv=Pb+\"\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";var _v=new RegExp(\"^[\"+Pb+\"][\"+Rv+\"]*$\");var Lh=/(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])([\\s\\S]*?)\\5)?/g;var Fs=-1;function Mh(r){return r===\" \"||r===\"\t\"||r===\"\\n\"||r===\"\\r\"}a(Mh,\"isWhiteSpace\");function Nb(r){return _v.test(r)}a(Nb,\"isName\");function Ib(r,e){const t=e;for(;e<r.length;e++){if(r[e]===\"?\"||r[e]===\" \"){const s=r.substring(t,e);if(e>5&&s===\"xml\")return Fs;if(r[e]===\"?\"&&r[e+1]===\">\"){e++;break}}}return e}a(Ib,\"readProcessingInstruction\");function Ob(r,e){if(r.length>e+5&&r[e+1]===\"-\"&&r[e+2]===\"-\"){for(e+=3;e<r.length;e++){if(r[e]===\"-\"&&r[e+1]===\"-\"&&r[e+2]===\">\"){e+=2;break}}}else if(r.length>e+8&&r.startsWith(\"DOCTYPE\",e+1)){let t=1;for(e+=8;e<r.length;e++){if(r[e]===\"<\"){t++}else if(r[e]===\">\"){t--;if(t===0)break}}}else if(r.length>e+9&&r.startsWith(\"[CDATA[\",e+1)){for(e+=8;e<r.length;e++){if(r[e]===\"]\"&&r[e+1]===\"]\"&&r[e+2]===\">\"){e+=2;break}}}return e}a(Ob,\"readCommentAndCDATA\");function Cv(r,e){const t=e;let s=\"\";let n=false;for(;e<r.length;e++){const i=r[e];if(i==='\"'||i===\"'\"){if(s===\"\"){s=i}else if(s===i){s=\"\"}}else if(i===\">\"&&s===\"\"){n=true;break}}if(s!==\"\")return void 0;return{value:r.substring(t,e),index:e,tagClosed:n}}a(Cv,\"readAttributes\");function kb(r){const e=new Set;Lh.lastIndex=0;for(let t=Lh.exec(r);t;t=Lh.exec(r)){if(t[1].length===0||t[3]!==void 0&&t[4]===void 0)return false;if(!Nb(t[2])||e.has(t[2]))return false;e.add(t[2])}return true}a(kb,\"validateAttributes\");function vv(r,e){let t=/\\d/;if(r[e]===\"x\"){e++;t=/[\\da-fA-F]/}for(;e<r.length;e++){if(r[e]===\";\")return e;if(!t.test(r[e]))break}return Fs}a(vv,\"readNumericReference\");function Av(r,e){e++;if(r[e]===\";\")return Fs;if(r[e]===\"#\")return vv(r,e+1);for(let t=0;e<r.length;e++,t++){if(/\\w/.test(r[e])&&t<20)continue;if(r[e]===\";\")break;return Fs}return e}a(Av,\"readReference\");function Lb(r){const e=[];let t=false;let s=false;if(r[0]===\"\\uFEFF\")r=r.substring(1);for(let n=0;n<r.length;n++){if(r[n]===\"<\"&&r[n+1]===\"?\"){n=Ib(r,n+2);if(n===Fs)return false}else if(r[n]===\"<\"){n++;if(r[n]===\"!\"){n=Ob(r,n);continue}let i=false;if(r[n]===\"/\"){i=true;n++}const o=n;while(n<r.length&&r[n]!==\">\"&&!Mh(r[n]))n++;let c=r.substring(o,n).trim();if(c[c.length-1]===\"/\"){c=c.substring(0,c.length-1);n--}if(!Nb(c))return false;const l=Cv(r,n);if(!l)return false;let u=l.value;n=l.index;if(u[u.length-1]===\"/\"){u=u.substring(0,u.length-1);if(!kb(u))return false;if(s)return false;if(e.length===0)s=true;t=true}else if(i){if(!l.tagClosed||u.trim().length>0||e.length===0)return false;if(e.pop()!==c)return false;if(e.length===0)s=true}else{if(!kb(u))return false;if(s)return false;e.push(c);t=true}for(n++;n<r.length;n++){if(r[n]===\"<\"){if(r[n+1]===\"!\"){n=Ob(r,n+1);continue}else if(r[n+1]===\"?\"){n=Ib(r,n+2);if(n===Fs)return false}else{break}}else if(r[n]===\"&\"){n=Av(r,n);if(n===Fs)return false}else if(s&&!Mh(r[n])){return false}}if(r[n]===\"<\")n--}else if(!Mh(r[n])){return false}}return t&&e.length===0}a(Lb,\"validateXML\");function Mb(r){return typeof r===\"string\"&&Lb(r)}a(Mb,\"isXML\");var Iv={alias:false,seconds:false,allowBlankDay:false,allowSevenAsSunday:false,allowNthWeekdayOfMonth:false};var Ov={jan:\"1\",feb:\"2\",mar:\"3\",apr:\"4\",may:\"5\",jun:\"6\",jul:\"7\",aug:\"8\",sep:\"9\",oct:\"10\",nov:\"11\",dec:\"12\"};var kv={sun:\"0\",mon:\"1\",tue:\"2\",wed:\"3\",thu:\"4\",fri:\"5\",sat:\"6\"};function Xo(r){return/^\\d+$/.test(r)?Number(r):NaN}a(Xo,\"safeParseInt\");function Vo(r,e,t){return r>=e&&r<=t}a(Vo,\"isInRange\");function Pv(r,e,t){const s=r.split(\"-\");switch(s.length){case 1:return r===\"*\"||Vo(Xo(r),e,t);case 2:{const[n,i]=s.map(Xo);return n<=i&&Vo(n,e,t)&&Vo(i,e,t)}default:return false}}a(Pv,\"isValidRange\");function Nv(r){return r===void 0||r.search(/[^\\d]/)===-1&&Xo(r)>0}a(Nv,\"isValidStep\");function Zn(r,e,t){if(r.search(/[^\\d-,\\/*]/)!==-1)return false;return r.split(\",\").every(s=>{const n=s.split(\"/\");if(s.trim().endsWith(\"/\")||n.length>2)return false;return Pv(n[0],e,t)&&Nv(n[1])})}a(Zn,\"validateForRange\");function Db(r,e){return r.toLowerCase().replace(/[a-z]{3}/g,t=>e[t]??t)}a(Db,\"unalias\");function Lv(r,e){return e&&r===\"?\"||Zn(r,1,31)}a(Lv,\"hasValidDays\");function Mv(r,e){if(r.search(/\\/[a-zA-Z]/)!==-1)return false;return Zn(e?Db(r,Ov):r,1,12)}a(Mv,\"hasValidMonths\");function Dv(r,e){if(r===\"?\")return e.allowBlankDay;if(r.search(/\\/[a-zA-Z]/)!==-1)return false;const t=e.alias?Db(r,kv):r;const s=e.allowSevenAsSunday?7:6;const n=t.split(\"#\");if(e.allowNthWeekdayOfMonth&&n.length>=2){const[i,o,...c]=n;if(c.length)return false;return Vo(Xo(o),1,5)&&Vo(Xo(i),0,s)}return Zn(t,0,s)}a(Dv,\"hasValidWeekdays\");function Bb(r,e){const t={...Iv,...e};const s=r.trim().split(/\\s+/);if(s.length>(t.seconds?6:5)||s.length<5)return false;const n=[];if(s.length===6){const f=s.shift();if(f)n.push(Zn(f,0,59))}const[i,o,c,l,u]=s;n.push(Zn(i,0,59));n.push(Zn(o,0,23));n.push(Lv(c,t.allowBlankDay));n.push(Mv(l,t.alias));n.push(Dv(u,t));n.push(!(t.allowBlankDay&&c===\"?\"&&u===\"?\"));return n.every(Boolean)}a(Bb,\"isValidCron\");var Hs=class{static{a(this,\"DataValidator\")}static Build(e){return Ce.build(e)}static Any(){return Ce.any().strict(true)}static String(){return Ce.string().strict(true)}static Number(){return Ce.number().strict(true)}static BigInt(){return Ce.bigint().strict(true)}static Boolean(){return Ce.boolean().strict(true)}static Date(){return Ce.date().strict(true)}static Object(e){return Ce.object(e).strict(true)}static Array(...e){return Ce.array().items(...e).strict(true)}static Binary(){return Ce.binary().strict(true)}static Function(){return Ce.func().strict(true)}static AsyncFunction(){return this.Function().custom(Us((e,t)=>{if((0,Ub.isAsyncFunction)(e))return e;return t.error(\"asyncFunc.invalid\")}),\"Async Function Validation\").error(e=>{for(const t of e){if(t.code===\"asyncFunc.invalid\"){t.message=\"Expected AsyncFunction but got Function\";return t}}return e[0]})}static Class(e){if(!e)return Ce.func().class();return this.Function().class().custom(Us((t,s)=>{if(!v(e).prototype)e=v(e)();if(t instanceof v(e)||t[\"prototype\"]instanceof v(e))return t;return s.error(\"any.invalid\")}),\"Class Validation\")}static InstanceOf(e){return this.Any().custom(Us((t,s)=>{if(t instanceof v(e)||t[\"prototype\"]instanceof v(e))return t;return s.error(\"any.invalid\")}),\"Class Instance Validation\")}static Glob(){return this.String().custom(Us((e,t)=>{if(typeof e===\"string\"&&vb(e))return e;return t.error(\"any.invalid\")}),\"Glob Validation\")}static Cron(e){const t={...e,alias:e?.alias!==void 0?e.alias:false,seconds:e?.seconds!==void 0?e.seconds:true,allowBlankDay:e?.allowBlankDay!==void 0?e.allowBlankDay:true,allowSevenAsSunday:e?.allowSevenAsSunday!==void 0?e.allowSevenAsSunday:true};return this.String().custom(Us((s,n)=>{if(typeof s===\"string\"&&Bb(s,t))return s;return n.error(\"any.invalid\")}),\"Cron Validation\")}static HttpDocument(){return this.String().custom(Us((e,t)=>{if(typeof e===\"string\"&&(Ab(e)||Mb(e)))return e;return t.error(\"any.invalid\")}),\"HttpDocument Validation\")}static Symbol(){return Ce.symbol().strict(true)}static Alternatives(...e){return Ce.alternatives(...e).strict(true)}static Ref(e,t){return Ce.ref(e,t)}static In(e,t){return Ce.in(e,t)}static Attempt(e,t,s){return Ce.attempt(e,t,s)}static Link(e){return Ce.link(e)}};var RB=Ye(Bn(),1);var Dh=Symbol(\"LAKUTATA.DTO.CONSTRUCTOR\");var Qn=Symbol(\"LAKUTATA.DTO.INDEX.SIGNATURE.SCHEMA\");var vr=Symbol(\"LAKUTATA.DTO.PROPERTY.SCHEMAS\");var Bh=Symbol(\"LAKUTATA.DTO.OBJECT.REFINEMENT\");function me(r){return v(r.constructor)}a(me,\"objectConstructor\");function Uh(r){const e=Symbol.constructor.prototype.constructor.__proto__;const t=!!r[Symbol.hasInstance]&&r.prototype?r:r.constructor;const s=t.prototype.constructor.__proto__;return s===e?null:s}a(Uh,\"objectParentConstructor\");function ps(r){const e=[];let t=Uh(r);while(t){e.push(t);t=Uh(t)}return e}a(ps,\"objectParentConstructors\");function jh(r){return r.prototype}a(jh,\"objectPrototype\");function bt(r){return typeof r===\"symbol\"}a(bt,\"isSymbol\");var $h=0;function ei(){$h++}a(ei,\"invalidateDTOSchemas\");function ti(r,e,t){const s=r.get(e);if(s&&s.revision===$h)return s.value;const n=t();r.set(e,{revision:$h,value:n});return n}a(ti,\"getCachedDTOSchema\");var Bv=new WeakMap;function jb(r){Reflect.defineMetadata(Dh,true,r);ei();return r}a(jb,\"defineObjectAsDTO\");function Fh(r){return!!Reflect.getMetadata(Dh,r)}a(Fh,\"isDTO\");function $b(r,e){Reflect.defineMetadata(Qn,e,r);ei();return r}a($b,\"setObjectIndexSignatureSchema\");function Hh(r){if(Reflect.hasOwnMetadata(Qn,me(r)))return Reflect.getOwnMetadata(Qn,me(r));for(const e of ps(me(r))){if(Reflect.hasOwnMetadata(Qn,e))return Reflect.getOwnMetadata(Qn,e)}return null}a(Hh,\"getObjectIndexSignatureSchemaByPrototype\");function Fb(r){return Hh(jh(r))}a(Fb,\"getObjectIndexSignatureSchemaByConstructor\");function Al(r,e,t){if(bt(e))return;if(!Fh(v(me(r))))return;e=v(e);let s;if(Reflect.hasOwnMetadata(vr,me(r))){s=Reflect.getOwnMetadata(vr,me(r))}else{s=new Map;const n=[];ps(me(r)).forEach(i=>{if(Reflect.hasOwnMetadata(vr,i))n.unshift(Reflect.getOwnMetadata(vr,i))});n.forEach(i=>i.forEach((o,c)=>s.set(v(c),o)))}s.set(e,t);Reflect.defineMetadata(vr,s,me(r));ei()}a(Al,\"setObjectPropertySchema\");function Uv(r){const e=new Map;const t=[];ps(me(r)).forEach(s=>{if(Reflect.hasOwnMetadata(vr,s))t.unshift(Reflect.getOwnMetadata(vr,s))});t.forEach(s=>s.forEach((n,i)=>e.set(v(i),n)));v(Reflect.getOwnMetadata(vr,me(r)))?.forEach((s,n)=>e.set(v(n),s));return e}a(Uv,\"getObjectPropertySchemas\");function qh(r){return ti(Bv,me(r),()=>{const e={};Uv(r).forEach((s,n)=>{e[n]=s});const t=Reflect.getMetadata(Bh,me(r));return t?t(Hs.Object(e)):Hs.Object(e)})}a(qh,\"getObjectSchemaByPrototype\");function Hb(r){return qh(jh(r))}a(Hb,\"getObjectSchemaByConstructor\");function qb(r,e){Reflect.defineMetadata(Bh,e,r);ei();return r}a(qb,\"setObjectSchemaRefinement\");var Ue=class extends rs{static{a(this,\"SchemaConversionException\")}constructor(){super(...arguments);this.errno=\"E_SCHEMA_CONVERSION\"}};function zb(r,e,t){e=e||1;t=t<r.length?t:r.length;const s=a((i,o,c,l)=>{if(i==0){if(c.length>0)l[l.length]=c;return}for(let u=0;u<o.length;u++)s(i-1,o.slice(u+1),c.concat([o[u]]),l)},\"fn\");const n=[];for(let i=e;i<r.length;i++)s(i,r,[],n);if(r.length==t)n.push(r);return n}a(zb,\"combinations\");var jv=new Set([\"[object Float32Array]\",\"[object Float64Array]\",\"[object Int8Array]\",\"[object Int16Array]\",\"[object Int32Array]\",\"[object Uint8Array]\",\"[object Uint8ClampedArray]\",\"[object Uint16Array]\",\"[object Uint32Array]\"]);var $v=Function.prototype.toString.call(Object);function Kh(r){return Object.prototype.toString.call(r)}a(Kh,\"tagOf\");function Yo(r){return r!==null&&(typeof r===\"object\"||typeof r===\"function\")}a(Yo,\"isObject\");function Il(r){return r!==null&&typeof r===\"object\"}a(Il,\"isObjectLike\");function Fv(r){return typeof r===\"number\"&&r>-1&&r%1===0&&r<=Number.MAX_SAFE_INTEGER}a(Fv,\"isLength\");function ri(r){return r!==null&&r!==void 0&&typeof r!==\"function\"&&Fv(r.length)}a(ri,\"isArrayLike\");function zh(r){return Il(r)&&Kh(r)===\"[object Arguments]\"}a(zh,\"isArguments\");function Wh(r){return Il(r)&&jv.has(Kh(r))}a(Wh,\"isTypedArray\");function Hv(r){if(!Il(r)||Kh(r)!==\"[object Object]\")return false;const e=Object.getPrototypeOf(r);if(e===null)return true;const t=Object.prototype.hasOwnProperty.call(e,\"constructor\")&&e.constructor;return typeof t===\"function\"&&t instanceof t&&Function.prototype.toString.call(t)===$v}a(Hv,\"isPlainObject\");function Wb(r){return/^(?:0|[1-9]\\d*)$/.test(r)&&Number(r)<Number.MAX_SAFE_INTEGER}a(Wb,\"isIndex\");function Vb(r,e){return r===e||r!==r&&e!==e}a(Vb,\"eq\");function Xb(r){if(ri(r)){const e=[];for(let t=0;t<r.length;++t)e.push(String(t));return e}return Object.keys(r)}a(Xb,\"keysOf\");function He(r,e){if(r===null||r===void 0)return void 0;if(e in Object(r))return r[e];let t=r;for(const s of e.split(\".\")){if(t===null||t===void 0)return void 0;t=t[s]}return t}a(He,\"get\");function Yb(r,e,t){if(!Yo(r))return r;const s=e in r?[e]:e.split(\".\");let n=r;for(let i=0;i<s.length&&n!==null&&n!==void 0;++i){const o=s[i];if(o===\"__proto__\"||o===\"constructor\"||o===\"prototype\")return r;if(i===s.length-1){Gb(n,o,t);break}const c=n[o];Gb(n,o,Yo(c)?c:Wb(s[i+1])?[]:{});n=n[o]}return r}a(Yb,\"set\");function Gb(r,e,t){if(!Yo(r))return;const s=r[e];if(!(Object.prototype.hasOwnProperty.call(r,e)&&Vb(s,t))||t===void 0&&!(e in r))r[e]=t}a(Gb,\"assignValue\");function fr(r){if(r===null||r===void 0)return true;if(ri(r)&&(Array.isArray(r)||typeof r===\"string\"||typeof r.splice===\"function\"||Buffer.isBuffer(r)||Wh(r)||zh(r)))return!r.length;if(r instanceof Map||r instanceof Set)return!r.size;for(const e in r){if(Object.prototype.hasOwnProperty.call(r,e))return false}return true}a(fr,\"isEmpty\");function Kt(r,e){if(r===null||r===void 0)return[];if(Array.isArray(r)){const s=new Array(r.length);for(let n=0;n<r.length;++n)s[n]=e(r[n],n);return s}const t=Object(r);return Xb(t).map(s=>e(t[s],ri(r)?Number(s):s))}a(Kt,\"map\");function It(r,e){if(r===null||r===void 0)return;const t=Object(r);const s=ri(r);for(const n of Xb(t)){if(e(t[n],s?Number(n):n)===false)return}}a(It,\"each\");function Vh(r){return r&&r.length?[...new Set(r)]:[]}a(Vh,\"uniq\");function Ol(r,e){const t=[];if(!(r&&r.length))return t;const s=[];for(let n=0;n<r.length;++n){const i=r[n];if(e(i,n,r)){t.push(i);s.push(n)}}for(let n=s.length-1;n>=0;--n)r.splice(s[n],1);return t}a(Ol,\"remove\");function Jb(r){const e=[];if(!r)return e;for(const t of r){if(t)e.push(t)}return e}a(Jb,\"compact\");function ms(r,e){if(!r)return false;for(const t of r){if(e(t))return true}return false}a(ms,\"some\");function Zb(r,e){const t={};if(r===null||r===void 0)return t;const s=r;for(const n in s){if(n!==\"__proto__\"&&e(s[n],n))t[n]=s[n]}return t}a(Zb,\"pickBy\");function St(r,...e){for(const t of e){if(t)Qb(r,t,new Map)}return r}a(St,\"merge\");function qv(r){const e=[];if(ri(r)){const t=Buffer.isBuffer(r);const s=!t&&Wh(r);for(let n=0;n<r.length;++n)e.push(String(n));for(const n in r){if(Wb(n)||n===\"length\")continue;if(t&&(n===\"offset\"||n===\"parent\"))continue;if(s&&(n===\"buffer\"||n===\"byteLength\"||n===\"byteOffset\"))continue;e.push(n)}return e}for(const t in r)e.push(t);return e}a(qv,\"keysIn\");function Kb(r,e){if(e===\"constructor\"&&typeof r[e]===\"function\")return void 0;if(e===\"__proto__\")return void 0;return r[e]}a(Kb,\"safeGet\");function Gh(r,e,t){if(t!==void 0&&!Vb(r[e],t)||t===void 0&&!(e in r)){if(e===\"__proto__\"){Object.defineProperty(r,e,{configurable:true,enumerable:true,value:t,writable:true})}else{r[e]=t}}}a(Gh,\"assignMergeValue\");function Qb(r,e,t){if(r===e)return;for(const s of qv(e)){const n=e[s];if(Yo(n)){zv(r,e,s,t)}else{Gh(r,s,n)}}}a(Qb,\"baseMerge\");function zv(r,e,t,s){const n=Kb(r,t);const i=Kb(e,t);const o=s.get(i);if(o){Gh(r,t,o);return}let c=true;let l=i;const u=Array.isArray(i);const f=!u&&Buffer.isBuffer(i);const d=!u&&!f&&Wh(i);if(u||f||d){if(Array.isArray(n)){l=n}else if(Il(n)&&ri(n)){l=Array.from(n)}else if(f){c=false;l=i.subarray()}else if(d){c=false;const h=i;const p=h.constructor;l=new p(h.buffer.slice(0),h.byteOffset,h.length)}else{l=[]}}else if(Hv(i)||zh(i)){l=n;if(zh(n)){l=Object.assign({},n)}else if(!Yo(n)||typeof n===\"function\"){l=typeof i.constructor===\"function\"?Object.create(Object.getPrototypeOf(i)):{}}}else{c=false}if(c){s.set(i,l);Qb(l,i,s);s.delete(i)}Gh(r,t,l)}a(zv,\"baseMergeDeep\");var Gv={or:a(function(r,e){r.anyOf=Kt(e.peers,t=>{return{required:[t]}})},\"or\"),and:a(function(r,e){r.oneOf=[{required:e.peers}];r.oneOf.push({allOf:Kt(e.peers,t=>{return{not:{required:[t]}}})})},\"and\"),nand:a(function(r,e){r.not={required:e.peers}},\"nand\"),xor:a(function(r,e){r.if={propertyNames:{enum:e.peers},minProperties:2};r.then=false;r.else={oneOf:Kt(e.peers,t=>{return{required:[t]}})}},\"xor\"),oxor:a(function(r,e){r.oneOf=Kt(e.peers,t=>{return{required:[t]}});r.oneOf.push({not:{oneOf:Kt(zb(e.peers,1,2),t=>{return{required:t}})}})},\"oxor\"),with:a(function(r,e){r.dependencies=r.dependencies||{};r.dependencies[e.key]=e.peers},\"with\"),without:a(function(r,e){r.if={required:[e.key]};r.then={not:{anyOf:Kt(e.peers,t=>{return{required:[t]}})}}},\"without\")};var Kv=[\"integer\",\"port\",...Object.keys(At)];var Wv={any:[\"allOf\"],alternatives:[\"allOf\"],boolean:[\"allOf\"],number:[\"allOf\",\"min\",\"max\",\"greater\",\"less\",\"multiple\",\"sign\",\"port\",\"float\",\"double\",\"integer\",...Object.keys(At)],bigint:[\"allOf\",\"min\",\"max\",\"greater\",\"less\",\"multiple\",\"negative\",\"positive\"],string:[\"allOf\",\"min\",\"max\",\"length\",\"format\",\"email\",\"hostname\",\"uri\",\"ip\",\"pattern\",\"alphanum\",\"token\",\"hex\",\"trim\",\"isoDate\",\"isoDuration\",\"guid\",\"uuid\"],object:[\"allOf\",\"min\",\"max\",\"length\",\"keyNames\"],array:[\"allOf\",\"min\",\"max\",\"length\",\"unique\",\"has\",\"items\",\"ordered\"]};var eS=[\"function\",\"symbol\"];var kl=[\"title\",\"description\",\"default\",\"examples\",\"example\",\"deprecated\",\"readOnly\",\"writeOnly\",\"$comment\"];var tS=[\"if\",\"then\",\"else\"];function Vv(r){return typeof r===\"object\"&&r!==null&&Object.keys(r).length===1&&r.override===true}a(Vv,\"isOverride\");function Ll(r){if(r===null||typeof r===\"string\"||typeof r===\"boolean\")return true;if(typeof r===\"number\")return isFinite(r);if(Array.isArray(r))return r.every(Ll);if(typeof r===\"object\"&&Object.getPrototypeOf(r)===Object.prototype)return Object.values(r).every(Ll);return false}a(Ll,\"isJsonValue\");function rS(r){const e=[];for(const t of r||[]){if(Vv(t))continue;if(t!==null&&typeof t===\"object\"){const s=Object.keys(t);if(s.length===1&&s[0]===\"value\"){e.push(t.value);continue}return null}e.push(t)}return e}a(rS,\"literals\");function Nl(r){if(typeof r===\"number\"&&isFinite(r))return r;if(typeof r===\"bigint\"&&r<=BigInt(Number.MAX_SAFE_INTEGER)&&r>=BigInt(Number.MIN_SAFE_INTEGER))return Number(r);return void 0}a(Nl,\"numberLimit\");function Xv(r,e,t,s){const n=Nl(e);if(n===void 0)return r;if(!r||(s?n>r.value:n<r.value))return{value:n,exclusive:t};if(n===r.value&&t)return{value:n,exclusive:t};return r}a(Xv,\"tighter\");function Pl(r){if(typeof r!==\"string\")return null;const e=/^\\/([\\s\\S]*)\\/([a-z]*)$/.exec(r);if(!e)return null;const[,t,s]=e;if(/[imsgyv]/.test(s))return null;try{new RegExp(t,\"u\")}catch{return null}return{source:t,flags:s}}a(Pl,\"toPattern\");function Yv(r){const e=r.map(t=>Array.from(t).map(s=>{const n=s.toLowerCase();const i=s.toUpperCase();if(n===i||Array.from(n).length!==1||Array.from(i).length!==1)return mt(s);return`[${mt(n)}${mt(i)}]`}).join(\"\"));return`^(?:${e.join(\"|\")})$`}a(Yv,\"insensitivePattern\");var Ar=class{static{a(this,\"JsonSchemaParser\")}constructor(e={}){this._exact=true;this._inexactSchemas=new WeakSet;const t=e;this.$schema=t.$schema||\"http://json-schema.org/draft-07/schema#\";this.includeSchemaDialect=t.includeSchemaDialect||false;this.childrenFieldName=this._getChildrenFieldName();this.optionsFieldName=this._getOptionsFieldName();this.ruleArgFieldName=this._getRuleArgFieldName();this.enumFieldName=this._getEnumFieldName();this.allowUnknownFlagName=this._getAllowUnknownFlagName();this.inheritedPreferences=t.preferences?[t.preferences]:[];if(t.logicalOpParser===false){this.logicalOpParser={}}else{this.logicalOpParser=St({},Gv,t.logicalOpParser)}}parse(e,t={},s=0){const n=this._exact;this._exact=true;const i=this._parse(e,t,s);if(!this._exact)this._inexactSchemas.add(i);this._exact=n&&this._exact;return i}isExact(e){return!this._inexactSchemas.has(e)}_inexact(){this._exact=false}_parse(e,t,s){let n={};const i=this._pushInheritiedPreferences(e);if(this._getPresence(e)===\"forbidden\"){if(i)this._popInheritiedPreferences();n.not={};return n}this._checkRules(e);this._setBasicProperties(n,e);this._setNumberFieldProperties(n,e);this._setBinaryFieldProperties(n,e);this._setStringFieldProperties(n,e);this._setDateFieldProperties(n,e);this._setArrayFieldProperties(n,e,t,s);this._setObjectProperties(n,e,t,s);this._setAlternativesProperties(n,e,t,s);this._setConditionProperties(n,e,t,s,\"whens\");this._setAllOf(n,e,t,s);this._setMetaProperties(n,e);this._setLinkFieldProperties(n,e);this._setAnyProperties(n);this._setNonJsonProperties(n,e);n=this._setSingle(n,e);n=this._setValues(n,e);if(!fr(e.shared)){It(e.shared,c=>{this.parse(c,t,s)})}this._copyMetasToSchema(e,n);n=this._retainKnownKeys(n);const o=He(e,\"flags.id\");if(o){t[o]=n;n={$ref:`${this._getLocalSchemaBasePath()}/${o}`}}if(s===0&&!fr(t))Yb(n,`${this._getLocalSchemaBasePath().replace(\"#/\",\"\").replace(/\\//,\".\")}`,t);if(this.includeSchemaDialect&&s===0&&this.$schema)n.$schema=this.$schema;if(i)this._popInheritiedPreferences();return n}_retainKnownKeys(e){if(!this.knownKeys)return e;const t=this.knownKeys;const s=Zb(e,(n,i)=>t.includes(i)||this._isKnownMetaKey(i));if(Object.keys(e).some(n=>!(n in s)&&!kl.includes(n)))this._inexact();return s}_checkRules(e){const t=Wv[e.type];if(!t){if(![\"any\",\"alternatives\",\"link\",\"function\",\"symbol\"].includes(e.type))this._inexact();if(e.type===\"link\"&&He(e,\"link.ref.type\")!==\"local\")this._inexact()}for(const n of e.rules||[]){if(!t||!t.includes(n.name))this._inexact()}const s=e.flags||{};if(s.empty!==void 0||s.single)this._inexact();if(e.renames||e.externals)this._inexact()}_pushInheritiedPreferences(e){if(e.preferences){this.inheritedPreferences.push(St({},this._getInheritedPreferences(),e.preferences));return true}return false}_popInheritiedPreferences(){this.inheritedPreferences.pop()}_getInheritedPreferences(){return this.inheritedPreferences[this.inheritedPreferences.length-1]||{}}_getPreferences(e){const t=e[this.optionsFieldName];return t?{...this._getInheritedPreferences(),...t}:this._getInheritedPreferences()}_isIfThenElseSupported(){return true}_getChildrenFieldName(){return\"keys\"}_getOptionsFieldName(){return\"preferences\"}_getRuleArgFieldName(){return\"args\"}_getEnumFieldName(){return\"allow\"}_getAllowUnknownFlagName(){return\"unknown\"}_getLocalSchemaBasePath(){return\"#/$defs\"}_getFieldDescription(e){return He(e,\"flags.description\")}_getFieldType(e){const t=e.type;if(t===\"number\"&&ms(e.rules,s=>Kv.includes(s.name)))return\"integer\";if(t===\"bigint\")return\"integer\";if(eS.includes(t))return void 0;return t}_addNullTypeIfNullable(e,t){}_getFieldExample(e){const t=He(e,\"examples\");if(!Array.isArray(t))return t;const s=t.filter(Ll);return s.length?s:void 0}_getPresence(e){const t=He(e,\"flags.presence\");if(t!==void 0)return t;const s=this._getPreferences(e);return He(s,\"presence\")}_isRequired(e){const t=this._getPresence(e);return t===\"required\"}_getDefaultValue(e){const t=He(e,\"flags.default\");return Ll(t)&&!(t!==null&&typeof t===\"object\"&&He(t,\"special\")===\"deep\")?t:void 0}_getUnknown(e){const t=He(e,`flags.${this.allowUnknownFlagName}`);if(t!==void 0)return t;const s=this._getPreferences(e);if(s.allowUnknown)return true;const n=s.stripUnknown;return n===true||!!(n&&n.objects)}_stripsUnknown(e){if(He(e,`flags.${this.allowUnknownFlagName}`)!==void 0)return false;if(!e[this.childrenFieldName]&&!e.patterns)return false;const t=He(this._getPreferences(e),\"stripUnknown\");return t===true||!!(t&&t.objects)}_stripsArrayItems(e){const t=He(this._getPreferences(e),\"stripUnknown\");return!!(t&&typeof t===\"object\"&&t.arrays)}_setIfNotEmpty(e,t,s){if(s!==null&&s!==void 0)e[t]=s}_bound(e,t,s,n){if(Nl(t)===void 0)this._inexact();return Xv(e,t,s,n)}_addKeyword(e,t,s){if(e[t]===void 0){e[t]=s}else{e.allOf=e.allOf||[];e.allOf.push({[t]:s})}}_mergeKeywords(e,t){const s=Object.keys(t);if(!s.length)return;const n=s.some(i=>e[i]!==void 0)||s.some(i=>tS.includes(i))&&tS.some(i=>e[i]!==void 0);if(!n){Object.assign(e,t)}else if(s.length===1&&s[0]===\"allOf\"){e.allOf=[...e.allOf||[],...t.allOf]}else{e.allOf=e.allOf||[];e.allOf.push(t)}}_setBasicProperties(e,t){this._setIfNotEmpty(e,\"type\",this._getFieldType(t));this._setIfNotEmpty(e,\"examples\",this._getFieldExample(t));this._setIfNotEmpty(e,\"description\",this._getFieldDescription(t));this._setIfNotEmpty(e,\"default\",this._getDefaultValue(t))}_getValuesSchema(e){return e.length===1?{const:e[0]}:{enum:e}}_setValues(e,t){const s=t.flags||{};const n=rS(t[this.enumFieldName]);const i=rS(t.invalid);const o={};for(const f of Object.keys(e)){if(kl.includes(f)||f.startsWith(\"x-\"))o[f]=e[f]}if(!n||!i)this._inexact();if(s.only){if(!n||!n.length)return{...o};const f=Vh(n);const d=f.filter(h=>typeof h===\"string\");if(s.insensitive&&d.length){const h=f.filter(m=>typeof m!==\"string\");const p={type:\"string\",pattern:Yv(d)};if(!h.length)return{...o,...p};return{...o,anyOf:[p,this._getValuesSchema(h)]}}return{...o,...this._getValuesSchema(f)}}if(i&&i.length)this._addKeyword(e,\"not\",{enum:i});const c=!!n&&n.includes(\"\")||ms(t.rules,f=>f.name===\"min\"&&He(f,`${this.ruleArgFieldName}.limit`)===0);if(e.type===\"string\"&&t.type===\"string\"&&!c&&s.empty===void 0&&!this._rejectsEmpty(e))e.minLength=1;if(!n)return{...o};if(!n.length){this._addNullTypeIfNullable(e,t);return e}if(Object.keys(e).every(f=>o[f]!==void 0))return e;let l=Vh(n);if(e.type===\"string\"&&l.includes(\"\")&&this._acceptsEmpty(e))l=l.filter(f=>f!==\"\");if(l.includes(null)&&this._canAddType(e)){if(Array.isArray(e.type)){if(!e.type.includes(\"null\"))e.type=[...e.type,\"null\"]}else if(e.type!==\"null\"){e.type=[e.type,\"null\"]}l=l.filter(f=>f!==null)}this._addNullTypeIfNullable(e,t);if(!l.length)return e;const u={};for(const f of Object.keys(e)){if(o[f]===void 0)u[f]=e[f]}return{...o,anyOf:[u,this._getValuesSchema(l)]}}_setSingle(e,t){if(t.type!==\"array\"||!He(t,\"flags.single\"))return e;const s={};const n={};for(const c of Object.keys(e)){if(kl.includes(c)||c.startsWith(\"x-\")){s[c]=e[c]}else{n[c]=e[c]}}const i=e.prefixItems||e.items;const o=Array.isArray(i)?i.length?{anyOf:i}:{}:i||{};return{...s,anyOf:[n,o]}}_acceptsEmpty(e){for(const t of Object.keys(e)){if(kl.includes(t)||t.startsWith(\"x-\")||t===\"type\"||t===\"maxLength\"||t===\"contentEncoding\")continue;if(t===\"minLength\"&&e.minLength<1)continue;if(t===\"pattern\"&&new RegExp(e.pattern,\"u\").test(\"\"))continue;return false}return true}_rejectsEmpty(e){if(typeof e.minLength===\"number\"&&e.minLength>=1)return true;if(typeof e.pattern===\"string\"&&!new RegExp(e.pattern,\"u\").test(\"\"))return true;return typeof e.format===\"string\"&&[\"date\",\"time\",\"date-time\",\"duration\",\"email\",\"idn-email\",\"hostname\",\"ipv4\",\"ipv6\",\"uri\",\"uuid\"].includes(e.format)}_canAddType(e){if(!e.type)return false;return![\"enum\",\"const\",\"anyOf\",\"oneOf\",\"allOf\",\"not\",\"if\",\"$ref\"].some(t=>e[t]!==void 0)}_setBinaryFieldProperties(e,t){if(e.type!==\"binary\")return;e.type=\"string\";if(t.flags&&t.flags.encoding)e.contentEncoding=t.flags.encoding;this._setIfNotEmpty(e,\"format\",this._getBinaryFormat())}_getBinaryFormat(){return void 0}_setObjectProperties(e,t,s,n){if(e.type!==\"object\")return;const i=t[this.childrenFieldName];const o=this._getUnknown(t);if(!i&&!t.patterns){if(typeof o===\"object\")e.additionalProperties=this.parse(o,s,n+1)}else{const c={};const l=[];e.properties=c;Kt(i,(f,d)=>{const h=this.parse(f,s,n+1);if(this._isRequired(f))l.push(d);c[d]=h});if(l.length)e.required=l;const u=this._setPatternProperties(e,t,Object.keys(i||{}),s,n);if(!u||t.renames){this._inexact();e.additionalProperties=true}else if(typeof o===\"object\"){e.additionalProperties=this.parse(o,s,n+1)}else{e.additionalProperties=o}}It(t.rules,c=>{const l=c[this.ruleArgFieldName]||{};const u=Nl(l.limit);switch(c.name){case\"min\":case\"length\":if(u!==void 0&&!ms(Object.values(i||{}),f=>He(f,\"flags.default\")!==void 0)){this._addKeyword(e,\"minProperties\",u);if(this._stripsUnknown(t))this._inexact()}else{this._inexact()}if(c.name===\"min\")break;case\"max\":if(u!==void 0&&!this._stripsUnknown(t)){this._addKeyword(e,\"maxProperties\",u)}else{this._inexact()}break;case\"keyNames\":{const f=this.parse(l.schema,s,n+1);this._setPropertyNames(e,this._stripsUnknown(t)?{anyOf:[f,{not:this._knownKeys(t)}]}:f);break}default:break}});this._setObjectDependencies(e,t)}_setPropertyNames(e,t){this._addKeyword(e,\"propertyNames\",t)}_setPatternProperties(e,t,s,n,i){if(!t.patterns||!t.patterns.length)return true;const o={};const c=[];for(const l of t.patterns){if(typeof l.rule!==\"object\"||l.regex===void 0)return false;if(l.matches!==void 0)return false;const u=Pl(l.regex);if(!u)return false;const f=new RegExp(u.source,\"u\");const d=s.filter(m=>f.test(m));let h=u.source;if(d.length||c.length){if([u.source,...c].some(y=>/\\\\[1-9]|\\\\k</.test(y)))return false;const m=d.length?`(?!(?:${d.map(y=>mt(y)).join(\"|\")})$)`:\"\";h=`^${m}${c.map(y=>`(?![\\\\s\\\\S]*?(?:${y}))`).join(\"\")}[\\\\s\\\\S]*?(?:${u.source})`;try{new RegExp(h,\"u\")}catch{return false}}const p=this.parse(l.rule,n,i+1);if(o[h]){o[h]={allOf:[o[h],p]}}else{o[h]=p}if(!l.fallthrough)c.push(u.source)}e.patternProperties=o;return true}_knownKeys(e){const t=Object.keys(e[this.childrenFieldName]||{});const s=t.length?[{enum:t}]:[];for(const n of e.patterns||[]){const i=Pl(n.regex);if(!i)return{};s.push({pattern:i.source})}if(!s.length)return{not:{}};return s.length===1?s[0]:{anyOf:s}}_isKnownKey(e,t){if(Object.hasOwn(e[this.childrenFieldName]||{},t))return true;return ms(e.patterns,s=>{const n=Pl(s.regex);return!n||new RegExp(n.source,\"u\").test(t)})}_setObjectDependencies(e,t){if(!Array.isArray(t.dependencies)||t.dependencies.length===0)return;const s=this._stripsUnknown(t);const n=t.dependencies.filter(i=>{const o=[i.key,...i.peers];if(o.some(c=>typeof c===\"string\"&&(c.includes(\".\")||s&&!this._isKnownKey(t,c)))){this._inexact();return false}return true});if(n.length===1){this._mergeKeywords(e,this._setDependencySubSchema({},n[0]))}else if(n.length>1){const i=[];const o={};for(const c of n){if(c.rel===\"with\"){this._setDependencySubSchema(o,c);continue}const l=this._setDependencySubSchema({},c);if(!fr(l))i.push(l)}if(i.length)this._mergeKeywords(e,{allOf:i});this._mergeKeywords(e,o)}}_setDependencySubSchema(e,t){const s=this.logicalOpParser[t.rel];if(typeof s!==\"function\"){this._inexact();return e}s(e,t);return e}_getNumberFormat(e){return void 0}_setNumberFieldProperties(e,t){if(e.type!==\"number\"&&e.type!==\"integer\")return;const s=this.ruleArgFieldName;let n;let i;const o=t.rules||[];It(o,c=>{const l=c[s]||{};const u=At[c.name];if(u){n=this._bound(n,u[0],false,true);i=this._bound(i,u[1],false,false);return}switch(c.name){case\"max\":i=this._bound(i,l.limit,false,false);break;case\"min\":n=this._bound(n,l.limit,false,true);break;case\"greater\":n=this._bound(n,l.limit,true,true);break;case\"less\":i=this._bound(i,l.limit,true,false);break;case\"port\":n=this._bound(n,0,false,true);i=this._bound(i,65535,false,false);break;case\"float\":n=this._bound(n,-Gt,false,true);i=this._bound(i,Gt,false,false);break;case\"multiple\":{const f=Nl(l.base);if(f!==void 0){this._addKeyword(e,\"multipleOf\",f)}else{this._inexact()}break}case\"sign\":case\"positive\":case\"negative\":{const f=c.name===\"sign\"?l.sign:c.name;if(f===\"positive\")n=this._bound(n,0,true,true);if(f===\"negative\")i=this._bound(i,0,true,false);break}default:break}});if(n)e[n.exclusive?\"exclusiveMinimum\":\"minimum\"]=n.value;if(i)e[i.exclusive?\"exclusiveMaximum\":\"maximum\"]=i.value;this._setIfNotEmpty(e,\"format\",this._getNumberFormat(o))}_setStringFieldProperties(e,t){if(e.type!==\"string\"||t.type!==\"string\")return;if(t.flags&&t.flags.encoding)e.contentEncoding=t.flags.encoding;const s=this.ruleArgFieldName;let n;let i;const o=a((c,l=false)=>{if(l){this._addKeyword(e,\"not\",{pattern:c})}else{this._addKeyword(e,\"pattern\",c)}},\"addPattern\");It(t.rules,c=>{const l=c[s]||{};const u=l.options||{};switch(c.name){case\"min\":case\"max\":case\"length\":if(l.encoding){this._inexact();break}if(c.name!==\"max\")n=this._bound(n,l.limit,false,true);if(c.name!==\"min\")i=this._bound(i,l.limit,false,false);break;case\"format\":this._addKeyword(e,\"format\",l.name);break;case\"email\":this._addKeyword(e,\"format\",\"email\");break;case\"hostname\":this._addKeyword(e,\"format\",\"hostname\");break;case\"uri\":this._addKeyword(e,\"format\",u.allowRelative||u.relativeOnly?\"uri-reference\":\"uri\");if(u.scheme||u.relativeOnly)this._inexact();break;case\"ip\":{const f=u.version||[];const d=f.length?f.filter(p=>p===\"ipv4\"||p===\"ipv6\"):[\"ipv4\",\"ipv6\"];const h=u.cidr===\"required\"?[]:d.map(p=>({format:p}));if(u.cidr!==\"forbidden\"||d.length!==(f.length||2)){this._inexact();h.push({pattern:\"^[0-9a-zA-Z:.]+(?:/[0-9]{1,3})?$\"})}if(h.length===1){this._mergeKeywords(e,h[0])}else{this._addKeyword(e,\"anyOf\",h)}break}case\"pattern\":{const f=Pl(l.regex);if(f){o(f.source,!!u.invert)}else{this._inexact()}break}case\"alphanum\":o(\"^[a-zA-Z0-9]+$\");break;case\"token\":o(\"^[a-zA-Z0-9_]+$\");break;case\"hex\":o(u.prefix===\"optional\"?\"^(?:0[xX])?[0-9a-fA-F]+$\":u.prefix===true?\"^0[xX][0-9a-fA-F]+$\":\"^[0-9a-fA-F]+$\");if(u.byteAligned)o(\"^(?:[\\\\s\\\\S]{2})*$\");break;case\"trim\":if(l.enabled!==false)o(\"^(?:\\\\S(?:[\\\\s\\\\S]*\\\\S)?)?$\");break;case\"isoDate\":this._addKeyword(e,\"format\",\"date-time\");break;case\"isoDuration\":this._addKeyword(e,\"format\",\"duration\");break;case\"uuid\":case\"guid\":this._addKeyword(e,\"format\",\"uuid\");break;default:break}});if(n&&n.value>0)e.minLength=n.value;if(i)e.maxLength=i.value}_setContains(e,t,s){const n=s.min===void 0?1:s.min;if(n!==1||s.max!==void 0)this._inexact();if(n<1)return;this._addKeyword(e,\"contains\",t)}_setTuple(e,t,s){e.items=t;e.additionalItems=s===void 0?false:s}_setArrayFieldProperties(e,t,s,n){if(e.type!==\"array\")return;const i=this.ruleArgFieldName;let o;let c;It(t.rules,f=>{const d=f[i]||{};switch(f.name){case\"max\":c=this._bound(c,d.limit,false,false);break;case\"min\":o=this._bound(o,d.limit,false,true);break;case\"length\":o=this._bound(o,d.limit,false,true);c=this._bound(c,d.limit,false,false);break;case\"unique\":if(typeof d.comparator!==\"function\"){e.uniqueItems=true}else{this._inexact()}break;case\"has\":this._setContains(e,this.parse(d.schema,s,n+1),d.options||{});break;default:break}});if(o)e.minItems=o.value;if(c)e.maxItems=c.value;if(this._stripsArrayItems(t)){this._inexact();e.items={};return}if(ms([...t.items||[],...t.ordered||[]],f=>this._getPresence(f)!==void 0&&this._getPresence(f)!==\"optional\"))this._inexact();let l;if(t.items&&t.items.length){if(t.items.length===1){l=this.parse(t.items[0],s,n+1)}else{l={anyOf:Kt(t.items,f=>{return this.parse(f,s,n+1)})}}}const u=t.ordered;if(u&&u.length){this._setTuple(e,u.map(f=>this.parse(f,s,n+1)),l)}else{e.items=l||{}}}_setDateFieldProperties(e,t){if(e.type!==\"date\")return;const s=t.flags&&t.flags.format;if(s===\"javascript\"||s===\"unix\"){e.type=\"number\"}else{e.type=\"string\";e.format=\"date-time\"}}_setAlternativesProperties(e,t,s,n){if(e.type!==\"alternatives\")return;delete e.type;if(t.matches.length===0)return;const i=t.matches;if(i[0].schema){const o=t.flags&&t.flags.match;const c=Kt(i,u=>{return this.parse(u.schema,s,n+1)});const l=c.every(u=>this.isExact(u));if(o===\"none\"){if(l)this._mergeKeywords(e,{not:c.length===1?c[0]:{anyOf:c}})}else if(c.length===1){this._mergeKeywords(e,c[0])}else{this._mergeKeywords(e,{[o===\"one\"?l?\"oneOf\":\"anyOf\":o===\"all\"?\"allOf\":\"anyOf\"]:c})}}else{this._setConditionProperties(e,t,s,n,\"matches\",\"anyOf\")}}_setConditionProperties(e,t,s,n,i,o=\"allOf\"){const c=t[i];if(!c||c.length===0)return;if(i===\"whens\"&&(t.type!==\"any\"||t.rules||t.allow||t.invalid))this._inexact();let l=this._isIfThenElseSupported();const u=Ol(t.metas,f=>{return typeof f[\"if-style\"]!==\"undefined\"});if(l&&u.length>0&&u[0][\"if-style\"]===false)l=false;if(c.length>1){this._mergeKeywords(e,{[o]:Jb(Kt(c,f=>{return this._setConditionSchema(l,{},f,s,n+1)}))})}else{const f=this._setConditionSchema(l,{},c[0],s,n+1);if(f)this._mergeKeywords(e,f)}}_setConditionSchema(e,t,s,n,i){if(!s.is&&!s.switch)return;if(s.switch){this._parseSwitchCondition(e,t,s,n,i)}else{if(e){this._parseIfThenElseCondition(t,s,n,i)}else{this._setConditionCompositionStyle(t,s,n,i)}}return t}_parseIfThenElseCondition(e,t,s,n){if(t.ref)return this._setConditionCompositionStyle(e,t,s,n);const i=this.parse(t.is,s,n);if(!this.isExact(i))return this._setBranches(e,t,s,n);e.if=i;if(t.then)e.then=this.parse(t.then,s,n);if(t.otherwise)e.else=this.parse(t.otherwise,s,n);return e}_setBranches(e,t,s,n){this._inexact();if(!t.then||!t.otherwise)return e;e.anyOf=[this.parse(t.then,s,n),this.parse(t.otherwise,s,n)];return e}_parseSwitchCondition(e,t,s,n,i){if(s.ref)this._inexact();const o=[];for(const c of s.switch){if(e&&!s.ref){const l=this._parseIfThenElseCondition({},c,n,i+1);o.push(l)}else{if(c.then)o.push(this.parse(c.then,n,i+1));if(c.otherwise)o.push(this.parse(c.otherwise,n,i+1))}}if(o.length>1){t.anyOf=o}else{St(t,o[0])}}_setConditionCompositionStyle(e,t,s,n){if(t.ref){this._inexact();const i=e.anyOf||[];if(t.then)i.push(this.parse(t.then,s,n+1));if(t.otherwise)i.push(this.parse(t.otherwise,s,n+1));if(i.length>1){e.anyOf=i}else{St(e,i[0])}}else{if(t.is&&!this.isExact(this.parse(t.is,s,n+1))){this._setBranches(e,t,s,n+1)}else if(t.is&&t.then&&t.otherwise){e.allOf=[{anyOf:[{not:this.parse(t.is,s,n+1)},this.parse(t.then,s,n+1)]},{anyOf:[this.parse(t.is,s,n+1),this.parse(t.otherwise,s,n+1)]}]}else if(t.is&&t.then){e.anyOf=[{not:this.parse(t.is,s,n+1)},this.parse(t.then,s,n+1)]}else if(t.is&&t.otherwise){e.anyOf=[this.parse(t.is,s,n+1),this.parse(t.otherwise,s,n+1)]}}return e}_setAnyProperties(e){if(e.type!==\"any\")return;e.type=[\"array\",\"boolean\",\"number\",\"object\",\"string\",\"null\"]}_setAllOf(e,t,s,n){for(const i of t.rules||[]){if(i.name!==\"allOf\")continue;const o=He(i,`${this.ruleArgFieldName}.schemas`);this._mergeKeywords(e,{allOf:o.map(c=>this.parse(c,s,n+1))})}}_setNonJsonProperties(e,t){if(!eS.includes(t.type))return;this._addKeyword(e,\"not\",{})}_setMetaProperties(e,t){It(t.metas,s=>{if(s.contentMediaType)e.contentMediaType=s.contentMediaType;if(s.format)e.format=s.format;if(s.title)e.title=s.title})}_setLinkFieldProperties(e,t){if(e.type!==\"link\")return;delete e.type;if(He(t,\"link.ref.type\")===\"local\"){e.$ref=`${this._getLocalSchemaBasePath()}/${t.link.ref.path.join(\"/\")}`}}_copyMetasToSchema(e,t){if(!fr(e.metas)){It(e.metas,s=>{It(s,(n,i)=>{if(this._isKnownMetaKey(i))t[i]=n})})}}_isKnownMetaKey(e){return false}};var qs=class extends Ar{static{a(this,\"JsonDraft04SchemaParser\")}constructor(e={}){super(St({$schema:\"http://json-schema.org/draft-04/schema#\",logicalOpParser:{xor:null,with:a(function(t,s){t.dependencies=t.dependencies||{};t.dependencies[s.key]=s.peers},\"with\"),without:null}},e))}_isIfThenElseSupported(){return false}_setNumberFieldProperties(e,t){super._setNumberFieldProperties(e,t);if(typeof e.exclusiveMinimum!==\"undefined\"){e.minimum=e.exclusiveMinimum;e.exclusiveMinimum=true}if(typeof e.exclusiveMaximum!==\"undefined\"){e.maximum=e.exclusiveMaximum;e.exclusiveMaximum=true}if(typeof e.minimum!==\"undefined\"&&e.minimum===e.exclusiveMinimum)e.exclusiveMinimum=true;if(typeof e.maximum!==\"undefined\"&&e.maximum===e.exclusiveMaximum)e.exclusiveMaximum=true}_getLocalSchemaBasePath(){return\"#/definitions\"}_setContains(e,t,s){this._inexact()}_setPropertyNames(e,t){this._inexact()}_getValuesSchema(e){return{enum:e}}};var zs=class extends Ar{static{a(this,\"JsonDraft201909SchemaParser\")}constructor(e={}){super(St({$schema:\"https://json-schema.org/draft/2019-09/schema\",logicalOpParser:{with:a(function(t,s){t.dependentRequired=t.dependentRequired||{};t.dependentRequired[s.key]=s.peers},\"with\")}},e))}_setContains(e,t,s){const n={contains:t};if(s.min!==void 0&&s.min!==1)n.minContains=s.min;if(s.max!==void 0)n.maxContains=s.max;this._mergeKeywords(e,n)}_isKnownMetaKey(e){return e===\"deprecated\"||e===\"readOnly\"||e===\"writeOnly\"}};var Gs=class extends zs{static{a(this,\"JsonDraft202012SchemaParser\")}constructor(e={}){super(St({$schema:\"https://json-schema.org/draft/2020-12/schema\"},e))}_setTuple(e,t,s){e.prefixItems=t;e.items=s===void 0?false:s}};function Xh(r){const e=r.map(t=>t.name);if(e.some(t=>[\"int8\",\"uint8\",\"int16\",\"uint16\",\"int32\",\"port\"].includes(t)))return\"int32\";if(e.some(t=>[\"uint32\",\"int64\",\"uint64\"].includes(t)))return\"int64\";if(e.includes(\"float\"))return\"float\";if(e.includes(\"double\"))return\"double\";return void 0}a(Xh,\"openApiNumberFormat\");var Jo=class extends qs{static{a(this,\"OpenApiSchemaParser\")}constructor(e={}){super(St({logicalOpParser:{xor:null,with:null,without:null}},e));this.$schema=void 0;this.knownKeys=[\"$ref\",\"title\",\"multipleOf\",\"maximum\",\"exclusiveMaximum\",\"minimum\",\"exclusiveMinimum\",\"maxLength\",\"minLength\",\"pattern\",\"maxItems\",\"minItems\",\"uniqueItems\",\"maxProperties\",\"minProperties\",\"required\",\"enum\",\"description\",\"format\",\"default\",\"type\",\"allOf\",\"oneOf\",\"anyOf\",\"not\",\"items\",\"properties\",\"additionalProperties\",\"example\",\"nullable\"]}parse(e,t={},s=0){const n=super.parse(e,t,s);if(s===0&&!fr(t))n.schemas=t;delete n.components;if(n.const)n.enum=[n.const];return n}_isIfThenElseSupported(){return false}_getNumberFormat(e){return Xh(e)}_setAnyProperties(e){if(e.type===\"any\")delete e.type}_getBinaryFormat(){return\"binary\"}_setTuple(e,t,s){this._inexact();e.items={anyOf:s===void 0?t:[...t,s]};if(s===void 0&&!(typeof e.maxItems===\"number\"&&e.maxItems<=t.length))e.maxItems=t.length}_setObjectProperties(e,t,s,n){super._setObjectProperties(e,t,s,n);if(!e.patternProperties)return;const i=Object.values(e.patternProperties);delete e.patternProperties;this._inexact();if(e.additionalProperties===true)return;const o=typeof e.additionalProperties===\"object\"?[...i,e.additionalProperties]:i;e.additionalProperties=o.length===1?o[0]:{anyOf:o}}_getLocalSchemaBasePath(){return\"#/components/schemas\"}_setBasicProperties(e,t){super._setBasicProperties(e,t);if(!fr(e.examples)){e.example=e.examples[0];delete e.examples}}_addNullTypeIfNullable(e,t){super._addNullTypeIfNullable(e,t);if(e.type===\"null\"){e.type=\"object\";e.nullable=true}else if(Array.isArray(e.type)&&e.type.includes(\"null\")){Ol(e.type,s=>{return s===\"null\"});e.nullable=true;if(e.type.length===1){e.type=e.type[0]}else if(!e.type){e.type=\"object\"}}if(Array.isArray(e.type)){const s=e.anyOf||[];e.anyOf=s;It(e.type,n=>{const i=ms(s,o=>{return o.type===n});if(!i){const o={type:n};if(n===\"array\")o.items={};s.push(o)}});It(s,n=>{if(e.nullable)n.nullable=true});delete e.type;delete e.nullable}}_isKnownMetaKey(e){return e.startsWith(\"x-\")||e===\"deprecated\"||e===\"readOnly\"||e===\"writeOnly\"}};var Zo=class extends Gs{static{a(this,\"OpenApi31SchemaParser\")}constructor(e={}){super(e);this.$schema=void 0}parse(e,t={},s=0){const n=super.parse(e,t,s);if(s===0&&!fr(t))n.schemas=t;delete n.components;return n}_getNumberFormat(e){return Xh(e)}_getBinaryFormat(){return\"binary\"}_getLocalSchemaBasePath(){return\"#/components/schemas\"}_isKnownMetaKey(e){return e.startsWith(\"x-\")||e===\"deprecated\"||e===\"readOnly\"||e===\"writeOnly\"}};var Jv=[\"null\",\"boolean\",\"number\",\"integer\",\"string\",\"array\",\"object\"];var Qo={string:[\"minLength\",\"maxLength\",\"pattern\",\"format\"],number:[\"minimum\",\"maximum\",\"exclusiveMinimum\",\"exclusiveMaximum\",\"multipleOf\",\"format\"],array:[\"items\",\"prefixItems\",\"additionalItems\",\"contains\",\"minContains\",\"maxContains\",\"minItems\",\"maxItems\",\"uniqueItems\"],object:[\"properties\",\"required\",\"patternProperties\",\"additionalProperties\",\"propertyNames\",\"minProperties\",\"maxProperties\",\"dependentRequired\",\"dependencies\"]};var sS=[\"title\",\"description\",\"default\",\"examples\",\"example\",\"deprecated\",\"readOnly\",\"writeOnly\",\"$comment\"];var Zv=[\"enum\",\"const\",\"default\",\"examples\",\"example\"];var ni=\"https://lakutata.invalid/schema.json\";var Qv=[[/draft-04/,\"draft-04\"],[/draft-06/,\"draft-06\"],[/draft-07/,\"draft-07\"],[/2019-09/,\"draft-2019-09\"],[/2020-12/,\"draft-2020-12\"],[/oas\\/3\\.1/,\"openapi-3.1\"]];function qe(r){return r!==null&&typeof r===\"object\"&&!Array.isArray(r)}a(qe,\"isObject\");function de(r){return typeof r===\"boolean\"||qe(r)}a(de,\"isSchema\");function ea(r){const e=r.indexOf(\"#\");return e<0?r:r.slice(0,e)}a(ea,\"withoutFragment\");function ii(r,e){try{return new URL(r,e).href}catch{return r}}a(ii,\"resolveUri\");function ta(){return b.alternatives().try(b.any()).match(\"none\")}a(ta,\"never\");function Yh(r){if(r.length===1)return r[0];if(r[0]._valids)return b.any().allOf(...r);return r[0].allOf(...r.slice(1))}a(Yh,\"all\");function ra(r){const e=r.filter(n=>!Array.isArray(n));const t=r.filter(n=>Array.isArray(n));const s=t.map(n=>{const i=b.array().length(n.length);return n.length?i.ordered(...n.map(o=>ra([o]))):i});if(e.length)s.unshift(b.any().valid(...e));if(!s.length)return ta();return s.length===1?s[0]:b.alternatives().try(...s)}a(ra,\"literals\");var Jh=class{static{a(this,\"Importer\")}constructor(e,t){this.root=e;this.registry=new Map;this.converted=new Map;this.pending=new Map;this.shared=[];this.memo=new WeakMap;this.ids=0;this.usedIds=new Set;const s=qe(e)?e.$schema:void 0;let n=t.dialect;if(!n&&typeof s===\"string\"){n=Qv.find(([o])=>o.test(s))?.[1]}this.dialect=n||\"draft-2020-12\";this.convert=!!t.convert;const i=t.document===void 0?e:t.document;if(de(i))this.register(i,ni);if(!de(i)&&i!==null&&typeof i===\"object\")this.registry.set(ni,{node:i,base:ni});for(const[o,c]of Object.entries(t.schemas||{})){if(de(c))this.register(c,ii(o,ni))}}run(){let e=this.node(this.root,ni);for(const t of this.shared)e=e.shared(t);return e.prefs({convert:this.convert})}get idKeyword(){return this.dialect===\"draft-04\"||this.dialect===\"openapi-3.0\"?\"id\":\"$id\"}register(e,t){if(Array.isArray(e)){for(const n of e)this.register(n,t);return}if(!qe(e))return;const s=e[this.idKeyword];if(typeof s===\"string\"&&!s.startsWith(\"#\")){t=ii(s,t);this.registry.set(ea(t),{node:e,base:t})}if(!this.registry.has(ea(t)))this.registry.set(ea(t),{node:e,base:t});for(const n of[e.$anchor,e.$dynamicAnchor,typeof s===\"string\"&&s.startsWith(\"#\")?s.slice(1):void 0]){if(typeof n===\"string\"&&n)this.registry.set(`${ea(t)}#${n}`,{node:e,base:t})}for(const[n,i]of Object.entries(e)){if(Zv.includes(n))continue;if(i!==null&&typeof i===\"object\")this.register(i,t)}}resolve(e,t){const s=ii(e,t);const n=s.indexOf(\"#\");const i=n<0?\"\":decodeURIComponent(s.slice(n+1));const o=this.registry.get(ea(s));if(!i.startsWith(\"/\")&&i){const l=this.registry.get(s);if(l)return l}if(!o)throw new Ue(`Cannot resolve the reference ${e}`);if(!i)return o;if(!i.startsWith(\"/\"))throw new Ue(`Cannot resolve the reference ${e}`);let c=o.node;for(const l of i.slice(1).split(\"/\")){const u=l.replace(/~1/g,\"/\").replace(/~0/g,\"~\");if(c===null||typeof c!==\"object\"||!Object.prototype.hasOwnProperty.call(c,u))throw new Ue(`Cannot resolve the reference ${e}`);c=c[u]}if(!de(c))throw new Ue(`The reference ${e} is not a schema`);return{node:c,base:o.base}}idOf(e){const t=e.slice(e.indexOf(\"#\")+1);const s=decodeURIComponent(t.split(\"/\").pop()||\"\").replace(/~1/g,\"/\").replace(/~0/g,\"~\").replace(/[^\\w-]/g,\"_\")||\"schema\";let n=s;while(this.usedIds.has(n))n=`${s}_${++this.ids}`;this.usedIds.add(n);return n}reference(e,t){const{node:s,base:n}=this.resolve(e,t);const i=this.converted.get(s);if(i)return i;const o=this.pending.get(s);if(o){o.used=true;return b.link(`#${o.id}`)}const c=this.idOf(e);this.pending.set(s,{id:c,used:false});let l=this.node(s,n);const{used:u}=this.pending.get(s);this.pending.delete(s);if(u){this.shared.push(l.id(c));l=b.link(`#${c}`)}this.converted.set(s,l);return l}node(e,t){if(e===true)return b.any();if(e===false)return ta();if(!qe(e))throw new Ue(\"A JSON Schema must be an object or a boolean\");const s=this.memo.get(e);if(s)return s;const n=this.convertNode(e,t);this.memo.set(e,n);return n}convertNode(e,t){const s=e[this.idKeyword];if(typeof s===\"string\"&&!s.startsWith(\"#\"))t=ii(s,t);const n=[];const i=this.typed(e,t);if(i)n.push(i);if(de(e.not))n.push(b.alternatives().try(this.node(e.not,t)).match(\"none\"));const o=this.list(e.anyOf);if(o.length)n.push(o.length===1?this.node(o[0],t):b.alternatives().try(...o.map(d=>this.node(d,t))));const c=this.list(e.oneOf);if(c.length)n.push(b.alternatives().try(...c.map(d=>this.node(d,t))).match(\"one\"));for(const d of this.list(e.allOf))n.push(this.node(d,t));if(de(e.if)&&(de(e.then)||de(e.else))){n.push(b.any().when(this.node(e.if,t),{then:de(e.then)?this.node(e.then,t):b.any(),otherwise:de(e.else)?this.node(e.else,t):b.any()}))}for(const[d,h]of Object.entries(this.dependentSchemas(e))){n.push(b.any().when(b.object({[d]:b.any().required()}).unknown(),{then:this.node(h,t),otherwise:b.any()}))}const l=e.$ref??e.$dynamicRef??e.$recursiveRef;if(typeof l===\"string\")n.push(this.reference(l,t));const u=this.unevaluated(e,t);if(u)n.push(u);let f=this.values(e,n);f=this.annotate(f,e);return f}list(e){return Array.isArray(e)?e.filter(de):[]}dependentSchemas(e){const t={};for(const s of[\"dependencies\",\"dependentSchemas\"]){const n=e[s];if(!qe(n))continue;for(const[i,o]of Object.entries(n)){if(de(o))t[i]=o}}return t}values(e,t){let s;if(Array.isArray(e.enum))s=e.enum;if(Object.prototype.hasOwnProperty.call(e,\"const\"))s=s?s.filter(i=>ra([e.const]).validate(i).error===void 0):[e.const];const n=t.length===0?void 0:Yh(t);if(!s)return n||b.any();if(!s.length)return ta();if(!n)return ra(s);try{return ra(s.filter(i=>n.validate(i,{convert:this.convert}).error===void 0))}catch{return Yh([ra(s),n])}}typed(e,t){let s=typeof e.type===\"string\"?[e.type]:Array.isArray(e.type)?e.type.filter(l=>typeof l===\"string\"):void 0;if(s&&this.dialect===\"openapi-3.0\"&&e.nullable===true&&!s.includes(\"null\"))s=[...s,\"null\"];if(!s){const l=Object.keys(Qo).filter(u=>Qo[u].some(f=>e[f]!==void 0));if(!l.length)return void 0;s=[\"null\",\"boolean\",\"number\",\"string\",\"array\",\"object\"]}s=s.filter(l=>Jv.includes(l));if(s.includes(\"number\"))s=s.filter(l=>l!==\"integer\");const n=[...new Set(s)];const i=n.length>1&&n.includes(\"null\");const o=n.filter(l=>!i||l!==\"null\").map(l=>this.type(l,e,t));if(!o.length)return ta();const c=o.length===1?o[0]:b.alternatives().try(...o);return i?c.allow(null):c}type(e,t,s){switch(e){case\"null\":return b.any().valid(null);case\"boolean\":return b.boolean();case\"integer\":case\"number\":return this.number(t,e===\"integer\");case\"string\":return this.string(t);case\"array\":return this.array(t,s);default:return this.object(t,s)}}number(e,t){let s=b.number().unsafe();let n=typeof e.minimum===\"number\"?e.minimum:void 0;let i=typeof e.maximum===\"number\"?e.maximum:void 0;let o=typeof e.exclusiveMinimum===\"number\"?e.exclusiveMinimum:void 0;let c=typeof e.exclusiveMaximum===\"number\"?e.exclusiveMaximum:void 0;if(e.exclusiveMinimum===true&&n!==void 0){o=n;n=void 0}if(e.exclusiveMaximum===true&&i!==void 0){c=i;i=void 0}const l=e.format;const u=typeof l===\"string\"&&[\"int32\",\"int64\",\"float\",\"double\"].includes(l)?l:t?Object.keys(At).find(f=>At[f][0]===n&&At[f][1]===i):n===-Gt&&i===Gt?\"float\":void 0;if(u){s=s[u].call(s);if(u in At||u===\"float\"){const[f,d]=u===\"float\"?[-Gt,Gt]:At[u];if(n===f)n=void 0;if(i===d)i=void 0}}if(t&&!(u&&u in At))s=s.integer();if(n!==void 0)s=s.min(n);if(i!==void 0)s=s.max(i);if(o!==void 0)s=s.greater(o);if(c!==void 0)s=s.less(c);if(typeof e.multipleOf===\"number\"&&e.multipleOf>0)s=s.multiple(e.multipleOf);return s}string(e){let t=b.string().min(typeof e.minLength===\"number\"?e.minLength:0);if(typeof e.maxLength===\"number\")t=t.max(e.maxLength);if(typeof e.pattern===\"string\"){let n;try{n=new RegExp(e.pattern,\"u\")}catch{throw new Ue(`Invalid pattern: ${e.pattern}`)}t=t.pattern(n)}const s=e.format;if(typeof s===\"string\"&&Object.prototype.hasOwnProperty.call(Yn,s))t=t.format(s);return t}array(e,t){let s=b.array();const n=Array.isArray(e.prefixItems)?this.list(e.prefixItems):Array.isArray(e.items)?this.list(e.items):void 0;const i=n?Array.isArray(e.prefixItems)?e.items:e.additionalItems:e.items;let o=typeof e.maxItems===\"number\"?e.maxItems:void 0;if(n&&n.length)s=s.ordered(...n.map(c=>this.node(c,t)));if(i===false){const c=n?n.length:0;if(!n||!n.length)o=o===void 0?c:Math.min(o,c)}else if(de(i)&&i!==true){s=s.items(this.node(i,t))}else if(n&&n.length){s=s.items(b.any())}if(typeof e.minItems===\"number\")s=s.min(e.minItems);if(o!==void 0)s=s.max(o);if(e.uniqueItems===true)s=s.unique();if(de(e.contains)){const c=typeof e.minContains===\"number\"?e.minContains:1;const l=typeof e.maxContains===\"number\"?e.maxContains:void 0;if(l!==void 0&&c>l)return ta();s=s.has(this.node(e.contains,t),c===1&&l===void 0?{}:{min:c,max:l})}return s}object(e,t){return this.refineObject(b.object(this.objectKeys(e,t)),e,t)}objectPatterns(e,t){const s=[];if(!qe(e.patternProperties))return s;for(const[n,i]of Object.entries(e.patternProperties)){if(!de(i))continue;let o;try{o=new RegExp(n,\"u\")}catch{throw new Ue(`Invalid pattern: ${n}`)}s.push({regex:o,schema:this.node(i,t)})}return s}objectKeys(e,t){const s=qe(e.properties)?e.properties:{};const n=Array.isArray(e.required)?e.required.filter(l=>typeof l===\"string\"):[];const i=this.objectPatterns(e,t);const o=e.additionalProperties;const c={};for(const l of new Set([...Object.keys(s),...n])){const u=i.filter(({regex:h})=>h.test(l)).map(({schema:h})=>h);const f=[...de(s[l])?[this.node(s[l],t)]:[],...u];if(!de(s[l])&&!u.length&&de(o)&&o!==true)f.push(this.node(o,t));const d=f.length===0?b.any():Yh(f);c[l]=n.includes(l)?d.required():d.optional()}return c}refineObject(e,t,s){for(const{regex:i,schema:o}of this.objectPatterns(t,s))e=e.pattern(i,o,{fallthrough:true});const n=t.additionalProperties;if(n===false){e=e.unknown(false)}else if(de(n)&&n!==true){e=e.unknown(this.node(n,s))}else{e=e.unknown(true)}if(de(t.propertyNames))e=e.keyNames(this.node(t.propertyNames,s));if(typeof t.minProperties===\"number\")e=e.min(t.minProperties);if(typeof t.maxProperties===\"number\")e=e.max(t.maxProperties);for(const i of[\"dependencies\",\"dependentRequired\"]){const o=t[i];if(!qe(o))continue;for(const[c,l]of Object.entries(o)){if(Array.isArray(l)&&l.length)e=e.with(c,l.filter(u=>typeof u===\"string\"))}}return e}objectParts(){let e=this.root;let t=ni;while(qe(e)&&typeof e.$ref===\"string\"&&Object.keys(e).every(N=>N===\"$ref\"||sS.includes(N))){const N=e;const A=this.resolve(e.$ref,t);e=qe(A.node)?{...N,...A.node}:A.node;delete e.$ref;if(qe(A.node)&&typeof A.node.$ref===\"string\")e.$ref=A.node.$ref;t=A.base}if(!qe(e))throw new Ue(\"The JSON Schema of a DTO must describe objects\");const s=e.type;if(s!==void 0&&!(s===\"object\"||Array.isArray(s)&&s.includes(\"object\")))throw new Ue(\"The JSON Schema of a DTO must describe objects\");const n=e[this.idKeyword];if(typeof n===\"string\"&&!n.startsWith(\"#\"))t=ii(n,t);const i=e;const o=this.objectKeys(i,t);const{type:c,properties:l,required:u,patternProperties:f,additionalProperties:d,propertyNames:h,minProperties:p,maxProperties:m,dependentRequired:y,...w}=i;const S=Object.fromEntries(Object.entries(w).filter(([N])=>!Qo.string.includes(N)&&!Qo.number.includes(N)&&!Qo.array.includes(N)));if(qe(S.dependencies))S.dependencies=Object.fromEntries(Object.entries(S.dependencies).filter(([,N])=>de(N)));const T=Object.keys(S).some(N=>!sS.includes(N)&&![\"$schema\",\"$id\",\"id\",\"$defs\",\"definitions\",\"$comment\",\"nullable\",\"discriminator\",\"xml\",\"externalDocs\"].includes(N));const _=!T?void 0:S.unevaluatedProperties!==void 0||S.unevaluatedItems!==void 0?this.node(i,t):this.node({...S,type:\"object\"},t);const x=this.shared;const k=a(N=>{for(const A of x)N=N.shared(A);return N},\"withShared\");for(const N of Object.keys(o))o[N]=k(o[N]);return{keys:o,refine:a(N=>{let A=this.refineObject(N,i,t);if(_)A=A.allOf(_);return k(A)},\"refine\"),title:typeof i.title===\"string\"?i.title:void 0,description:typeof i.description===\"string\"?i.description:void 0}}evaluated(e,t,s,n,i=new Set){const o={keys:new Set,items:new Set,all:false};if(!qe(e)||i.has(e))return o;i=new Set(i).add(e);const c=e[this.idKeyword];if(typeof c===\"string\"&&!c.startsWith(\"#\"))t=ii(c,t);const l=a(d=>{d.keys.forEach(h=>o.keys.add(h));d.items.forEach(h=>o.items.add(h));o.all=o.all||d.all},\"add\");const u=a(d=>{const h=this.node(d,t);return h.$_match(s,n.state.nest(h,\"unevaluated\"),n.prefs)},\"matches\");if(Array.isArray(s)){const d=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:void 0;if(Array.isArray(d))for(let h=0;h<Math.min(d.length,s.length);++h)o.items.add(h);if(e.items!==void 0&&!Array.isArray(e.items)||e.additionalItems!==void 0||e.unevaluatedItems!==void 0)o.all=true;if(de(e.contains)&&this.dialect!==\"draft-2019-09\"){const h=this.node(e.contains,t);s.forEach((p,m)=>{if(h.$_match(p,n.state.nest(h,\"unevaluated\"),n.prefs))o.items.add(m)})}}else if(qe(s)){const d=Object.keys(s);if(qe(e.properties)){for(const h of Object.keys(e.properties)){if(Object.prototype.hasOwnProperty.call(s,h))o.keys.add(h)}}if(qe(e.patternProperties)){const h=Object.keys(e.patternProperties).map(p=>new RegExp(p,\"u\"));for(const p of d){if(h.some(m=>m.test(p)))o.keys.add(p)}}if(e.additionalProperties!==void 0||e.unevaluatedProperties!==void 0)o.all=true;for(const[h,p]of Object.entries(this.dependentSchemas(e))){if(Object.prototype.hasOwnProperty.call(s,h)&&u(p))l(this.evaluated(p,t,s,n,i))}}for(const d of this.list(e.allOf))l(this.evaluated(d,t,s,n,i));for(const d of[...this.list(e.anyOf),...this.list(e.oneOf)]){if(u(d))l(this.evaluated(d,t,s,n,i))}if(de(e.if)){if(u(e.if)){l(this.evaluated(e.if,t,s,n,i));if(de(e.then))l(this.evaluated(e.then,t,s,n,i))}else if(de(e.else)){l(this.evaluated(e.else,t,s,n,i))}}const f=e.$ref??e.$dynamicRef??e.$recursiveRef;if(typeof f===\"string\"){const d=this.resolve(f,t);l(this.evaluated(d.node,d.base,s,n,i))}return o}unevaluated(e,t){const{unevaluatedProperties:s,unevaluatedItems:n,...i}=e;const o=de(s)&&s!==true?this.node(s,t):void 0;const c=de(n)&&n!==true?this.node(n,t):void 0;if(!o&&!c)return void 0;return b.any().custom((l,u)=>{const f=Array.isArray(l);if(f?!c:!o||!qe(l))return l;const d=this.evaluated(i,t,l,u);if(d.all)return l;const h=f?c:o;const p=f?l.map((m,y)=>[y,m]):Object.entries(l);for(const[m,y]of p){if(f?d.items.has(m):d.keys.has(m))continue;if(!h.$_match(y,u.state.nest(h,\"unevaluated\"),u.prefs)){return u.message({custom:`{{#label}} has an unevaluated ${f?\"item\":\"key\"} {{#name}} which is not allowed`},{name:m})}}return l},\"unevaluated keys and items\")}annotate(e,t){if(typeof t.description===\"string\"&&t.description)e=e.description(t.description);if(t.default!==void 0)e=e.default(t.default);const s=Array.isArray(t.examples)?t.examples:t.example!==void 0?[t.example]:[];for(const i of s)e=e.example(i);const n={};for(const[i,o]of Object.entries(t)){if([\"title\",\"deprecated\",\"readOnly\",\"writeOnly\",\"contentEncoding\",\"contentMediaType\"].includes(i)||i.startsWith(\"x-\"))n[i]=o}if(typeof t.format===\"string\"&&!Object.prototype.hasOwnProperty.call(Yn,t.format)&&![\"int32\",\"int64\",\"float\",\"double\"].includes(t.format))n.format=t.format;if(Object.keys(n).length)e=e.meta(n);return e}};function nS(r,e={}){if(!de(r))throw new Ue(\"A JSON Schema must be an object or a boolean\");return new Jh(r,e).objectParts()}a(nS,\"importObject\");var eA={\"draft-2020-12\":Gs,\"draft-2019-09\":zs,\"draft-07\":Ar,\"draft-04\":qs,\"openapi-3.0\":Jo,\"openapi-3.1\":Zo};function Zh(r,e={}){const t=typeof r===\"function\"&&typeof r.Schema===\"function\"?r.Schema():r;if(!t||typeof t.describe!==\"function\")throw new Ue(\"Not a schema object.\");const s=e.target||\"draft-2020-12\";const n=eA[s];if(!n)throw new Ue(`Unknown JSON Schema target: ${s}`);const i=new n({includeSchemaDialect:!!e.dialect,preferences:{...e.preferences||Wo}});const o=e.definitions||{};const c=i.parse(t.describe(),o);return c}a(Zh,\"toJsonSchema\");var tA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var rA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var sa;function na(r){return ti(sA,me(r),()=>{const e=Hh(r);const t=qh(r);return e?t.pattern(I.String(),e):t})}a(na,\"getObjectSchema\");var sA=new WeakMap;var nA=new WeakMap;var iA=new WeakMap;var oA=[\"presence\",\"description\",\"label\",\"unknown\"];function aA(r){const e=r.$_terms;for(const s of[\"dependencies\",\"renames\",\"externals\",\"whens\",\"alterations\"]){const n=e[s];if(n&&(!Array.isArray(n)||n.length))return false}if(r._rules.length||r._valids||r._invalids)return false;for(const[s,n]of Object.entries(r._flags)){if(!oA.includes(s)||s===\"unknown\"&&typeof n===\"object\")return false}const t=e.keys||[];return t.every(({schema:s})=>!s.$_rootReferences().length)}a(aA,\"arePropertiesIndependent\");function cA(r,e){const t=ti(iA,me(r),()=>new Map);let s=t.get(e);if(s!==void 0)return s;s=null;const n=v(na(r));if(aA(n)){const i=(n.$_terms.keys||[]).find(({key:o})=>o===e);if(i){const o=v(Ce.object({[e]:i.schema}));s=v(n._preferences?o.prefs(n._preferences):o)}}t.set(e,s);return s}a(cA,\"getPropertySchema\");var lA=new WeakMap;function uA(r){if(!r||r.type!==\"any\"||r._rules.length||r._valids||r._invalids)return false;const e=r.$_terms;return![\"whens\",\"externals\"].some(t=>Array.isArray(e[t])&&e[t].length>0)}a(uA,\"acceptsAnything\");function fA(r,e){if(typeof e!==\"string\")return false;const t=ti(lA,me(r),()=>new Map);let s=t.get(e);if(s!==void 0)return s;const n=v(na(r));const i=(n.$_terms.keys||[]).find(({key:c})=>c===e);const o=i?void 0:(n.$_terms.patterns||[]).find(c=>c.regex?c.regex.test(e):!c.schema.validate(e).error);s=uA(i?i.schema:o?.rule);t.set(e,s);return s}a(fA,\"acceptsAnyValue\");function dA(r){const e=r.constructor;if(e===Object||e===Array)return true;return e===void 0&&Object.getPrototypeOf(r)===null}a(dA,\"isPlainData\");function Qh(r,e,t){if(typeof e===\"string\"){const s=cA(r,e);if(s)return I.validate({[e]:t},s,{noDefaults:true})[e]}return I.validate({...r,[e]:t},na(r),{noDefaults:true})[e]}a(Qh,\"validatePropertyValue\");var hA=[\"push\",\"pop\",\"shift\",\"unshift\",\"splice\",\"sort\",\"reverse\",\"fill\",\"copyWithin\"];function pA(r,e){r.length=0;for(let t=0;t<e.length;++t){if(t in e)r[t]=e[t]}r.length=e.length}a(pA,\"restoreArray\");function iS(r,e,t){if(t.had){Reflect.set(r,e,t.value)}else{Reflect.deleteProperty(r,e)}if(t.length!==void 0)r.length=t.length}a(iS,\"restoreProperty\");function oS(r,e){return{had:Object.prototype.hasOwnProperty.call(r,e),value:Reflect.get(r,e),length:Array.isArray(r)?r.length:void 0}}a(oS,\"propertyState\");function cS(r,e,t,s,n,i){const o=Reflect.get(r,e,t);if(!o)return o;if(typeof o!==\"object\"){if(typeof o!==\"function\")return o;if(Array.isArray(r)&&typeof e===\"string\"&&hA.includes(e)){return(...c)=>{const l=r.slice();try{const u=o.apply(r,c);s();return u}catch(u){pA(r,l);throw u}}}return new Proxy(o,{apply:a((c,l,u)=>Reflect.apply(c,r,u),\"apply\")})}if(n?.(i)&&!dA(o))return o;return new Proxy(o,{set(c,l,u,f){const d=oS(c,l);try{const h=Reflect.set(c,l,u,f);s();return h}catch(h){iS(c,l,d);throw h}},get(c,l,u){return cS(c,l,u,s,n,i)},deleteProperty:a((c,l)=>{const u=oS(c,l);try{const f=Reflect.deleteProperty(c,l);s();return f}catch(f){iS(c,l,u);throw f}},\"deleteProperty\")})}a(cS,\"dynamicProxyProperty\");var aS=Symbol(\"DTO.DESCRIPTION\");var I=sa=class QU extends Hs{static{a(this,\"DTO\")}constructor(e={}){super();let t;const s=a(i=>{if(typeof i!==\"string\")return false;t??=Object.create(null);return t[i]??=fA(this,i)},\"acceptsAny\");const n=new Proxy(this,{set:a((i,o,c,l)=>{if(!bt(o))c=Qh(this,o,c);return Reflect.set(i,o,c,l)},\"set\"),get:a((i,o,c)=>cS(i,o,c,()=>{if(bt(o)){sa.validate({...this},na(this),{noDefaults:true})}else{Qh(this,o,Reflect.get(i,o))}},s,o),\"get\"),deleteProperty:a((i,o)=>{if(!bt(o))Qh(this,o,void 0);return Reflect.deleteProperty(i,o)},\"deleteProperty\")});try{const i=sa.validate(e,na(this));Object.keys(i).forEach(o=>Reflect.set(this,o,i[o]))}catch(i){throw hs(new ur(v(i).message),i)}return n}static prepareValidation(e,t){const s=e?$s.isSchema(e)?v(e):this.Schema():this.Schema();const n=t?t:e?$s.isSchema(e)?{}:v(e):{};return{schema:s,options:n}}static toJsonSchema(e=\"draft-2020-12\",t={}){return Zh(this,{...t,target:e})}static toOpenAPIJsonSchema(e=\"3.1\",t={}){return Zh(this,{...t,target:e===\"3.0\"?\"openapi-3.0\":\"openapi-3.1\"})}static fromJsonSchema(e,t={}){const s=nS(e,t);const n=this;const i=t.name||s.title||`${n.name}FromJsonSchema`;const o=v({[i]:class extends n{}}[i]);for(const[c,l]of Object.entries(s.keys))Al(o.prototype,c,v(l));qb(o,c=>v(s.refine(v(c))));if(s.description)o.description(s.description);return o}static fromOpenAPI(e,t={}){const s=e.openapi;const n=t.dialect||(typeof s===\"string\"&&s.startsWith(\"3.0\")?\"openapi-3.0\":\"openapi-3.1\");const i=e.components?.schemas;if(!i||typeof i!==\"object\")throw new Ue(\"The OpenAPI document has no schemas\");const o={};for(const[c,l]of Object.entries(i)){if(!l||typeof l!==\"object\")continue;const u=l.type;if(u!==void 0&&u!==\"object\")continue;const f=`#/components/schemas/${c.replace(/~/g,\"~0\").replace(/\\//g,\"~1\")}`;o[c]=this.fromJsonSchema({$ref:f},{...t,dialect:n,document:e,name:c})}return o}static description(e){Reflect.defineMetadata(aS,e,this);ei();return this}static Schema(){return ti(nA,this,()=>{const e=Hb(this);const t=Fb(this);const s=Reflect.getOwnMetadata(aS,this);const n=t?e.pattern(sa.String(),t):e;return s===void 0?n:n.description(s)})}static required(){return this.Schema().required()}static optional(){return this.Schema().optional()}static options(e){return this.Schema().options(e)}static isValid(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return $s.isValid(e,n,i)}static async isValidAsync(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return await $s.isValidAsync(e,n,i)}static validate(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return $s.validate(e,n,i)}static async validateAsync(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return await $s.validateAsync(e,n,i)}};I=sa=tA([(r=>jb(r)),rA(\"design:paramtypes\",[Object])],I);var zl=Ye(require(\"util\"),1);var Ks=class extends Z{static{a(this,\"DependencyInjectionException\")}constructor(){super(...arguments);this.errno=\"E_DEPENDENCY_INJECTION\"}};var o2=Ye(Bn(),1);var ep=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.LIFETIME\");var tp=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.LIFETIME.LOCK\");var rp=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.INJECTS\");var sp=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.CONFIGURABLE.PROPERTIES\");var Ml=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.SYMBOL\");var Dl=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.AUTOLOAD\");var np=Symbol(\"LAKUTATA.DI.TARGET.CONTAINER\");var Bl=Symbol(\"LAKUTATA.DI.TARGET.ID\");var lS=require(\"node:crypto\");var uS=new Map;function gs(r){if(!Reflect.hasOwnMetadata(Ml,r)){const e=Symbol((0,lS.randomUUID)());uS.set(e,r.name);Reflect.defineMetadata(Ml,e,r)}return Reflect.getOwnMetadata(Ml,r)}a(gs,\"constructorSymbol\");function ip(r){const e=uS.get(r);if(e)return e;return r}a(ip,\"resolveConstructorNameBySymbol\");var ia=class extends Ks{static{a(this,\"ExtendableError\")}constructor(e){super(e);Object.defineProperty(this,\"message\",{enumerable:false,value:e});Object.defineProperty(this,\"name\",{enumerable:false,value:this.constructor.name});if(\"captureStackTrace\"in Error){Error.captureStackTrace(this,this.constructor)}else{Object.defineProperty(this,\"stack\",{enumerable:false,value:Error(e).stack,writable:true,configurable:true})}}};var ys=class r extends ia{static{a(this,\"DependencyInjectionTypeError\")}constructor(e,t,s,n){super(`${e}: expected ${t} to be ${s}, but got ${n}.`)}static assert(e,t,s,n,i){if(!e){throw new r(t,s,n,i)}return e}};var Ws=class extends ia{static{a(this,\"DependencyInjectionResolutionError\")}constructor(e,t,s){if(bt(e))e=ip(e).toString();const n=e.split(\"_$$\").reverse()[0];t=t.map(c=>bt(c)?ip(c).toString():c.name);t.push(v(n));const i=t.join(\" -> \");let o=`Could not resolve '${n}'.`;if(s)o=`${o} ${s}`;o=`${o} Resolution path: ${i}`;super(o)}};var Ul=class extends ia{static{a(this,\"DependencyInjectionRegistrationError\")}constructor(e,t){const s=e.toString();let n=`Could not register '${s}'.`;if(t){n+=` ${t}`}super(n)}};var ke={SINGLETON:\"SINGLETON\",TRANSIENT:\"TRANSIENT\",SCOPED:\"SCOPED\"};function fS(r,e){return r===ke.SINGLETON&&e!==ke.SINGLETON||r===ke.SCOPED&&e===ke.TRANSIENT}a(fS,\"isLifetimeLonger\");var oi=require(\"node:fs\");var ct=Ye(require(\"node:path\"),1);var mA=/[*?[]/;function dS(r){const e=[];let t=0;let s=0;for(let n=0;n<r.length;n++){const i=r[n];if(i===\"\\\\\"){n++}else if(i===\"{\"){t++}else if(i===\"}\"){t--}else if(i===\",\"&&t===0){e.push(r.substring(s,n));s=n+1}}e.push(r.substring(s));return e}a(dS,\"splitAlternatives\");function gA(r){const e=/^(-?\\d+|[a-zA-Z])\\.\\.(-?\\d+|[a-zA-Z])(?:\\.\\.(-?\\d+))?$/.exec(r);if(!e)return void 0;const t=/\\d/.test(e[1]);if(t!==/\\d/.test(e[2]))return void 0;const s=t?parseInt(e[1]):e[1].charCodeAt(0);const n=t?parseInt(e[2]):e[2].charCodeAt(0);const i=Math.max(Math.abs(e[3]?parseInt(e[3]):1),1);const o=t&&(/^-?0\\d/.test(e[1])||/^-?0\\d/.test(e[2]))?Math.max(e[1].length,e[2].length):0;const c=[];for(let l=s;s<=n?l<=n:l>=n;l+=s<=n?i:-i){if(!t){c.push(String.fromCharCode(l))}else{const u=String(Math.abs(l)).padStart(o-(l<0?1:0),\"0\");c.push(l<0?`-${u}`:u)}}return c}a(gA,\"sequence\");function oa(r){let e=0;let t=-1;for(let s=0;s<r.length;s++){const n=r[s];if(n===\"\\\\\"){s++}else if(n===\"{\"){if(e++===0)t=s}else if(n===\"}\"&&e>0&&--e===0){const i=r.substring(0,t);const o=r.substring(t+1,s);const c=r.substring(s+1);const l=gA(o)??(dS(o).length>1?dS(o):void 0);if(!l)return oa(c).map(u=>`${i}{${o}}${u}`);return l.flatMap(u=>oa(`${i}${u}${c}`))}}return[r]}a(oa,\"expandBraces\");function yA(r,e){let t=e+1;let s=\"[\";if(r[t]===\"!\"||r[t]===\"^\"){s+=\"^\";t++}if(r[t]===\"]\"){s+=\"\\\\]\";t++}for(;t<r.length;t++){const n=r[t];if(n===\"]\")return{source:s+\"]\",end:t};if(n===\"\\\\\"&&t+1<r.length){s+=`\\\\${r[++t]}`}else if(n===\"[\"||n===\"^\"){s+=`\\\\${n}`}else{s+=n}}return void 0}a(yA,\"parseCharacterClass\");function bA(r){return r.replace(/\\\\(.)/g,\"$1\")}a(bA,\"unescape\");function SA(r){return mA.test(r.replace(/\\\\./g,\"\"))}a(SA,\"isMagic\");function op(r,e){if(r===\"**\")return{type:\"globstar\"};if(!SA(r))return{type:\"name\",name:bA(r)};let t=\"^\";for(let s=0;s<r.length;s++){const n=r[s];if(n===\"\\\\\"&&s+1<r.length){t+=r[++s].replace(/[.*+?^${}()|[\\]\\\\/]/g,\"\\\\$&\")}else if(n===\"*\"){while(r[s+1]===\"*\")s++;t+=\"[^/]*\"}else if(n===\"?\"){t+=\"[^/]\"}else if(n===\"[\"){const i=yA(r,s);if(i){t+=i.source;s=i.end}else{t+=\"\\\\[\"}}else{t+=n.replace(/[.*+?^${}()|[\\]\\\\/]/g,\"\\\\$&\")}}return{type:\"pattern\",regex:new RegExp(t+\"$\",e?\"i\":\"\"),dot:r[0]===\".\"}}a(op,\"compileSegment\");function hS(r,e){return r?aa(r,e):e}a(hS,\"joinRelative\");function aa(r,e){return r.endsWith(ct.default.sep)?r+e:r+ct.default.sep+e}a(aa,\"joinName\");function wA(r,e){const t=ct.default.isAbsolute(r);const s=t?ct.default.parse(r).root:\"\";const n=r.substring(s.length);const i=n.split(\"/\");const o=i.length>1&&i[i.length-1]===\"\";const c=i.filter((d,h)=>d!==\"\"||h===0&&i.length===1);const l=c.map(d=>op(d,e.nocase));let u=t?s:e.cwd;let f=t?s:\"\";while(l.length>1&&l[0].type===\"name\"){const d=l.shift().name;u=ct.default.join(u,d);f=t||f?ct.default.join(f,d):d}return{base:u,prefix:f,segments:l,directoryOnly:o}}a(wA,\"compilePattern\");function EA(r,e){const t=\"\\0\";return oa(r.replace(/^\\.\\//,\"\")).map(s=>{const n=s.split(\"/\").filter(i=>i!==\"\").map(i=>{if(i===\"**\")return t;const o=op(i,false);return o.type===\"pattern\"?o.regex.source.slice(1,-1):o.type===\"name\"?o.name.replace(/[.*+?^${}()|[\\]\\\\/]/g,\"\\\\$&\"):t}).join(\"/\").replace(new RegExp(`^${t}$`),\".*\").replace(new RegExp(`^${t}/`),\"(?:.*/)?\").replace(new RegExp(`/${t}/`,\"g\"),\"(?:/.*)?/\").replace(new RegExp(`/${t}$`),\"(?:/.*)?\");return new RegExp(`^${n}$`,e?\"i\":\"\")})}a(EA,\"compileIgnore\");function*TA(r,e,t){function*s(u){const f=yield{type:\"readdir\",path:u};if(!f)return[];const d=[];for(const h of f){const p=h.isSymbolicLink();let m=h.isDirectory();if(p){const y=yield{type:\"stat\",path:aa(u,h.name)};m=!!y&&y.isDirectory()}d.push({name:h.name,directory:m,link:p})}return d}a(s,\"entriesOf\");const n=a((u,f)=>u[0]!==\".\"||e.dot||f,\"visible\");const i=new Set;function*o(u,f,d){if(!u.link)return aa(d,u.name);return yield{type:\"realpath\",path:f}}a(o,\"realOf\");function*c(u,f,d,h,p){const m=r.segments[h];if(!m){t(f,u,true);return}const y=h===r.segments.length-1;if(m.type===\"globstar\"){const S=p??(yield*s(u));if(y){t(f,u,true)}else{yield*c(u,f,d,h+1,S)}for(const T of S){if(!n(T.name,false))continue;const _=aa(u,T.name);const x=hS(f,T.name);if(!T.directory){if(y)t(x,_,false);continue}if(T.link&&!e.follow){if(y)t(x,_,true);continue}const k=yield*o(T,_,d);if(!k||i.has(k))continue;i.add(k);yield*c(_,x,k,h);i.delete(k)}return}const w=[];if(m.type===\"name\"&&(m.name===\".\"||m.name===\"..\")){w.push({name:m.name,directory:true,link:false})}else if(m.type===\"name\"&&!e.nocase&&!p){const S=yield{type:\"stat\",path:ct.default.join(u,m.name)};if(S)w.push({name:m.name,directory:S.isDirectory(),link:false})}else{const S=m.type===\"name\"?e.nocase?m.name.toLowerCase():m.name:void 0;for(const T of p??(yield*s(u))){const _=m.type===\"name\"?(e.nocase?T.name.toLowerCase():T.name)===S:n(T.name,m.dot)&&m.regex.test(T.name);if(_)w.push(T)}}for(const S of w){const T=S.name===\".\"||S.name===\"..\";const _=T?ct.default.join(u,S.name):aa(u,S.name);const x=T?f?ct.default.join(f,S.name):S.name:hS(f,S.name);if(y){t(x,_,S.directory)}else if(S.directory){const k=yield*o(S,_,d);if(k)yield*c(_,x,k,h+1)}}}a(c,\"step\");if(!r.segments.length){const u=yield{type:\"stat\",path:r.base};if(u)t(r.prefix,r.base,u.isDirectory());return}const l=yield{type:\"realpath\",path:r.base};if(!l)return;i.add(l);yield*c(r.base,r.prefix,l,0)}a(TA,\"walkPattern\");function xA(r){const e=r.nocase??(process.platform===\"darwin\"||process.platform===\"win32\");const t=r.ignore===void 0?[]:Array.isArray(r.ignore)?r.ignore:[r.ignore];return{cwd:ct.default.resolve(r.cwd??process.cwd()),absolute:r.absolute??false,dot:r.dot??false,nodir:r.nodir??false,follow:r.follow??false,nocase:e,ignore:t.flatMap(s=>EA(s,e))}}a(xA,\"configure\");function RA(r,e){const t=xA(e);const s=new Map;const n=[];for(const i of Array.isArray(r)?r:[r]){for(const o of oa(i)){const c=wA(o,t);const l=ct.default.isAbsolute(o);n.push(TA(c,t,(u,f,d)=>{if(t.nodir&&d)return;if(c.directoryOnly&&!d)return;if(t.ignore.length){const h=ct.default.relative(t.cwd,f).split(ct.default.sep).join(\"/\")||\".\";if(t.ignore.some(p=>p.test(h)))return}s.set(f,t.absolute||l?f:u||\".\")}))}}return{walks:n,results:a(()=>[...new Set(s.values())].sort(),\"results\")}}a(RA,\"prepare\");function _A(r){try{switch(r.type){case\"readdir\":return(0,oi.readdirSync)(r.path,{withFileTypes:true});case\"stat\":return(0,oi.statSync)(r.path);case\"realpath\":return(0,oi.realpathSync)(r.path)}}catch{return null}}a(_A,\"answerSync\");function pS(r,e={}){const{walks:t,results:s}=RA(r,e);for(const n of t){let i;for(let o=n.next();!o.done;o=n.next(i))i=_A(o.value)}return s()}a(pS,\"GlobSync\");var jl=Ye(require(\"path\"),1);function mS(r){const e=[];r.forEach(t=>{t.forEach(s=>{e.push(s)})});return e}a(mS,\"flatten\");function gS(r,e){const t=r;if(typeof t===\"string\"||bt(t))return{[r]:e};return v(t)}a(gS,\"nameValueToObject\");function bs(r){if(typeof r!==\"function\")return false;const e=Object.getOwnPropertyDescriptor(r,\"prototype\");if(!e)return false;if(!e.writable)return true;return!!r.name&&r.name[0]===r.name[0].toUpperCase()}a(bs,\"isClass\");function Vs(r){return typeof r===\"function\"}a(Vs,\"isFunction\");function yS(r){return Array.from(new Set(r))}a(yS,\"uniq\");function CA(r,e){return pS(r,{cwd:e.cwd,nodir:true,follow:true,nocase:false})}a(CA,\"defaultGlob\");var vA=/(.*)\\..*/i;function bS(r,e){e={cwd:process.cwd(),glob:CA,...e};let t=null;if(Array.isArray(r)){t=r[1];r=r[0]}r=r.replace(/\\\\/g,\"/\");const s=e.glob(r,{cwd:e.cwd});const n=s.map(i=>({name:vA.exec(jl.basename(i))[1],path:jl.resolve(e.cwd,i),opts:t}));return n}a(bS,\"_listModules\");function $l(r,e){if(Array.isArray(r)){return mS(r.map(t=>bS(t,e)))}return bS(r,e)}a($l,\"listModules\");function SS(r){return import(r)}a(SS,\"importModule\");var vS=require(\"url\");var ca=Symbol(\"Dependency Injection Resolver Config\");function cp(r){return{resolve:a(()=>r,\"resolve\"),isLeakSafe:true}}a(cp,\"asValue\");function Hl(r,e){if(!Vs(r)){throw new ys(\"asFunction\",\"fn\",\"function\",r)}const t={lifetime:ke.TRANSIENT};e=wS(t,e,r[ca]);const s=TS(r);const n={resolve:s,...e};return lp(Fl(n))}a(Hl,\"asFunction\");function ai(r,e){if(!Vs(r)){throw new ys(\"asClass\",\"Type\",\"class\",r)}const t={lifetime:ke.TRANSIENT};e=wS(t,e,r[ca]);const s=a(function i(...o){return Reflect.construct(r,o)},\"newClass\");const n=TS(s);return lp(Fl({...e,resolve:n}))}a(ai,\"asClass\");function Fl(r){function e(s){return Fl({...this,lifetime:s})}a(e,\"setLifetime\");function t(s){return Fl({...this,injector:s})}a(t,\"inject\");return ES(r,{setLifetime:e,inject:t,transient:ap(e,ke.TRANSIENT),scoped:ap(e,ke.SCOPED),singleton:ap(e,ke.SINGLETON)})}a(Fl,\"createBuildResolver\");function lp(r){function e(t){return lp({...this,dispose:t})}a(e,\"disposer\");return ES(r,{disposer:e})}a(lp,\"createDisposableResolver\");function ap(r,e){return a(function t(){return r.call(this,e)},\"partiallyApplied\")}a(ap,\"partial\");function wS(r,...e){return Object.assign({},r,...e)}a(wS,\"makeOptions\");function ES(r,e){const t={...r,...e};return t}a(ES,\"updateResolver\");function AA(r,e){const t=e(r);const s=yS([...Reflect.ownKeys(r.cradle),...Reflect.ownKeys(t)]);const n=new Proxy({},{get(i,o){if(o===Symbol.iterator){return a(function*c(){for(const l in r.cradle){yield l}for(const l in t){yield l}},\"iterateRegistrationsAndLocals\")}if(o in t){return t[o]}return r.resolve(o)},ownKeys(){return s},getOwnPropertyDescriptor(i,o){if(s.indexOf(o)>-1){return{enumerable:true,configurable:true}}return void 0}});return n}a(AA,\"createInjectorProxy\");function TS(r){return a(function e(t){const s=this.injector?AA(t,this.injector):t.cradle;return r(s)},\"resolve\")}a(TS,\"generateResolve\");var IA=new RegExp(\"([\\\\p{Ll}\\\\d])(\\\\p{Lu})\",\"gu\");var OA=new RegExp(\"(\\\\p{Lu})([\\\\p{Lu}][\\\\p{Ll}])\",\"gu\");var kA=new RegExp(\"(\\\\d)(\\\\p{Ll})\",\"gu\");var PA=new RegExp(\"(\\\\p{L})(\\\\d)\",\"gu\");var NA=/[^\\p{L}\\d]+/giu;var ql=\"$1\\0$2\";function xS(r,e){let t=r.replace(IA,ql).replace(OA,ql);if(e&&e.separateNumbers){t=t.replace(kA,ql).replace(PA,ql)}t=t.replace(NA,\"\\0\");let s=0;let n=t.length;while(t.charAt(s)===\"\\0\")s++;if(s===n)return[];while(t.charAt(n-1)===\"\\0\")n--;return t.slice(s,n).split(/\\0/g)}a(xS,\"split\");function RS(r){return r===false?e=>e.toLowerCase():e=>e.toLocaleLowerCase(r)}a(RS,\"toLower\");function _S(r){return r===false?e=>e.toUpperCase():e=>e.toLocaleUpperCase(r)}a(_S,\"toUpper\");function CS(r,e){const t=RS(e?.locale);const s=_S(e?.locale);return xS(r,e).map((n,i)=>{if(i===0){return t(n)}const o=n[0];const c=o>=\"0\"&&o<=\"9\"?\"_\"+o:s(o);return c+t(n.slice(1))}).join(\"\")}a(CS,\"camelCase\");var LA={camelCase:a(r=>CS(r),\"camelCase\")};function up(r,e,t){t??={};const s=r.container;t=DA(t);const n=r.listModules(e,t);if(t.esModules){return MA(r,s,n,t)}else{const i=n.map(o=>{const c=r.require(o.path);return AS(c,o)});return IS(i,s,n,t)}}a(up,\"loadModules\");async function MA(r,e,t,s){const n=[];for(const c of t){const l=(0,vS.pathToFileURL)(c.path).toString();n.push(v(r.require(l)))}const i=await Promise.all(n);const o=[];for(let c=0;c<t.length;c++){o.push(v(AS(i[c],t[c])))}return IS(o,e,t,s)}a(MA,\"loadEsModules\");function AS(r,e){const t=[];if(!r)return t;if(Vs(r)){t.push({name:e.name,path:e.path,value:r,opts:e.opts});return t}if(r.default&&Vs(r.default)){t.push({name:e.name,path:e.path,value:r.default,opts:e.opts})}for(const s of Object.keys(r)){if(s===\"default\")continue;if(Vs(r[s])&&ca in r[s]){t.push({name:s,path:e.path,value:r[s],opts:e.opts})}}return t}a(AS,\"parseLoadedModule\");function IS(r,e,t,s){r.reduce((n,i)=>n.concat(i),[]).filter(n=>n).forEach(BA.bind(null,e,s));return{loadedModules:t}}a(IS,\"registerModules\");function DA(r){return{resolverOptions:{lifetime:ke.TRANSIENT,...r&&r.resolverOptions},...r}}a(DA,\"optsWithDefaults\");function BA(r,e,t){const s=t.value[ca];let n=s&&s.name;if(!n){n=t.name;let l=e.formatName;if(l){if(typeof l===\"string\"){l=LA[l]}if(l){n=l(n,t)}}}let i=t.opts;if(typeof i===\"string\"){i={lifetime:i}}const o={...e.resolverOptions,...i,...s};const c=o.register?o.register:bs(t.value)?ai:Hl;r.register(n,c(t.value,o))}a(BA,\"registerDescriptor\");var la=class extends Z{static{a(this,\"LifetimeLockedException\")}constructor(){super(...arguments);this.errno=\"E_LIFETIME_LOCKED\"}};function ci(r){return Reflect.getMetadata(ep,r)}a(ci,\"getObjectLifetime\");function UA(r){return!!Reflect.getMetadata(tp,r)}a(UA,\"getObjectLifetimeLocked\");function OS(r,e,t=false){if(UA(r)&&ci(r)!==e)throw new la(\"[{0}] Object lifecycle settings cannot be applied because the parent object lifecycle of the current operation object is locked\",[r.name]);if(t)Reflect.defineMetadata(tp,true,r);Reflect.defineMetadata(ep,e,r);return r}a(OS,\"setObjectLifetime\");var Ss=Symbol(\"OWR\");var fp=Symbol(\"OFR\");function dp(r){if(!Reflect.hasOwnMetadata(fp,r))Reflect.defineMetadata(fp,new FinalizationRegistry(e=>{const t=Reflect.getOwnMetadata(Ss,r)||new Set;t.delete(e);Reflect.defineMetadata(Ss,t,r)}),r);if(!Reflect.hasOwnMetadata(Ss,r))Reflect.defineMetadata(Ss,new Set,r);return Reflect.getOwnMetadata(Ss,r)}a(dp,\"getObjectWeakRefs\");function ua(r,e){const t=dp(r);const s=new WeakRef(e);v(Reflect.getOwnMetadata(fp,r)).register(e,s);t.add(s);Reflect.defineMetadata(Ss,t,r)}a(ua,\"appendObjectWeakRefs\");function kS(r){if(!Reflect.hasOwnMetadata(Ss,r))return;Reflect.deleteMetadata(Ss,r)}a(kS,\"clearObjectWeakRefs\");var PS=Symbol(\"familyTree\");var NS=Symbol(\"rollUpRegistrations\");var jA=\"DependencyInjectionContainerCradle\";function hp(r={}){return LS(r)}a(hp,\"createContainer\");function LS(r,e,t){r={strict:false,...r};const s=t??[];const n={};const i=new Proxy({[zl.inspect.custom]:p},{get:a((x,k)=>y(k),\"get\"),set:a((x,k)=>{throw new Error(`Attempted setting property \"${k}\" on container cradle - this is not allowed.`)},\"set\"),ownKeys(){return Array.from(i)},getOwnPropertyDescriptor(x,k){const N=u();if(Object.getOwnPropertyDescriptor(N,k)){return{enumerable:true,configurable:true}}return void 0}});const o={options:r,cradle:i,inspect:l,cache:new Map,loadModules:T,createScope:d,register:h,build:S,resolve:y,hasRegistration:w,dispose:_,getRegistration:m,[zl.inspect.custom]:l,[NS]:u,get registrations(){return u()}};const c=e?[o].concat(v(e)[PS]):[o];o[PS]=c;return o;function l(){return`[DependencyInjectionContainer (${e?\"scoped, \":\"\"}registrations: ${Object.keys(o.registrations).length})]`}a(l,\"inspect\");function u(){return{...e&&e[NS](),...n}}a(u,\"rollUpRegistrations\");function*f(){const x=u();for(const k in x){yield k}}a(f,\"cradleIterator\");function d(){return LS(r,o,s)}a(d,\"createScope\");function h(x,k){const N=gS(x,k);const A=[...Object.keys(N),...Object.getOwnPropertySymbols(N)];for(const B of A){const ee=N[B];if(r.strict&&ee.lifetime===ke.SINGLETON){if(e){throw new Ul(B,\"Cannot register a singleton on a scoped container.\")}}n[B]=ee}return o}a(h,\"register\");function p(){return Object.prototype.toString.call(i)}a(p,\"toStringRepresentationFn\");function m(x){const k=n[x];if(k){return k}if(e){return e.getRegistration(x)}return null}a(m,\"getRegistration\");function y(x,k){k=k||{};try{const N=m(x);if(N&&!r.strict){const fe=N.lifetime||ke.TRANSIENT;if(fe!==ke.TRANSIENT){const Rt=o.cache.get(x);if(Rt!==void 0)return Rt.value}}for(let fe=0;fe<s.length;fe++){if(s[fe].name===x){throw new Ws(x,s,\"Cyclic dependencies detected.\")}}if(x===\"toJSON\"){return p}if(x===\"constructor\"){return hp}if(!N){switch(x){case zl.inspect.custom:case\"inspect\":case\"toString\":return p;case Symbol.toStringTag:return jA;case\"then\":return void 0;case Symbol.iterator:return f}if(k.allowUnregistered){return void 0}throw new Ws(x,s)}const A=N.lifetime||ke.TRANSIENT;if(r.strict&&!N.isLeakSafe){const fe=s.findIndex(({lifetime:Rt})=>fS(Rt,A));if(fe>-1){throw new Ws(x,s,`Dependency '${x.toString()}' has a shorter lifetime than its ancestor: '${s[fe].name.toString()}'`)}}s.push({name:x,lifetime:A});let B;let ee;switch(A){case ke.TRANSIENT:ee=N.resolve(o);break;case ke.SINGLETON:B=o.cache.get(x);if(B!==void 0){ee=B.value;break}ee=N.resolve(o);o.cache.set(x,{resolver:N,value:ee});break;case ke.SCOPED:B=o.cache.get(x);if(B!==void 0){ee=B.value;break}ee=N.resolve(o);o.cache.set(x,{resolver:N,value:ee});break;default:throw new Ws(x,s,`Unknown lifetime \"${N.lifetime}\"`)}s.pop();if(ci(ee.constructor)===ke.TRANSIENT)ua(this,ee);return ee}catch(N){s.length=0;throw N}}a(y,\"resolve\");function w(x){return!!m(x)}a(w,\"hasRegistration\");function S(x,k){if(x&&x.resolve){return x.resolve(o)}const N=\"build\";const A=\"targetOrResolver\";ys.assert(x,N,A,\"a registration, function or class\",x);ys.assert(typeof x===\"function\",N,A,\"a function or class\",x);const B=bs(x)?ai(x,k):Hl(x,k);return B.resolve(o)}a(S,\"build\");function T(x,k){const N={require:r.require||function(A){return require(A)},listModules:$l,container:o};if(k?.esModules){N.require=SS;return up(N,x,k).then(()=>o)}else{up(N,x,k);return o}}a(T,\"loadModules\");async function _(){const x=Array.from(o.cache.entries());o.cache.clear();return Promise.all(x.map(async([,k])=>{const{resolver:N,value:A}=k;const B=N;if(B.dispose){await Promise.resolve();return B.dispose(A)}return Promise.resolve()})).then(()=>void 0)}a(_,\"dispose\")}a(LS,\"createContainerInternal\");function MS(r){return(typeof r===\"object\"||typeof r===\"function\")&&r!==null&&typeof r.then===\"function\"}a(MS,\"isPromiseLike\");function BS(r,e,t){async function s(){await Promise.resolve();await Reflect.apply(e,r,t!==null&&t!==void 0?t:[]);delete r[\"then\"];return r}a(s,\"applyAsyncConstructor\");if(MS(r)){DS(r,Promise.resolve(r).then(s))}else{DS(r,s())}}a(BS,\"appendAsyncConstructor\");function DS(r,e){r.then=e.then.bind(e)}a(DS,\"setThenMethod\");var Gl=class extends Object{static{a(this,\"AsyncConstructor\")}constructor(e){super();BS(this,e)}};function Kl(r,e=false){return t=>OS(t,r,e)}a(Kl,\"Lifetime\");function Xs(r=false){return Kl(\"SINGLETON\",r)}a(Xs,\"Singleton\");function fa(r=false){return Kl(\"TRANSIENT\",r)}a(fa,\"Transient\");function pp(r=false){return Kl(\"SCOPED\",r)}a(pp,\"Scoped\");var da=class extends Z{static{a(this,\"MethodNotFoundException\")}constructor(){super(...arguments);this.errno=\"E_METHOD_NOT_FOUND\"}};var lw=require(\"node:crypto\");var US=new WeakMap;function jS(r,e){US.set(r,e)}a(jS,\"setConfigurableRecords\");function $S(r){return(r&&US.get(r))??{}}a($S,\"getConfigurableRecords\");function FS(r,e){Reflect.defineMetadata(Bl,e,r)}a(FS,\"setIdToInstance\");function HS(r){const e=Reflect.getOwnMetadata(Bl,r);if(typeof e===\"string\")return e;if(gs(v(r.constructor))!==e)return e;return void 0}a(HS,\"getIdFromInstance\");function Wl(r){return Reflect.getOwnMetadata(Bl,r)}a(Wl,\"getRegistrationNameFromInstance\");function qS(r,e){Reflect.defineMetadata(r.$uuid,e,r)}a(qS,\"setConfigurableRecordsToInstance\");function mp(r){const e=Reflect.getOwnMetadata(r.$uuid,r);if(e)return e;return{}}a(mp,\"getConfigurableRecordsFromInstance\");var Vl=Symbol(\"REMOVED\");function Xl(r,e){let t=Reflect.getOwnMetadata(r,e);if(!t){t=new Map;Reflect.defineMetadata(r,t,e)}return t}a(Xl,\"ownDeclarations\");function Yl(r,e){const t=new Map;for(const s of[...ps(e).reverse(),e]){const n=Reflect.getOwnMetadata(r,s);n?.forEach((i,o)=>{if(i===Vl){t.delete(o)}else{t.set(o,i)}})}return t}a(Yl,\"mergedDeclarations\");function zS(r,e,t=I.Any(),s){Xl(sp,me(r)).set(e,{schema:t,fn:s?s:n=>n})}a(zS,\"setObjectConfigurableProperty\");function Jl(r){return Yl(sp,me(r))}a(Jl,\"getObjectConfigurableProperties\");function GS(r,e){Xl(rp,me(r)).set(e,Vl)}a(GS,\"removeObjectInjectItem\");function KS(r){return Yl(rp,me(r))}a(KS,\"getObjectInjectItemsByPrototype\");function WS(r){if(!Reflect.hasOwnMetadata(Dl,r))Reflect.defineMetadata(Dl,true,r);return r}a(WS,\"markObjectAsAutoload\");function VS(r){return!!Reflect.getOwnMetadata(Dl,r)}a(VS,\"getObjectIsAutoload\");function XS(r,e){Reflect.defineMetadata(np,()=>e,r)}a(XS,\"setObjectContainerGetter\");function ha(r){const e=Reflect.getOwnMetadata(np,r);return e()}a(ha,\"getObjectContainer\");function pa(r,e){return typeof r===\"function\"&&!!r.prototype&&r.prototype instanceof e}a(pa,\"isSubclassOf\");var ma=Symbol(\"OBJECT.TYPE\");var je;(function(r){r[\"Unknown\"]=\"Unknown\";r[\"Object\"]=\"Object\";r[\"Provider\"]=\"Provider\";r[\"Component\"]=\"Component\";r[\"Module\"]=\"Module\"})(je||(je={}));var gp;function YS(r){gp=r}a(YS,\"registerBaseObject\");function ws(r){return e=>JS(e,r)}a(ws,\"DefineObjectType\");function JS(r,e){Reflect.defineMetadata(ma,gp&&pa(r,gp)?e:je.Unknown,r);return r}a(JS,\"setObjectType\");function ga(r){if(Reflect.hasOwnMetadata(ma,r))return Reflect.getOwnMetadata(ma,r);let e=je.Unknown;for(const t of ps(r)){if(Reflect.hasOwnMetadata(ma,t)){e=Reflect.getOwnMetadata(ma,t);break}}JS(r,e);return ga(r)}a(ga,\"getObjectType\");var yp;var ZS=new WeakSet;var Zl=new WeakMap;function QS(r){yp=r}a(QS,\"declareApplicationClass\");function ew(r){ZS.add(r);Zl.get(r)?.resolve();Zl.delete(r)}a(ew,\"markApplicationLaunched\");function tw(r){let e=r;while(e&&!(yp&&e instanceof v(yp)))e=e.getParent?.();if(!e)return void 0;if(ZS.has(e))return Promise.resolve();let t=Zl.get(e);if(!t){let s=a(()=>void 0,\"resolve\");const n=new Promise(i=>{s=i});t={promise:n,resolve:s};Zl.set(e,t)}return t.promise}a(tw,\"whenApplicationLaunched\");var rw=require(\"node:async_hooks\");var bp=new rw.AsyncLocalStorage;var Sp=new WeakMap;function sw(r,e){const t={object:r,active:true};const s=bp.run([...bp.getStore()??[],t],async()=>{try{await e()}finally{t.active=false}});const n={promise:s,ended:false};s.catch($t).finally(()=>n.ended=true);Sp.set(r,n);return s}a(sw,\"runObjectStartup\");function nw(r){return!!bp.getStore()?.some(e=>e.active&&e.object===r)}a(nw,\"isInObjectStartup\");async function li(r){const e=Sp.get(r);if(!e||nw(r))return;await e.promise}a(li,\"waitForObjectStartup\");function wp(r){const e=Sp.get(r);if(!e||e.ended||nw(r))return void 0;return e.promise.catch($t)}a(wp,\"waitForObjectStartupEnd\");var iw=a((r,e)=>{_r(`${e}: ${r.stack?r.stack:r.message}`)},\"defaultLifecycleErrorReporter\");var ow=iw;function aw(r){ow=r?r:iw}a(aw,\"setLifecycleErrorReporter\");function Ep(r,e){if(r instanceof AggregateError)return r.errors.flatMap(s=>Ep(s,r.message));const t=r instanceof Error?r:new Error(String(r));return[e?new Error(`${e}: ${t.message}`,{cause:t}):t]}a(Ep,\"flatten\");function cw(r,e){for(const t of r){try{ow(t,e)}catch{}}}a(cw,\"report\");function Ql(r,e){const t=e&&!(r instanceof AggregateError)?`Failed to destroy object \"${e}\"`:void 0;cw(Ep(r,t),\"An error occurred while destroying an object\")}a(Ql,\"reportDestroyError\");function Tp(r,e){cw(Ep(r,`Failed to run the launched() hook of object \"${e}\"`),\"An error occurred in the launched() hook of an object\")}a(Tp,\"reportLaunchedError\");var Es=class extends Z{static{a(this,\"ObjectDestroyedException\")}constructor(){super(...arguments);this.errno=\"E_OBJECT_DESTROYED\"}};var $A=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var FA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var ya;var dr=Symbol(\"__init\");var st=Symbol(\"__destroy\");var ba=Symbol(\"__revive\");var HA=Symbol(\"anonymous\");var xp=Symbol(\"OBJECT.SYMBOL.PROPERTY\");var Re=ya=class U$ extends Gl{static{a(this,\"BaseObject\")}#e;#t;#r=(0,lw.randomUUID)();#s=false;#u=false;#n=\"constructing\";#a;#o;#c=0;#i(){if(this.#n===\"destroying\"||this.#n===\"destroyed\")throw new Es('Object \"{className}\" has been destroyed',{className:this.className})}async#f(){const e=mp(this);const t=[];Jl(this).forEach((s,n)=>{if(bt(n))return;const i=e[v(n)];const o=i!==void 0?i:this[n];t.push(new Promise((c,l)=>{I.validateAsync(o,s.schema,{targetName:n}).then(u=>{return Promise.resolve(s.fn.bind(this)(u)).then(f=>{this[n]=f;return c()}).catch(l)}).catch(l)}))});await Promise.all(t)}async#m(){const e=KS(this);const t=[];e.forEach((s,n)=>{const i=v(s.name);t.push(new Promise((o,c)=>{this.#e.get(i).then(l=>{Promise.resolve(s.transform(l)).then(u=>{Reflect.set(this,n,u);return o()}).catch(c)}).catch(l=>c(new Ks(\"Unable to inject value for property {0} of {1} because: {2}\",[n,this.className,l.message])))}))});await Promise.all(t)}#l(){const e=HS(this);this.#t=e?e:HA}constructor(e){super(async()=>{this.#l();const t=Object.getOwnPropertyDescriptor(this,\"then\");if(t)Object.defineProperty(this,\"then\",{enumerable:false});await this[dr]()});this.#e=new Wt(e[Rp],this);XS(this,this.#e);if(this.beforeDestroy!==ya.prototype.beforeDestroy){uw(this.#e,()=>this.#o?Promise.resolve():this.#d())}}#d(){return this.#o??=(async()=>{const e=wp(this);if(e)await e;await this.beforeDestroy()})()}static get className(){return this.name}static acceptsOption(e,t){$t(e,t);return false}get className(){return me(this).name}async[dr](...e){this.#i();this.#e.registerContainerToItsParent();if(!this.#s){await this.#m();this.#s=true}if(!this.#u){await this.#f();this.#u=true}for(const t of e)await t();await this.init();this.#i();this.#n=\"ready\";if(this.startup!==ya.prototype.startup)void sw(this,()=>this.startup());if(this.launched!==ya.prototype.launched)this.#h()}#h(){const e=++this.#c;const t=a(()=>{if(e!==this.#c||this.#n!==\"ready\")return;try{Promise.resolve(this.launched()).catch(s=>Tp(s,this.className))}catch(s){Tp(s,this.className)}},\"run\");void(tw(this)??Promise.resolve()).then(()=>li(this)).then(t,$t)}[ba](){if(this.#n!==\"destroyed\")return;this.#e.revive();this.#a=void 0;this.#o=void 0;this.#s=false;this.#n=\"constructing\"}async[st](...e){if(this.#a)return await this.#a.catch($t);this.#n=\"destroying\";this.#a=(async()=>{const t=[];const s=wp(this);if(s)await s;if(this.#o){await this.#o.catch($t)}else{try{await this.#d()}catch(n){t.push(n)}}await this.#e.destroy();for(const n of e){try{await n()}catch(i){t.push(i)}}try{await this.destroy()}catch(n){t.push(n)}this.#n=\"destroyed\";if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,`Failed to destroy object \"${this.className}\"`)})();return await this.#a}async init(){}async startup(){}async launched(){}async beforeDestroy(){}async destroy(){}async getObject(e,t={}){this.#i();return await this.#e.get(e,t)}async buildObject(e,t={}){this.#i();return this.#e.build(e,t)}getConfigurableRecords(){return{...mp(this)}}getParent(){return this.#e.parent?.owner()}getModule(){let e=this.getParent();while(e&&ga(v(me(e)))!==je.Module){e=e.getParent()}return v(e)}get $uuid(){return this.#r}get $id(){return this.#t}get $symbol(){if(Reflect.hasOwnMetadata(xp,this))return Reflect.getOwnMetadata(xp,this);Reflect.defineMetadata(xp,Symbol(this.$uuid),this);return this.$symbol}setProperty(e,t){this[e]=t}getProperty(e,t){if(this.hasProperty(e))return v(this[e]);return v(t)}hasProperty(e){return typeof e===\"string\"?this.propertyNames().includes(e):this.propertySymbols().includes(e)}propertySymbols(){return Object.getOwnPropertySymbols(this)}propertyNames(){return Object.getOwnPropertyNames(this)}hasMethod(e){const t=this.hasProperty(e);if(t)return false;return typeof this[e]===\"function\"}getMethod(e,t=false){if(this.hasMethod(e)){const s=a((...n)=>this[e](...n),\"callMethod\");return s}else if(t){throw new da('Method \"{methodName}\" not found in \"{className}\"',{methodName:e,className:this.constructor.name})}else{return(...s)=>$t(...s)}}async dispose(){try{await this[st]()}finally{const e=Wl(this);if(e!==void 0)this.#e.parent?.forget(e,this)}}async[Symbol.asyncDispose](){await this.dispose()}};Re=ya=$A([fa(),ws(je.Object),FA(\"design:paramtypes\",[Object])],Re);YS(Re);function ve(r){return(e,t)=>Al(e,t,r)}a(ve,\"Expect\");function hr(r){return e=>$b(e,r)}a(hr,\"IndexSignature\");var _p=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var fw=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var dw;var lt=Symbol(\"OBJECT_ID\");var Ir=class J$ extends I{static{a(this,\"LoadObjectOptions\")}static{dw=lt}};_p([ve(I.Alternatives(I.String(),I.Symbol()).optional()),fw(\"design:type\",Object)],Ir.prototype,dw,void 0);_p([ve(I.Class(()=>Re).required()),fw(\"design:type\",Object)],Ir.prototype,\"class\",void 0);Ir=_p([hr(I.Any())],Ir);var hw=require(\"node:util/types\");var ui=class extends Z{static{a(this,\"InvalidMethodAcceptException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_METHOD_ACCEPT\"}};function pw(r,e,t,s){const n=[];s.forEach(l=>n.push(Fh(v(l))?v(l).Schema():v(l)));t.writable=false;const i=t.value;const o=I.Array().sparse(true).ordered(...n);const c=Array.isArray(n)?n.length:1;if((0,hw.isAsyncFunction)(i)){t.value=async function(...l){const u=l.length-c;try{l=await I.validateAsync(l,o.concat(I.Array().sparse(true).ordered(...new Array(u>=0?u:0).fill(I.Any()))))}catch(f){throw hs(new ui(\"Method [{propertyKey}] accept argument {reason}\",{propertyKey:e,reason:f.message}),f)}return i.apply(this,l)}}else{t.value=function(...l){const u=l.length-c;try{l=I.validate(l,o.concat(I.Array().sparse(true).ordered(...new Array(u>=0?u:0).fill(I.Any()))))}catch(f){throw hs(new ui(\"Method [{propertyKey}] accept argument {reason}\",{propertyKey:e,reason:f.message}),f)}return i.apply(this,l)}}return t}a(pw,\"setMethodAcceptArgumentsValidator\");function Sa(...r){return(e,t,s)=>pw(e,t,s,r)}a(Sa,\"Accept\");var gw=require(\"url\");var eu=Symbol(\"LAKUTATA.MODULE.INITIALIZATION\");function tu(r){if(r===null||r===void 0)return true;if(typeof r!==\"object\"&&typeof r!==\"function\")return false;if(r instanceof Map||r instanceof Set)return r.size===0;return!Object.getOwnPropertyNames(r).length&&!Object.getOwnPropertySymbols(r).length}a(tu,\"isEmptyObject\");var zA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Cp=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Rp=Symbol(\"LAKUTATA.DI.CONTAINER.SYMBOL\");var mw=Symbol(\"LAKUTATA.DI.OWNER.SYMBOL\");var vp=new WeakMap;function uw(r,e){let t=vp.get(r);if(!t)vp.set(r,t=new Set);t.add(e);return()=>void t.delete(e)}a(uw,\"registerTeardownHook\");var Wt=class r{static{a(this,\"Container\")}#e;static#t=new FinalizationRegistry(({refs:e,ref:t})=>e.delete(t));#r;#s;#u;#n;#a;#o;constructor(e,t){this.#r=new Set;this.#s=new Set;this.#u=new WeakRef(this);this.#n=false;this.injectionNames=new Set;this.parent=e;this.#o=!e;this.#e=e?e.#e.createScope():hp({strict:false});if(this.parent)r.#t.register(this,{refs:this.parent.#s,ref:this.#u});this.#c();this.#e.register(Rp,cp(this));if(t)this.#e.register(mw,cp(new WeakRef(t)))}#c(){if(!this.parent)return;if(this.#o){this.parent.#r.add(this)}else{this.parent.#s.add(this.#u)}}#i(e){return ai(e,v(this.buildResolverOptions(e)))}#f(){if(this.#n)throw new Es(\"The container has been destroyed\")}#m(){let e=this;while(!e.#o&&e.parent)e=e.parent;return e}#l(){let e=this;while(e.parent)e=e.parent;return e}#d(){if(!this.parent)return;this.parent.#r.delete(this);this.parent.#s.delete(this.#u)}async disposer(e){try{await e.getMethod(st,false)()}catch(t){Ql(t,e.className)}}buildResolverOptions(e){const t=ci(e);return{lifetime:t,dispose:a(s=>this.disposer(s),\"dispose\")}}async processResolved(e,t,s={}){const n=pa(e?.constructor,Re);const i=n&&Wl(v(e))===void 0;if(n&&!i&&!tu(s)&&process.env.NODE_ENV!==\"production\"){_r(`The configuration passed for the already created object \"${v(e).className}\" is ignored. Use a scoped or transient object to get an instance with its own configuration.`)}if(i){const o=$S(this.#e.getRegistration(t));FS(v(e),t);qS(v(e),{...o,...s})}return Promise.resolve(e)}buildNameAndRegistrationPairFromOptions(e){const t={};const s=e[lt]?e[lt]:gs(e.class);const n={...e,class:void 0};delete n.id;delete n.class;t[s]=this.#i(e.class);jS(t[s],n);return t}async buildNameAndRegistrationPairFromGlob(e){const t=await Promise.all($l(e).map(async s=>{let n;try{n=await import((0,gw.pathToFileURL)(s.path).toString())}catch(o){throw new Error(`The file ${s.path} matched by \"${e}\" cannot be imported: ${o?.message??o}`,{cause:o})}const i={};for(const o of Object.values(n)){if(bs(o)&&pa(o,Re))i[gs(o)]=this.#i(v(o))}return i}));return Object.assign({},...t)}owner(){const e=this.#e.resolve(mw,{allowUnregistered:true});return e?e.deref():void 0}async load(e){this.#f();let t={};const s=[];e.forEach(n=>{if(typeof n===\"string\"){s.push(this.buildNameAndRegistrationPairFromGlob(n))}else if(bs(v(n))){const i={class:v(n)};t={...t,...this.buildNameAndRegistrationPairFromOptions(i)}}else{const i=v(n);t={...t,...this.buildNameAndRegistrationPairFromOptions(i)}}});if(s.length){const n=await Promise.all(s);n.forEach(i=>{t={...i,...t}})}if(!tu(t)){Object.getOwnPropertyNames(t).forEach(n=>this.injectionNames.add(n));Object.getOwnPropertySymbols(t).forEach(n=>this.injectionNames.add(n));this.#e.register(t)}}async get(e,t={}){return await this.#h(e,t,false)}async getShared(e,t={}){return await this.#h(e,t,true)}async#h(e,t,s){const n=typeof e===\"function\"?gs(e):e;this.#f();if(!this.#e.hasRegistration(n)&&typeof e===\"function\"&&VS(v(e))){const u=v(ci(v(e)));const f=u===\"SCOPED\"?this.#m():u===\"SINGLETON\"?this.#l():this;await f.load([{id:n,class:v(e)}])}const i=this.#e.getRegistration(n);const o=i?.lifetime;if(!s&&i&&o===\"SCOPED\"&&!tu(t)){const u=await this.processResolved(this.#e.build(i),n,t);ua(this.#e,u);await li(u);return u}let c=this;if(o===\"SINGLETON\"){while(!c.injectionNames.has(n)&&c.parent)c=c.parent}else if(o===\"SCOPED\"){while(!c.injectionNames.has(n)&&!c.#o&&c.parent)c=c.parent}c.#f();const l=await c.processResolved(c.#e.resolve(n),n,t);await this.#g(l);await li(l);return l}async#g(e){const t=e?.[eu];if(typeof t!==\"function\")return;for(let s=this;s;s=s.parent)if(s.owner()===e)return;await t.call(e)}has(e){if(typeof e===\"function\")return this.#e.hasRegistration(gs(e));return this.#e.hasRegistration(e)}async set(e,t={}){if(!this.has(e)){await this.load([{...t,class:e}])}return await this.get(e,{...t})}async setNamed(e,t,s={}){await this.load([{...s,class:t,[lt]:e}]);return await this.get(e)}async register(e,t={}){await this.load([{...t,class:e}])}async registerNamed(e,t,s={}){await this.load([{...s,class:t,[lt]:e}])}async build(e,t={}){this.#f();const s=await this.processResolved(this.#e.build(e,this.buildResolverOptions(e)),gs(e),t);ua(this.#e,s);await li(s);return s}createScope(){this.#f();const e=new r(this,this.owner());e.#d();e.#o=true;e.#c();return e}registerContainerToItsParent(){this.#c()}revive(){if(this.parent&&this.parent.#n)throw new Es(\"Cannot revive a container whose parent container has been destroyed\");this.#n=false;this.#a=void 0;this.#c()}forget(e,t){const s=this.#e.cache.get(e);if(s&&s.value===t)this.#e.cache.delete(e)}async clear(){const e=vp.get(this);if(e?.size){const n=await Promise.allSettled([...e].map(i=>i()));n.forEach(i=>i.status===\"rejected\"&&Ql(i.reason))}const t=[...this.#r];this.#s.forEach(n=>{const i=n.deref();if(i)t.push(i)});await Promise.all(t.map(n=>n.destroy()));try{await this.#e.dispose()}catch(n){Ql(n)}const s=[];dp(this.#e).forEach(n=>{const i=n.deref();if(i)s.push(i)});await Promise.all(s.map(n=>this.disposer(n)));kS(this.#e)}async destroy(){if(this.#a)return await this.#a;this.#n=true;this.#d();this.#a=this.clear();await this.#a}};zA([Sa(I.Array(I.Alternatives(Ir.Schema(),I.Class(()=>Re),I.Glob()))),Cp(\"design:type\",Function),Cp(\"design:paramtypes\",[Array]),Cp(\"design:returntype\",Promise)],Wt.prototype,\"load\",null);var GA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Ys=class KF extends Re{static{a(this,\"Provider\")}getEnv(e,t){const s=process.env[e];return s===void 0&&t!==void 0?t:s}};Ys=GA([pp(),ws(je.Provider)],Ys);var pr=Reflect.ownKeys;function ru(){return Object.create(null)}a(ru,\"node\");var su=class r{static{a(this,\"EventEmitter2\")}static get defaultMaxListeners(){return r.prototype._maxListeners}static set defaultMaxListeners(e){if(typeof e!==\"number\"||e<0||Number.isNaN(e))throw TypeError(\"n must be a non-negative number\");r.prototype._maxListeners=e}static{r.prototype._maxListeners=10}constructor(e){this.delimiter=\".\";this.event=\"\";this.verboseMemoryLeak=false;this._newListener=false;this._removeListener=false;this._events={};this.configure(e)}init(){this._events={};if(this._conf)this.configure(this._conf)}configure(e){if(!e)return;this._conf=e;if(e.delimiter)this.delimiter=e.delimiter;if(e.maxListeners!==void 0)this._maxListeners=e.maxListeners;if(e.wildcard)this.wildcard=e.wildcard;if(e.newListener)this._newListener=e.newListener;if(e.removeListener)this._removeListener=e.removeListener;if(e.verboseMemoryLeak)this.verboseMemoryLeak=e.verboseMemoryLeak;if(e.ignoreErrors)this.ignoreErrors=e.ignoreErrors;if(this.wildcard)this.listenerTree=ru()}logPossibleMemoryLeak(e,t){let s=`(node) warning: possible EventEmitter memory leak detected. ${e} listeners added. Use emitter.setMaxListeners() to increase limit.`;if(this.verboseMemoryLeak)s+=` Event name: ${String(t)}.`;const n=new Error(s);n.name=\"MaxListenersExceededWarning\";n.emitter=this;n.count=e;process.emitWarning(n)}split(e){if(typeof e!==\"string\")return e;const t=[];let s=0;let n;while((n=e.indexOf(this.delimiter,s))!==-1){t.push(e.slice(s,n));s=n+this.delimiter.length}t.push(e.slice(s));return t}searchListenerTree(e,t,s,n,i){if(!s)return null;if(n===0){const p=typeof t;if(p===\"string\"){const m=this.split(t);i=m.length;t=m.length>1&&m.length<5?Object.assign(new Array(5),m):m}else if(p===\"object\"){i=t.length}else{t=[t];i=1}}let o=null;let c;const l=t[n];const u=t[n+1];const f=a(p=>{if(!p)return;if(o)o.push(...p);else o=p},\"add\");if(n===i){if(s._listeners){if(typeof s._listeners===\"function\")e?.push(s._listeners);else e?.push(...s._listeners);o=[s]}}else if(l===\"*\"){const p=pr(s);let m=p.length;while(m-- >0){const y=p[m];if(y!==\"_listeners\")f(this.searchListenerTree(e,t,s[y],n+1,i))}return o}else if(l===\"**\"){const p=n+1===i||n+2===i&&u===\"*\";if(p&&s._listeners)o=this.searchListenerTree(e,t,s,i,i);const m=pr(s);let y=m.length;while(y-- >0){const w=m[y];if(w===\"_listeners\")continue;if(w===\"*\"||w===\"**\"){if(s[w]._listeners&&!p)f(this.searchListenerTree(e,t,s[w],i,i));c=this.searchListenerTree(e,t,s[w],n,i)}else if(w===u){c=this.searchListenerTree(e,t,s[w],n+2,i)}else{c=this.searchListenerTree(e,t,s[w],n,i)}f(c)}return o}else if(s[l]){o=this.searchListenerTree(e,t,s[l],n+1,i)}const d=s[\"*\"];if(d)this.searchListenerTree(e,t,d,n+1,i);const h=s[\"**\"];if(h){if(n<i){if(h._listeners)this.searchListenerTree(e,t,h,i,i);const p=pr(h);let m=p.length;while(m-- >0){const y=p[m];if(y===\"_listeners\")continue;if(y===u){this.searchListenerTree(e,t,h[y],n+2,i)}else if(y===l){this.searchListenerTree(e,t,h[y],n+1,i)}else{const w=ru();w[y]=h[y];const S=ru();S[\"**\"]=w;this.searchListenerTree(e,t,S,n+1,i)}}}else if(h._listeners){this.searchListenerTree(e,t,h,i,i)}else if(h[\"*\"]&&h[\"*\"]._listeners){this.searchListenerTree(e,t,h[\"*\"],i,i)}}return o}growListenerTree(e,t,s){const n=typeof e===\"string\"?this.split(e):e;const i=n.length;if(i>1){for(let c=0;c+1<i;c++)if(n[c]===\"**\"&&n[c+1]===\"**\")return}let o=this.listenerTree;for(let c=0;c<i;c++){const l=n[c];o=o[l]||(o[l]=ru());if(c===i-1){if(!o._listeners){o._listeners=t}else{if(typeof o._listeners===\"function\")o._listeners=[o._listeners];const u=o._listeners;if(s)u.unshift(t);else u.push(t);if(!u.warned&&this._maxListeners>0&&u.length>this._maxListeners){u.warned=true;this.logPossibleMemoryLeak(u.length,l)}}return true}}return true}collectTreeEvents(e,t,s,n){const i=pr(e);let o=i.length;const c=e._listeners;while(o-- >0){const l=i[o];const u=e[l];const f=l===\"_listeners\"?s:s?s.concat(l):[l];const d=!!n||typeof l===\"symbol\";if(c)t.push(d?f:f.join(this.delimiter));if(typeof u===\"object\")this.collectTreeEvents(u,t,f,d)}return t}recursivelyGarbageCollect(e){const t=pr(e);let s=t.length;let n;while(s-- >0){const i=t[s];const o=e[i];if(o){n=true;if(i!==\"_listeners\"&&!this.recursivelyGarbageCollect(o))delete e[i]}}return n}setupListener(e,t){let s;let n;let i;if(t===true){n=true}else if(t===false){s=true}else{if(!t||typeof t!==\"object\")throw TypeError(\"options should be an object or true\");s=t.async;n=t.promisify;i=t.nextTick}if(s||i||n){const o=e;const c=e._origin||e;if(n===void 0)n=e.constructor.name===\"AsyncFunction\";s=true;e=a(function(...l){const u=this;const f=this.event;if(n){return(i?Promise.resolve():new Promise(h=>setImmediate(h))).then(()=>{u.event=f;return o.apply(u,l)})}const d=a(()=>{u.event=f;o.apply(u,l)},\"call\");return i?process.nextTick(d):setImmediate(d)},\"listener\");e._async=s;e._origin=c}return e}setMaxListeners(e){if(e===void 0)return;this._maxListeners=e;if(!this._conf)this._conf={};this._conf.maxListeners=e}getMaxListeners(){return this._maxListeners}once(e,t,s){return this._many(e,1,t,false,s)}prependOnceListener(e,t,s){return this._many(e,1,t,true,s)}many(e,t,s,n){return this._many(e,t,s,false,n)}prependMany(e,t,s,n){return this._many(e,t,s,true,n)}_many(e,t,s,n,i){if(typeof s!==\"function\")throw new Error(\"many only accepts instances of Function\");const o=this;const c=a(function(...l){if(--t===0)o.off(e,c);return s.apply(this,l)},\"listener\");c._origin=s;return this._on(e,c,n,i)}eventOf(e){if(!this.wildcard||e===\"newListener\"||e===\"removeListener\"||typeof e!==\"object\")return e;return e.some(t=>typeof t===\"symbol\")?e:e.join(this.delimiter)}emit(e,...t){if(!this._events&&!this._all)return false;if(!this._events)this.init();if(e===\"newListener\"&&!this._newListener&&!this._events.newListener)return false;const s=e;e=this.eventOf(e);if(this._all&&this._all.length){for(const i of this._all.slice()){this.event=e;i.call(this,t.length>=3?s:e,...t)}}let n;if(this.wildcard){n=[];this.searchListenerTree(n,s,this.listenerTree,0)}else{n=this._events[e];if(typeof n===\"function\"){this.event=e;n.apply(this,t);return true}if(n)n=n.slice()}if(n&&n.length){for(const i of n){this.event=e;i.apply(this,t)}return true}if(!this.ignoreErrors&&!this._all&&e===\"error\"){if(t[0]instanceof Error)throw t[0];throw new Error(\"Uncaught, unspecified 'error' event.\")}return!!this._all}emitAsync(e,...t){if(!this._events&&!this._all)return false;if(!this._events)this.init();if(e===\"newListener\"&&!this._newListener&&!this._events.newListener)return Promise.resolve([false]);const s=e;e=this.eventOf(e);const n=[];if(this._all){for(const o of this._all){this.event=e;n.push(o.call(this,t.length>=3?s:e,...t))}}let i;if(this.wildcard){i=[];this.searchListenerTree(i,s,this.listenerTree,0)}else{i=this._events[e]}if(typeof i===\"function\"){this.event=e;n.push(i.apply(this,t))}else if(i&&i.length){for(const o of i.slice()){this.event=e;n.push(o.apply(this,t))}}else if(!this.ignoreErrors&&!this._all&&e===\"error\"){return Promise.reject(t[0]instanceof Error?t[0]:\"Uncaught, unspecified 'error' event.\")}return Promise.all(n)}on(e,t,s){return this._on(e,t,false,s)}prependListener(e,t,s){return this._on(e,t,true,s)}addListener(e,t,s){return this._on(e,t,false,s)}onAny(e){return this._onAny(e,false)}prependAny(e){return this._onAny(e,true)}_onAny(e,t){if(typeof e!==\"function\")throw new Error(\"onAny only accepts instances of Function\");if(!this._all)this._all=[];if(t)this._all.unshift(e);else this._all.push(e);return this}_on(e,t,s,n){if(typeof e===\"function\"){this._onAny(e,!!t);return this}if(typeof t!==\"function\")throw new Error(\"on only accepts instances of Function\");if(!this._events)this.init();if(n!==void 0)t=this.setupListener(t,n);if(this._newListener)this.emit(\"newListener\",e,t);if(this.wildcard){this.growListenerTree(e,t,s);return this}const i=this._events;const o=e;const c=i[o];if(!c){i[o]=t;return this}const l=typeof c===\"function\"?[c]:c;i[o]=l;if(s)l.unshift(t);else l.push(t);if(!l.warned&&this._maxListeners>0&&l.length>this._maxListeners){l.warned=true;this.logPossibleMemoryLeak(l.length,o)}return this}isListener(e,t){return e===t||!!e.listener&&e.listener===t||!!e._origin&&e._origin===t}off(e,t){if(typeof t!==\"function\")throw new Error(\"removeListener only takes instances of Function\");let s=[];if(this.wildcard){const n=typeof e===\"string\"?e.split(this.delimiter):e.slice();const i=this.searchListenerTree(null,n,this.listenerTree,0);if(!i)return this;s=i}else{if(!this._events[e])return this;s.push({_listeners:this._events[e]})}for(const n of s){const i=n._listeners;if(Array.isArray(i)){const o=i.findIndex(c=>this.isListener(c,t));if(o<0)continue;if(this.wildcard)n._listeners.splice(o,1);else this._events[e].splice(o,1);if(i.length===0){if(this.wildcard)delete n._listeners;else delete this._events[e]}if(this._removeListener)this.emit(\"removeListener\",e,t);return this}if(i&&this.isListener(i,t)){if(this.wildcard)delete n._listeners;else delete this._events[e];if(this._removeListener)this.emit(\"removeListener\",e,t)}}if(this.listenerTree)this.recursivelyGarbageCollect(this.listenerTree);return this}removeListener(e,t){return this.off(e,t)}offAny(e){if(e&&this._all&&this._all.length>0){const t=this._all.indexOf(e);if(t>=0){this._all.splice(t,1);if(this._removeListener)this.emit(\"removeListenerAny\",e)}return this}if(this._removeListener)for(const t of this._all)this.emit(\"removeListenerAny\",t);this._all=[];return this}removeAllListeners(e){if(e===void 0){if(this._events)this.init();return this}if(this.wildcard){const t=this.searchListenerTree(null,e,this.listenerTree,0);if(!t)return this;for(const s of t)s._listeners=null;if(this.listenerTree)this.recursivelyGarbageCollect(this.listenerTree)}else if(this._events){this._events[e]=null}return this}listeners(e){const t=this._events;if(e===void 0){if(this.wildcard)throw Error(\"event name required for wildcard emitter\");if(!t)return[];const n=[];const i=pr(t);let o=i.length;while(o-- >0){const c=t[i[o]];if(typeof c===\"function\")n.push(c);else n.push(...c)}return n}if(this.wildcard){if(!this.listenerTree)return[];const n=[];const i=typeof e===\"string\"?e.split(this.delimiter):e.slice();this.searchListenerTree(n,i,this.listenerTree,0);return n}if(!t)return[];const s=t[e];if(!s)return[];return typeof s===\"function\"?[s]:s}eventNames(e){if(this.wildcard)return this.collectTreeEvents(this.listenerTree,[],null,e);return this._events?pr(this._events):[]}listenerCount(e){return this.listeners(e).length}hasListeners(e){if(this.wildcard){const n=[];const i=typeof e===\"string\"?e.split(this.delimiter):e.slice();this.searchListenerTree(n,i,this.listenerTree,0);return n.length>0}const t=this._events;const s=this._all;return!!(s&&s.length||t&&(e===void 0?pr(t).length:t[e]))}listenersAny(){return this._all?this._all:[]}countAllListeners(){const e=a(s=>!s?0:typeof s===\"function\"?1:s.length,\"count\");if(!this.wildcard)return this._events?pr(this._events).reduce((s,n)=>s+e(this._events[n]),0):0;const t=a(s=>pr(s).reduce((n,i)=>i===\"_listeners\"?n+e(s._listeners):n+t(s[i]),0),\"countTree\");return this.listenerTree?t(this.listenerTree):0}};var fi={async:true,nextTick:false,promisify:true,objectify:false};var KA={wildcard:true,delimiter:\".\",newListener:false,removeListener:false,maxListeners:11,verboseMemoryLeak:true,ignoreErrors:false};function We(r){return typeof r===\"symbol\"?[r]:r}a(We,\"eventName\");var wa=class{static{a(this,\"EventEmitter\")}constructor(e={}){Reflect.defineMetadata(this.constructor.name,new su({...KA,...e}),this)}emit(e,...t){return Reflect.getMetadata(this.constructor.name,this).emit(We(e),...t)}async emitRequest(e,...t){return Reflect.getMetadata(this.constructor.name,this).emitAsync(We(e),...t)}addListener(e,t){Reflect.getMetadata(this.constructor.name,this).addListener(We(e),t);return this}on(e,t){Reflect.getMetadata(this.constructor.name,this).on(We(e),t,fi);return this}prependListener(e,t){Reflect.getMetadata(this.constructor.name,this).prependListener(We(e),t,fi);return this}once(e,t){Reflect.getMetadata(this.constructor.name,this).once(We(e),t,fi);return this}prependOnceListener(e,t){Reflect.getMetadata(this.constructor.name,this).prependOnceListener(We(e),t,fi);return this}many(e,t,s){Reflect.getMetadata(this.constructor.name,this).many(We(e),t,s,fi);return this}prependMany(e,t,s){Reflect.getMetadata(this.constructor.name,this).prependMany(We(e),t,s,fi);return this}onAny(e){Reflect.getMetadata(this.constructor.name,this).onAny(e);return this}prependAny(e){Reflect.getMetadata(this.constructor.name,this).prependAny(e);return this}offAny(e){Reflect.getMetadata(this.constructor.name,this).offAny(e);return this}removeListener(e,t){Reflect.getMetadata(this.constructor.name,this).removeListener(We(e),t);return this}off(e,t){Reflect.getMetadata(this.constructor.name,this).off(We(e),t);return this}removeAllListeners(e){Reflect.getMetadata(this.constructor.name,this).removeAllListeners(We(e));return this}setMaxListeners(e){return Reflect.getMetadata(this.constructor.name,this).setMaxListeners(e)}getMaxListeners(){return Reflect.getMetadata(this.constructor.name,this).getMaxListeners()}eventNames(e){const t=Reflect.getMetadata(this.constructor.name,this).eventNames(e);return e?t:t.map(s=>Array.isArray(s)&&s.length===1&&typeof s[0]===\"symbol\"?s[0]:s)}listenerCount(e){if(e===void 0)return Reflect.getMetadata(this.constructor.name,this).countAllListeners();return Reflect.getMetadata(this.constructor.name,this).listenerCount(We(e))}listeners(e){const t=Reflect.getMetadata(this.constructor.name,this);if(e===void 0)return t.eventNames(true).flatMap(s=>t.listeners(s));return t.listeners(We(e))}listenersAny(){return[...Reflect.getMetadata(this.constructor.name,this).listenersAny()]}hasListeners(e){const t=Reflect.getMetadata(this.constructor.name,this);if(e===void 0)return t.countAllListeners()>0;return t.hasListeners(We(e)).valueOf()}};var nu=class extends wa{static{a(this,\"SynchronousEventEmitter\")}on(e,t){Reflect.getMetadata(this.constructor.name,this).on(We(e),t);return this}once(e,t){Reflect.getMetadata(this.constructor.name,this).once(We(e),t);return this}};function Ve(r=I.Any(),e){return(t,s)=>{zS(t,s,r,e);GS(t,s)}}a(Ve,\"Configurable\");var yw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var WA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Ts=class hH extends Ys{static{a(this,\"Component\")}#e=new wa;async[dr](...e){await super[dr](...e)}async[st](...e){await super[st](async()=>{this.#e.removeAllListeners()},...e)}get container(){return ha(this)}createScope(){return ha(this).createScope()}emit(e,...t){return this.#e.emit(e,...t)}async emitRequest(e,...t){return this.#e.emitRequest(e,...t)}addListener(e,t){this.#e.addListener(e,t);return this}on(e,t){this.#e.on(e,t);return this}prependListener(e,t){this.#e.prependListener(e,t);return this}once(e,t){this.#e.once(e,t);return this}prependOnceListener(e,t){this.#e.prependOnceListener(e,t);return this}many(e,t,s){this.#e.many(e,t,s);return this}prependMany(e,t,s){this.#e.prependMany(e,t,s);return this}onAny(e){this.#e.onAny(e);return this}prependAny(e){this.#e.prependAny(e);return this}offAny(e){this.#e.offAny(e);return this}removeListener(e,t){this.#e.removeListener(e,t);return this}off(e,t){this.#e.off(e,t);return this}removeAllListeners(e){this.#e.removeAllListeners(e);return this}setMaxListeners(e){this.#e.setMaxListeners(e)}getMaxListeners(){return this.#e.getMaxListeners()}eventNames(e){return this.#e.eventNames(e)}listenerCount(e){return this.#e.listenerCount(e)}listeners(e){return this.#e.listeners(e)}listenersAny(){return this.#e.listenersAny()}hasListeners(e){return this.#e.hasListeners(e)}async reload(){await this[st]();this[ba]();await this[dr]()}};yw([Ve(I.Number().integer().min(0).optional().default(11),function(r){this.setMaxListeners(r);return r}),WA(\"design:type\",Number)],Ts.prototype,\"maxListeners\",void 0);Ts=yw([Xs(true),ws(je.Component)],Ts);var VA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var di=class SH extends I{static{a(this,\"LoadNamedObjectOptions\")}};di=VA([hr(Ir.Schema())],di);var bw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var XA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var hi=class CH extends I{static{a(this,\"LoadAnonymousObjectOptions\")}};bw([ve(I.Class(()=>Re).required()),XA(\"design:type\",Object)],hi.prototype,\"class\",void 0);hi=bw([hr(I.Any())],hi);var Sw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var ww=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var xs=class extends I{static{a(this,\"ModuleLoadObjectsOptions\")}};Sw([ve(di.optional().default({})),ww(\"design:type\",di)],xs.prototype,\"named\",void 0);Sw([ve(I.Array(I.Alternatives(hi.Schema(),I.Class(Re),I.Glob())).optional().default([])),ww(\"design:type\",Array)],xs.prototype,\"anonymous\",void 0);var Ew=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var YA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var pi=class $H extends I{static{a(this,\"OverridableObjectOptions\")}};Ew([ve(I.Class(()=>Re).optional()),YA(\"design:type\",Object)],pi.prototype,\"class\",void 0);pi=Ew([hr(I.Any())],pi);var JA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Rs=class KH extends I{static{a(this,\"OverridableNamedObjectOptions\")}};Rs=JA([hr(pi.Schema())],Rs);var Ea=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Ta=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var wt=class extends I{static{a(this,\"ModuleOptions\")}};Ea([ve(Rs.optional()),Ta(\"design:type\",Rs)],wt.prototype,\"components\",void 0);Ea([ve(Rs.optional()),Ta(\"design:type\",Rs)],wt.prototype,\"providers\",void 0);Ea([ve(xs.optional().default({named:{},anonymous:[]})),Ta(\"design:type\",xs)],wt.prototype,\"objects\",void 0);Ea([ve(I.Array(I.Alternatives(I.String(),I.Class(Re),I.AsyncFunction())).optional().default([])),Ta(\"design:type\",Array)],wt.prototype,\"bootstrap\",void 0);Ea([ve(I.Boolean().optional()),Ta(\"design:type\",Boolean)],wt.prototype,\"checkOptions\",void 0);var xa=class extends Z{static{a(this,\"OverridableObjectTargetConfigNotFoundException\")}constructor(){super(...arguments);this.errno=\"E_OVERRIDABLE_OBJECT_TARGET_CONFIG_NOT_FOUND\"}};var Ra=class extends Z{static{a(this,\"InvalidObjectTypeException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_OBJECT_TYPE\"}};function Tw(r){return new Set(r)}a(Tw,\"arrayToSet\");function xw(r){return Array.from(r)}a(xw,\"setToArray\");var mi=class{static{a(this,\"ModuleConfigLoader\")}constructor(e,t,s=[]){this.$presetLoadOptionsSet=new Set;this.$loadOptions=[];this.$bootstrap=[];this.$module=e;this.$presetLoadOptionsSet=Tw(s);this.$bootstrap=t.bootstrap?t.bootstrap:[];t.objects?.anonymous?.forEach(n=>this.$loadOptions.push(n));if(t.objects&&t.objects.named){const n=t.objects.named;Object.keys(n).forEach(i=>this.$loadOptions.push({...n[i],[lt]:i}))}this.processOverridableNamedObjectOptions(je.Component,t.components);this.processOverridableNamedObjectOptions(je.Provider,t.providers)}validateObjectType(e,t,s){const n=ga(t);if(n===e)return t;const i=e.toLowerCase();const o=n.toLowerCase();const c=n===je.Component||n===je.Provider?`, declare it in the ${o}s configuration`:n===je.Module?\", declare it in the objects configuration (objects.named)\":\"\";throw new Ra('{0} configuration only accepts object declarations of {1} types: \"{2}\" ({3}) is a {4}{5}',[e,i,s??t.name,t.name,o,c])}processOverridableNamedObjectOptions(e,t){if(!t)return;Object.keys(t).forEach(s=>{const n=t[s];n[lt]=s;if(n.class){n.class=this.validateObjectType(e,n.class,s);for(const i of this.$presetLoadOptionsSet){if(typeof i===\"string\"||i instanceof Re)continue;if(s===i[lt])this.$presetLoadOptionsSet.delete(i)}return this.$loadOptions.push(v(n))?void 0:void 0}for(const i of this.$presetLoadOptionsSet){if(typeof i===\"string\")continue;if(i instanceof Re)continue;if(n[lt]===i[lt]){this.$loadOptions.push(Object.assign({},i,n));return this.$presetLoadOptionsSet.delete(i)?void 0:void 0}}throw new xa(\"No applicable configuration target found\")})}get loadOptions(){return[...this.$loadOptions,...xw(this.$presetLoadOptionsSet)]}get bootstrap(){return this.$bootstrap}};var Ow=require(\"node:util/types\");var _w=require(\"node:crypto\");var Rw={alphanumeric:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",alphabetic:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",numeric:\"0123456789\",hex:\"0123456789abcdef\",binary:\"01\",octal:\"01234567\"};function Cw(r=32,e=\"alphanumeric\"){if(!Number.isInteger(r)||r<0)throw new RangeError(`Invalid length: ${r}, a non-negative integer is expected`);const t=a(o=>Object.hasOwn(Rw,o)?Rw[o]:o,\"charsetOf\");const s=[...Array.isArray(e)?e.map(t).join(\"\"):t(e)];if(!s.length)throw new RangeError(\"The character set is empty\");const n=2**32-2**32%s.length;const i=[];while(i.length<r){const o=(0,_w.getRandomValues)(new Uint32Array(Math.min(r-i.length,16384)));for(const c of o)if(c<n)i.push(s[c%s.length])}return i.join(\"\")}a(Cw,\"randomString\");function Ap(){return Cw(32,\"alphanumeric\")}a(Ap,\"nonceString\");var _a=class extends Z{static{a(this,\"InvalidObjectOptionsException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_OBJECT_OPTIONS\"}};var ZA=new Set([\"class\",\"id\"]);function vw(r){const e=[];const t=[];for(const s of r){if(typeof s!==\"object\"||!s||typeof s.class!==\"function\")continue;const n=s.class;const i=s[lt];const o=typeof i===\"string\"?`\"${i}\" (${n.name})`:n.name;const c=Jl(v(n.prototype));for(const l of Object.keys(s)){const u=s[l];if(ZA.has(l)||u===void 0)continue;const f=c.get(l);if(!f){if(!n.acceptsOption(l,u))t.push(QA(o,l,c));continue}try{I.validate(u,f.schema,{targetName:l})}catch(d){if(!(d instanceof ur))continue;e.push(`The option \"${l}\" of ${o} is invalid: ${d.message}`)}}}t.forEach(s=>_r(s));if(e.length)throw new _a(e.join(\"\\n\"))}a(vw,\"checkObjectOptions\");function QA(r,e,t){const s=[...t.keys()].filter(i=>typeof i===\"string\").sort();const n=s.length?`its configurable properties: ${s.join(\", \")}`:\"it has no configurable property\";return`The option \"${e}\" of ${r} is not a configurable property, it is ignored (${n})`}a(QA,\"unknownOptionMessage\");var Aw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Iw=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Ip=`_$.MODULE.INITIALIZED_${Ap()}`;var Op=`_$.MODULE.INITIALIZE_ERROR_${Ap()}`;var Ca=class kw extends Ts{static{a(this,\"Module\")}get container(){return ha(this)}#e;#t;#r;constructor(e){super(e);this.ConfigLoader=mi;this.options={};this.#e=[];this.#t=[];this.#r=true}async[dr](...e){const t={};t.promise=new Promise((s,n)=>{t.resolve=s;t.reject=n});t.promise.catch(()=>void 0);this.#s=t;setImmediate(()=>void(async()=>{try{await super[dr](...e,async()=>{if(this.#r)vw(this.#e);await this.container.load(this.#e)},async()=>{Reflect.defineMetadata(\"#bootstrap\",this.#t,this);for(const s of this.#t){if((0,Ow.isAsyncFunction)(s)){await v(s)(this)}else{await this.getObject(v(s))}}Reflect.deleteMetadata(\"#bootstrap\",this)});this.emit(Ip);t.resolve()}catch(s){this.emit(Op,s);t.reject(s)}})())}#s;async[eu](){await this.#s?.promise}async[st](...e){this.#s?.resolve();return await super[st](...e)}mode(){return Ad()}async reload(){await this[st]();this[ba]();await new Promise((e,t)=>{const s=a(()=>{this.off(Op,n);e()},\"onInitialized\");const n=a(i=>{this.off(Ip,s);t(i)},\"onInitializeError\");this.once(Ip,s);this.once(Op,n);this[dr]().catch(t)})}async getObject(e,t={}){return await super.getObject(e,t)}static{Aw([Ve(wt.optional().default({}).options({stripUnknown:false}),function(e){const t=this.getConfigurableRecords().options!==void 0?e:{};const{bootstrap:s,loadOptions:n}=new this.ConfigLoader(this,this.options);s.forEach(o=>this.#t.push(o));const i=new this.ConfigLoader(this,t,n);i.bootstrap.forEach(o=>this.#t.push(o));this.#e=i.loadOptions;this.#r=(t.checkOptions??this.options.checkOptions)!==false;return e}),Iw(\"design:type\",wt)],kw.prototype,\"options\",void 0)}};Ca=Aw([Xs(true),ws(je.Module),Iw(\"design:paramtypes\",[Object])],Ca);var Pw=require(\"node:os\");var va=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Aa=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var eI=Object.keys(Pw.constants.signals).filter(r=>r!==\"SIGKILL\"&&r!==\"SIGSTOP\");var Ot=class extends wt{static{a(this,\"ApplicationOptions\")}};va([ve(I.String().required()),Aa(\"design:type\",String)],Ot.prototype,\"id\",void 0);va([ve(I.String().required()),Aa(\"design:type\",String)],Ot.prototype,\"name\",void 0);va([ve(I.String().optional().default(\"auto\")),Aa(\"design:type\",String)],Ot.prototype,\"timezone\",void 0);va([ve(I.String().valid(\"development\",\"production\").optional()),Aa(\"design:type\",String)],Ot.prototype,\"mode\",void 0);va([ve(I.Alternatives(I.Boolean().valid(false),I.Array(I.String().valid(...eI))).optional().default(()=>[\"SIGTERM\",\"SIGINT\"])),Aa(\"design:type\",Object)],Ot.prototype,\"shutdownSignals\",void 0);var iu=class extends mi{static{a(this,\"ApplicationConfigLoader\")}constructor(e,t,s=[]){if(Ot.isValid(t)){const n=Kg({appId:t.id,appName:t.name,timezone:t.timezone?t.timezone:\"auto\",mode:Gg(t.mode)}).appId;if(!process.versions.nw)process.title=n}super(e,t,s)}};var ou=Ye(require(\"path\"),1);var Js=class extends Z{static{a(this,\"InvalidAliasNameException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_ALIAS_NAME\"}};var Ia=class extends Z{static{a(this,\"AliasExistsException\")}constructor(){super(...arguments);this.errno=\"E_ALIAS_EXISTS\"}};var Oa=class extends Z{static{a(this,\"AliasNotFoundException\")}constructor(){super(...arguments);this.errno=\"E_ALIAS_NOT_FOUND\"}};var ka=class{static{a(this,\"Alias\")}constructor(){this.aliasNameRegExp=/^@[a-zA-Z0-9]+$/;this.aliasMap=new Map;const e=ou.default.resolve;ou.default.resolve=(...t)=>{const s=t.map(n=>this.resolve(n));return e(...s)}}static init(){const e=new this;Reflect.defineMetadata(this,e,this)}static getAliasInstance(){if(!Reflect.hasOwnMetadata(this,this))this.init();return Reflect.getMetadata(this,this)}set(e,t,s=false){if(!this.aliasNameRegExp.test(e))throw new Js(\"The alias should start with '@' and only contain characters a-z|A-Z|0-9. The current alias '{aliasName}' does not comply with this rule.\",{aliasName:e});if(this.aliasMap.has(e)&&!s)throw new Ia(\"The alias '{aliasName}' already exists.\",{aliasName:e});this.aliasMap.set(e,t)}get(e){if(!this.aliasNameRegExp.test(e))throw new Js(\"The alias should start with '@' and only contain characters a-z|A-Z|0-9. The current alias '{aliasName}' does not comply with this rule.\",{aliasName:e});if(!this.aliasMap.has(e))throw new Oa(\"The alias '{aliasName}' not found.\",{aliasName:e});const t=this.aliasMap.get(e);return this.resolve(t)}has(e){if(!this.aliasNameRegExp.test(e))throw new Js(\"The alias should start with '@' and only contain characters a-z|A-Z|0-9. The current alias '{aliasName}' does not comply with this rule.\",{aliasName:e});return this.aliasMap.has(e)}resolve(e){let t=true;const s=[];this.aliasMap.forEach((n,i)=>s.push({name:i,path:n}));s.sort((n,i)=>n.name.length<i.name.length?1:-1);while(t){let n=false;s.forEach(({name:i,path:o})=>{if(e.includes(i)){n=true;e=e.replace(i,o)}});t=n}return ou.default.normalize(e)}list(){const e={};this.aliasMap.forEach((t,s)=>Reflect.set(e,s,t));return e}};var Lw=require(\"node:util\");var Nw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var tI=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Pa={trace:10,debug:20,info:30,warn:40,error:50,silent:Infinity};var Na=class I4 extends Ts{static{a(this,\"ConsoleLogger\")}write(e,t){if(Pa[e]<Pa[this.level])return;const[s,...n]=t;const i=typeof s===\"object\"&&s!==null&&typeof n[0]===\"string\"?[...n,s]:t;const o=`[${new Date().toISOString()}] ${e.toUpperCase()} (${Qr()}): ${(0,Lw.formatWithOptions)({colors:false},...i)}\n`;Pa[e]>=Pa.warn?process.stderr.write(o):process.stdout.write(o)}error(...e){this.write(\"error\",e)}warn(...e){this.write(\"warn\",e)}info(...e){this.write(\"info\",e)}debug(...e){this.write(\"debug\",e)}trace(...e){this.write(\"trace\",e)}};Nw([Ve(I.String().valid(...Object.keys(Pa)).optional().default(\"info\")),tI(\"design:type\",String)],Na.prototype,\"level\",void 0);Na=Nw([Xs()],Na);var Uw=require(\"fs\");var Pp=Ye(require(\"node:path\"),1);var jw=require(\"node:fs\");var $w=require(\"node:os\");function Mw(r){const e=new Map;for(const i in r)if(i.toUpperCase().startsWith(\"MIGRATION_\")&&r[i]!==void 0)e.set(i.toUpperCase(),r[i]);const t=a(i=>[\"1\",\"true\",\"yes\"].includes((e.get(i)??\"\").toLowerCase()),\"flag\");const s=e.get(\"MIGRATION_TRANSACTION\")||void 0;if(s!==void 0&&s!==\"all\"&&s!==\"none\"&&s!==\"each\")throw new Error(`MIGRATION_TRANSACTION is all, none or each, not \"${s}\"`);const n={database:e.get(\"MIGRATION_DATABASE\")||void 0,transaction:s,fake:t(\"MIGRATION_FAKE\")};if(e.get(\"MIGRATION_GENERATE\"))return{action:\"generate\",path:e.get(\"MIGRATION_GENERATE\"),...n};if(t(\"MIGRATION_RUN\"))return{action:\"run\",...n};if(t(\"MIGRATION_REVERT\"))return{action:\"revert\",...n};if(t(\"MIGRATION_SHOW\"))return{action:\"show\",...n};return void 0}a(Mw,\"readMigrationCommand\");var kp=false;function La(r,e=500){if(kp)return;kp=true;process.exitCode=r;setTimeout(()=>process.exit(r),e).unref()}a(La,\"endProcess\");function Dw(){return kp}a(Dw,\"isEnding\");var Bw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var gi=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Je;(function(r){r[\"Launched\"]=\"LAUNCHED\";r[\"Done\"]=\"DONE\";r[\"UncaughtException\"]=\"UNCAUGHT_EXCEPTION\";r[\"FatalException\"]=\"FATAL_EXCEPTION\"})(Je||(Je={}));var yi=class r extends Ca{static{a(this,\"Application\")}constructor(){super(...arguments);this.ConfigLoader=iu;this.options=r.copyPresetOptions()}static{this.eventEmitter=new nu}static{this.environmentVariableMap=new Map}static{this.aliasDeclarations=[]}static{this.launchStarted=false}static{this.presetOptions={}}static#e;static#t=false;static#r;static preset(e){const t=this.presetOptions;if(e.components)Reflect.set(t,\"components\",{...t.components,...e.components});if(e.providers)Reflect.set(t,\"providers\",{...t.providers,...e.providers});if(e.objects)Reflect.set(t,\"objects\",{named:{...t.objects?.named,...e.objects.named},anonymous:[...t.objects?.anonymous??[],...e.objects.anonymous??[]]});if(e.bootstrap)Reflect.set(t,\"bootstrap\",[...new Set([...t.bootstrap??[],...e.bootstrap])]);return this}static async getLogger(){return this.appInstance?await this.appInstance.getLogger():await this.getConsoleLogger()}static getConsoleLogger(){if(!this.#e)this.#e=new Wt().set(Na);return this.#e}static env(e){Object.keys(e).forEach(t=>this.environmentVariableMap.set(t,e[t]));return this.launch()}static alias(e,t=false){this.aliasDeclarations.push({alias:e?e:{},createIfNotExist:t});return this.launch()}static onLaunched(e){const t=this.appInstance;if(t){void(async()=>e(t,await t.getLogger()))();return this}this.eventEmitter.once(Je.Launched,async s=>e(s,await s.getLogger()));return this.launch()}static onDone(e){this.eventEmitter.once(Je.Done,async(t,s)=>e(t,await t.getLogger(),s));return this.launch()}static onUncaughtException(e){this.eventEmitter.on(Je.UncaughtException,async t=>{const s=await this.getLogger();await e(t,s)});return this.launch()}static onFatalException(e){this.eventEmitter.once(Je.FatalException,async t=>{const s=await this.getLogger();let n=await e(t,s);if(typeof n!==\"number\")n=1;return La(n)});return this.launch()}static run(e){Reflect.set(this,\"launchOptions\",e);return this.launch()}static launch(){if(this.launchStarted)return this;if(this.launchTimeout)clearTimeout(this.launchTimeout);this.launchTimeout=setTimeout(()=>{this.launchStarted=true;process.on(\"uncaughtException\",e=>void this.processUncaughtException(e));this.launchApplication().then(e=>Reflect.set(this,\"appInstance\",e)).catch(e=>this.processFatalException(e))});return this}static async processUncaughtException(e){if(this.eventEmitter.listenerCount(Je.UncaughtException)){this.eventEmitter.emit(Je.UncaughtException,e);return}const t=new Error(\"UncaughtException\",{cause:e});try{const s=await this.getLogger();s.warn(t)}catch(s){console.error(t,s)}}static processFatalException(e){if(Dw())return;if(!this.eventEmitter.listenerCount(Je.FatalException)){return process.nextTick(async()=>{const t=new Error(\"FatalException\",{cause:e});try{const s=await this.getLogger();s.error(t)}catch(s){console.error(t,s)}return La(1)})}this.eventEmitter.emit(Je.FatalException,e)}static listenShutdownSignals(e){let t=false;for(const s of e){process.on(s,()=>{const n=128+($w.constants.signals[s]??0);if(t||!this.appInstance)return process.exit(n);t=true;this.eventEmitter.emit(\"exit\",this.appInstance,0,s)})}}static listenNaturalEnd(e){r.stopListeningNaturalEnd();const t=a(()=>{r.stopListeningNaturalEnd();if(r.#t)return;const s=Number(process.exitCode??0);r.eventEmitter.emit(\"exit\",e,Number.isInteger(s)?s:1)},\"listener\");r.#r=t;process.once(\"beforeExit\",t)}static stopListeningNaturalEnd(){if(r.#r)process.removeListener(\"beforeExit\",r.#r);r.#r=void 0}static async launchApplication(){this.eventEmitter.once(\"exit\",async(i,o,c)=>{this.#t=true;try{const l=c?{code:o?o:0,signal:c}:{code:o?o:0};await this.eventEmitter.emitRequest(Je.Done,i,l);await n.destroy();La(o?o:0)}catch(l){La(1)}});this.environmentVariableMap.forEach((i,o)=>process.env[o]=i);const e=ka.getAliasInstance();e.set(\"@runtime\",process.cwd());this.aliasDeclarations.forEach(i=>{const o=i.alias;const c=i.createIfNotExist;Object.keys(o).forEach(l=>{e.set(l,o[l]);if(c){const u=Pp.default.resolve(l);if(!(0,jw.existsSync)(u))(0,Uw.mkdirSync)(Pp.default.resolve(l),{recursive:true})}})});const t=typeof this.launchOptions===\"object\"?this.launchOptions:await this.launchOptions();let s;try{s=Mw(process.env)}catch(i){console.error(i.message);process.exit(1)}if(s){this.eventEmitter.removeAllListeners(Je.Launched);this.eventEmitter.removeAllListeners(Je.Done);this.eventEmitter.removeAllListeners(Je.UncaughtException);this.eventEmitter.removeAllListeners(Je.FatalException);const i=s.action===\"generate\"?\"migrationGenerator\":\"migrationExecutor\";const o=a(u=>{const f=[];for(const d in u){const h=u[d]?.class;if(typeof h?.[i]===\"function\"){if(!u[d].options)continue;const p=Array.isArray(u[d].entities)?u[d].entities:[];const m=u[d].options.entities;const y={...u[d].options,...p.length?{entities:[...Array.isArray(m)?m:Object.values(m??{}),...p]}:{},dataSourceName:d};f.push({dataSourceName:d,dataSourceOptions:y,loader:h[i]})}}return f},\"getMigrationTargets\");let c=[...t.components?o(t.components):[],...t.providers?o(t.providers):[]];const l=c.map(u=>u.dataSourceName).join(\", \");if(s.database){c=c.filter(u=>u.dataSourceName===s.database);if(!c.length){console.error(`The application has no database ${s.database} (${l||\"no Database component or provider\"})`);process.exit(1)}}if(!c.length){if(s.action===\"generate\")process.exit(0);console.error(\"The application has no Database component or provider\");process.exit(1)}if(s.action===\"revert\"&&c.length>1){console.error(`The application has several databases (${l}): MIGRATION_DATABASE selects the one whose last migration is reverted`);process.exit(1)}t.bootstrap=[];if(!t.providers)t.providers={};for(let u=0;u<c.length;u++){const f=c[u];const d=`Migration${u}${Date.now()}`;const h={class:await f.loader(),exitProcess:u===c.length-1,dataSourceName:f.dataSourceName,dataSource:f.dataSourceOptions};t.providers[d]=s.action===\"generate\"?{...h,path:s.path,outputJs:false}:{...h,action:s.action,transaction:s.transaction,fake:s.fake};t.bootstrap.push(d)}}const n=new Wt;return new Promise((i,o)=>{Ot.validateAsync(t).then(c=>{if(c.shutdownSignals)this.listenShutdownSignals(c.shutdownSignals);c.bootstrap?.push(async l=>{if(r.#t)return;const u=a(function(){this.options.bootstrap?.pop();v(Reflect.getOwnMetadata(\"#bootstrap\",this))?.pop()},\"launchedCallbackRemover\");u.bind(v(l))();const f=await v(l).getLogger();aw((d,h)=>f.warn(d,h));ew(l);Reflect.set(this,\"appInstance\",l);r.listenNaturalEnd(v(l));this.eventEmitter.emit(Je.Launched,v(l))});n.set(r,{options:c}).then(i).catch(o)}).catch(o)})}static copyPresetOptions(){const e=r.presetOptions;return{...e.components?{components:{...e.components}}:{},...e.providers?{providers:{...e.providers}}:{},...e.objects?{objects:{named:{...e.objects.named},anonymous:[...e.objects.anonymous??[]]}}:{},bootstrap:[...e.bootstrap??[]]}}async getLogger(){return this.container.has(\"log\")?v(await this.getObject(\"log\")):await r.getConsoleLogger()}get alias(){return ka.getAliasInstance()}static get appId(){return jn()}static get appName(){return Qr()}get appId(){return jn()}get appName(){return Qr()}get timezone(){return Id().timezone}async[st](...e){r.stopListeningNaturalEnd();return await super[st](...e)}get uptime(){return Math.floor(process.uptime())}exit(e){if(typeof e===\"boolean\"&&e){return process.exit(2)}else{r.eventEmitter.emit(\"exit\",this,e?e:0)}}};Bw([Sa(I.Object().pattern(I.String(),I.String()).required()),gi(\"design:type\",Function),gi(\"design:paramtypes\",[Object]),gi(\"design:returntype\",Object)],yi,\"env\",null);Bw([Sa(I.Object().pattern(I.String(),I.String()).required(),I.Boolean().optional().default(false)),gi(\"design:type\",Function),gi(\"design:paramtypes\",[Object,Boolean]),gi(\"design:returntype\",Object)],yi,\"alias\",null);QS(yi);var rI=Object.freeze([\"en\",\"zh-CN\",\"zh-TW\",\"ja\",\"ko\",\"fr\",\"de\",\"es\",\"pt-BR\",\"it\",\"nl\",\"pl\",\"ru\",\"uk\",\"tr\",\"vi\",\"th\",\"id\",\"hi\",\"ar\"]);var au;var sI=new Set;function Fw(r){const e=!!au!==!!r;au=r;if(e)for(const t of sI)t(!!r)}a(Fw,\"setDebugHandler\");function P(r){return(...e)=>{if(au)au(r,e)}}a(P,\"debug\");var FE=require(\"node:events\");var Xp=require(\"node:crypto\");var Np=require(\"node:crypto\");function Lp(){return(0,Np.randomBytes)(2).readUInt16BE(0)}a(Lp,\"random16\");function cu(){return(0,Np.randomBytes)(4).readUInt32BE(0)}a(cu,\"random32\");var Or=class{static{a(this,\"BitWriter\")}constructor(e){this.bitLength=e;this.value=0}set(e,t,s){s&=(1<<e)-1;this.value|=s<<this.bitLength-e-t;return this}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};var Zs=class{static{a(this,\"BitWriter2\")}constructor(e){this.bitLength=e;this._value=0n;this.offset=0n;if(e>32){throw new Error}}set(e,t=1){let s=BigInt(e);const n=BigInt(t);s&=(1n<<n)-1n;this._value|=s<<BigInt(this.bitLength)-n-this.offset;this.offset+=n;return this}get value(){return Number(this._value)}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};function V(r,e,t=1){const s=Math.min(e+t,8);return r>>8-s&(1<<s-e)-1}a(V,\"getBit\");function he(r,e){return Ma(r)(e)}a(he,\"bufferWriter\");function Ma(r,e){const t=r.reduce((n,i)=>n+i,0);const s=e?Buffer.alloc(t):void 0;return n=>{const i=s||Buffer.alloc(t);let o=0;n.forEach((c,l)=>{const u=r[l];if(u===8)i.writeBigUInt64BE(c,o);else i.writeUIntBE(c,o,u);o+=u});return i}}a(Ma,\"createBufferWriter\");function Pe(r,e){let t=0;return e.map(s=>{let n;if(s===8){n=r.readBigUInt64BE(t)}else{n=r.readUIntBE(t,s)}t+=s;return n})}a(Pe,\"bufferReader\");var mr=class{static{a(this,\"BitStream\")}constructor(e){this.uint8Array=e;this.position=0;this.bitsPending=0}writeBits(e,t){if(e==0){return this}t&=4294967295>>>32-e;let s;if(this.bitsPending>0){if(this.bitsPending>e){this.uint8Array[this.position-1]|=t<<this.bitsPending-e;s=e;this.bitsPending-=e}else if(this.bitsPending==e){this.uint8Array[this.position-1]|=t;s=e;this.bitsPending=0}else{this.uint8Array[this.position-1]|=t>>e-this.bitsPending;s=this.bitsPending;this.bitsPending=0}}else{s=Math.min(8,e);this.bitsPending=8-s;this.uint8Array[this.position++]=t>>e-s<<this.bitsPending}e-=s;if(e>0){this.writeBits(e,t)}return this}readBits(e){return this._readBits(e)}_readBits(e,t){if(typeof t==\"undefined\"){t=0}if(e==0){return t}let s;let n;if(this.bitsPending>0){const i=this.uint8Array[this.position-1]&255>>8-this.bitsPending;n=Math.min(this.bitsPending,e);this.bitsPending-=n;s=i>>this.bitsPending}else{n=Math.min(8,e);this.bitsPending=8-n;s=this.uint8Array[this.position++]>>this.bitsPending}e-=n;t=t<<n|s;return e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0;this.bitsPending=e%8;if(this.bitsPending>0){this.bitsPending=8-this.bitsPending;this.position++}}};var nI=3988292384;var iI=2197175160;function Hw(r){return typeof r!==\"string\"}a(Hw,\"isBufferLike\");function qw(r){const e=new Array(256);for(let t=0;t<256;++t){let s=t;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;e[t]=s}return new Int32Array(e)}a(qw,\"generateCRCTable\");function zw(r){const e=new Int32Array(4096);let t;let s;let n;for(n=0;n<256;++n)e[n]=r[n];for(n=0;n<256;++n){s=r[n];for(t=256+n;t<4096;t+=256){s=e[t]=s>>>8^r[s&255]}}const i=[];for(n=1;n<16;++n){i[n-1]=e.subarray(n*256,n*256+256)}return i}a(zw,\"generateSliceBy16Tables\");function Gw(r,e,t){let s=e^-1;let n=0;const i=r.length;let o;let c;while(n<i){o=r.charCodeAt(n++);if(o<128){s=s>>>8^t[(s^o)&255]}else if(o<2048){s=s>>>8^t[(s^(192|o>>6&31))&255];s=s>>>8^t[(s^(128|o&63))&255]}else if(o>=55296&&o<57344){o=(o&1023)+64;c=r.charCodeAt(n++)&1023;s=s>>>8^t[(s^(240|o>>8&7))&255];s=s>>>8^t[(s^(128|o>>2&63))&255];s=s>>>8^t[(s^(128|c>>6&15|(o&3)<<4))&255];s=s>>>8^t[(s^(128|c&63))&255]}else{s=s>>>8^t[(s^(224|o>>12&15))&255];s=s>>>8^t[(s^(128|o>>6&63))&255];s=s>>>8^t[(s^(128|o&63))&255]}}return~s>>>0}a(Gw,\"crcGenericString\");function Kw(r,e,t,s){const[n,i,o,c,l,u,f,d,h,p,m,y,w,S,T]=s;let _=e^-1;let x=0;let k=r.length-15;while(x<k){_=T[r[x++]^_&255]^S[r[x++]^_>>>8&255]^w[r[x++]^_>>>16&255]^y[r[x++]^_>>>24]^m[r[x++]]^p[r[x++]]^h[r[x++]]^d[r[x++]]^f[r[x++]]^u[r[x++]]^l[r[x++]]^c[r[x++]]^o[r[x++]]^i[r[x++]]^n[r[x++]]^t[r[x++]]}for(k+=15;x<k;){_=_>>>8^t[(_^r[x++])&255]}return~_>>>0}a(Kw,\"crcBuffer\");var Mp=qw(nI);var oI=zw(Mp);var Dp=qw(iI);var aI=zw(Dp);function Ww(r,e=0){if(Hw(r)){return Kw(r,e,Mp,oI)}return Gw(r,e,Mp)}a(Ww,\"crc32\");function Da(r,e=0){if(Hw(r)){return Kw(r,e,Dp,aI)}return Gw(r,e,Dp)}a(Da,\"crc32c\");function Vw(r,e){return r+e&255}a(Vw,\"uint8Add\");function $e(r,e){return r+e&65535}a($e,\"uint16Add\");function gr(r,e){return Number(BigInt(r)+BigInt(e)&0xffffffffn)}a(gr,\"uint32Add\");function lu(r,e){const t=32768;return r<e&&e-r>t||r>e&&r-e<t}a(lu,\"uint16Gt\");function Et(r,e){const t=2147483648;return r<e&&e-r>t||r>e&&r-e<t}a(Et,\"uint32Gt\");function bi(r,e){return r===e||Et(r,e)}a(bi,\"uint32Gte\");var _s=a(r=>Number.parseInt(r,10),\"int\");function Ne(r,e){try{const t=r();if(t instanceof Promise)t.catch(e)}catch(t){e(t)}}a(Ne,\"runDetached\");function Vt(r,e){return(...t)=>{try{const s=r(...t);if(s instanceof Promise)s.catch(e)}catch(s){e(s)}}}a(Vt,\"detached\");var Bp=require(\"node:dgram\");var uu=a((r,e)=>e?e[r]:void 0,\"interfaceAddress\");async function fu(r=\"udp4\",e){const t=(0,Bp.createSocket)(r);setImmediate(()=>t.bind({port:0,address:uu(r,e)}));await new Promise(n=>{t.once(\"error\",n);t.once(\"listening\",n)});const s=t.address()?.port;await new Promise(n=>t.close(()=>n()));return s}a(fu,\"randomPort\");async function Xw(r,e,t=\"udp4\",s){let n;for(let i=r;i<=e;i++){const o=(0,Bp.createSocket)(t);setImmediate(()=>o.bind({port:i,address:uu(t,s)}));const c=await new Promise(l=>{o.once(\"error\",u=>l(u));o.once(\"listening\",()=>l())});if(c){await new Promise(l=>o.close(()=>l()));continue}n=o.address()?.port;await new Promise(l=>o.close(()=>l()));if(r<=n&&n<=e){break}}if(!n)throw new Error(\"port not found\");return n}a(Xw,\"findPort\");function Qs(r){if(r===\"IPv4\")return 4;if(r===\"IPv6\")return 6;return r}a(Qs,\"normalizeFamilyNodeV18\");var du=class{static{a(this,\"Subscribers\")}constructor(){this.list=[];this.size=0;this.#e=0}#e;add(e){this.list.push(e);this.size++}remove(e){if(e.removed)return false;e.removed=true;this.size--;if(++this.#e>16&&this.#e>this.size){this.list=this.list.filter(t=>!t.removed);this.#e=0}return true}clear(){for(const e of this.list)e.removed=true;this.list=[];this.size=0;this.#e=0}};var O=class{static{a(this,\"Event\")}constructor(){this.subscribers=new du;this.queued=new du;this.ended=false;this.onerror=e=>{};this.execute=(...e)=>{if(this.ended){return}for(const t of this.subscribers.list){if(!t.removed)t.execute(...e)}if(this.queued.size===0)return;(async()=>{for(const t of this.queued.list){if(!t.removed)await t.execute(...e)}})().catch(t=>{this.onerror(t)})};this.complete=()=>{if(this.ended){return}for(const e of this.subscribers.list){if(e.complete&&!e.removed){e.complete()}}this.allUnsubscribe();this.ended=true;if(this.onended){this.onended();this.onended=void 0}};this.error=e=>{if(this.ended){return}for(const t of this.subscribers.list){if(t.error&&!t.removed){t.error(e)}}this.allUnsubscribe()};this.allUnsubscribe=()=>{if(this.ended){return}this.subscribers.clear();this.queued.clear();this.onsubscriberschange?.()};this.subscribe=(e,t,s)=>{const n={execute:e,complete:t,error:s};const i=this.subscribers;i.add(n);this.onsubscriberschange?.();const o=a(()=>{if(i.remove(n))this.onsubscriberschange?.()},\"unSubscribe\");const c=a(l=>{l.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.queuingSubscribe=(e,t,s)=>{if(this.ended)throw new Error(\"event completed\");const n={execute:e,complete:t,error:s};const i=this.queued;i.add(n);const o=a(()=>{i.remove(n)},\"unSubscribe\");const c=a(l=>{l.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.once=(e,t,s)=>{const n=this.subscribe((...i)=>{n.unSubscribe();e(...i)},t,s)};this.watch=(e,t)=>new Promise((s,n)=>{const i=t&&setTimeout(()=>{n(\"Event watch timeout\")},t);const{unSubscribe:o}=this.subscribe((...c)=>{const l=e(...c);if(l){if(i)clearTimeout(i);o();s(c)}})});this.asPromise=e=>new Promise((t,s)=>{const n=e&&setTimeout(()=>{s(\"Event asPromise timeout\")},e);this.once((...i)=>{if(n)clearTimeout(n);t(i)},()=>{if(n)clearTimeout(n);t([])},i=>{if(n)clearTimeout(n);s(i)})})}pipe(e){this.subscribe((...t)=>{e.execute(...t)})}get returnTrigger(){const{execute:e,error:t,complete:s}=this;return{execute:e,error:t,complete:s}}get returnListener(){const{subscribe:e,once:t,asPromise:s}=this;return{subscribe:e,once:t,asPromise:s}}get length(){return this.subscribers.size}};var hu=class{static{a(this,\"EventDisposer\")}constructor(){this._disposer=[]}push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e());this._disposer=[]}};var Jw=require(\"node:dgram\");var Up=Ye(require(\"node:net\"),1);var Zw=Ye(require(\"node:tls\"),1);var Qw=require(\"node:net\");var kr=P(\"webrtc/common/transport\");var cI=8e3;var Yw=4*1024*1024;function lI(r){try{if(r.getRecvBufferSize()<Yw)r.setRecvBufferSize(Yw)}catch(e){kr(\"the receive buffer cannot grow\",e)}}a(lI,\"growReceiveBuffer\");function uI(r,e){return r===e||r[1]===e[1]&&r[0]===e[0]}a(uI,\"sameAddress\");var en=class r{static{a(this,\"UdpTransport\")}constructor(e,t={}){this.socketType=e;this.options=t;this.type=\"udp\";this.onData=()=>{};this.closed=false;this.send=async(s,n)=>{const i=this.connected;if(i){if(!n||uI(n,i)){this.socket.send(s)}else{kr(\"not sent to an address other than the connected one\",n)}return}if(this.waiting){this.waiting.push([s,n]);return}if(n&&!Up.isIP(n[0])){return new Promise((o,c)=>{this.socket.send(s,n[1],n[0],l=>{if(l){kr(\"send error\",n,s);c(l)}else{o()}})})}else{n=n??[this.rinfo.address,this.rinfo.port];this.socket.send(s,n[1],n[0])}};this.close=()=>new Promise(s=>{this.closed=true;this.connectOnReceive=void 0;this.connecting=void 0;this.connected=void 0;this.waiting=void 0;this.socket.once(\"close\",s);try{this.socket.close()}catch(n){s()}});this.socket=(0,Jw.createSocket)(e);this.socket.on(\"message\",(s,n)=>{if(Qs(n.family)===6){[n.address]=n.address.split(\"%\")}this.rinfo=n;if(this.connectOnReceive&&s[0]>3&&n.port===this.connectOnReceive[1]&&n.address===this.connectOnReceive[0])this.connectNow(this.connectOnReceive);try{this.onData(s,[n.address,n.port])}catch(i){kr(\"onData error\",i)}})}static async init(e,t={}){const s=new r(e,t);await s.init();return s}async init(){const e=uu(this.socketType,this.options.interfaceAddresses);if(this.options.port){this.socket.bind({port:this.options.port,address:e})}else if(this.options.portRange){const t=await Xw(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else{this.socket.bind({port:await fu(this.socketType,this.options.interfaceAddresses),address:e})}await new Promise((t,s)=>{const n=a(i=>s(i),\"failed\");this.socket.once(\"error\",n);this.socket.once(\"listening\",()=>{this.socket.off(\"error\",n);t()})});this.socket.on(\"error\",t=>kr(\"socket error\",t));lI(this.socket)}connectTo(e){if(this.closed||this.connected||this.waiting||!Up.isIP(e[0]))return;this.connectOnReceive=e}disconnect(){this.connectOnReceive=void 0;this.connecting=void 0;if(!this.connected)return;this.connected=void 0;try{this.socket.disconnect()}catch(e){kr(\"disconnect\",e)}}connectNow(e){this.connectOnReceive=void 0;this.connecting=e;const t=[];this.waiting=t;const s=a(n=>{if(this.waiting===t)this.waiting=void 0;const i=this.connecting===e;if(i)this.connecting=void 0;if(this.closed)return;if(n){kr(\"connect\",e,n)}else if(i){this.connected=e}else{this.socket.disconnect()}for(const[o,c]of t)this.send(o,c).catch(l=>kr(\"send\",l))},\"done\");try{this.socket.connect(e[1],e[0],s)}catch(n){s(n)}}get address(){return this.socket.address()}get addressFamily(){return this.socketType===\"udp6\"?6:4}get host(){return this.socket.address().address}get port(){return this.socket.address().port}};var Ba=class r{static{a(this,\"TcpTransport\")}constructor(e,t={}){this.type=\"tcp\";this.send=async(s,n)=>{await this.stream.send(s,n)};this.close=async()=>{await this.stream.close()};this.stream=new pu(\"tcp\",()=>(0,Qw.connect)({port:e[1],host:e[0]}),void 0,t.connectTimeoutMs)}static async init(e,t={}){const s=new r(e,t);try{await s.init();return s}catch(n){await s.close();throw n}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var Ua=class r{static{a(this,\"TlsTransport\")}constructor(e,t={},s={}){this.type=\"tls\";this.send=async(n,i)=>{await this.stream.send(n,i)};this.close=async()=>{await this.stream.close()};this.stream=new pu(\"tls\",()=>Zw.connect({...t,host:e[0],port:e[1]}),void 0,s.connectTimeoutMs)}static async init(e,t={},s={}){const n=new r(e,t,s);try{await n.init();return n}catch(i){await n.close();throw i}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var pu=class{static{a(this,\"StreamTransport\")}constructor(e,t,s=e===\"tls\"?\"secureConnect\":\"connect\",n=cI){this.createClient=t;this.connectEvent=s;this.connectTimeoutMs=n;this.onData=()=>{};this.closed=false;this.send=async(i,o)=>{void o;await this.connecting;await new Promise((c,l)=>{this.client.write(i,u=>{if(u){l(u);return}c()})})};this.close=async()=>{this.closed=true;this.rejectConnecting?.(new Error(`${this.type} transport closed`));this.client?.destroy()};this.type=e;this.connect()}connect(){if(this.closed){return}if(this.client){this.client.destroy()}const e=this.createClient();this.client=e;this.connecting=new Promise((t,s)=>{let n=false;const i=a(u=>{if(n)return;n=true;clearTimeout(l);e.off(this.connectEvent,o);e.off(\"error\",c);this.rejectConnecting=void 0;u?s(u):t()},\"settle\");const o=a(()=>{i()},\"onConnect\");const c=a(u=>{this.closed=true;i(u);e.destroy()},\"onConnectError\");const l=setTimeout(()=>{this.closed=true;i(new Error(`${this.type} connect timed out after ${this.connectTimeoutMs}ms`));e.destroy()},this.connectTimeoutMs);this.rejectConnecting=u=>i(u);e.once(this.connectEvent,o);e.once(\"error\",c)});e.on(\"data\",t=>{this.onData(t,this.remoteAddress)});e.on(\"error\",t=>{kr(`${this.type} transport error`,t)})}async waitForConnect(){await this.connecting}get address(){return{}}get remoteAddress(){const{remoteAddress:e,remotePort:t}=this.client;if(!e||!t){return void 0}return[fI(e),t]}};function fI(r){return r.split(\"%\")[0]}a(fI,\"stripZoneId\");var q={};__(q,{BinaryReader:()=>gu,BinaryWriter:()=>$a,NotEnoughDataError:()=>mu,decode:()=>hI,encode:()=>dI,types:()=>yI});var mu=class extends Error{static{a(this,\"NotEnoughDataError\")}constructor(e,t){super(`requested ${e} bytes but only ${t} available`);this.name=\"NotEnoughDataError\"}};var gu=class{static{a(this,\"BinaryReader\")}constructor(e){this.buf=e;this.offset=0}get length(){return this.buf.length-this.offset}get bytes(){return this.offset}readBuffer(e){this.assertSize(e);const t=this.buf.subarray(this.offset,this.offset+e);this.offset+=e;return t}readUIntBE(e){this.assertSize(e);const t=this.buf.readUIntBE(this.offset,e);this.offset+=e;return t}assertSize(e){if(e>this.length){throw new mu(e,this.length)}}};var $a=class{static{a(this,\"BinaryWriter\")}constructor(){this.chunks=[];this.written=0}get bytes(){return this.written}writeBuffer(e){this.chunks.push(e);this.written+=e.length}writeUIntBE(e,t){const s=Buffer.allocUnsafe(t);switch(t){case 1:s.writeUInt8(e,0);break;case 2:s.writeUInt16BE(e,0);break;case 4:s.writeUInt32BE(e,0);break;default:s.writeUIntBE(e,0,t)}this.writeBuffer(s)}toBuffer(){return Buffer.concat(this.chunks,this.written)}};var tE=a(r=>typeof r===\"object\"&&r!==null,\"isObject\");var ut=a(r=>tE(r)&&typeof r.encode===\"function\"&&typeof r.decode===\"function\",\"isType\");var rE=a(r=>{if(!tE(r))return false;const e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},\"isPlainObject\");var sE=a(()=>({node:void 0,current:void 0}),\"createContext\");var eE=a(r=>({node:r.node,current:r.current}),\"cloneContext\");var nE=a((r,e)=>{if(!rE(r)){throw new TypeError(e)}},\"assertSchema\");var iE=a((r,e,t,s)=>{if(ut(e)){e.encode(r,t,s)}else{oE(r,e,t,s)}},\"encodeCommon\");var oE=a((r,e,t,s)=>{nE(e,\"Argument `schema` should be a plain object.\");if(s.node===void 0){s.node=r}s.current=r;for(const n of Object.keys(e)){const i=e[n];const o=r[n];if(ut(i)){i.encode(o,t,s)}else{oE(o,i,t,s);s.current=r}}},\"encodeSchema\");var jp=a((r,e,t)=>{if(ut(e)){return e.decode(r,t)}return aE(r,e,t)},\"decodeCommon\");var aE=a((r,e,t)=>{nE(e,\"Argument #2 should be a plain object.\");const s=Object.create(null);if(t.node===void 0){t.node=s}t.current=s;for(const n of Object.keys(e)){const i=e[n];if(ut(i)){s[n]=i.decode(r,t)}else{s[n]=aE(r,i,t);t.current=s}}return s},\"decodeSchema\");function dI(r,e){const t=new $a;iE(r,e,t,sE());return t.toBuffer()}a(dI,\"encode\");function hI(r,e){return jp(new gu(r),e,sE())}a(hI,\"decode\");var ja=a(r=>({encode:a((e,t)=>t.writeUIntBE(e,r),\"encode\"),decode:a(e=>e.readUIntBE(r),\"decode\")}),\"createUIntBE\");var $p=a(r=>{if(typeof r!==\"number\"&&!ut(r)&&typeof r!==\"function\"){throw new TypeError(\"Unknown type of argument #1.\")}},\"assertLengthSpec\");var Fa=a((r,e,t)=>{if(r!==e){throw new Error(`${t} required length ${r} instead of ${e}`)}},\"checkLength\");var tn=a((r,e)=>{if(typeof r!==\"number\"){throw new TypeError(e)}},\"checkLengthType\");function pI(r){$p(r);const e=\"Length of a buffer should be a number.\";return{encode(t,s,n){if(!Buffer.isBuffer(t)){throw new TypeError(\"Argument 1 should be a Buffer or a BinaryStream.\")}if(typeof r===\"number\"){Fa(r,t.length,\"Buffer\")}else if(ut(r)){r.encode(t.length,s,n)}else{const i=r(n);tn(i,e);Fa(i,t.length,\"Buffer\")}s.writeBuffer(t)},decode(t,s){let n;if(typeof r===\"number\"){n=r}else if(ut(r)){n=r.decode(t,s)}else{n=r(s)}tn(n,e);return t.readBuffer(n)}}}a(pI,\"buffer\");function mI(r,e,t=\"count\"){if(!ut(r)&&!rE(r)){throw new TypeError(\"Argument #1 should be a valid type.\")}$p(e);const s=t===\"bytes\";const n=\"Length of an array should be a number.\";return{encode(i,o,c){if(!Array.isArray(i)){throw new TypeError(\"Argument #1 should be an Array.\")}const l=eE(c);let u;if(typeof e===\"number\"){u=e}else if(ut(e)){u=i.length}else{u=e(l);tn(u,n)}const f=new $a;for(const d of i){iE(d,r,f,l)}if(s){if(ut(e)){u=f.bytes}Fa(f.bytes,u,\"Argument #1\")}else{Fa(u,i.length,\"Argument #1\")}if(ut(e)){e.encode(u,o,l)}o.writeBuffer(f.toBuffer())},decode(i,o){const c=eE(o);let l;if(typeof e===\"number\"){l=e}else if(ut(e)){l=e.decode(i,c)}else{l=e(c)}tn(l,n);const u=[];if(s){const f=i.bytes;let d=0;while(d<l){u.push(jp(i,r,c));d=i.bytes-f}if(d>l){throw new Error(\"Incorrect length of an array.\")}}else{for(let f=0;f<l;f++){u.push(jp(i,r,c))}}return u}}}a(mI,\"array\");function gI(r,e=\"ascii\"){if(!Buffer.isEncoding(e)){throw new Error(\"Argument #2 should be an encoding name.\")}$p(r);const t=\"Length of a buffer should be a number.\";return{encode(s,n,i){const o=Buffer.from(s.toString(),e);if(typeof r===\"number\"){if(o.length!==r){throw new Error(`Size of string should be ${r} in bytes.`)}}else if(ut(r)){r.encode(o.length,n,i)}else{const c=r(i);tn(c,t);Fa(c,o.length,\"Buffer\")}n.writeBuffer(o)},decode(s,n){let i;if(typeof r===\"number\"){i=r}else if(ut(r)){i=r.decode(s,n);tn(i,\"Size of a string should be a number.\")}else{i=r(n);tn(i,t)}return s.readBuffer(i).toString(e)}}}a(gI,\"string\");var yI={uint8:ja(1),uint16be:ja(2),uint24be:ja(3),uint32be:ja(4),uint48be:ja(6),buffer:pI,array:mI,string:gI};var Ha=class{static{a(this,\"Deque\")}#e=new Array(16);#t=0;#r=0;get length(){return this.#r}push(e){if(this.#r===this.#e.length)this.#s();this.#e[this.#t+this.#r&this.#e.length-1]=e;this.#r++}unshift(e){if(this.#r===this.#e.length)this.#s();this.#t=this.#t-1&this.#e.length-1;this.#e[this.#t]=e;this.#r++}shift(){if(!this.#r)return void 0;const e=this.#e[this.#t];this.#e[this.#t]=void 0;this.#t=this.#t+1&this.#e.length-1;this.#r--;return e}at(e){const t=e<0?this.#r+e:e;if(t<0||t>=this.#r)return void 0;return this.#e[this.#t+t&this.#e.length-1]}findIndex(e){for(let t=0;t<this.#r;t++){if(e(this.#e[this.#t+t&this.#e.length-1]))return t}return-1}clear(){this.#e=new Array(16);this.#t=0;this.#r=0}*[Symbol.iterator](){for(let e=0;e<this.#r;e++)yield this.#e[this.#t+e&this.#e.length-1]}#s(){const e=new Array(this.#e.length*2);for(let t=0;t<this.#r;t++)e[t]=this.#e[this.#t+t&this.#e.length-1];this.#e=e;this.#t=0}};var cE=require(\"node:events\");var a3=P(\"webrtc/peer/helper\");function Fp(r){return r.map((e,t)=>[t,e])}a(Fp,\"enumerate\");function yr(r,e){const t=r.split(e);return[t[0],t.slice(1).join(e)]}a(yr,\"divide\");var kt=class extends cE.EventEmitter{static{a(this,\"EventTarget\")}constructor(){super(...arguments);this.addEventListener=(e,t,s)=>{if(typeof s===\"object\"&&s?.once){this.once(e,t);return}this.addListener(e,t)};this.removeEventListener=(e,t)=>{this.removeListener(e,t)};this.dispatchEvent=e=>this.emit(e.type,e)}emit(e,...t){if(typeof e!==\"string\"){return super.emit(e,...t)}if(t.length===0){return super.emit(e,new Event(e))}const[s,...n]=t;if(s&&typeof s===\"object\"&&!(\"type\"in s)){try{Object.defineProperty(s,\"type\",{configurable:true,enumerable:true,value:e})}catch{return super.emit(e,{type:e,...s},...n)}}return super.emit(e,s,...n)}};var Si=1;var Cs=7;var lE=a(r=>{switch(r){case Si:case Cs:return 16}},\"keyLength\");var uE=a(r=>{switch(r){case Si:return 14;case Cs:return 12}},\"saltLength\");function fE(r){if(!Number.isInteger(r)||r<0||!Number.isSafeInteger(r)){throw new Error(\"LEB128 encode requires a non-negative safe integer\")}const e=[];let t=r;do{let s=t&127;t=Math.floor(t/128);if(t!==0){s|=128}e.push(s)}while(t!==0);return Buffer.from(e)}a(fE,\"leb128encode\");var bI=P(\"webrtc/rtp/codec/av1\");var Hp=class r{static{a(this,\"AV1RtpPayload\")}constructor(){this.obu_or_fragment=[]}static{this.deSerialize=e=>{const t=new r;let s=0;t.zBit_RtpStartsWithFragment=V(e[s],0);t.yBit_RtpEndsWithFragment=V(e[s],1);t.w_RtpNumObus=V(e[s],2,2);t.nBit_RtpStartsNewCodedVideoSequence=V(e[s],4);s++;if(t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment){throw new Error}[...Array(t.w_RtpNumObus-1).keys()].forEach(i=>{const[o,c]=SI(e.subarray(s));const l=s+c;const u=l+o;let f=false;if(t.zBit_RtpStartsWithFragment&&i===0){f=true}t.obu_or_fragment.push({data:e.subarray(l,u),isFragment:f});s+=c+o});let n=false;if(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment){n=true}t.obu_or_fragment.push({data:e.subarray(s),isFragment:n});return t}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){const t=[];const s=e.flatMap(c=>c.obu_or_fragment).reduce((c,l,u)=>{c[u]=l;return c},{});const n=Object.keys(s).length;for(const c of Object.keys(s).map(Number)){const l=s[c];if(!l)continue;const{data:u,isFragment:f}=l;if(f){let d=[];for(let h=c;h<n;h++){const p=s[h];if(p.isFragment){d.push(p.data);delete s[h]}else{break}}if(d.length<=1){bI(\"fragment lost, maybe packet lost\");d=[]}t.push(Buffer.concat(d))}else{t.push(u)}}const i=t.map(c=>qp.deSerialize(c));const o=i.pop();return Buffer.concat([...i.map(c=>{c.obu_has_size_field=1;return c.serialize()}),o.serialize()])}};var qp=class r{static{a(this,\"AV1Obu\")}static deSerialize(e){const t=new r;let s=0;t.obu_forbidden_bit=V(e[s],0);t.obu_type=dE[V(e[s],1,4)];t.obu_extension_flag=V(e[s],5);t.obu_has_size_field=V(e[s],6);t.obu_reserved_1bit=V(e[s],7);s++;t.payload=e.subarray(s);return t}serialize(){const e=new Zs(8).set(this.obu_forbidden_bit).set(wI[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer;let t=Buffer.alloc(0);if(this.obu_has_size_field){t=fE(this.payload.length)}return Buffer.concat([e,t,this.payload])}};function SI(r){let e=0;let t=0;for(let s=0;s<8;s++){if(s>=r.length){throw new Error(\"LEB128 decode incomplete\")}const n=r.readUInt8(s);e+=(n&127)*128**s;t++;if(!(n&128)){if(!Number.isSafeInteger(e)){throw new Error(\"LEB128 value exceeds safe integer\")}return[e,t]}}throw new Error(\"LEB128 decode incomplete\")}a(SI,\"leb128decode\");var dE={0:\"Reserved\",1:\"OBU_SEQUENCE_HEADER\",2:\"OBU_TEMPORAL_DELIMITER\",3:\"OBU_FRAME_HEADER\",4:\"OBU_TILE_GROUP\",5:\"OBU_METADATA\",6:\"OBU_FRAME\",7:\"OBU_REDUNDANT_FRAME_HEADER\",8:\"OBU_TILE_LIST\",15:\"OBU_PADDING\"};var wI=Object.entries(dE).reduce((r,[e,t])=>{r[t]=Number(e);return r},{});var E3=Buffer.from([0,0,0,1]);function zp(r,e){const t=Buffer.alloc(e);r.copy(t);return t}a(zp,\"growBufferSize\");function wi(r){return Number.parseInt(r.toString(),10)}a(wi,\"Int\");function hE(r){const e=r[0];return e>127&&e<192}a(hE,\"isMedia\");var qa=4;var ze=class r{static{a(this,\"RtcpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.count=0;this.type=0;this.length=0;Object.assign(this,e)}static serialize(e,t,s,n){const i=new r({type:e,count:t,version:2,length:n});const o=i.serialize();return Buffer.concat([o,s])}serialize(){const e=new Or(8);e.set(2,0,this.version);if(this.padding)e.set(1,2,1);e.set(5,3,this.count);const t=he([1,1,2],[e.value,this.type,this.length]);return t}static deSerialize(e){const[t,s,n]=Pe(e,[1,1,2]);const i=V(t,0,2);const o=V(t,2,1)>0;const c=V(t,3,5);return new r({version:i,padding:o,count:c,type:s,length:n})}};var za=class r{static{a(this,\"FullIntraRequest\")}static{this.count=4}constructor(e={}){this.count=r.count;this.fir=[];Object.assign(this,e)}get length(){return this.serialize().length/4}static deSerialize(e){const[t,s]=Pe(e,[4,4]);const n=[];for(let i=8;i<e.length;i+=8){n.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]})}return new r({senderSsrc:t,mediaSsrc:s,fir:n})}serialize(){const e=he([4,4],[this.senderSsrc,this.mediaSsrc]);const t=Buffer.alloc(this.fir.length*8);this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{t.writeUInt32BE(s,i*8);t[i*8+4]=n});return Buffer.concat([e,t])}};var Pr=class r{static{a(this,\"PictureLossIndication\")}static{this.count=1}constructor(e={}){this.count=r.count;this.length=2;Object.assign(this,e)}static deSerialize(e){const[t,s]=Pe(e,[4,4]);return new r({senderSsrc:t,mediaSsrc:s})}serialize(){return he([4,4],[this.senderSsrc,this.mediaSsrc])}};var Nr=class r{static{a(this,\"ReceiverEstimatedMaxBitrate\")}static{this.count=15}constructor(e={}){this.count=r.count;this.uniqueID=\"REMB\";this.ssrcNum=0;this.ssrcFeedbacks=[];Object.assign(this,e)}static deSerialize(e){const[t,s,n,i,o]=Pe(e,[4,4,4,1,1]);const c=V(o,0,6);const l=(V(o,6,2)<<16)+(e[14]<<8)+e[15];const u=c>46?18446744073709551615n:BigInt(l)<<BigInt(c);const f=[];for(let d=16;d<e.length;d+=4){const h=e.slice(d).readUIntBE(0,4);f.push(h)}return new r({senderSsrc:t,mediaSsrc:s,uniqueID:he([4],[n]).toString(),ssrcNum:i,brExp:c,brMantissa:l,ssrcFeedbacks:f,bitrate:u})}serialize(){const e=Buffer.concat([he([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),he([1],[this.ssrcNum])]);const t=new Or(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);const s=Buffer.concat(this.ssrcFeedbacks.map(i=>he([4],[i])));const n=Buffer.concat([e,he([3],[t.value]),s]);this.length=n.length/4;return n}};var TI=P(\"webrtc/rtp/rtcp/psfb/index\");var Xt=class r{static{a(this,\"RtcpPayloadSpecificFeedback\")}static{this.type=206}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return ze.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let s;switch(t.count){case za.count:s=za.deSerialize(e);break;case Pr.count:s=Pr.deSerialize(e);break;case Nr.count:s=Nr.deSerialize(e);break;default:TI(\"unknown psfb packet\",t.count);break}return new r({feedback:s})}};var Yt=class r{static{a(this,\"RtcpRrPacket\")}static{this.type=201}constructor(e={}){this.ssrc=0;this.reports=[];this.type=r.type;Object.assign(this,e)}serialize(){let e=he([4],[this.ssrc]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return ze.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const[s]=Pe(e,[4]);let n=4;const i=[];for(let o=0;o<t;o++){i.push(rn.deSerialize(e.slice(n,n+24)));n+=24}return new r({ssrc:s,reports:i})}};var rn=class r{static{a(this,\"RtcpReceiverInfo\")}constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return he([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){const[t,s,n,i,o,c,l]=Pe(e,[4,1,3,4,4,4,4]);return new r({ssrc:t,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:c,dlsr:l})}};var yu=205;var Lr=class r{static{a(this,\"GenericNack\")}static{this.count=1}toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){this.count=r.count;this.lost=[];Object.assign(this,e);if(!this.header){this.header=new ze({type:yu,count:this.count,version:2})}}static deSerialize(e,t){const[s,n]=Pe(e,[4,4]);const i=[];for(let o=8;o<e.length;o+=4){const[c,l]=Pe(e.subarray(o),[2,2]);i.push(c);for(let u=0;u<16;u++){if(l>>u&1){i.push(c+u+1)}}}return new r({header:t,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){const e=he([4,4],[this.senderSsrc,this.mediaSourceSsrc]);const t=[];if(this.lost.length>0){let n=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{const c=o-n-1;if(c>=0&&c<16){i|=1<<c}else{t.push(he([2,2],[n,i]));n=o;i=0}});t.push(he([2,2],[n,i]))}const s=Buffer.concat([e,Buffer.concat(t)]);this.header.length=s.length/4;return Buffer.concat([this.header.serialize(),s])}};var xI=P(\"webrtc/rtp/rtcp/rtpfb/twcc\");var Mr=class r{static{a(this,\"TransportWideCC\")}static{this.count=15}constructor(e={}){this.count=r.count;this.length=2;this.packetChunks=[];this.recvDeltas=[];Object.assign(this,e);if(!this.header){this.header=new ze({type:205,count:this.count,version:2})}}static deSerialize(e,t){const[s,n,i,o,c,l]=Pe(e,[4,4,2,2,3,1]);const u=[];const f=[];let d=16;for(let p=0;p<o;){const m=V(e.slice(d,d+1)[0],0,1);let y;switch(m){case vs.TypeTCCRunLengthChunk:{const w=Ei.deSerialize(e.slice(d,d+2));y=w;const S=Math.min(o-p,w.runLength);if(w.packetStatus===Te.TypeTCCPacketReceivedSmallDelta||w.packetStatus===Te.TypeTCCPacketReceivedLargeDelta){for(let T=0;T<S;T++){f.push(new sn({type:w.packetStatus}))}}p+=S}break;case vs.TypeTCCStatusVectorChunk:{const w=Ga.deSerialize(e.slice(d,d+2));y=w;if(w.symbolSize===0){w.symbolList.forEach(S=>{if(S===Te.TypeTCCPacketReceivedSmallDelta){f.push(new sn({type:Te.TypeTCCPacketReceivedSmallDelta}))}})}if(w.symbolSize===1){w.symbolList.forEach(S=>{if(S===Te.TypeTCCPacketReceivedSmallDelta||S===Te.TypeTCCPacketReceivedLargeDelta){f.push(new sn({type:S}))}})}p+=w.symbolList.length}break}if(!y)throw new Error;d+=2;u.push(y)}let h=d;f.forEach(p=>{if(p.type===Te.TypeTCCPacketReceivedSmallDelta){p.deSerialize(e.slice(h,h+1));h++}if(p.type===Te.TypeTCCPacketReceivedLargeDelta){p.deSerialize(e.slice(h,h+2));h+=2}});return new r({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:c,fbPktCount:l,recvDeltas:f,packetChunks:u,header:t})}serialize(){const e=he([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]);const t=Buffer.concat(this.packetChunks.map(o=>o.serialize()));const s=Buffer.concat(this.recvDeltas.map(o=>{try{return o.serialize()}catch(c){xI(c?.message);return void 0}}).filter(o=>o));const n=Buffer.concat([e,t,s]);const i=n.length%4;this.header.padding=i!==0;if(i!==0){const o=Buffer.alloc(4-i);o[o.length-1]=o.length;this.header.length=(n.length+o.length)/4;return Buffer.concat([this.header.serialize(),n,o])}this.header.length=n.length/4;return Buffer.concat([this.header.serialize(),n])}get packetResults(){const e=[];for(const i of this.packetChunks){if(i instanceof Ei){for(let o=0;o<i.runLength;o++)e.push(i.packetStatus)}else{e.push(...i.symbolList)}}if(e.length>this.packetStatusCount)e.length=this.packetStatusCount;const t=[];let s=this.referenceTime*64e3;let n=0;e.forEach((i,o)=>{const c=new Gp({sequenceNumber:this.baseSequenceNumber+o&65535});if(i===Te.TypeTCCPacketReceivedSmallDelta||i===Te.TypeTCCPacketReceivedLargeDelta){const l=this.recvDeltas[n++];if(l){s+=l.delta;c.received=true;c.delta=l.delta;c.receivedAtMs=s/1e3}}t.push(c)});return t}};var Ei=class r{static{a(this,\"RunLengthChunk\")}constructor(e={}){Object.assign(this,e);this.type=vs.TypeTCCRunLengthChunk}static deSerialize(e){const t=V(e[0],1,2);const s=(V(e[0],3,5)<<8)+e[1];return new r({type:0,packetStatus:t,runLength:s})}serialize(){const e=new Zs(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer;return e}};var Ga=class r{static{a(this,\"StatusVectorChunk\")}constructor(e={}){this.symbolList=[];Object.assign(this,e)}static deSerialize(e){const t=vs.TypeTCCStatusVectorChunk;let s=V(e[0],1,1);const n=[];function i(o,c){for(let l=0;l<o;l++){c(l)}}a(i,\"range\");switch(s){case 0:i(6,o=>n.push(V(e[0],2+o,1)));i(8,o=>n.push(V(e[1],o,1)));break;case 1:i(3,o=>n.push(V(e[0],2+o*2,2)));i(4,o=>n.push(V(e[1],o*2,2)));break;default:s=(V(e[0],2,6)<<8)+e[1]}return new r({type:t,symbolSize:s,symbolList:n})}serialize(){const e=Buffer.alloc(2);const t=new Zs(16).set(1).set(this.symbolSize);const s=this.symbolSize===0?1:2;this.symbolList.forEach(n=>{t.set(n,s)});e.writeUInt16BE(t.value);return e}};var sn=class r{static{a(this,\"RecvDelta\")}constructor(e={}){this.parsed=false;Object.assign(this,e)}static deSerialize(e){let t;let s;if(e.length===1){t=Te.TypeTCCPacketReceivedSmallDelta;s=250*e[0]}else if(e.length===2){t=Te.TypeTCCPacketReceivedLargeDelta;s=250*e.readInt16BE()}if(t===void 0||s===void 0)throw new Error;return new r({type:t,delta:s})}deSerialize(e){const t=r.deSerialize(e);this.delta=t.delta}parseDelta(){this.delta=Math.floor(this.delta/250);if(this.delta<0||this.delta>255){if(this.delta>32767)this.delta=32767;if(this.delta<-32768)this.delta=-32768;if(!this.type)this.type=Te.TypeTCCPacketReceivedLargeDelta}else{if(!this.type)this.type=Te.TypeTCCPacketReceivedSmallDelta}this.parsed=true}serialize(){if(!this.parsed)this.parseDelta();if(this.type===Te.TypeTCCPacketReceivedSmallDelta){const e=Buffer.alloc(1);e.writeUInt8(this.delta);return e}else if(this.type===Te.TypeTCCPacketReceivedLargeDelta){const e=Buffer.alloc(2);e.writeInt16BE(this.delta);return e}throw new Error(\"errDeltaExceedLimit \"+this.delta+\" \"+this.type)}};var vs;(function(r){r[r[\"TypeTCCRunLengthChunk\"]=0]=\"TypeTCCRunLengthChunk\";r[r[\"TypeTCCStatusVectorChunk\"]=1]=\"TypeTCCStatusVectorChunk\";r[r[\"packetStatusChunkLength\"]=2]=\"packetStatusChunkLength\"})(vs||(vs={}));var Te;(function(r){r[r[\"TypeTCCPacketNotReceived\"]=0]=\"TypeTCCPacketNotReceived\";r[r[\"TypeTCCPacketReceivedSmallDelta\"]=1]=\"TypeTCCPacketReceivedSmallDelta\";r[r[\"TypeTCCPacketReceivedLargeDelta\"]=2]=\"TypeTCCPacketReceivedLargeDelta\";r[r[\"TypeTCCPacketReceivedWithoutDelta\"]=3]=\"TypeTCCPacketReceivedWithoutDelta\"})(Te||(Te={}));var Gp=class{static{a(this,\"PacketResult\")}constructor(e){this.sequenceNumber=0;this.delta=0;this.received=false;this.receivedAtMs=0;Object.assign(this,e)}};var RI=P(\"webrtc/rtp/rtcp/rtpfb/index\");var nt=class r{static{a(this,\"RtcpTransportLayerFeedback\")}static{this.type=yu}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return e}static deSerialize(e,t){let s;switch(t.count){case Lr.count:s=Lr.deSerialize(e,t);break;case Mr.count:s=Mr.deSerialize(e,t);break;default:RI(\"unknown rtpfb packet\",t.count);break}return new r({feedback:s,header:t})}};var Dr=class r{static{a(this,\"RtcpSourceDescriptionPacket\")}static{this.type=202}constructor(e){this.type=r.type;this.chunks=[];Object.assign(this,e)}get length(){let e=0;this.chunks.forEach(t=>e+=t.length);return e}serialize(){let e=Buffer.concat(this.chunks.map(t=>t.serialize()));while(e.length%4)e=Buffer.concat([e,Buffer.from([0])]);return ze.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){const s=[];for(let n=0;n<e.length;){const i=Ka.deSerialize(e.slice(n));s.push(i);n+=i.length}return new r({chunks:s})}};var Ka=class r{static{a(this,\"SourceDescriptionChunk\")}constructor(e={}){this.items=[];Object.assign(this,e)}get length(){let e=4;this.items.forEach(t=>e+=t.length);e+=1;e+=pE(e);return e}serialize(){const e=Buffer.concat([he([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);const t=Buffer.concat([e,Buffer.alloc(pE(e.length))]);return t}static deSerialize(e){const t=e.readUInt32BE();const s=[];for(let n=4;n<e.length;){const i=e[n];if(i===0)break;const o=Wa.deSerialize(e.slice(n));s.push(o);n+=o.length}return new r({source:t,items:s})}};var Wa=class r{static{a(this,\"SourceDescriptionItem\")}constructor(e){Object.assign(this,e)}get length(){return 1+1+Buffer.from(this.text).length}serialize(){const e=Buffer.from(this.text);return Buffer.concat([he([1,1],[this.type,e.length]),e])}static deSerialize(e){const t=e[0];const s=e[1];const n=e.slice(2,2+s).toString();return new r({type:t,text:n})}};function pE(r){if(r%4==0){return 0}return 4-r%4}a(pE,\"getPadding\");var Pt=class r{static{a(this,\"RtcpSrPacket\")}static{this.type=200}constructor(e){this.ssrc=0;this.reports=[];this.type=r.type;Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);e.writeUInt32BE(this.ssrc);e=Buffer.concat([e,this.senderInfo.serialize()]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return ze.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const s=e.readUInt32BE();const n=Va.deSerialize(e.subarray(4,24));let i=24;const o=[];for(let l=0;l<t;l++){o.push(rn.deSerialize(e.subarray(i,i+24)));i+=24}const c=new r({ssrc:s,senderInfo:n,reports:o});return c}};var Va=class r{static{a(this,\"RtcpSenderInfo\")}constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:_I(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return he([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){const[t,s,n,i]=Pe(e,[8,4,4,4]);return new r({ntpTimestamp:t,rtpTimestamp:s,packetCount:n,octetCount:i})}};var _I=a(r=>{const[e,t]=Pe(he([8],[r]),[4,4]);return Number(`${e}.${t}`)},\"ntpTime2Sec\");var CI=P(\"webrtc/rtp/rtcp/rtcp\");var bu=class{static{a(this,\"RtcpPacketConverter\")}static deSerialize(e){let t=0;const s=[];while(t<e.length){const n=ze.deSerialize(e.subarray(t,t+qa));t+=qa;let i=e.subarray(t,t+n.length*4);t+=n.length*4;if(n.padding){i=i.subarray(0,i.length-i.subarray(-1)[0])}try{switch(n.type){case Pt.type:s.push(Pt.deSerialize(i,n.count));break;case Yt.type:s.push(Yt.deSerialize(i,n.count));break;case Dr.type:s.push(Dr.deSerialize(i,n));break;case nt.type:s.push(nt.deSerialize(i,n));break;case Xt.type:s.push(Xt.deSerialize(i,n));break;default:break}}catch(o){CI(\"deSerialize RTCP\",o)}}return s}};function mE(r){return r.length>=2&&r[1]>=192&&r[1]<=208}a(mE,\"isRtcp\");var pe={sdesMid:\"urn:ietf:params:rtp-hdrext:sdes:mid\",sdesRTPStreamID:\"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\",repairedRtpStreamId:\"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\",transportWideCC:\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\",absSendTime:\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\",dependencyDescriptor:\"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension\",audioLevelIndication:\"urn:ietf:params:rtp-hdrext:ssrc-audio-level\",videoOrientation:\"urn:3gpp:video-orientation\"};function gE(r,e){return r.map(t=>{const s=e[t.id];if(!s){return{uri:\"unknown\",value:t.payload}}switch(s){case pe.sdesMid:case pe.sdesRTPStreamID:case pe.repairedRtpStreamId:return{uri:s,value:vI(t.payload)};case pe.transportWideCC:return{uri:s,value:AI(t.payload)};case pe.absSendTime:return{uri:s,value:II(t.payload)};case pe.audioLevelIndication:{return{uri:s,value:OI(t.payload)}}case pe.videoOrientation:return{uri:s,value:kI(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>{if(s)t[s.uri]=s.value;return t},{})}a(gE,\"rtpHeaderExtensionsParser\");function yE(r){return Buffer.from(r)}a(yE,\"serializeSdesMid\");function bE(r){return Buffer.from(r)}a(bE,\"serializeSdesRTPStreamID\");function SE(r){return Buffer.from(r)}a(SE,\"serializeRepairedRtpStreamId\");function Kp(r){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(r);return e}a(Kp,\"serializeTransportWideCC\");function vI(r){return r.toString()}a(vI,\"deserializeString\");function AI(r){return r.readUInt16BE()}a(AI,\"deserializeUint16BE\");function II(r){return Pe(r,[3])[0]}a(II,\"deserializeAbsSendTime\");function OI(r){const e=new mr(r);const t={v:e.readBits(1)===1,level:e.readBits(7)};return t}a(OI,\"deserializeAudioLevelIndication\");function kI(r){const e=new mr(r);e.readBits(4);const t={c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)};return t}a(kI,\"deserializeVideoOrientation\");var PI=P(\"packages/rtp/src/rtp/red/packet.ts\");var Ti=class r{static{a(this,\"Red\")}constructor(){this.blocks=[]}static deSerialize(e){const t=e instanceof ArrayBuffer?Buffer.from(e):e;const s=new r;let n=0;[s.header,n]=Su.deSerialize(t);s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:c})=>{if(i&&o){const l=t.subarray(n,n+i);s.blocks.push({block:l,blockPT:c,timestampOffset:o});n+=i}else{const l=t.subarray(n);s.blocks.push({block:l,blockPT:c})}});return s}serialize(){this.header=new Su;for(const{timestampOffset:t,blockPT:s,block:n}of this.blocks){if(t){this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:t})}else{this.header.fields.push({fBit:0,blockPT:s})}}let e=this.header.serialize();for(const{block:t}of this.blocks){e=Buffer.concat([e,t])}return e}};var Su=class r{static{a(this,\"RedHeader\")}constructor(){this.fields=[]}static deSerialize(e){let t=0;const s=new r;for(;;){const n={};s.fields.push(n);const i=new mr(e.subarray(t));n.fBit=i.readBits(1);n.blockPT=i.readBits(7);t++;if(n.fBit===0){break}n.timestampOffset=i.readBits(14);n.blockLength=i.readBits(10);t+=3}return[s,t]}serialize(){let e=Buffer.alloc(0);for(const t of this.fields){try{if(t.timestampOffset&&t.blockLength){const s=new mr(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,s.uint8Array])}else{const s=new mr(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){PI(s?.message)}}return e}};var wu=class{static{a(this,\"RedEncoder\")}constructor(e=1){this.distance=e;this.cache=[];this.cacheSize=10}push(e){this.cache.push(e);if(this.cache.length>this.cacheSize){this.cache.shift()}}build(){const e=new Ti;const t=this.cache.slice(-(this.distance+1));const s=t.pop();if(!s){return e}t.forEach(n=>{const i=gr(s.timestamp,-n.timestamp);if(i>NI){return}e.blocks.push({block:n.block,blockPT:n.blockPT,timestampOffset:i})});e.blocks.push({block:s.block,blockPT:s.blockPT});return e}};var NI=(1<<14)-1;var Eu=class{static{a(this,\"RedHandler\")}constructor(){this.size=150;this.sequenceNumbers=[]}push(e,t){const s=[];e.blocks.forEach(({blockPT:i,timestampOffset:o,block:c},l)=>{const u=$e(t.header.sequenceNumber,-(e.blocks.length-(l+1)));if(o){s.push(new Le(new Xe({timestamp:gr(t.header.timestamp,-o),payloadType:i,ssrc:t.header.ssrc,sequenceNumber:u,marker:true}),c))}else{s.push(new Le(new Xe({timestamp:t.header.timestamp,payloadType:i,ssrc:t.header.ssrc,sequenceNumber:u,marker:true}),c))}});const n=s.filter(i=>{if(this.sequenceNumbers.includes(i.header.sequenceNumber)){return false}else{if(this.sequenceNumbers.length>this.size){this.sequenceNumbers.shift()}this.sequenceNumbers.push(i.header.sequenceNumber);return true}});return n}};var nn={OneByte:48862,TwoByte:4096};var wE=2;var EE=4;var TE=8;var xE=12;var RE=4;var Xe=class r{static{a(this,\"RtpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.paddingSize=0;this.extension=false;this.marker=false;this.payloadOffset=0;this.payloadType=0;this.sequenceNumber=0;this.timestamp=0;this.ssrc=0;this.csrcLength=0;this.csrc=[];this.extensionProfile=nn.OneByte;this.extensions=[];Object.assign(this,e)}static deSerialize(e){const t=new r;let s=0;const n=e[s++];t.version=V(n,0,2);t.padding=V(n,2)>0;t.extension=V(n,3)>0;t.csrcLength=V(n,4,4);t.csrc=[...Array(t.csrcLength)].map(()=>{const o=e.readUInt32BE(s);s+=4;return o});s+=xE-1;const i=e[1];t.marker=V(i,0)>0;t.payloadType=V(i,1,7);t.sequenceNumber=e.readUInt16BE(wE);t.timestamp=e.readUInt32BE(EE);t.ssrc=e.readUInt32BE(TE);for(let o=0;o<t.csrc.length;o++){const c=xE+o*RE;t.csrc[o]=e.subarray(c).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(s).readUInt16BE();s+=2;const o=e.subarray(s).readUInt16BE()*4;t.extensionLength=o;s+=2;switch(t.extensionProfile){case nn.OneByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const l=e[s]>>4;const u=(e[s]&(e[s]^240))+1;s++;if(l===15){break}const f={id:l,payload:e.subarray(s,s+u)};t.extensions=[...t.extensions,f];s+=u}}break;case nn.TwoByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const l=e[s];s++;const u=e[s];s++;const f={id:l,payload:e.subarray(s,s+u)};t.extensions=[...t.extensions,f];s+=u}}break;default:{const c={id:0,payload:e.subarray(s,s+o)};t.extensions=[...t.extensions,c];s+=t.extensions[0].payload.length}break}}t.payloadOffset=s;if(t.padding){t.paddingSize=e[e.length-1]}return t}get serializeSize(){const{csrc:e,extensionProfile:t,extensions:s}=this;let n=12+e.length*RE;if(s.length>0||this.extension===true){let i=4;switch(t){case nn.OneByte:for(const o of s){i+=1+o.payload.length}break;case nn.TwoByte:for(const o of s){i+=2+o.payload.length}break;default:i+=s[0].payload.length}n+=Math.floor((i+3)/4)*4}return n}serialize(e){const t=Buffer.alloc(e);let s=0;const n=new Or(8);n.set(2,0,this.version);if(this.padding)n.set(1,2,1);if(this.extensions.length>0)this.extension=true;if(this.extension)n.set(1,3,1);n.set(4,4,this.csrc.length);t.writeUInt8(n.value,s++);const i=new Or(8);if(this.marker)i.set(1,0,1);i.set(7,1,this.payloadType);t.writeUInt8(i.value,s++);t.writeUInt16BE(this.sequenceNumber,wE);s+=2;t.writeUInt32BE(this.timestamp,EE);s+=4;t.writeUInt32BE(this.ssrc,TE);s+=4;for(const o of this.csrc){t.writeUInt32BE(o,s);s+=4}if(this.extension){const o=s;t.writeUInt16BE(this.extensionProfile,s);s+=4;const c=s;switch(this.extensionProfile){case nn.OneByte:for(const f of this.extensions){t.writeUInt8(f.id<<4|f.payload.length-1,s++);f.payload.copy(t,s);s+=f.payload.length}break;case nn.TwoByte:for(const f of this.extensions){t.writeUInt8(f.id,s++);t.writeUInt8(f.payload.length,s++);f.payload.copy(t,s);s+=f.payload.length}break;default:{const f=this.extensions[0].payload.length;if(f%4!=0){throw new Error}this.extensions[0].payload.copy(t,s);s+=f}}const l=s-c;const u=Math.trunc((l+3)/4)*4;t.writeUInt16BE(Math.trunc(u/4),o+2);for(let f=0;f<u-l;f++){t.writeUInt8(0,s);s++}}this.payloadOffset=s;return t}};var Le=class r{static{a(this,\"RtpPacket\")}constructor(e,t){this.header=e;this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new r(new Xe({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length);const{payloadOffset:t}=this.header;this.payload.copy(e,t);if(this.header.padding){const s=Buffer.alloc(this.header.paddingSize);s.writeUInt8(this.header.paddingSize,this.header.paddingSize-1);e=Buffer.concat([e,s])}return e}static deSerialize(e){const t=Xe.deSerialize(e);const s=new r(t,e.subarray(t.payloadOffset,e.length-t.paddingSize));return s}clear(){this.payload=null}};function _E(r,e,t){const s=new Le(new Xe({payloadType:e,marker:r.header.marker,sequenceNumber:r.payload.readUInt16BE(0),timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2));return s}a(_E,\"unwrapRtx\");function CE(r,e,t,s){const n=Buffer.allocUnsafe(2);n.writeUInt16BE(r.header.sequenceNumber,0);const i=new Le(new Xe({payloadType:e,marker:r.header.marker,sequenceNumber:t,timestamp:r.header.timestamp,ssrc:s,csrc:r.header.csrc,extensions:r.header.extensions}),Buffer.concat([n,r.payload]));return i}a(CE,\"wrapRtx\");var Ci=require(\"node:crypto\");var Jt=require(\"node:crypto\");var xi=class{static{a(this,\"CipherAesBase\")}constructor(e,t,s,n){this.srtpSessionKey=e;this.srtpSessionSalt=t;this.srtcpSessionKey=s;this.srtcpSessionSalt=n}encryptRtp(e,t,s){return Buffer.from([])}decryptRtp(e,t,s){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}};var Nt=class extends Error{static{a(this,\"SrtpAuthenticationError\")}constructor(e){super(e);this.name=\"SrtpAuthenticationError\"}};var vE=12;var LI=8;function Ri(r,e,t=\"Failed to authenticate SRTP packet\"){const s=r.length-e;Xa(r.length>=vE+e,t);const n=AE(()=>Xe.deSerialize(r.subarray(0,s)),t);n.paddingSize=0;Xa(n.payloadOffset>=vE&&n.payloadOffset<=s,t);return n}a(Ri,\"parseSrtpRtpHeader\");function Tu(r,e,t,s=\"Failed to authenticate SRTCP packet\"){Xa(r.length>=LI+e+t,s);return AE(()=>ze.deSerialize(r.subarray(0,qa)),s)}a(Tu,\"parseSrtcpHeader\");function Xa(r,e){if(!r){throw new Nt(e)}}a(Xa,\"assertAuthenticatedPacketLength\");function AE(r,e){try{return r()}catch{throw new Nt(e)}}a(AE,\"wrapAuthenticationError\");function xu(r,e,t=\"Failed to authenticate SRTP packet\"){if(!r.padding){r.paddingSize=0;return r}Xa(e.length>r.payloadOffset,t);const s=e[e.length-1];Xa(s>0&&s<=e.length-r.payloadOffset,t);r.paddingSize=s;return r}a(xu,\"finalizeSrtpRtpHeader\");var Ru=class extends xi{static{a(this,\"CipherAesCtr\")}constructor(e,t,s,n,i,o){super(e,t,s,n);this.srtpSessionAuthTag=i;this.srtcpSessionAuthTag=o;this.authTagLength=10}encryptRtp(e,t,s){const n=e.serialize(e.serializeSize);const i=this.generateCounter(e.sequenceNumber,s,e.ssrc,this.srtpSessionSalt);const o=(0,Jt.createCipheriv)(\"aes-128-ctr\",this.srtpSessionKey,i);const c=o.update(t);const l=this.generateSrtpAuthTag(s,n,c);return Buffer.concat([n,c,l])}decryptRtp(e,t,s=Ri(e,this.authTagLength)){const n=e.length-this.authTagLength;const i=e.subarray(0,n);const o=e.subarray(n);const c=this.generateSrtpAuthTag(t,i.subarray(0,s.payloadOffset),i.subarray(s.payloadOffset));OE(o,c,\"Failed to authenticate SRTP packet\");const l=this.generateCounter(s.sequenceNumber,t,s.ssrc,this.srtpSessionSalt);const u=(0,Jt.createDecipheriv)(\"aes-128-ctr\",this.srtpSessionKey,l);const f=i.subarray(s.payloadOffset);const d=u.update(f);const h=Buffer.concat([i.subarray(0,s.payloadOffset),d]);return[h,xu(s,h,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){let s=Buffer.from(e);const n=s.readUInt32BE(4);const i=this.generateCounter(t&65535,t>>16,n,this.srtcpSessionSalt);const o=(0,Jt.createCipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,i);const c=o.update(s.slice(8));c.copy(s,8);s=Buffer.concat([s,Buffer.alloc(4)]);s.writeUInt32BE(t,s.length-4);s[s.length-4]|=128;const l=this.generateSrtcpAuthTag(s);s=Buffer.concat([s,l]);return s}decryptRTCP(e){const t=Tu(e,this.authTagLength,IE);const s=e.length-(this.authTagLength+IE);const n=e.subarray(0,e.length-this.authTagLength);const i=e.subarray(e.length-this.authTagLength);const o=this.generateSrtcpAuthTag(n);OE(i,o,\"Failed to authenticate SRTCP packet\");const c=Buffer.from(e).slice(0,s);const l=e[s]>>>7;if(l===0)return[c,t];let u=e.readUInt32BE(s);u&=~(1<<31);const f=e.readUInt32BE(4);const d=this.generateCounter(u&65535,u>>16,f,this.srtcpSessionSalt);const h=(0,Jt.createDecipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,d);const p=h.update(c.subarray(8));p.copy(c,8);return[c,t]}generateSrtcpAuthTag(e){const t=(0,Jt.createHmac)(\"sha1\",this.srtcpSessionAuthTag);return t.update(e).digest().slice(0,10)}generateCounter(e,t,s,n){const i=Buffer.alloc(16);i.writeUInt32BE(s,4);i.writeUInt32BE(t,8);i.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let o=0;o<n.length;o++){i[o]^=n[o]}return i}generateSrtpAuthTag(e,...t){const s=(0,Jt.createHmac)(\"sha1\",this.srtpSessionAuthTag);const n=Buffer.alloc(4);n.writeUInt32BE(e);for(const i of t){s.update(i)}return s.update(n).digest().subarray(0,10)}};var IE=4;function OE(r,e,t){if(r.length!==e.length||!(0,Jt.timingSafeEqual)(r,e)){throw new Nt(t)}}a(OE,\"assertAuthTag\");var _i=require(\"node:crypto\");var _u=class extends xi{static{a(this,\"CipherAesGcm\")}constructor(e,t,s,n){super(e,t,s,n);this.aeadAuthTagLen=16;this.rtpIvWriter=Ma([2,4,4,2],true);this.rtcpIvWriter=Ma([2,4,2,4],true);this.aadWriter=Ma([4],true)}encryptRtp(e,t,s){const n=e.serialize(e.serializeSize);const i=this.rtpInitializationVector(e,s);const o=(0,_i.createCipheriv)(\"aes-128-gcm\",this.srtpSessionKey,i);o.setAAD(n);const c=o.update(t);o.final();const l=o.getAuthTag();const u=Buffer.concat([n,c,l]);return u}decryptRtp(e,t,s=Ri(e,this.aeadAuthTagLen)){const n=e.subarray(0,s.payloadOffset);const i=e.length-this.aeadAuthTagLen;const o=e.subarray(i);let c=Buffer.from([]);c=zp(c,e.length-this.aeadAuthTagLen);n.copy(c);const l=this.rtpInitializationVector(s,t);const u=e.slice(s.payloadOffset,i);const f=(0,_i.createDecipheriv)(\"aes-128-gcm\",this.srtpSessionKey,l);f.setAAD(n);f.setAuthTag(o);const d=f.update(u);PE(f,\"SRTP\");d.copy(c,s.payloadOffset);return[c,xu(s,c,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){const s=e.readUInt32BE(4);const n=e.length+this.aeadAuthTagLen;let i=Buffer.from([]);i=zp(i,n+Wp);e.slice(0,8).copy(i);const o=this.rtcpInitializationVector(s,t);const c=this.rtcpAdditionalAuthenticatedData(e,t);const l=(0,_i.createCipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,o);l.setAAD(c);const u=l.update(e.slice(8));l.final();u.copy(i,8);const f=l.getAuthTag();f.copy(i,8+u.length);c.slice(8,12).copy(i,n);return i}decryptRTCP(e){const t=Tu(e,this.aeadAuthTagLen,Wp);const s=e.length-Wp;const n=s-this.aeadAuthTagLen;const i=e.readUInt32BE(4);const o=e.readUInt32BE(s);const c=o>>>31===1;const l=o&~(kE<<24);const u=this.rtcpInitializationVector(i,l);const f=c?Buffer.concat([e.subarray(0,8),e.subarray(s)]):Buffer.concat([e.subarray(0,n),e.subarray(s)]);const d=c?e.slice(8,n):Buffer.alloc(0);const h=c?Buffer.alloc(n):Buffer.from(e.subarray(0,n));if(c){e.slice(0,8).copy(h)}const p=(0,_i.createDecipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,u);p.setAAD(f);p.setAuthTag(e.subarray(n,s));const m=p.update(d);PE(p,\"SRTCP\");if(c){m.copy(h,8)}return[h,t]}rtpInitializationVector(e,t){const s=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let n=0;n<s.length;n++){s[n]^=this.srtpSessionSalt[n]}return s}rtcpInitializationVector(e,t){const s=this.rtcpIvWriter([0,e,0,t]);for(let n=0;n<s.length;n++){s[n]^=this.srtcpSessionSalt[n]}return s}rtcpAdditionalAuthenticatedData(e,t){const s=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);s[8]|=kE;return s}};var Wp=4;var kE=128;function PE(r,e){try{r.final()}catch{throw new Nt(`Failed to authenticate ${e} packet`)}}a(PE,\"finalizeAuthenticatedDecryption\");function Cu(r,e){const t=(0,Ci.createCipheriv)(\"aes-128-ecb\",r,null);t.setAutoPadding(false);return Buffer.concat([t.update(e),t.final()])}a(Cu,\"aes128EcbEncrypt\");var vi=class{static{a(this,\"Context\")}constructor(e,t,s){this.masterKey=e;this.masterSalt=t;this.profile=s;this.srtpSSRCStates={};this.srtcpSSRCStates={};{const n=14-t.length;if(n>0){this.masterSalt=Buffer.concat([t,Buffer.alloc(n)])}}this.srtpSessionKey=this.generateSessionKey(0);this.srtpSessionSalt=this.generateSessionSalt(2);this.srtpSessionAuthTag=this.generateSessionAuthTag(1);this.srtpSessionAuth=(0,Ci.createHmac)(\"sha1\",this.srtpSessionAuthTag);this.srtcpSessionKey=this.generateSessionKey(3);this.srtcpSessionSalt=this.generateSessionSalt(5);this.srtcpSessionAuthTag=this.generateSessionAuthTag(4);this.srtcpSessionAuth=(0,Ci.createHmac)(\"sha1\",this.srtcpSessionAuthTag);switch(s){case Si:this.cipher=new Ru(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case Cs:this.cipher=new _u(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}generateSessionKey(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let n=s.length-1,i=t.length-1;n>=0;n--,i--){t[i]=t[i]^s[n]}t=Buffer.concat([t,Buffer.from([0,0])]);return Cu(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let n=s.length-1,i=t.length-1;n>=0;n--,i--){t[i]=t[i]^s[n]}t=Buffer.concat([t,Buffer.from([0,0])]);t=Cu(this.masterKey,t);return t.subarray(0,14)}generateSessionAuthTag(e){const t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let o=s.length-1,c=t.length-1;o>=0;o--,c--){t[c]=t[c]^s[o]}let n=Buffer.concat([t,Buffer.from([0,0])]);let i=Buffer.concat([t,Buffer.from([0,1])]);n=Cu(this.masterKey,n);i=Cu(this.masterKey,i);return Buffer.concat([n,i.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];if(t)return t;t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0};this.srtpSSRCStates[e]=t;return t}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];if(t)return t;t={srtcpIndex:0,ssrc:e};this.srtcpSSRCStates[e]=t;return t}updateRolloverCount(e,t){if(!t.rolloverHasProcessed){t.rolloverHasProcessed=true}else if(e===0){if(t.lastSequenceNumber>Ya){t.rolloverCounter++}}else if(t.lastSequenceNumber<Ya&&e>NE-Ya){if(t.rolloverCounter>0){t.rolloverCounter--}}else if(e<Ya&&t.lastSequenceNumber>NE-Ya){t.rolloverCounter++}t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=(0,Ci.createHmac)(\"sha1\",this.srtpSessionAuthTag);const s=Buffer.alloc(4);s.writeUInt32BE(t);return this.srtpSessionAuth.update(e).update(s).digest().slice(0,10)}index(e){const t=this.srtcpSSRCStates[e];if(!t){return 0}return t.srtcpIndex}setIndex(e,t){const s=this.getSrtcpSsrcState(e);s.srtcpIndex=t%2147483647}};var Ya=100;var NE=65535;var vu=class extends vi{static{a(this,\"SrtcpContext\")}constructor(e,t,s){super(e,t,s)}encryptRTCP(e){const t=e.readUInt32BE(4);const s=this.getSrtcpSsrcState(t);s.srtcpIndex++;if(s.srtcpIndex>>MI){s.srtcpIndex=0}const n=this.cipher.encryptRTCP(e,s.srtcpIndex);return n}decryptRTCP(e){const t=this.cipher.decryptRTCP(e);return t}};var MI=2147483647;var Ai=class{static{a(this,\"Session\")}constructor(e){this.ContextCls=e}start(e,t,s,n,i){this.localContext=new this.ContextCls(e,t,i);this.remoteContext=new this.ContextCls(s,n,i)}};var Au=class extends Ai{static{a(this,\"SrtcpSession\")}constructor(e){super(vu);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRTCP(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e){const t=this.localContext.encryptRTCP(e);return t}};var Iu=class extends vi{static{a(this,\"SrtpContext\")}constructor(e,t,s){super(e,t,s)}encryptRtp(e,t){const s=this.getSrtpSsrcState(t.ssrc);this.updateRolloverCount(t.sequenceNumber,s);const n=this.cipher.encryptRtp(t,e,s.rolloverCounter);return n}decryptRtp(e){const t=Ri(e,this.rtpAuthTagLength);const s=this.srtpSSRCStates[t.ssrc];const n=s?{...s}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,n);const i=this.cipher.decryptRtp(e,n.rolloverCounter,t);if(s){Object.assign(s,n)}else{this.srtpSSRCStates[t.ssrc]=n}return i}get rtpAuthTagLength(){return this.profile===Cs?16:10}};var Ou=class extends Ai{static{a(this,\"SrtpSession\")}constructor(e){super(Iu);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRtp(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e,t){return this.localContext.encryptRtp(e,t)}};var ku=new WeakMap;var Pu=new WeakSet;function DI(r,e){Pu.add(r);if(e==void 0)ku.delete(r);else ku.set(r,e)}a(DI,\"setTrackSourceCodecs\");function br(r){return r==void 0?void 0:ku.get(r)}a(br,\"getTrackSourceCodecs\");function on(r){if(Pu.has(r))return;Pu.add(r);if(r.codec!=void 0){ku.set(r,[r.codec])}}a(on,\"captureTrackSourceCodecs\");var Vp=class{static{a(this,\"TrackBroadcastSource\")}constructor(){this.tracks=new Set;this.upstreamStops=new Set}attach(e){this.tracks.add(e)}detach(e){this.tracks.delete(e);if(this.tracks.size>0){return}for(const t of[...this.upstreamStops]){t()}this.upstreamStops.clear()}addUpstreamStop(e){const t=a(()=>{this.upstreamStops.delete(t);e()},\"once\");this.upstreamStops.add(t)}deliverRtp(e,t){const s=[...this.tracks].filter(n=>!n.stopped);for(const n of s){n.applyIncomingRtp(e.clone(),t)}}deliverRtcp(e){for(const t of this.tracks){if(!t.stopped){t.onReceiveRtcp.execute(e)}}}deliverSourceChanged(e){for(const t of this.tracks){if(!t.stopped){t.onSourceChanged.execute(e)}}}stopAllTracks(){for(const e of[...this.tracks]){e.stop()}}};var Zt=class r extends kt{static{a(this,\"MediaStreamTrack\")}constructor(e){super();this.uuid=(0,Xp.randomUUID)().toString();this.remote=false;this.enabled=true;this.onReceiveRtp=new O;this.onReceiveRtcp=new O;this.onSourceChanged=new O;this.stopped=false;this.muted=true;this.stop=()=>{if(this.stopped){return}this.stopped=true;this.muted=true;this.onReceiveRtp.complete();this.emit(\"ended\");this.broadcastSource.detach(this)};this.writeRtp=s=>{if(this.remote){throw new Error(\"this is remoteTrack\")}const n=Buffer.isBuffer(s)?Le.deSerialize(s):s.clone();n.header.payloadType=this.codec?.payloadType??n.header.payloadType;this.broadcastSource.deliverRtp(n)};this.writeRtcp=s=>{this.broadcastSource.deliverRtcp(s)};const t=e.broadcastSource;Object.assign(this,e);this.id??=this.uuid;this.broadcastSource=t??new Vp;if(!this.stopped){this.broadcastSource.attach(this)}this.onReceiveRtp.subscribe(s=>{this.muted=false;this.header=s.header});this.label=`${this.remote?\"remote\":\"local\"} ${this.kind}`}get readyState(){return this.stopped?\"ended\":\"live\"}notifySourceChanged(e){this.broadcastSource.deliverSourceChanged(e)}applyIncomingRtp(e,t){if(this.stopped){return}this.onReceiveRtp.execute(e,t)}bindUpstreamStop(e){this.broadcastSource.addUpstreamStop(e)}stopMediaSource(){this.broadcastSource.stopAllTracks()}clone(){const e=new r({kind:this.kind,remote:this.remote,enabled:this.enabled,muted:this.muted,stopped:this.stopped,codec:this.codec,ssrc:this.ssrc,rid:this.rid,header:this.header,broadcastSource:this.broadcastSource});if(Pu.has(this)){DI(e,br(this))}else{on(e)}return e}};var Br=class r{static{a(this,\"MediaStream\")}constructor(e={}){this.tracks=[];if(Array.isArray(e)){this.tracks=e}else{Object.assign(this,e)}this.id??=(0,Xp.randomUUID)().toString()}addTrack(e){e.streamId=this.id;this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e);if(e.streamId===this.id){e.streamId=void 0}}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===\"audio\")}getVideoTracks(){return this.tracks.filter(e=>e.kind===\"video\")}getTrackById(e){return this.tracks.find(t=>t.id===e)}get active(){return this.tracks.some(e=>!e.stopped)}clone(){const e=new r;for(const t of this.tracks){e.addTrack(t.clone())}return e}};var Ja=a(()=>({type:\"nack\"}),\"useNACK\");var an=a(()=>({type:\"nack\",parameter:\"pli\"}),\"usePLI\");var Za=a(()=>({type:\"goog-remb\"}),\"useREMB\");var Nu=a(()=>({type:\"transport-cc\"}),\"useTWCC\");var ft=class{static{a(this,\"RTCRtpCodecParameters\")}constructor(e){this.rtcpFeedback=[];this.direction=\"all\";Object.assign(this,e)}get name(){return this.mimeType.split(\"/\")[1]}get contentType(){return this.mimeType.split(\"/\")[0]}get str(){let e=`${this.name}/${this.clockRate}`;if(this.channels===2)e+=\"/2\";return e}};var Qt=class{static{a(this,\"RTCRtpHeaderExtensionParameters\")}constructor(e){Object.assign(this,e)}};var Lu=class{static{a(this,\"RTCRtcpFeedback\")}constructor(e={}){Object.assign(this,e)}};var Mu=class{static{a(this,\"RTCRtpRtxParameters\")}constructor(e={}){Object.assign(this,e)}};var Du=class{static{a(this,\"RTCRtpCodingParameters\")}constructor(e){Object.assign(this,e)}};var Ii=class{static{a(this,\"RTCRtpSimulcastParameters\")}constructor(e){Object.assign(this,e)}};var Yp=a((r={})=>new ft({mimeType:\"video/h264\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],parameters:\"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1\",...r}),\"useH264\");var Bu=a((r={})=>new ft({mimeType:\"video/VP8\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],...r}),\"useVP8\");var Jp=a((r={})=>new ft({mimeType:\"video/VP9\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],...r}),\"useVP9\");var BI=a((r={})=>new ft({mimeType:\"video/AV1X\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],...r}),\"useAV1X\");var Uu=a((r={})=>new ft({mimeType:\"audio/OPUS\",clockRate:48e3,channels:2,...r}),\"useOPUS\");var ju=a((r={})=>new ft({mimeType:\"audio/PCMU\",clockRate:8e3,channels:1,payloadType:0,...r}),\"usePCMU\");function LE(){return{audio:[Uu(),ju()],video:[Bu()]}}a(LE,\"defaultCodecs\");function ME(r){return new ft({mimeType:r.mimeType,clockRate:r.clockRate,...r.channels!=void 0?{channels:r.channels}:{},...r.payloadType!=void 0?{payloadType:r.payloadType}:{},rtcpFeedback:r.rtcpFeedback.map(e=>({...e})),...r.parameters!=void 0?{parameters:r.parameters}:{},direction:r.direction})}a(ME,\"cloneCodecParameters\");var DE=[BI(),Jp(),Bu(),Yp(),Uu(),ju()].map(r=>r.mimeType);var rW=DE.filter(r=>r.toLowerCase().startsWith(\"video/\"));var sW=DE.filter(r=>r.toLowerCase().startsWith(\"audio/\"));var UI={\"audio/opus\":a(()=>Uu(),\"audio/opus\"),\"audio/pcmu\":a(()=>ju(),\"audio/pcmu\"),\"video/vp8\":a(()=>Bu(),\"video/vp8\"),\"video/vp9\":a(()=>Jp(),\"video/vp9\"),\"video/h264\":a(()=>Yp(),\"video/h264\")};var $u=[\"audio/opus\",\"audio/PCMU\",\"video/VP8\",\"video/VP9\",\"video/H264\"];var BE=[\"audio/opus\",\"audio/PCMU\",\"video/VP8\",\"video/H264\",\"video/VP9\"];function UE(r){return $u.find(e=>e.toLowerCase()===r.toLowerCase())??r}a(UE,\"canonicalCodec\");function Zp(r){const e=UI[r.toLowerCase()];if(!e)throw new TypeError(`The codec ${r} is not supported: ${$u.join(\", \")}`);return e()}a(Zp,\"engineCodecOf\");function jE(r){const e=r.map(Zp);return{audio:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"audio/\")),video:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"video/\"))}}a(jE,\"engineCodecsOf\");var Qa=class{static{a(this,\"RtpPacket\")}constructor(e){this.payloadType=e.payloadType;this.sequenceNumber=e.sequenceNumber;this.timestamp=e.timestamp;this.ssrc=e.ssrc??0;this.marker=e.marker??false;this.payload=Buffer.isBuffer(e.payload)?e.payload:Buffer.from(e.payload.buffer,e.payload.byteOffset,e.payload.byteLength)}static parse(e){return Qp(Le.deSerialize(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)))}toBuffer(){return em(this).serialize()}};function Qp(r){const{header:e}=r;return new Qa({payloadType:e.payloadType,sequenceNumber:e.sequenceNumber,timestamp:e.timestamp,ssrc:e.ssrc,marker:e.marker,payload:r.payload})}a(Qp,\"rtpPacketOf\");function em(r){return new Le(new Xe({payloadType:r.payloadType,sequenceNumber:r.sequenceNumber,timestamp:r.timestamp,ssrc:r.ssrc,marker:r.marker}),r.payload)}a(em,\"enginePacketOf\");var HE=new WeakMap;var qE=new WeakMap;var zE=new WeakMap;var GE=new WeakMap;var KE=new WeakMap;var $E=new WeakMap;var jI=500;var tm;var rm=class{static{a(this,\"MediaTrack\")}#e;#t;#r=new FE.EventEmitter;#s;constructor(e,t={}){const s=tm??new Zt({kind:e,codec:t.codec?Zp(t.codec):void 0});if(t.codec&&!s.codec?.mimeType.toLowerCase().startsWith(`${e}/`))throw new TypeError(`The codec ${t.codec} is not one of ${e}`);this.#e=s;this.#t=t.id??s.id??s.uuid;this.#r.setMaxListeners(0);HE.set(s,this);qE.set(this,s);zE.set(this,this.#r);s.on(\"ended\",()=>void this.#r.emit(\"ended\"));this.#r.on(\"newListener\",n=>{if(n===\"rtp\"&&!this.#s)this.#s=this.#e.onReceiveRtp.subscribe((i,o)=>{if(this.#e.remote)this.#r.emit(\"rtp\",Qp(i))}).unSubscribe});this.#r.on(\"removeListener\",n=>{if(n===\"rtp\"&&!this.#r.listenerCount(\"rtp\")){this.#s?.();this.#s=void 0}})}get id(){return this.#t}get kind(){return this.#e.kind}get remote(){return this.#e.remote}get readyState(){return this.#e.readyState}get codec(){const e=this.#e.codec?.mimeType;return e?UE(e):void 0}writeRtp(e){if(e instanceof Qa){this.#e.writeRtp(em(e))}else{this.#e.writeRtp(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength))}}requestKeyFrame(){const e=KE.get(this);if(e)return e();const t=GE.get(this);const s=this.#e.ssrc;if(t&&s!==void 0)void t.sendRtcpPLI(s)}stop(){this.#e.stop()}on(e,t){this.#r.on(e,t);return this}once(e,t){this.#r.once(e,t);return this}off(e,t){this.#r.off(e,t);return this}};function cn(r,e){let t=HE.get(r);if(!t){tm=r;try{t=new rm(r.kind)}finally{tm=void 0}}if(e)GE.set(t,e);return t}a(cn,\"trackOf\");function er(r){return qE.get(r)}a(er,\"engineTrackOf\");function WE(r){zE.get(r).emit(\"keyframerequest\");if(!r.remote)return;const e=Date.now();if(e-($E.get(r)??0)<jI)return;$E.set(r,e);r.requestKeyFrame()}a(WE,\"keyFrameRequested\");function VE(r,e,t,s){const n=new Zt({kind:r,codec:e,remote:true,...t===void 0?{}:{id:t}});const i=cn(n);KE.set(i,s.requestKeyFrame);const o=n.onReceiveRtp.length;let c=false;n.onReceiveRtp.onsubscriberschange=()=>{const l=!n.stopped&&n.onReceiveRtp.length>o;if(l!==c)s.wanted(c=l)};return{track:i,receive:a((l,u)=>n.onReceiveRtp.execute(l,u),\"receive\")}}a(VE,\"relayedTrack\");var IW=Ye(Bn(),1);function sm(){return r=>WS(r)}a(sm,\"Autoload\");var xg=require(\"node:crypto\");var nm;(function(r){r[r[\"DCEP\"]=50]=\"DCEP\";r[r[\"STRING\"]=51]=\"STRING\";r[r[\"BINARY\"]=53]=\"BINARY\";r[r[\"STRING_EMPTY\"]=56]=\"STRING_EMPTY\";r[r[\"BINARY_EMPTY\"]=57]=\"BINARY_EMPTY\"})(nm||(nm={}));var Q;(function(r){r[r[\"CLOSED\"]=1]=\"CLOSED\";r[r[\"COOKIE_WAIT\"]=2]=\"COOKIE_WAIT\";r[r[\"COOKIE_ECHOED\"]=3]=\"COOKIE_ECHOED\";r[r[\"ESTABLISHED\"]=4]=\"ESTABLISHED\";r[r[\"SHUTDOWN_PENDING\"]=5]=\"SHUTDOWN_PENDING\";r[r[\"SHUTDOWN_SENT\"]=6]=\"SHUTDOWN_SENT\";r[r[\"SHUTDOWN_RECEIVED\"]=7]=\"SHUTDOWN_RECEIVED\";r[r[\"SHUTDOWN_ACK_SENT\"]=8]=\"SHUTDOWN_ACK_SENT\"})(Q||(Q={}));var cc=require(\"node:crypto\");var ec=4;var Sr=12;var Fu=4;var XE=12;var As=Fu+XE;var Lt=class r{static{a(this,\"Chunk\")}get body(){return this._body}set body(e){this._body=e}static{this.type=-1}constructor(e=0,t=Buffer.from(\"\")){this.flags=e;this._body=t}get type(){return r.type}get bytes(){if(!this.body)throw new Error;const e=Buffer.alloc(Fu);e.writeUInt8(this.type,0);e.writeUInt8(this.flags,1);e.writeUInt16BE(this.body.length+Fu,2);const t=Buffer.concat([e,this.body,...[...Array(hn(this.body.length))].map(()=>Buffer.from(\"\\0\"))]);return t}};var tc=class extends Lt{static{a(this,\"BaseInitChunk\")}constructor(e=0,t){super(e,t);this.flags=e;if(t){this.initiateTag=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);this.outboundStreams=t.readUInt16BE(8);this.inboundStreams=t.readUInt16BE(10);this.initialTsn=t.readUInt32BE(12);this.params=JE(t.slice(16))}else{this.initiateTag=0;this.advertisedRwnd=0;this.outboundStreams=0;this.inboundStreams=0;this.initialTsn=0;this.params=[]}}get body(){const e=Buffer.alloc(16);e.writeUInt32BE(this.initiateTag,0);e.writeUInt32BE(this.advertisedRwnd,4);e.writeUInt16BE(this.outboundStreams,8);e.writeUInt16BE(this.inboundStreams,10);e.writeUInt32BE(this.initialTsn,12);return Buffer.concat([e,YE(this.params)])}};var ln=class r extends tc{static{a(this,\"InitChunk\")}static{this.type=1}get type(){return r.type}};var Oi=class r extends tc{static{a(this,\"InitAckChunk\")}static{this.type=2}get type(){return r.type}};var Hu=class r extends tc{static{a(this,\"ReConfigChunk\")}static{this.type=130}get type(){return r.type}};var un=class r extends Lt{static{a(this,\"ForwardTsnChunk\")}static{this.type=192}constructor(e=0,t){super(e,t);this.flags=e;this.streams=[];if(t){this.cumulativeTsn=t.readUInt32BE(0);let s=4;while(s<t.length){this.streams.push([t.readUInt16BE(s),t.readUInt16BE(s+2)]);s+=4}}else{this.cumulativeTsn=0}}get type(){return r.type}set body(e){}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return Buffer.concat([e,...this.streams.map(([t,s])=>{const n=Buffer.alloc(4);n.writeUInt16BE(t,0);n.writeUInt16BE(s,2);return n})])}};var tr=class r extends Lt{static{a(this,\"DataChunk\")}static{this.type=0}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.tsn=0;this.streamId=0;this.streamSeqNum=0;this.protocol=0;this.userData=Buffer.from(\"\");this.abandoned=false;this.acked=false;this.misses=0;this.retransmit=false;this.sentCount=0;this.bookSize=0;if(t){this.tsn=t.readUInt32BE(0);this.streamId=t.readUInt16BE(4);this.streamSeqNum=t.readUInt16BE(6);this.protocol=t.readUInt32BE(8);this.userData=t.slice(12)}}get bytes(){const e=As+this.userData.length;const t=Buffer.alloc(As);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.tsn,4);t.writeUInt16BE(this.streamId,8);t.writeUInt16BE(this.streamSeqNum,10);t.writeUInt32BE(this.protocol,12);let s=Buffer.concat([t,this.userData]);if(e%4){s=Buffer.concat([s,...[...Array(hn(e))].map(()=>Buffer.from(\"\\0\"))])}return s}};var ki=class r extends Lt{static{a(this,\"CookieEchoChunk\")}static{this.type=10}get type(){return r.type}};var Pi=class r extends Lt{static{a(this,\"CookieAckChunk\")}static{this.type=11}get type(){return r.type}};var fn=class extends Lt{static{a(this,\"BaseParamsChunk\")}constructor(e=0,t=void 0){super(e,t);this.flags=e;this.params=[];if(t){this.params=JE(t)}}get body(){return YE(this.params)}};var Ni=class r extends fn{static{a(this,\"AbortChunk\")}static{this.type=6}get type(){return r.type}};var dn=class r extends fn{static{a(this,\"ErrorChunk\")}static{this.type=9}static{this.CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13}}get type(){return r.type}get descriptions(){return this.params.map(([e,t])=>{const s=(Object.entries(r.CODE).find(([,n])=>n===e)||[])[0];return{name:s,body:t}})}};var Li=class r extends fn{static{a(this,\"HeartbeatChunk\")}static{this.type=4}get type(){return r.type}};var rc=class r extends fn{static{a(this,\"HeartbeatAckChunk\")}static{this.type=5}get type(){return r.type}};var Mi=class r extends fn{static{a(this,\"ReconfigChunk\")}static{this.type=130}get type(){return r.type}};var Di=class r extends Lt{static{a(this,\"SackChunk\")}static{this.type=3}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.gaps=[];this.duplicates=[];this.cumulativeTsn=0;this.advertisedRwnd=0;if(t){this.cumulativeTsn=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);const s=t.readUInt16BE(8);const n=t.readUInt16BE(10);let i=12;[...Array(s)].forEach(()=>{this.gaps.push([t.readUInt16BE(i),t.readUInt16BE(i+2)]);i+=4});[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(i));i+=4})}}get bytes(){const e=16+4*(this.gaps.length+this.duplicates.length);const t=Buffer.alloc(16);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.cumulativeTsn,4);t.writeUInt32BE(this.advertisedRwnd,8);t.writeUInt16BE(this.gaps.length,12);t.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([t,...this.gaps.map(n=>{const i=Buffer.alloc(4);i.writeUInt16BE(n[0],0);i.writeUInt16BE(n[1],2);return i})]);s=Buffer.concat([s,...this.duplicates.map(n=>{const i=Buffer.alloc(4);i.writeUInt32BE(n,0);return i})]);return s}};var sc=class r extends Lt{static{a(this,\"ShutdownChunk\")}static{this.type=7}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.cumulativeTsn=0;if(t){this.cumulativeTsn=t.readUInt32BE(0)}}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return e}};var nc=class r extends Lt{static{a(this,\"ShutdownAckChunk\")}static{this.type=8}get type(){return r.type}};var ic=class r extends Lt{static{a(this,\"ShutdownCompleteChunk\")}static{this.type=14}get type(){return r.type}};var $I=[tr,ln,Oi,Di,Li,rc,Ni,sc,nc,dn,ki,Pi,ic,Mi,un];var FI=$I.reduce((r,e)=>{r[e.type]=e;return r},{});function hn(r){const e=r%ec;return e?ec-e:0}a(hn,\"padL\");function YE(r){let e=Buffer.from(\"\");let t=Buffer.from(\"\");r.forEach(([s,n])=>{const i=n.length+4;const o=Buffer.alloc(4);o.writeUInt16BE(s,0);o.writeUInt16BE(i,2);e=Buffer.concat([e,t,o,n]);t=Buffer.concat([...Array(hn(i))].map(()=>Buffer.from(\"\\0\")))});return e}a(YE,\"encodeParams\");function JE(r){const e=[];let t=0;while(t<=r.length-4){const s=r.readUInt16BE(t);const n=r.readUInt16BE(t+2);e.push([s,r.slice(t+4,t+n)]);t+=n+hn(n)}return e}a(JE,\"decodeParams\");function ZE(r){if(r.length<Sr)throw new Error(\"SCTP packet length is less than 12 bytes\");const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);const s=r.readUInt32BE(4);const n=r.readUInt32LE(8);let i=Da(r.subarray(0,8));i=Da(HI,i);i=Da(r.subarray(Sr),i);if(n!==i>>>0)throw new Error(\"SCTP packet has invalid checksum\");const o=[];let c=Sr;while(c+4<=r.length){const l=r.readUInt8(c);const u=r.readUInt8(c+1);const f=r.readUInt16BE(c+2);const d=r.slice(c+4,c+f);const h=FI[l.toString()];if(h){o.push(new h(u,d))}else{throw new Error(\"unknown\")}c+=f+hn(f)}return[e,t,s,o]}a(ZE,\"parsePacket\");var HI=Buffer.alloc(4);function QE(r,e){if(r instanceof tr){const t=As+r.userData.length;return t+hn(t)}return e.length}a(QE,\"wireLength\");function im(r,e,t,s){const n=s.map(l=>l instanceof tr?void 0:l.bytes);let i=Sr;for(let l=0;l<s.length;l++){i+=QE(s[l],n[l])}const o=Buffer.allocUnsafe(i);o.writeUInt16BE(r,0);o.writeUInt16BE(e,2);o.writeUInt32BE(t,4);o.writeUInt32LE(0,8);let c=Sr;for(let l=0;l<s.length;l++){const u=s[l];const f=n[l];if(f){f.copy(o,c);c+=f.length;continue}const d=u;const h=As+d.userData.length;o.writeUInt8(d.type,c);o.writeUInt8(d.flags,c+1);o.writeUInt16BE(h,c+2);o.writeUInt32BE(d.tsn,c+4);o.writeUInt16BE(d.streamId,c+8);o.writeUInt16BE(d.streamSeqNum,c+10);o.writeUInt32BE(d.protocol,c+12);d.userData.copy(o,c+As);const p=hn(h);if(p)o.fill(0,c+h,c+h+p);c+=h+p}o.writeUInt32LE(Da(o)>>>0,8);return o}a(im,\"serializePackets\");function eT(r){return QE(r,r instanceof tr?void 0:r.bytes)}a(eT,\"chunkWireLength\");function tT(r,e,t,s){return im(r,e,t,[s])}a(tT,\"serializePacket\");function rT(r){return r.map((e,t)=>[t,e])}a(rT,\"enumerate\");function sT(r){return r.reduce((e,t)=>{e[t]=new O;return e},{})}a(sT,\"createEventsFromList\");var Bi=class r{static{a(this,\"OutgoingSSNResetRequestParam\")}static{this.type=13}constructor(e,t,s,n){this.requestSequence=e;this.responseSequence=t;this.lastTsn=s;this.streams=n}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(12);e.writeUInt32BE(this.requestSequence,0);e.writeUInt32BE(this.responseSequence,4);e.writeUInt32BE(this.lastTsn,8);return Buffer.concat([e,...this.streams.map(t=>{const s=Buffer.allocUnsafe(2);s.writeUInt16BE(t,0);return s})])}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);const n=e.readUInt32BE(8);const i=[];for(let o=12;o<e.length;o+=2){i.push(e.readUInt16BE(o))}return new r(t,s,n,i)}};var oc=class r{static{a(this,\"StreamAddOutgoingParam\")}static{this.type=17}constructor(e,t){this.requestSequence=e;this.newStreams=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.requestSequence,0);e.writeUInt16BE(this.newStreams,4);e.writeUInt16BE(0,6);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt16BE(4);return new r(t,s)}};var ac={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5};var pn=class r{static{a(this,\"ReconfigResponseParam\")}static{this.type=16}constructor(e,t){this.responseSequence=e;this.result=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.responseSequence,0);e.writeUInt32BE(this.result,4);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);return new r(t,s)}};var om={13:Bi,16:pn,17:oc};var X=P(\"webrtc/sctp/sctp\");var qI=24;var zI=60;var nT=65535;var ji=1191;function lm(r,e=As){const t=Sr+e;if(r<=t)return 0;const s=r-t;return s-s%ec}a(lm,\"maxPayloadSizeForMtu\");function Gu(r){if(!Number.isSafeInteger(r)||r<=0){throw new Error(\"SCTP MTU must be a positive integer\")}if(lm(r)===0){throw new Error(\"SCTP MTU is too small for a DATA chunk\")}}a(Gu,\"validateSctpMtu\");var Ui=1;var qu=2;var zu=4;var iT=10;var GI=8;var KI=10;var WI=2;var oT=1/8;var aT=1/4;var cT=3;var VI=1;var XI=60;var Ur=2**32;var YI=20;var JI=4096;var ZI=30;var lT=135;var uT=7;var fT=32776;var dT=49152;var QI=[\"new\",\"closed\",\"connected\",\"connecting\"];var lc=class r{static{a(this,\"SCTP\")}get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}constructor(e,t=5e3,s={}){this.transport=e;this.port=t;this.flush=new O;this.stateChanged=sT(QI);this.onReconfigStreams=new O;this.onReceive=new O;this.onSackReceived=async()=>{};this.associationState=Q.CLOSED;this.started=false;this.state=\"new\";this.isServer=true;this.isStopping=false;this.isClosed=false;this.hmacKey=(0,cc.randomBytes)(16);this.localPartialReliability=true;this.localVerificationTag=cu();this.remoteExtensions=[];this.remotePartialReliability=true;this.remoteVerificationTag=0;this.advertisedRwnd=1024*1024;this.lastAdvertisedRwnd=this.advertisedRwnd;this.peerAdvertisedRwnd=this.advertisedRwnd;this.inboundStreams={};this._inboundStreamsCount=0;this._inboundStreamsMax=nT;this.pendingChunks=0;this.sackDuplicates=[];this.sackMisOrdered=new Set;this.sackNeeded=false;this.sackPacketCount=0;this.sackHasNewDataInPacket=false;this.sackImmediate=false;this.fastRecoveryTransmit=false;this.flightSize=0;this.outboundQueue=new Ha;this.outboundStreamSeq={};this._outboundStreamsCount=nT;this.localTsn=Number(cu());this.lastSackedTsn=mn(this.localTsn);this.advancedPeerAckTsn=mn(this.localTsn);this.partialBytesAcked=0;this.sentQueue=new Ha;this.retransmitPending=false;this.transmitting=false;this.transmitRequested=false;this.transmitScheduled=false;this.reconfigRequestSeq=this.localTsn;this.reconfigResponseSeq=0;this.reconfigQueue=[];this.rto=cT;this.timer1Failures=0;this.timer2Failures=0;this.timerReconfigFailures=0;this.heartbeatInterval=ZI;this.send=async(n,i,o,{expiry:c,maxRetransmits:l,ordered:u}={expiry:void 0,maxRetransmits:void 0,ordered:true})=>{const f=u?this.outboundStreamSeq[n]||0:0;const d=Math.ceil(o.length/this.maxPayloadSize);let h=0;const p=[];for(let m=0;m<d;m++){const y=new tr(0,void 0);y.flags=0;if(!u){y.flags=zu}if(m===0){y.flags|=qu}if(m===d-1){y.flags|=Ui}y.tsn=this.localTsn;y.streamId=n;y.streamSeqNum=f;y.protocol=i;y.userData=o.subarray(h,h+this.maxPayloadSize);y.bookSize=y.userData.length;y.expiry=c;y.maxRetransmits=l;h+=this.maxPayloadSize;this.localTsn=gn(this.localTsn);p.push(y)}for(const m of p){this.outboundQueue.push(m)}if(u){this.outboundStreamSeq[n]=$e(f,1)}this.transmitSoon()};this.timer1Expired=()=>{if(this.isStopped)return;this.timer1Failures++;this.timer1Handle=void 0;if(this.timer1Failures>GI){this.setState(Q.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer1Chunk).catch(n=>{X(\"send timer1 chunk failed\",n.message)})});if(this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};this.timer2Expired=()=>{if(this.isStopped)return;this.timer2Failures++;this.timer2Handle=void 0;if(this.timer2Failures>iT){this.setState(Q.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer2Chunk).catch(n=>{X(\"send timer2Chunk failed\",n.message)})});if(this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};this.timer3Expired=()=>{if(this.isStopped)return;this.timer3Handle=void 0;for(const n of this.sentQueue){if(!this.maybeAbandon(n)){n.retransmit=true;this.retransmitPending=true}}this.updateAdvancedPeerAckPoint();this.fastRecoveryExit=void 0;this.flightSize=0;this.partialBytesAcked=0;this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.maxPayloadSize;this.transmit().catch(n=>X(\"transmit failed\",n))};this.timerReconfigHandleExpired=async()=>{if(this.isStopped)return;this.timerReconfigFailures++;this.rto=Math.ceil(this.rto*1.5);if(this.timerReconfigFailures>iT){X(\"timerReconfigFailures\",this.timerReconfigFailures);this.setState(Q.CLOSED);this.timerReconfigHandle=void 0}else if(this.reconfigRequest){X(\"timerReconfigHandleExpired\",this.timerReconfigFailures,this.rto);await this.sendReconfigParam(this.reconfigRequest);if(this.isStopped)return;this.timerReconfigHandle=setTimeout(Vt(this.timerReconfigHandleExpired,n=>X(\"reconfig timer failed\",n)),this.rto*1e3)}};this.timerHeartbeatExpired=async()=>{this.timerHeartbeatHandle=void 0;if(this.associationState!==Q.ESTABLISHED)return;if(this.flightSize===0&&this.outboundQueue.length===0){const n=new Li;const i=Buffer.allocUnsafe(4);i.writeUInt32BE(Math.floor(Date.now()/1e3),0);n.params.push([1,i]);await this.sendChunk(n).catch(o=>{X(\"send heartbeat failed\",o.message)})}this.heartbeatStart()};this.mtu=s.mtu??ji;Gu(this.mtu);this.maxPayloadSize=lm(this.mtu);this.cwnd=KI*this.maxPayloadSize;this.localPort=this.port;this.transport.onData=n=>{this.handleData(n).catch(i=>X(\"receive failed\",i))}}get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0){return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}return void 0}static client(e,t=5e3,s={}){const n=new r(e,t,s);n.isServer=false;return n}static server(e,t=5e3,s={}){const n=new r(e,t,s);n.isServer=true;return n}async handleData(e){if(this.isStopped)return;let t;const[,,s,n]=ZE(e);const i=n.filter(o=>o.type===ln.type).length;if(i>0){if(n.length!=1){throw new Error}t=0}else{t=this.localVerificationTag}if(s!==t){return}this.sackHasNewDataInPacket=false;for(const o of n){if(o.type===tr.type)this.receiveDataChunk(o);else await this.receiveChunk(o)}if(this.sackNeeded){if(this.sackHasNewDataInPacket){this.sackPacketCount++}if(this.sackPacketCount>=2){this.sackImmediate=true}await this.scheduleSack()}}async scheduleSack(){if(this.isStopped)return;if(!this.sackNeeded)return;if(this.sackImmediate){if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}await this.sendSack();return}if(this.sackTimeout)return;this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0;this.sendSack().catch(e=>{X(\"send delayed sack failed\",e.message)})},YI)}async sendSack(){if(this.isStopped)return;if(!this.sackNeeded)return;await this.sendChunk(this.takeSack()).catch(e=>{X(\"send sack failed\",e.message)})}takeSack(){const e=[];let t;const s=[...this.sackMisOrdered].sort((i,o)=>(i-this.lastReceivedTsn+Ur)%Ur-(o-this.lastReceivedTsn+Ur)%Ur);for(const i of s){const o=(i-this.lastReceivedTsn+Ur)%Ur;if(i===t){e[e.length-1][1]=o}else{e.push([o,o])}t=gn(i)}const n=new Di(0,void 0);n.cumulativeTsn=this.lastReceivedTsn;n.advertisedRwnd=Math.max(0,this.advertisedRwnd);this.lastAdvertisedRwnd=n.advertisedRwnd;n.duplicates=[...this.sackDuplicates];n.gaps=e;this.sackDuplicates=[];this.sackNeeded=false;this.sackPacketCount=0;this.sackImmediate=false;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}return n}async receiveChunk(e){switch(e.type){case tr.type:{this.receiveDataChunk(e)}break;case ln.type:{if(!this.isServer)return;const t=e;X(\"receive init\",t);this.lastReceivedTsn=mn(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=mn(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new Oi;s.initiateTag=this.localVerificationTag;s.advertisedRwnd=this.advertisedRwnd;s.outboundStreams=this._outboundStreamsCount;s.inboundStreams=this._inboundStreamsCount;s.initialTsn=this.localTsn;this.setExtensions(s.params);const n=Math.floor(Date.now()/1e3);const i=Buffer.allocUnsafe(4);i.writeUInt32BE(n,0);let o=i;o=Buffer.concat([o,(0,cc.createHmac)(\"sha1\",this.hmacKey).update(o).digest()]);s.params.push([uT,o]);X(\"send initAck\",s);await this.sendChunk(s).catch(c=>{X(\"send initAck failed\",c.message)})}break;case Oi.type:{if(this.associationState!=Q.COOKIE_WAIT)return;const t=e;this.timer1Cancel();this.lastReceivedTsn=mn(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=mn(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new ki;for(const[n,i]of t.params){if(n===uT){s.body=i;break}}await this.sendChunk(s).catch(n=>{X(\"send echo failed\",n.message)});this.timer1Start(s);this.setState(Q.COOKIE_ECHOED)}break;case Di.type:{await this.receiveSackChunk(e)}break;case Li.type:{const t=new rc;t.params=e.params;await this.sendChunk(t).catch(s=>{X(\"send heartbeat ack failed\",s.message)})}break;case Ni.type:{this.setState(Q.CLOSED)}break;case sc.type:{this.timer2Cancel();this.setState(Q.SHUTDOWN_RECEIVED);const t=new nc;await this.sendChunk(t).catch(s=>{X(\"send shutdown ack failed\",s.message)});this.t2Start(t);this.setState(Q.SHUTDOWN_SENT)}break;case dn.type:{X(\"ErrorChunk\",e.descriptions)}break;case ki.type:{if(!this.isServer)return;const t=e;const s=t.body;const n=(0,cc.createHmac)(\"sha1\",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=qI||!s.slice(4).equals(n)){X(\"x State cookie is invalid\");return}const i=Math.floor(Date.now()/1e3);const o=s.readUInt32BE(0);if(o<i-zI||o>i){const l=new dn(0,void 0);l.params.push([dn.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(\"\\0\")))]);await this.sendChunk(l).catch(u=>{X(\"send errorChunk failed\",u.message)});return}const c=new Pi;await this.sendChunk(c).catch(l=>{X(\"send cookieAck failed\",l.message)});this.setState(Q.ESTABLISHED)}break;case Pi.type:{if(this.associationState!=Q.COOKIE_ECHOED)return;this.timer1Cancel();this.setState(Q.ESTABLISHED)}break;case ic.type:{if(this.associationState!=Q.SHUTDOWN_ACK_SENT)return;this.timer2Cancel();this.setState(Q.CLOSED)}break;case Mi.type:{if(this.associationState!=Q.ESTABLISHED)return;const t=e;for(const[s,n]of t.params){const i=om[s];if(i){await this.receiveReconfigParam(i.parse(n))}}}break;case un.type:{this.receiveForwardTsnChunk(e)}break}}getExtensions(e){for(const[t,s]of e){if(t===dT){this.remotePartialReliability=true}else if(t===fT){this.remoteExtensions=[...s]}}}async receiveReconfigParam(e){X(\"receiveReconfigParam\",om[e.type]);switch(e.type){case Bi.type:{const t=e;const s=new pn(t.requestSequence,ac.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s);await Promise.all(t.streams.map(async n=>{const i=this.inboundStreams[n];if(i){this.pendingChunks-=i.reassembly.length;this.advertisedRwnd+=i.reassembly.reduce((o,c)=>o+c.userData.length,0)}delete this.inboundStreams[n];if(this.outboundStreamSeq[n]){if(!this.reconfigQueue.includes(n)){this.reconfigQueue.push(n)}}}));await this.transmitReconfigRequest();this.onReconfigStreams.execute(t.streams)}break;case pn.type:{const t=e;if(t.result!==ac.ReconfigResultSuccessPerformed){X(\"OutgoingSSNResetRequestParam failed\",Object.keys(ac).find(s=>ac[s]===t.result))}else if(t.responseSequence===this.reconfigRequest?.requestSequence){const s=this.reconfigRequest.streams.map(n=>{delete this.outboundStreamSeq[n];return n});this.onReconfigStreams.execute(s);this.reconfigRequest=void 0;this.timerReconfigCancel();this.rto=cT;this.timerReconfigFailures=0;if(this.reconfigQueue.length>0){await this.transmitReconfigRequest()}}}break;case oc.type:{const t=e;this._inboundStreamsCount+=t.newStreams;const s=new pn(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s)}break}}receiveDataChunk(e){this.sackNeeded=true;if((this.advertisedRwnd<=0||this.pendingChunks>=JI)&&Et(e.tsn,this.highestReceivedTsn)){this.sackImmediate=true;return}if(this.markReceived(e.tsn)){this.sackImmediate=true;return}this.sackHasNewDataInPacket=true;if(this.sackMisOrdered.size>0){this.sackImmediate=true}const t=this.getInboundStream(e.streamId);if((e.flags&(qu|Ui))===(qu|Ui)){if(e.flags&zu){this.receive(e.streamId,e.protocol,e.userData);return}if(t.reassembly.length===0&&e.streamSeqNum===t.streamSequenceNumber){t.streamSequenceNumber=$e(t.streamSequenceNumber,1);this.receive(e.streamId,e.protocol,e.userData);return}}const s=t.reassembly.length;t.addChunk(e);this.advertisedRwnd-=e.userData.length;for(const n of t.popMessages()){this.advertisedRwnd+=n[2].length;this.receive(...n)}this.pendingChunks+=t.reassembly.length-s}async receiveSackChunk(e){if(Et(this.lastSackedTsn,e.cumulativeTsn))return;const t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;const s=this.flightSize>=this.cwnd;let n=0,i=0;while(this.sentQueue.length>0&&bi(this.lastSackedTsn,this.sentQueue.at(0).tsn)){const c=this.sentQueue.shift();n++;if(!c?.acked){i+=c.bookSize;this.flightSizeDecrease(c)}if(n===1&&c.sentCount===1){this.updateRto(t-c.sentTime)}}let o=false;if(e.gaps.length>0){const c=new Set;let l;e.gaps.forEach(f=>{for(let d=f[0];d<f[1]+1;d++){l=(e.cumulativeTsn+d)%Ur;c.add(l)}});let u=e.cumulativeTsn;for(const f of this.sentQueue){if(Et(f.tsn,l)){break}if(c.has(f.tsn)&&!f.acked){i+=f.bookSize;f.acked=true;this.flightSizeDecrease(f);u=f.tsn}}for(const f of this.sentQueue){if(Et(f.tsn,u)){break}if(!c.has(f.tsn)){f.misses++;if(f.misses===3){f.misses=0;if(!this.maybeAbandon(f)){f.retransmit=true;this.retransmitPending=true}f.acked=false;this.flightSizeDecrease(f);o=true}}}}if(this.fastRecoveryExit===void 0){if(n&&s){if(this.cwnd<=this.ssthresh){this.cwnd+=Math.min(i,WI*this.maxPayloadSize)}else{this.partialBytesAcked+=i;if(this.partialBytesAcked>=this.cwnd){this.partialBytesAcked-=this.cwnd;this.cwnd+=this.maxPayloadSize}}}if(o){this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.ssthresh;this.partialBytesAcked=0;this.fastRecoveryExit=this.sentQueue.at(-1).tsn;this.fastRecoveryTransmit=true}}else if(bi(e.cumulativeTsn,this.fastRecoveryExit)){this.fastRecoveryExit=void 0}if(this.sentQueue.length===0){this.timer3Cancel()}else if(n>0){this.timer3Restart()}this.peerAdvertisedRwnd=e.advertisedRwnd;this.updateAdvancedPeerAckPoint();await this.onSackReceived();await this.transmit()}receiveForwardTsnChunk(e){this.sackNeeded=true;this.sackImmediate=true;if(bi(this.lastReceivedTsn,e.cumulativeTsn)){return}const t=a(s=>Et(s,this.lastReceivedTsn),\"isObsolete\");this.lastReceivedTsn=e.cumulativeTsn;this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const s of[...this.sackMisOrdered].sort()){if(s===gn(this.lastReceivedTsn)){this.lastReceivedTsn=s}else{break}}this.sackDuplicates=this.sackDuplicates.filter(t);this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const[s,n]of e.streams){const i=this.getInboundStream(s);i.streamSequenceNumber=$e(n,1);for(const o of i.popMessages()){this.advertisedRwnd+=o[2].length;this.receive(...o)}}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)});this.pendingChunks=Object.values(this.inboundStreams).reduce((s,n)=>s+n.reassembly.length,0);if(Et(this.lastReceivedTsn,this.highestReceivedTsn))this.highestReceivedTsn=this.lastReceivedTsn}updateRto(e){if(!this.srtt){this.rttvar=e/2;this.srtt=e}else{this.rttvar=(1-aT)*this.rttvar+aT*Math.abs(this.srtt-e);this.srtt=(1-oT)*this.srtt+oT*e}this.rto=Math.max(VI,Math.min(this.srtt+4*this.rttvar,XI))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){if(!this.inboundStreams[e]){this.inboundStreams[e]=new am}return this.inboundStreams[e]}markReceived(e){if(bi(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e)){this.sackDuplicates.push(e);return true}if(Et(e,this.highestReceivedTsn))this.highestReceivedTsn=e;if(e===gn(this.lastReceivedTsn)){this.lastReceivedTsn=e;while(this.sackMisOrdered.size>0){const t=gn(this.lastReceivedTsn);if(!this.sackMisOrdered.delete(t))break;this.lastReceivedTsn=t}if(this.sackDuplicates.length>0){const t=a(s=>Et(s,this.lastReceivedTsn),\"isObsolete\");this.sackDuplicates=this.sackDuplicates.filter(t)}}else{this.sackMisOrdered.add(e)}return false}holdReceived(e){this.advertisedRwnd-=e}releaseReceived(e){this.advertisedRwnd+=e;if(this.associationState!==Q.ESTABLISHED||this.lastReceivedTsn===void 0)return;if(this.lastAdvertisedRwnd*2<this.advertisedRwnd){this.sackNeeded=true;this.sackImmediate=true;this.scheduleSack().catch(t=>X(\"send window update failed\",t.message))}}transmitSoon(){if(this.transmitScheduled)return;this.transmitScheduled=true;queueMicrotask(()=>{this.transmitScheduled=false;this.transmit().catch(e=>X(\"transmit failed\",e))})}async transmit(){if(this.isStopped)return;if(this.transmitting){this.transmitRequested=true;return}this.transmitting=true;try{do{this.transmitRequested=false;this.transmitOnce()}while(this.transmitRequested)}finally{this.transmitting=false}}transmitOnce(){if(this.isStopped)return;const e=[];let t=Sr;let s=false;const n=a(()=>{if(e.length===0)return;this.sendChunks(e.splice(0,e.length));t=Sr},\"flush\");const i=a(u=>{const f=eT(u);if(e.length>0&&t+f>this.mtu)n();e.push(u);t+=f},\"add\");const o=a(u=>{if(!s&&this.sackNeeded&&this.lastReceivedTsn!==void 0){i(this.takeSack());s=true}i(u)},\"addData\");if(this.forwardTsnChunk){i(this.forwardTsnChunk);this.forwardTsnChunk=void 0;if(!this.timer3Handle){this.timer3Start()}}const c=this.fastRecoveryExit!=void 0?2*this.maxPayloadSize:4*this.maxPayloadSize;const l=Math.min(this.flightSize+c,this.cwnd);if(this.retransmitPending){let u=true;let f=true;for(const d of this.sentQueue){if(d.retransmit){if(this.fastRecoveryTransmit){this.fastRecoveryTransmit=false}else if(this.flightSize>=l){f=false;break}this.flightSizeIncrease(d);d.misses=0;d.retransmit=false;d.sentCount++;o(d);if(u){this.timer3Restart()}}u=false}if(f)this.retransmitPending=false}while(this.outboundQueue.length>0&&this.flightSize<l&&(this.peerRwnd>0||this.flightSize===0)){const u=this.outboundQueue.shift();if(!u)break;if(u.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(u);break}this.sentQueue.push(u);this.flightSizeIncrease(u);u.sentCount++;u.sentTime=Date.now()/1e3;o(u);this.onSent?.(u.streamId,u.protocol,u.userData.length);if(!this.timer3Handle){this.timer3Start()}}n();this.flush.execute()}sendChunks(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){X(\"send chunks failed\",\"invalid remote port\");return}const t=im(this.localPort,this.remotePort,this.remoteVerificationTag,e);this.transport.send(t).catch(s=>{X(\"send packet failed\",s.message)})}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===Q.ESTABLISHED&&!this.reconfigRequest){const e=[...new Set(this.reconfigQueue)];const t=e.slice(0,lT);this.reconfigQueue=e.slice(lT);const s=new Bi(this.reconfigRequestSeq,this.reconfigResponseSeq,mn(this.localTsn),t);this.reconfigRequestSeq=gn(this.reconfigRequestSeq);this.reconfigRequest=s;await this.sendReconfigParam(s);this.timerReconfigHandleStart()}}async sendReconfigParam(e){X(\"sendReconfigParam\",e);const t=new Mi;t.params.push([e.type,e.bytes]);await this.sendChunk(t).catch(s=>{X(\"send reconfig failed\",s.message)})}async sendResetRequest(e){X(\"sendResetRequest\",e);const t=new tr(0,void 0);t.streamId=e;this.outboundQueue.push(t);if(!this.timer3Handle){await this.transmit()}}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e;this.timer1Failures=0;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Cancel(){if(this.timer1Handle){clearTimeout(this.timer1Handle);this.timer1Handle=void 0;this.timer1Chunk=void 0}}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e;this.timer2Failures=0;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Cancel(){if(this.timer2Handle){clearTimeout(this.timer2Handle);this.timer2Handle=void 0;this.timer2Chunk=void 0}}timer3Start(){if(this.isStopped)return;if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Restart(){if(this.isStopped)return;this.timer3Cancel();this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Cancel(){if(this.timer3Handle){clearTimeout(this.timer3Handle);this.timer3Handle=void 0}}timerReconfigHandleStart(){if(this.isStopped)return;if(this.timerReconfigHandle)return;X(\"timerReconfigHandleStart\",{rto:this.rto});this.timerReconfigFailures=0;this.timerReconfigHandle=setTimeout(Vt(this.timerReconfigHandleExpired,e=>X(\"reconfig timer failed\",e)),this.rto*1e3)}timerReconfigCancel(){if(this.timerReconfigHandle){X(\"timerReconfigCancel\");clearTimeout(this.timerReconfigHandle);this.timerReconfigHandle=void 0;this.timerReconfigFailures=0}}heartbeatStart(){if(this.timerHeartbeatHandle||this.associationState!==Q.ESTABLISHED){return}this.timerHeartbeatHandle=setTimeout(Vt(this.timerHeartbeatExpired,e=>X(\"heartbeat failed\",e)),(this.rto+this.heartbeatInterval)*1e3)}heartbeatRestart(){this.heartbeatCancel();this.heartbeatStart()}heartbeatCancel(){if(this.timerHeartbeatHandle){clearTimeout(this.timerHeartbeatHandle);this.timerHeartbeatHandle=void 0}}setHeartbeatInterval(e){if(e<=0){throw new Error(\"heartbeat interval must be > 0\")}this.heartbeatInterval=e;this.heartbeatRestart()}updateAdvancedPeerAckPoint(){if(Et(this.lastSackedTsn,this.advancedPeerAckTsn)){this.advancedPeerAckTsn=this.lastSackedTsn}let e=0;const t={};while(this.sentQueue.length>0&&this.sentQueue.at(0).abandoned){const s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn;e++;if(!(s.flags&zu)){t[s.streamId]=s.streamSeqNum}}if(e){this.forwardTsnChunk=new un(0,void 0);this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn;this.forwardTsnChunk.streams=Object.entries(t).map(([s,n])=>[Number(s),n])}}maybeAbandon(e){if(e.abandoned)return true;const t=!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3;if(!t)return false;const s=this.sentQueue.findIndex(n=>n===e);for(let n=s;n>=0;n--){const i=this.sentQueue.at(n);i.abandoned=true;i.retransmit=false;if(i.flags&Ui){break}}for(let n=s;n<this.sentQueue.length;n++){const i=this.sentQueue.at(n);i.abandoned=true;i.retransmit=false;if(i.flags&Ui){break}}return true}static getCapabilities(){return new cm(65536)}setRemotePort(e){this.remotePort=e}async start(e){if(!this.started){this.started=true;this.setConnectionState(\"connecting\");if(e){this.setRemotePort(e)}if(!this.isServer){await this.init()}}}async init(){const e=new ln;e.initiateTag=this.localVerificationTag;e.advertisedRwnd=this.advertisedRwnd;e.outboundStreams=this._outboundStreamsCount;e.inboundStreams=this._inboundStreamsMax;e.initialTsn=this.localTsn;this.setExtensions(e.params);X(\"send init\",e);try{await this.sendChunk(e);this.timer1Start(e);this.setState(Q.COOKIE_WAIT)}catch(t){X(\"send init failed\",t.message)}}setExtensions(e){const t=[];if(this.localPartialReliability){e.push([dT,Buffer.from(\"\")]);t.push(un.type)}t.push(Hu.type);e.push([fT,Buffer.from(t)])}async sendChunk(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){throw new Error(\"invalid remote port\")}const t=tT(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}setState(e){if(e!=this.associationState){this.associationState=e}if(e===Q.ESTABLISHED){this.isStopping=false;this.isClosed=false;this.setConnectionState(\"connected\");this.heartbeatStart()}else if(e===Q.CLOSED){this.isClosed=true;this.timer1Cancel();this.timer2Cancel();this.timer3Cancel();this.timerReconfigCancel();this.heartbeatCancel();if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}this.setConnectionState(\"closed\");this.removeAllListeners()}}setConnectionState(e){this.state=e;X(\"setConnectionState\",e);this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(Q.CLOSED);return}this.isStopping=true;this.transport.onData=void 0;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}if(this.associationState!==Q.CLOSED){await this.abort()}this.setState(Q.CLOSED);clearTimeout(this.timer1Handle);clearTimeout(this.timer2Handle);clearTimeout(this.timer3Handle);clearTimeout(this.timerReconfigHandle);clearTimeout(this.timerHeartbeatHandle);clearTimeout(this.sackTimeout)}async abort(){const e=new Ni;await this.sendChunk(e).catch(t=>{X(\"send abort failed\",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}};var am=class{static{a(this,\"InboundStream\")}constructor(){this.reassembly=[];this.streamSequenceNumber=0}addChunk(e){if(this.reassembly.length===0||Et(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(const[t,s]of rT(this.reassembly)){if(s.tsn===e.tsn)throw new Error(\"duplicate chunk in reassembly\");if(Et(s.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0;let t;let s;let n;while(e<this.reassembly.length){const i=this.reassembly[e];if(t===void 0){n=!(i.flags&zu);if(!(i.flags&qu)){if(n){break}else{e++;continue}}if(n&&lu(i.streamSeqNum,this.streamSequenceNumber)){break}s=i.tsn;t=e}else if(i.tsn!==s){if(n){break}else{t=void 0;e++;continue}}if(i.flags&Ui){const o=this.reassembly.slice(t,e+1).map(l=>l.userData);const c=o.length===1?o[0]:Buffer.concat(o);this.reassembly.splice(t,e+1-t);if(n&&i.streamSeqNum===this.streamSequenceNumber){this.streamSequenceNumber=$e(this.streamSequenceNumber,1)}e=t;yield[i.streamId,i.protocol,c]}else{e++}s=gn(s)}}pruneChunks(e){let t=-1,s=0;for(const[n,i]of this.reassembly.entries()){if(bi(e,i.tsn)){t=n;s+=i.userData.length}else{break}}this.reassembly=this.reassembly.slice(t+1);return s}};var cm=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};function mn(r){return(r-1)%Ur}a(mn,\"tsnMinusOne\");function gn(r){return(r+1)%Ur}a(gn,\"tsnPlusOne\");function ne(r,e=r){return new DOMException(e,r)}a(ne,\"createWebRtcDomException\");function rr(r){return new TypeError(r)}a(rr,\"createWebRtcTypeError\");var IR=require(\"node:crypto\");var OR=require(\"node:net\");var hm=require(\"node:crypto\");var Tt={rsa_1:1,ecdsa_3:3};var Ku={sha256_4:4};var Wu={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199};var hT=Object.values(Wu);var jr={x25519_29:29,secp256r1_23:23};var Vu=Object.values(jr);var Xu={named_curve_3:3};var um={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027};var pT=[1,64];var Yu=[{hash:Ku.sha256_4,signature:Tt.rsa_1},{hash:Ku.sha256_4,signature:Tt.ecdsa_3}];var $r=require(\"node:crypto\");function Fr(r,e){const t=e.length;if(t<128)return Buffer.concat([Buffer.from([r,t]),e]);const s=[];for(let n=t;n>0;n=Math.floor(n/256))s.unshift(n&255);return Buffer.concat([Buffer.from([r,128|s.length,...s]),e])}a(Fr,\"der\");var yn=a((...r)=>Fr(48,Buffer.concat(r)),\"sequence\");var eO=a((...r)=>Fr(49,Buffer.concat(r)),\"set\");var tO=Buffer.from([5,0]);var rO=a(r=>Fr(12,Buffer.from(r,\"utf8\")),\"utf8String\");var sO=a(r=>Fr(3,Buffer.concat([Buffer.from([0]),r])),\"bitString\");var nO=a((r,e)=>Fr(160|r,e),\"explicit\");function mT(r){let e=0;while(e<r.length-1&&r[e]===0)e++;const t=r.subarray(e);return Fr(2,t[0]&128?Buffer.concat([Buffer.from([0]),t]):t)}a(mT,\"integer\");function fm(r){const e=r.split(\".\").map(Number);const t=[e[0]*40+e[1]];for(const s of e.slice(2)){const n=[s&127];for(let i=Math.floor(s/128);i>0;i=Math.floor(i/128))n.unshift(128|i&127);t.push(...n)}return Fr(6,Buffer.from(t))}a(fm,\"oid\");function gT(r){const e=r.toISOString().replace(/[-:T]/g,\"\").slice(0,14);return r.getUTCFullYear()<2050?Fr(23,Buffer.from(`${e.slice(2)}Z`)):Fr(24,Buffer.from(`${e}Z`))}a(gT,\"time\");var iO=a(r=>yn(eO(yn(fm(\"2.5.4.3\"),rO(r)))),\"commonName\");function yT(r=\"ecdsa\",e=\"WebRTC\",t=30){const{privateKey:s,publicKey:n}=r===\"ecdsa\"?(0,$r.generateKeyPairSync)(\"ec\",{namedCurve:\"prime256v1\"}):(0,$r.generateKeyPairSync)(\"rsa\",{modulusLength:2048,publicExponent:65537});const i=r===\"ecdsa\"?yn(fm(\"1.2.840.10045.4.3.2\")):yn(fm(\"1.2.840.113549.1.1.11\"),tO);const o=new Date(Date.now()-24*60*60*1e3);const c=new Date(o.getTime()+(t+1)*24*60*60*1e3);const l=(0,$r.randomBytes)(8);l[0]&=127;const u=iO(e);const f=yn(nO(0,mT(Buffer.from([2]))),mT(l),i,u,yn(gT(o),gT(c)),u,n.export({type:\"spki\",format:\"der\"}));const d=(0,$r.sign)(\"sha256\",f,s);const h=yn(f,i,sO(d));return{certPem:oO(h,\"CERTIFICATE\"),keyPem:s.export({type:\"pkcs8\",format:\"pem\"})}}a(yT,\"createDtlsCertificate\");function oO(r,e){const t=r.toString(\"base64\").match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----\n${t.join(\"\\n\")}\n-----END ${e}-----\n`}a(oO,\"toPem\");function Ju(r){const e=r.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);if(!e)throw new Error(\"no certificate in the PEM text\");return Buffer.from(e[1].replace(/\\s+/g,\"\"),\"base64\")}a(Ju,\"certificateDer\");function bT(r){return(0,$r.createPrivateKey)(r)}a(bT,\"privateKeyFromPem\");var Zu=require(\"node:crypto\");var sr=require(\"node:crypto\");var ST=a(()=>{const r=(0,sr.createECDH)(\"prime256v1\");const e=r.generateKeys();return{privateKey:r.getPrivateKey(),publicKey:e}},\"p256Keypair\");var wT=a(({publicKey:r,privateKey:e})=>{const t=(0,sr.createECDH)(\"prime256v1\");t.setPrivateKey(e);return t.computeSecret(r)},\"p256PreMasterSecret\");var ET=Buffer.from(\"302e020100300506032b656e04220420\",\"hex\");var TT=Buffer.from(\"302a300506032b656e032100\",\"hex\");var xT=a(()=>{const{privateKey:r,publicKey:e}=(0,sr.generateKeyPairSync)(\"x25519\");return{privateKey:r.export({type:\"pkcs8\",format:\"der\"}).subarray(ET.length),publicKey:e.export({type:\"spki\",format:\"der\"}).subarray(TT.length)}},\"x25519Keypair\");var RT=a(({publicKey:r,privateKey:e})=>(0,sr.diffieHellman)({privateKey:(0,sr.createPrivateKey)({key:Buffer.concat([ET,e]),format:\"der\",type:\"pkcs8\"}),publicKey:(0,sr.createPublicKey)({key:Buffer.concat([TT,r]),format:\"der\",type:\"spki\"})}),\"x25519PreMasterSecret\");function Qu(r,e,t){switch(t){case jr.secp256r1_23:return wT({publicKey:r,privateKey:e});case jr.x25519_29:return RT({publicKey:r,privateKey:e});default:throw new Error}}a(Qu,\"prfPreMasterSecret\");function _T(r,e,t){const s=(0,Zu.createHmac)(r,e);s.update(t);return s.digest()}a(_T,\"hmac\");function uc(r,e,t,s=\"sha256\"){const n=t;const i=[];let o=e;do{o=_T(s,r,o);const c=_T(s,r,Buffer.concat([o,e]));i.push(c);t-=c.length}while(t>0);return Buffer.concat(i,n)}a(uc,\"prfPHash\");function ef(r,e,t){const s=Buffer.concat([Buffer.from(\"master secret\"),e,t]);return uc(r,s,48)}a(ef,\"prfMasterSecret\");function tf(r,e){const t=vT(\"sha256\",e);const s=\"extended master secret\";return uc(r,Buffer.concat([Buffer.from(s),t]),48)}a(tf,\"prfExtendedMasterSecret\");function CT(r,e,t,s,n,i){const o=i?s:n;const c=i?n:s;const l=Buffer.concat([Buffer.from(r),o,c]);return uc(t,l,e)}a(CT,\"exportKeyingMaterial\");function vT(r,e){return(0,Zu.createHash)(r).update(e).digest()}a(vT,\"hash\");function AT(r,e,t,s=12){const n=vT(\"sha256\",e);return uc(r,Buffer.concat([Buffer.from(t),n]),s)}a(AT,\"prfVerifyData\");function IT(r,e){return AT(r,e,\"client finished\")}a(IT,\"prfVerifyDataClient\");function OT(r,e){return AT(r,e,\"server finished\")}a(OT,\"prfVerifyDataServer\");function kT(r,e,t,s,n,i,o=\"sha256\"){const c=s*2+n*2;const l=r;const u=Buffer.concat([t,e]);const f=uc(l,Buffer.concat([Buffer.from(\"key expansion\"),u]),c,o);const d=new q.BinaryReader(f);const h=d.readBuffer(s);const p=d.readBuffer(s);const m=d.readBuffer(n);const y=d.readBuffer(n);const w=Buffer.alloc(i,0);const S=Buffer.alloc(i,0);m.copy(w,0);y.copy(S,0);return{clientWriteKey:h,serverWriteKey:p,clientNonce:w,serverNonce:S}}a(kT,\"prfEncryptionKeys\");var dt={CLIENT:1,SERVER:2};var fc=class{static{a(this,\"AbstractCipher\")}constructor(){this.id=0;this.verifyDataLength=12}init(...e){throw new Error(\"not implemented\")}encrypt(...e){throw new Error(\"not implemented\")}decrypt(...e){throw new Error(\"not implemented\")}toString(){return this.name}};var{encode:aO,types:dm}=q;var Hr=class{static{a(this,\"CipherContext\")}constructor(e,t,s,n){this.sessionType=e;this.certPem=t;this.keyPem=s;if(t&&s&&n){this.parseX509(t,s,n)}}static{this.createSelfSignedCertificateWithKey=async(e,t)=>{const{certPem:s,keyPem:n}=yT(e.signature===Tt.rsa_1?\"rsa\":\"ecdsa\");return{certPem:s,keyPem:n,signatureHash:e}}}encryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const n=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});e.fragment=n;e.recordLayerHeader.contentLen=n.length;return e}decryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const n=this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});return n}verifyData(e){if(this.sessionType===dt.CLIENT)return IT(this.masterSecret,e);else return OT(this.masterSecret,e)}signatureData(e,t){return(0,hm.sign)(t,e,this.localPrivateKey)}generateKeySignature(e){const t=this.sessionType===dt.CLIENT?this.localRandom:this.remoteRandom;const s=this.sessionType===dt.SERVER?this.localRandom:this.remoteRandom;const n=this.valueKeySignature(t.serialize(),s.serialize(),this.localKeyPair.publicKey,this.namedCurve);return(0,hm.sign)(e,n,this.localPrivateKey)}parseX509(e,t,s){this.localCert=Ju(e);this.localPrivateKey=bT(t);this.signatureHashAlgorithm=s}valueKeySignature(e,t,s,n){const i=aO({type:Xu.named_curve_3,curve:n,len:s.length},{type:dm.uint8,curve:dm.uint16be,len:dm.uint8});return Buffer.concat([e,t,i,s])}};var qr=class{static{a(this,\"SrtpContext\")}static findMatchingSRTPProfile(e,t){for(const s of t){if(e.includes(s))return s}}};var dc=a(r=>\"0x\"+r.toString(\"hex\").replace(/(.)(.)/g,\"$1$2 \").split(\" \").filter(e=>e!=void 0&&e.length>0).join(\",0x\"),\"dumpBuffer\");var rf=a(r=>Object.entries({...r}).reduce((e,[t,s])=>{if(typeof s===\"number\"||typeof s===\"string\"){e[t]=s}if(Buffer.isBuffer(s)){e[t]=dc(s)}return e},{}),\"getObjectSummary\");var{decode:cO,encode:lO,types:$i}=q;var ge=class r{static{a(this,\"FragmentedHandshake\")}static{this.spec={msg_type:$i.uint8,length:$i.uint24be,message_seq:$i.uint16be,fragment_offset:$i.uint24be,fragment_length:$i.uint24be,fragment:$i.buffer(e=>e.current.fragment_length)}}constructor(e,t,s,n,i,o){this.msg_type=e;this.length=t;this.message_seq=s;this.fragment_offset=n;this.fragment_length=i;this.fragment=o}get summary(){return rf(this)}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(cO(e,r.spec)))}serialize(){return lO(this,r.spec)}chunk(e){let t=0;const s=this.fragment.length;if(s===0)return[new r(this.msg_type,s,this.message_seq,t,0,this.fragment)];const n=[];if(!e){e=1280-(20+8)-(1+3+2+3+3)}while(t<s){const i=Math.min(e,s-t);const o=Buffer.from(this.fragment.slice(t,t+i));if(o.length<=0){throw new Error(`Zero or less bytes processed while fragmenting handshake message.`)}n.push(new r(this.msg_type,s,this.message_seq,t,o.length,o));t+=o.length}return n}static assemble(e){if(!e?.length){throw new Error(\"cannot reassemble handshake from empty array\")}e=e.sort((s,n)=>s.fragment_offset-n.fragment_offset);const t=Buffer.alloc(e[0].length);for(const s of e){s.fragment.copy(t,s.fragment_offset)}return new r(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){const s=e.find(n=>n.msg_type===t);if(!s)return[];if(!e?.length)return[];return e.filter(n=>{return n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length})}};var{types:uO}=q;var{uint16be:sf,uint24be:fO,buffer:PT,array:dO,uint8:hc,string:hO}=uO;var pO={type:sf,data:PT(sf)};var pc=dO(pO,sf,\"bytes\");var NT=PT(fO);var LT=hc;var MT=hO(sf);var DT={hash:hc,signature:hc};var Fi={major:hc,minor:hc};var $;(function(r){r[r[\"hello_request_0\"]=0]=\"hello_request_0\";r[r[\"client_hello_1\"]=1]=\"client_hello_1\";r[r[\"server_hello_2\"]=2]=\"server_hello_2\";r[r[\"hello_verify_request_3\"]=3]=\"hello_verify_request_3\";r[r[\"certificate_11\"]=11]=\"certificate_11\";r[r[\"server_key_exchange_12\"]=12]=\"server_key_exchange_12\";r[r[\"certificate_request_13\"]=13]=\"certificate_request_13\";r[r[\"server_hello_done_14\"]=14]=\"server_hello_done_14\";r[r[\"certificate_verify_15\"]=15]=\"certificate_verify_15\";r[r[\"client_key_exchange_16\"]=16]=\"client_key_exchange_16\";r[r[\"finished_20\"]=20]=\"finished_20\"})($||($={}));var UT=require(\"node:crypto\");var{decode:mO,encode:gO,types:BT}=q;var ht=class r{static{a(this,\"DtlsRandom\")}static{this.spec={gmt_unix_time:BT.uint32be,random_bytes:BT.buffer(28)}}constructor(e=Math.floor(Date.now()/1e3),t=(0,UT.randomBytes)(28)){this.gmt_unix_time=e;this.random_bytes=t}static deSerialize(e){return new r(...Object.values(mO(e,r.spec)))}static from(e){return new r(...Object.values(e))}serialize(){return gO(this,r.spec)}};var{decode:yO,encode:bO,types:Mt}=q;var Hi=class r{static{a(this,\"ClientHello\")}static{this.spec={clientVersion:{major:Mt.uint8,minor:Mt.uint8},random:ht.spec,sessionId:Mt.buffer(Mt.uint8),cookie:Mt.buffer(Mt.uint8),cipherSuites:Mt.array(Mt.uint16be,Mt.uint16be,\"bytes\"),compressionMethods:Mt.array(Mt.uint8,Mt.uint8,\"bytes\"),extensions:pc}}constructor(e,t,s,n,i,o,c){this.clientVersion=e;this.random=t;this.sessionId=s;this.cookie=n;this.cipherSuites=i;this.compressionMethods=o;this.extensions=c;this.msgType=$.client_hello_1;this.messageSeq=0}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(yO(e,r.spec)))}serialize(){return bO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var $T=require(\"node:timers/promises\");var{decode:SO,encode:wO,types:nf}=q;var of=class r{static{a(this,\"MACHeader\")}static{this.spec={epoch:nf.uint16be,sequenceNumber:nf.uint48be,contentType:nf.uint8,protocolVersion:Fi,contentLen:nf.uint16be}}constructor(e,t,s,n,i){this.epoch=e;this.sequenceNumber=t;this.contentType=s;this.protocolVersion=n;this.contentLen=i}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(SO(e,r.spec)))}serialize(){return wO(this,r.spec)}};var qi=class r{static{a(this,\"DtlsPlaintext\")}constructor(e,t){this.recordLayerHeader=e;this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:dc(this.fragment)}}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){if(e.length<13){throw new Error(\"Invalid DTLS record: buffer is too short\")}const t=e.readUInt8(0);const s=e.readUInt8(1);const n=e.readUInt8(2);const i=e.readUInt16BE(3);const o=e.slice(5,11).readUIntBE(0,6);const c=e.readUInt16BE(11);if(e.length<13+c){throw new Error(\"Invalid DTLS record: fragment length exceeds buffer\")}const l=e.slice(13,13+c);const u=new r({contentType:t,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:c},l);return u}serialize(){const e=this.fragment.length;const t=13+e;const s=Buffer.alloc(t);s.writeUInt8(this.recordLayerHeader.contentType,0);s.writeUInt8(this.recordLayerHeader.protocolVersion.major,1);s.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2);s.writeUInt16BE(this.recordLayerHeader.epoch,3);s.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6);s.writeUInt16BE(e,11);this.fragment.copy(s,13);return s}computeMACHeader(){return new of(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}};var af=a(r=>e=>{r.lastFlight=e;return e.flatMap(t=>{t.messageSeq=r.sequenceNumber++;const s=t.toFragment();const n=s.chunk();return n})},\"createFragments\");var wr=a(r=>(e,t)=>{return e.map(s=>{const n=new qi({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment);return n})},\"createPlaintext\");var Ee;(function(r){r[r[\"changeCipherSpec\"]=20]=\"changeCipherSpec\";r[r[\"alert\"]=21]=\"alert\";r[r[\"handshake\"]=22]=\"handshake\";r[r[\"applicationData\"]=23]=\"applicationData\"})(Ee||(Ee={}));var mc;(function(r){r[r[\"CloseNotify\"]=0]=\"CloseNotify\";r[r[\"UnexpectedMessage\"]=10]=\"UnexpectedMessage\";r[r[\"BadRecordMac\"]=20]=\"BadRecordMac\";r[r[\"DecryptionFailed\"]=21]=\"DecryptionFailed\";r[r[\"RecordOverflow\"]=22]=\"RecordOverflow\";r[r[\"DecompressionFailure\"]=30]=\"DecompressionFailure\";r[r[\"HandshakeFailure\"]=40]=\"HandshakeFailure\";r[r[\"NoCertificate\"]=41]=\"NoCertificate\";r[r[\"BadCertificate\"]=42]=\"BadCertificate\";r[r[\"UnsupportedCertificate\"]=43]=\"UnsupportedCertificate\";r[r[\"CertificateRevoked\"]=44]=\"CertificateRevoked\";r[r[\"CertificateExpired\"]=45]=\"CertificateExpired\";r[r[\"CertificateUnknown\"]=46]=\"CertificateUnknown\";r[r[\"IllegalParameter\"]=47]=\"IllegalParameter\";r[r[\"UnknownCa\"]=48]=\"UnknownCa\";r[r[\"AccessDenied\"]=49]=\"AccessDenied\";r[r[\"DecodeError\"]=50]=\"DecodeError\";r[r[\"DecryptError\"]=51]=\"DecryptError\";r[r[\"ExportRestriction\"]=60]=\"ExportRestriction\";r[r[\"ProtocolVersion\"]=70]=\"ProtocolVersion\";r[r[\"InsufficientSecurity\"]=71]=\"InsufficientSecurity\";r[r[\"InternalError\"]=80]=\"InternalError\";r[r[\"UserCanceled\"]=90]=\"UserCanceled\";r[r[\"NoRenegotiation\"]=100]=\"NoRenegotiation\";r[r[\"UnsupportedExtension\"]=110]=\"UnsupportedExtension\"})(mc||(mc={}));var EO=P(\"webrtc/dtls/flight/flight:warn\");var jT=P(\"webrtc/dtls/flight/flight:err\");var Dt=class r{static{a(this,\"Flight\")}static{this.RetransmitCount=10}constructor(e,t,s,n){this.transport=e;this.dtls=t;this.flight=s;this.nextFlight=n;this.state=\"PREPARING\";this.send=i=>Promise.all(i.map(o=>this.transport.send(o)))}createPacket(e){const t=af(this.dtls)(e);this.dtls.bufferHandshakeCache(t,true,this.flight);const s=wr(this.dtls)(t.map(n=>({type:Ee.handshake,fragment:n.serialize()})),++this.dtls.recordSequenceNumber);return s}async transmit(e){const t=this.transport.closing.signal;let s=0;for(;s<=r.RetransmitCount;s++){if(t.aborted)return;this.setState(\"SENDING\");this.send(e).catch(n=>{jT(\"fail to send\",n)});this.setState(\"WAITING\");if(this.nextFlight===void 0){this.setState(\"FINISHED\");break}try{await(0,$T.setTimeout)(1e3*((s+1)/2),void 0,{signal:t})}catch{return}if(this.dtls.flight>=this.nextFlight){this.setState(\"FINISHED\");break}else{EO(this.dtls.sessionId,\"retransmit\",s,this.dtls.flight)}}if(s>r.RetransmitCount){jT(this.dtls.sessionId,\"retransmit failed\",s);throw new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}}setState(e){this.state=e}};var cf=class extends Dt{static{a(this,\"Flight1\")}constructor(e,t,s){super(e,t,1,3);this.cipher=s}async exec(e){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;const t=new Hi({major:255-1,minor:255-2},new ht,Buffer.from([]),Buffer.from([]),hT,[0],e);this.dtls.version=t.clientVersion;this.cipher.localRandom=ht.from(t.random);const s=this.createPacket([t]);const n=Buffer.concat(s.map(i=>i.serialize()));await this.transmit([n])}};var TO=P(\"webrtc/dtls/flight/client/flight3:log\");var lf=class extends Dt{static{a(this,\"Flight3\")}constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3;this.dtls.handshakeCache=[];const[t]=this.dtls.lastFlight;TO(\"dtls version\",t.clientVersion);t.cookie=e.cookie;this.dtls.cookie=e.cookie;const s=this.createPacket([t]);const n=Buffer.concat(s.map(i=>i.serialize()));await this.transmit([n])}};var uf={NULL:0,ECDHE:1};var gc={NULL:0,RSA:1,ECDSA:2,PSK:3};var yc={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5};var bn=class{static{a(this,\"KeyExchange\")}constructor(){this.id=0}toString(){return this.name}};function FT(){const r=new bn;r.id=yc.RSA;r.name=\"RSA\";r.keyType=gc.RSA;return r}a(FT,\"createRSAKeyExchange\");function HT(){const r=new bn;r.id=yc.ECDHE_RSA;r.name=\"ECDHE_RSA\";r.signType=uf.ECDHE;r.keyType=gc.RSA;return r}a(HT,\"createECDHERSAKeyExchange\");function qT(){const r=new bn;r.id=yc.ECDHE_ECDSA;r.name=\"ECDHE_ECDSA\";r.signType=uf.ECDHE;r.keyType=gc.ECDSA;return r}a(qT,\"createECDHEECDSAKeyExchange\");function zT(){const r=new bn;r.id=yc.PSK;r.name=\"PSK\";r.signType=uf.NULL;r.keyType=gc.PSK;return r}a(zT,\"createPSKKeyExchange\");function GT(){const r=new bn;r.id=yc.ECDHE_PSK;r.name=\"ECDHE_PSK\";r.signType=uf.ECDHE;r.keyType=gc.PSK;return r}a(GT,\"createECDHEPSKKeyExchange\");var ff=require(\"node:crypto\");var xO=P(\"webrtc/dtls/cipher/suites/aead:err\");var bc=class extends fc{static{a(this,\"AEADCipher\")}constructor(){super();this.keyLength=0;this.nonceLength=0;this.ivLength=0;this.authTagLength=0;this.nonceImplicitLength=0;this.nonceExplicitLength=0}get summary(){return rf(this)}init(e,t,s){const n=kT(e,s,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=n.clientWriteKey;this.serverWriteKey=n.serverWriteKey;this.clientNonce=n.clientNonce;this.serverNonce=n.serverNonce}encrypt(e,t,s){const n=e===dt.CLIENT;const i=n?this.clientNonce:this.serverNonce;const o=n?this.clientWriteKey:this.serverWriteKey;if(!i||!o)throw new Error;i.writeUInt16BE(s.epoch,this.nonceImplicitLength);i.writeUIntBE(s.sequenceNumber,this.nonceImplicitLength+2,6);const c=i.slice(this.nonceImplicitLength);const l=this.encodeAdditionalBuffer(s,t.length);const u=(0,ff.createCipheriv)(this.blockAlgorithm,o,i,{authTagLength:this.authTagLength});u.setAAD(l,{plaintextLength:t.length});const f=u.update(t);const d=u.final();const h=u.getAuthTag();return Buffer.concat([c,f,d,h])}encodeAdditionalBuffer(e,t){const s=Buffer.alloc(13);s.writeUInt16BE(e.epoch,0);s.writeUintBE(e.sequenceNumber,2,6);s.writeUInt8(e.type,8);s.writeUInt16BE(e.version,9);s.writeUInt16BE(t,11);return s}decrypt(e,t,s){const n=e===dt.CLIENT;const i=n?this.serverNonce:this.clientNonce;const o=n?this.serverWriteKey:this.clientWriteKey;if(!i||!o)throw new Error;const c=t.subarray(0,this.nonceExplicitLength);c.copy(i,this.nonceImplicitLength);const l=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength);const u=t.subarray(t.length-this.authTagLength);const f=this.encodeAdditionalBuffer(s,l.length);const d=(0,ff.createDecipheriv)(this.blockAlgorithm,o,i,{authTagLength:this.authTagLength});d.setAuthTag(u);d.setAAD(f,{plaintextLength:l.length});const h=d.update(l);try{const p=d.final();return p.length>0?Buffer.concat([h,p]):h}catch(p){xO(\"decrypt failed\",p,e,dc(t),s,this.summary);throw p}}};var Me={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395};var Sc={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var wc={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var KT=FT();var WT=HT();var VT=qT();var XT=zT();var YT=GT();function df(r){switch(r){case Me.TLS_RSA_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_RSA_WITH_AES_128_GCM_SHA256,\"TLS_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",KT,Sc);case Me.TLS_RSA_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_RSA_WITH_AES_256_GCM_SHA384,\"TLS_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",KT,wc,\"sha384\");case Me.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",WT,Sc);case Me.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",WT,wc,\"sha384\");case Me.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",VT,Sc);case Me.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",VT,wc,\"sha384\");case Me.TLS_PSK_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_PSK_WITH_AES_128_GCM_SHA256,\"TLS_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",XT,Sc,\"sha256\");case Me.TLS_PSK_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_PSK_WITH_AES_256_GCM_SHA384,\"TLS_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",XT,wc,\"sha384\");case Me.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",YT,Sc,\"sha256\");case Me.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",YT,wc,\"sha384\");default:break}return null}a(df,\"createCipher\");function Er(r,e,t,s,n,i=\"sha256\"){const o=new bc;o.id=r;o.name=e;o.blockAlgorithm=t;o.kx=s;o.hashAlgorithm=i;o.keyLength=n.K_LEN;o.nonceLength=n.N_MAX;o.nonceImplicitLength=4;o.nonceExplicitLength=8;o.ivLength=o.nonceImplicitLength;o.authTagLength=16;return o}a(Er,\"createAEADCipher\");function hf(r){switch(r){case jr.secp256r1_23:{const{privateKey:e,publicKey:t}=ST();return{curve:r,privateKey:e,publicKey:t}}case jr.x25519_29:{const{privateKey:e,publicKey:t}=xT();return{curve:r,privateKey:e,publicKey:t}}default:throw new Error}}a(hf,\"generateKeyPair\");var Tr=class{static{a(this,\"ExtendedMasterSecret\")}static{this.type=23}};var{decode:RO,encode:_O,types:JT}=q;var xr=class r{static{a(this,\"RenegotiationIndication\")}static{this.type=65281}static{this.spec={type:JT.uint16be,data:JT.uint8}}constructor(e={}){this.type=r.type;this.data=0;Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(RO(e,r.spec))}serialize(){return _O(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:CO,encode:vO,types:pm}=q;var Bt=class r{static{a(this,\"UseSRTP\")}static{this.type=14}static{this.spec={type:pm.uint16be,data:pm.buffer(pm.uint16be)}}constructor(e={}){this.type=r.type;this.data=Buffer.from([]);this.profiles=[];this.mki=Buffer.from([0]);Object.assign(this,e)}static create(e,t){const s=new r({profiles:e,mki:t});return s}static deSerialize(e){const t=new r(CO(e,r.spec));const s=t.data.readUInt16BE();const n=new Array(s/2);for(let i=0;i<n.length;i++){n[i]=t.data.readUInt16BE(i*2+2)}t.profiles=n;t.mki=t.data.slice(s+2);return t}serialize(){const e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);const t=Buffer.concat([e,...this.profiles.map(s=>{const n=Buffer.alloc(2);n.writeUInt16BE(s);return n}),this.mki]);this.data=t;return vO(this,r.spec)}static fromData(e){const t=Buffer.alloc(4);t.writeUInt16BE(r.type);t.writeUInt16BE(e.length,2);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}};var{decode:AO,encode:IO,types:ZT}=q;var zr=class r{static{a(this,\"Certificate\")}static{this.spec={certificateList:ZT.array(NT,ZT.uint24be,\"bytes\")}}constructor(e){this.certificateList=e;this.msgType=$.certificate_11}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(...Object.values(AO(e,r.spec)))}serialize(){return IO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:OO,encode:kO,types:PO}=q;var zi=class r{static{a(this,\"ChangeCipherSpec\")}static{this.spec={type:PO.uint8}}constructor(e=1){this.type=e}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(OO(e,r.spec)))}serialize(){return kO(this,r.spec)}};var{decode:NO,encode:LO,types:mm}=q;var Gi=class r{static{a(this,\"CertificateVerify\")}static{this.spec={algorithm:mm.uint16be,signature:mm.buffer(mm.uint16be)}}constructor(e,t){this.algorithm=e;this.signature=t;this.msgType=$.certificate_verify_15}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){const t=NO(e,r.spec);return new r(...Object.values(t))}serialize(){return LO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:MO,encode:DO,types:QT}=q;var Ki=class r{static{a(this,\"ClientKeyExchange\")}static{this.spec={publicKey:QT.buffer(QT.uint8)}}constructor(e){this.publicKey=e;this.msgType=$.client_key_exchange_16}static createEmpty(){return new r(void 0)}static deSerialize(e){const t=MO(e,r.spec);return new r(...Object.values(t))}serialize(){return DO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Sn=class r{static{a(this,\"Finished\")}constructor(e){this.verifyData=e;this.msgType=$.finished_20}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(e)}serialize(){return this.verifyData}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:BO,encode:UO,types:Wi}=q;var Vi=class r{static{a(this,\"ServerCertificateRequest\")}static{this.spec={certificateTypes:Wi.array(LT,Wi.uint8,\"bytes\"),signatures:Wi.array(DT,Wi.uint16be,\"bytes\"),authorities:Wi.array(MT,Wi.uint16be,\"bytes\")}}constructor(e,t,s){this.certificateTypes=e;this.signatures=t;this.authorities=s;this.msgType=$.certificate_request_13}static createEmpty(){return new r(void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(BO(e,r.spec)))}serialize(){return UO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:ex,encode:tx,types:pf}=q;var Xi=class r{static{a(this,\"ServerHello\")}static{this.spec={serverVersion:Fi,random:ht.spec,sessionId:pf.buffer(pf.uint8),cipherSuite:pf.uint16be,compressionMethod:pf.uint8}}constructor(e,t,s,n,i,o){this.serverVersion=e;this.random=t;this.sessionId=s;this.cipherSuite=n;this.compressionMethod=i;this.extensions=o;this.msgType=$.server_hello_2}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=ex(e,r.spec);const s=new r(...Object.values(t));const n=s.serialize();if(n.length<e.length){return new r(...Object.values(ex(e,{...r.spec,extensions:pc})))}return s}serialize(){return this.extensions===void 0?tx(this,r.spec):tx(this,{...r.spec,extensions:pc})}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:jO,encode:$O}=q;var Yi=class r{static{a(this,\"ServerHelloDone\")}constructor(){this.msgType=$.server_hello_done_14}static{this.spec={}}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(jO(e,r.spec)))}serialize(){return $O(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{encode:FO}=q;function rx(r,e){return FO(r,e)}a(rx,\"encodeBuffer\");var{decode:HO,types:Is}=q;var Ji=class r{static{a(this,\"ServerKeyExchange\")}static{this.spec={ellipticCurveType:Is.uint8,namedCurve:Is.uint16be,publicKeyLength:Is.uint8,publicKey:Is.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Is.uint8,signatureAlgorithm:Is.uint8,signatureLength:Is.uint16be,signature:Is.buffer(e=>e.current.signatureLength)}}constructor(e,t,s,n,i,o,c,l){this.ellipticCurveType=e;this.namedCurve=t;this.publicKeyLength=s;this.publicKey=n;this.hashAlgorithm=i;this.signatureAlgorithm=o;this.signatureLength=c;this.signature=l;this.msgType=$.server_key_exchange_12}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=HO(e,r.spec);return new r(...Object.values(t))}serialize(){const e=rx(this,r.spec);return e}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Ze=P(\"webrtc/dtls/flight/client/flight5:log\");var mf=class extends Dt{static{a(this,\"Flight5\")}constructor(e,t,s,n){super(e,t,5,7);this.cipher=s;this.srtp=n}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,4);const t=(()=>{switch(e.msg_type){case $.server_hello_2:return Xi.deSerialize(e.fragment);case $.certificate_11:return zr.deSerialize(e.fragment);case $.server_key_exchange_12:return Ji.deSerialize(e.fragment);case $.certificate_request_13:return Vi.deSerialize(e.fragment);case $.server_hello_done_14:return Yi.deSerialize(e.fragment)}})();if(t){Zi[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}}async exec(){if(this.dtls.flight===5){Ze(this.dtls.sessionId,\"flight5 twice\");this.send(this.dtls.lastMessage).catch(s=>Ze(\"send failed\",s));return}this.dtls.flight=5;const e=this.dtls.requestedCertificateTypes.length>0;Ze(this.dtls.sessionId,\"send flight5\",e);const t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(s=>s);this.dtls.lastMessage=t;await this.transmit(t)}sendCertificate(){const e=new zr([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);const s=Buffer.concat(t.map(n=>n.serialize()));return s}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;const e=new Ki(this.cipher.localKeyPair.publicKey);const t=this.createPacket([e]);const s=Buffer.concat(t.map(l=>l.serialize()));const n=this.cipher.localKeyPair;const i=this.cipher.remoteKeyPair;if(!i.publicKey)throw new Error(\"not exist\");const o=Qu(i.publicKey,n.privateKey,n.curve);Ze(this.dtls.sessionId,\"extendedMasterSecret\",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);const c=Buffer.concat(this.dtls.sortedHandshakeCache.map(l=>l.serialize()));this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?tf(o,c):ef(o,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize());this.cipher.cipher=df(this.cipher.cipherSuite);this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize());Ze(this.dtls.sessionId,\"cipher\",this.cipher.cipher.summary);return s}sendCertificateVerify(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(c=>c.serialize()));const t=this.cipher.signatureData(e,\"sha256\");const s=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case Tt.ecdsa_3:return um.ecdsa_secp256r1_sha256;case Tt.rsa_1:return um.rsa_pkcs1_sha256}})();if(!s)throw new Error;Ze(this.dtls.sessionId,\"signatureScheme\",this.cipher.signatureHashAlgorithm?.signature,s);const n=new Gi(s,t);const i=this.createPacket([n]);const o=Buffer.concat(i.map(c=>c.serialize()));return o}sendChangeCipherSpec(){const e=zi.createEmpty().serialize();const t=wr(this.dtls)([{type:Ee.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(n=>n.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Sn(t);this.dtls.epoch=1;const[n]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const i=this.cipher.encryptPacket(n).serialize();Ze(this.dtls.sessionId,\"finished\",this.cipher.cipher.summary);return i}};var Zi={};Zi[$.server_hello_2]=({cipher:r,srtp:e,dtls:t})=>s=>{Ze(t.sessionId,\"serverHello\",s.cipherSuite);r.remoteRandom=ht.from(s.random);r.cipherSuite=s.cipherSuite;Ze(t.sessionId,\"selected cipherSuite\",r.cipherSuite);if(s.extensions){s.extensions.forEach(n=>{switch(n.type){case Bt.type:{const i=Bt.fromData(n.data);const o=qr.findMatchingSRTPProfile(i.profiles,t.options.srtpProfiles||[]);Ze(t.sessionId,\"selected srtp profile\",o);if(o==void 0)return;e.srtpProfile=o}break;case Tr.type:t.remoteExtendedMasterSecret=true;break;case xr.type:Ze(t.sessionId,\"RenegotiationIndication\");break}})}};Zi[$.certificate_11]=({cipher:r,dtls:e})=>t=>{Ze(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Zi[$.server_key_exchange_12]=({cipher:r,dtls:e})=>t=>{if(!r.localRandom||!r.remoteRandom)throw new Error;Ze(e.sessionId,\"ServerKeyExchange\",t);Ze(e.sessionId,\"selected curve\",t.namedCurve);r.remoteKeyPair={curve:t.namedCurve,publicKey:t.publicKey};r.localKeyPair=hf(t.namedCurve)};Zi[$.certificate_request_13]=({dtls:r})=>e=>{Ze(r.sessionId,\"certificate_request\",e);r.requestedCertificateTypes=e.certificateTypes;r.requestedSignatureAlgorithms=e.signatures};Zi[$.server_hello_done_14]=({dtls:r})=>e=>{Ze(r.sessionId,\"server_hello_done\",e)};var{decode:qO,encode:zO,types:sx}=q;var Qi=class r{static{a(this,\"ServerHelloVerifyRequest\")}static{this.spec={serverVersion:Fi,cookie:sx.buffer(sx.uint8)}}constructor(e,t){this.serverVersion=e;this.cookie=t;this.msgType=$.hello_verify_request_3}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){return new r(...Object.values(qO(e,r.spec)))}serialize(){return zO(this,r.spec)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var ux=require(\"node:timers/promises\");var GO=P(\"webrtc/dtls/context/dtls:log\");var Ec=class{static{a(this,\"DtlsContext\")}constructor(e,t){this.options=e;this.sessionType=t;this.version={major:255-1,minor:255-2};this.lastFlight=[];this.lastMessage=[];this.recordSequenceNumber=0;this.sequenceNumber=0;this.epoch=0;this.flight=0;this.handshakeCache={};this.requestedCertificateTypes=[];this.requestedSignatureAlgorithms=[];this.remoteExtendedMasterSecret=false;this.checkHandshakesExist=s=>!s.find(n=>this.sortedHandshakeCache.find(i=>i.msg_type===n)==void 0)}get sessionId(){return this.cookie?this.cookie.toString(\"hex\").slice(0,10):\"\"}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((t,s)=>t.message_seq-s.message_seq))}bufferHandshakeCache(e,t,s){if(!this.handshakeCache[s]){this.handshakeCache[s]={data:[],isLocal:t,flight:s}}const n=e.filter(i=>{const o=this.handshakeCache[s].data.find(c=>c.msg_type===i.msg_type);if(o){GO(this.sessionId,\"exist\",o.summary,t,s);return false}return true});this.handshakeCache[s].data=[...this.handshakeCache[s].data,...n]}};var gf=class{static{a(this,\"TransportContext\")}constructor(e){this.socket=e;this.closing=new AbortController;this.send=(t,s)=>{return this.socket.send(t,s)}}close(){this.closing.abort()}};var{decode:nx,encode:KO,types:yf}=q;var wn=class r{static{a(this,\"EllipticCurves\")}static{this.type=10}static{this.spec={type:yf.uint16be,data:yf.array(yf.uint16be,yf.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){return new r}static fromData(e){return new r({type:r.type,data:nx(e,r.spec.data)})}static deSerialize(e){return new r(nx(e,r.spec))}serialize(){return KO(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:WO,encode:VO,types:Tc}=q;var En=class r{static{a(this,\"Signature\")}static{this.type=13}static{this.spec={type:Tc.uint16be,data:Tc.array({hash:Tc.uint8,signature:Tc.uint8},Tc.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(WO(e,r.spec))}serialize(){return VO(this,r.spec)}static fromData(e){const t=Buffer.alloc(2);t.writeUInt16BE(r.type);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:XO,encode:YO,types:ix}=q;var xc=class r{static{a(this,\"Alert\")}static{this.spec={level:ix.uint8,description:ix.uint8}}constructor(e,t){this.level=e;this.description=t}static deSerialize(e){return new r(...Object.values(XO(e,r.spec)))}serialize(){return YO(this,r.spec)}};var ox=P(\"webrtc/dtls/record/receive:log\");var gm=P(\"webrtc/dtls/record/receive:err\");var ax=a(r=>{let e=0;const t=[];while(r.length>e){const s=r.readUInt16BE(e+11);if(r.length<e+(12+s)){break}const n=qi.deSerialize(r.subarray(e));t.push(n);e+=13+s}return t},\"parsePacket\");var cx=a((r,e)=>t=>{const s=t.recordLayerHeader.contentType;switch(s){case Ee.changeCipherSpec:{ox(r.sessionId,\"change cipher spec\");return[{type:Ee.changeCipherSpec,data:void 0}]}case Ee.handshake:{let n=t.fragment;try{if(t.recordLayerHeader.epoch>0){ox(r.sessionId,\"decrypt handshake\");n=e.decryptPacket(t)}}catch(i){gm(r.sessionId,\"decrypt failed\",i);throw i}try{let i=0;const o=[];while(n.length>i){const c=ge.deSerialize(n.subarray(i));o.push({type:Ee.handshake,data:c});i+=c.fragment_length+12}return o}catch(i){gm(r.sessionId,\"decSerialize failed\",i,n);throw i}}case Ee.applicationData:{return[{type:Ee.applicationData,data:e.decryptPacket(t)}]}case Ee.alert:{let n=xc.deSerialize(t.fragment);if(mc[n.description]==void 0){const i=e.decryptPacket(t);n=xc.deSerialize(i)}gm(r.sessionId,\"ContentType.alert\",n,mc[n.description],\"flight\",r.flight,\"lastFlight\",r.lastFlight);if(n.level>1){throw new Error(\"alert fatal error\")}return[{type:Ee.alert,data:void 0}]}default:{return[{type:Ee.alert,data:void 0}]}}},\"parsePlainText\");var{decode:JO,types:bf}=q;var ym=P(\"webrtc/dtls/socket:log\");var lx=P(\"webrtc/dtls/socket:err\");var Tn=class{static{a(this,\"DtlsSocket\")}constructor(e,t){this.options=e;this.sessionType=t;this.onConnect=new O;this.onData=new O;this.onError=new O;this.onClose=new O;this.srtp=new qr;this.connected=false;this.extensions=[];this.bufferFragmentedHandshakes=[];this.udpOnMessage=s=>{const n=ax(s);for(const i of n){try{const o=cx(this.dtls,this.cipher)(i);for(const c of o){switch(c.type){case Ee.handshake:{const l=c.data;const u=this.handleFragmentHandshake([l]);const f=Object.values(u.reduce((d,h)=>{if(!d[h.msg_type])d[h.msg_type]=[];d[h.msg_type].push(h);return d},{})).map(d=>ge.assemble(d)).sort((d,h)=>d.msg_type-h.msg_type);this.onHandleHandshakes(f).catch(d=>{lx(this.dtls.sessionId,\"onHandleHandshakes error\",d);this.onError.execute(d)})}break;case Ee.applicationData:{this.onData.execute(c.data)}break;case Ee.alert:this.onClose.execute();break}}}catch(o){lx(this.dtls.sessionId,\"catch udpOnMessage error\",o)}}};this.waitForReady=async s=>{for(let n=0;n<10;n++){if(s())return;await(0,ux.setTimeout)(100*n)}throw new Error(\"waitForReady timeout\")};this.send=async(s,n)=>{const i=wr(this.dtls)([{type:Ee.applicationData,fragment:s}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(i).serialize(),n)};this.dtls=new Ec(this.options,this.sessionType);this.cipher=new Hr(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.transport=new gf(this.options.transport);this.setupExtensions();this.transport.socket.onData=this.udpOnMessage}renegotiation(){ym(\"renegotiation\",this.sessionType);this.connected=false;this.cipher=new Hr(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.dtls=new Ec(this.options,this.sessionType);this.srtp=new qr;this.extensions=[];this.bufferFragmentedHandshakes=[]}setupExtensions(){ym(this.dtls.sessionId,\"support srtpProfiles\",this.options.srtpProfiles);if(this.options.srtpProfiles&&this.options.srtpProfiles.length>0){const e=Bt.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{const e=wn.createEmpty();e.data=Vu;this.extensions.push(e.extension)}{const e=En.createEmpty();e.data=Yu;this.extensions.push(e.extension)}if(this.options.extendedMasterSecret){this.extensions.push({type:Tr.type,data:Buffer.alloc(0)})}{const e=xr.createEmpty();this.extensions.push(e.extension)}}handleFragmentHandshake(e){let t=e.filter(s=>{if(s.fragment_length!==s.length){this.bufferFragmentedHandshakes.push(s);return false}return true});if(this.bufferFragmentedHandshakes.length>1){const[s]=this.bufferFragmentedHandshakes.slice(-1);if(s.fragment_offset+s.fragment_length===s.length){t=[...this.bufferFragmentedHandshakes,...t];this.bufferFragmentedHandshakes=[]}}return t}close(){this.transport.close();Ne(()=>this.transport.socket.close(),e=>ym(\"close failed\",e))}extractSessionKeys(e,t){const s=this.exportKeyingMaterial(\"EXTRACTOR-dtls_srtp\",e*2+t*2);const{clientKey:n,serverKey:i,clientSalt:o,serverSalt:c}=JO(s,{clientKey:bf.buffer(e),serverKey:bf.buffer(e),clientSalt:bf.buffer(t),serverSalt:bf.buffer(t)});if(this.sessionType===dt.CLIENT){return{localKey:n,localSalt:o,remoteKey:i,remoteSalt:c}}else{return{localKey:i,localSalt:c,remoteKey:n,remoteSalt:o}}}exportKeyingMaterial(e,t){return CT(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===dt.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}};var bm=P(\"webrtc/dtls/client:log\");var eo=class extends Tn{static{a(this,\"DtlsClient\")}constructor(e){super(e,dt.CLIENT);this.handleHandshakes=async t=>{bm(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case $.hello_verify_request_3:{const n=Qi.deSerialize(s.fragment);await new lf(this.transport,this.dtls).exec(n)}break;case $.server_hello_2:{if(this.connected)return;this.flight5=new mf(this.transport,this.dtls,this.cipher,this.srtp);this.flight5.handleHandshake(s)}break;case $.certificate_11:case $.server_key_exchange_12:case $.certificate_request_13:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s)}break;case $.server_hello_done_14:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s);const n=[11,12,this.options.certificateRequest&&13].filter(i=>typeof i===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(n));await this.flight5?.exec()}break;case $.finished_20:{this.dtls.flight=7;this.connected=true;this.onConnect.execute();bm(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;bm(this.dtls.sessionId,\"start client\")}async connect(){await new cf(this.transport,this.dtls,this.cipher).exec(this.extensions)}};var fx=require(\"node:crypto\");var nr=P(\"webrtc/dtls/flight/server/flight2:log\");var dx=a((r,e,t,s)=>n=>{nr(\"dtls version\",n.clientVersion);e.flight=2;e.recordSequenceNumber=0;e.sequenceNumber=0;n.extensions.forEach(d=>{switch(d.type){case wn.type:{const h=wn.fromData(d.data).data;nr(e.sessionId,\"curves\",h);const p=h.filter(m=>Vu.includes(m))[0];t.namedCurve=p;nr(e.sessionId,\"curve selected\",t.namedCurve)}break;case En.type:{if(!t.signatureHashAlgorithm)throw new Error(\"need to set certificate\");const h=En.fromData(d.data).data;nr(e.sessionId,\"hash,signature\",h);const p=h.find(y=>y.signature===t.signatureHashAlgorithm?.signature)?.signature;const m=h.find(y=>y.hash===t.signatureHashAlgorithm?.hash)?.hash;if(p==void 0||m==void 0){throw new Error(\"invalid signatureHash\")}}break;case Bt.type:{if(!e.options?.srtpProfiles)return;if(e.options.srtpProfiles.length===0)return;const h=Bt.fromData(d.data);nr(e.sessionId,\"srtp profiles\",h.profiles);const p=qr.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!p){throw new Error}s.srtpProfile=p;nr(e.sessionId,\"srtp profile selected\",s.srtpProfile)}break;case Tr.type:{e.remoteExtendedMasterSecret=true}break;case xr.type:{nr(e.sessionId,\"RenegotiationIndication\",d.data)}break;case 43:{const h=d.data.subarray(1);const p=[...h].map(m=>m.toString(10));nr(\"dtls supported version\",p)}break}});t.localRandom=new ht;t.remoteRandom=ht.from(n.random);const i=n.cipherSuites;nr(e.sessionId,\"cipher suites\",i);const o=(()=>{switch(t.signatureHashAlgorithm?.signature){case Tt.ecdsa_3:return Wu.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case Tt.rsa_1:return Wu.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o)){throw new Error(\"dtls cipher suite negotiation failed\")}t.cipherSuite=o;nr(e.sessionId,\"selected cipherSuite\",t.cipherSuite);t.localKeyPair=hf(t.namedCurve);e.cookie||=(0,fx.randomBytes)(20);const c=new Qi({major:255-1,minor:255-2},e.cookie);const l=af(e)([c]);const u=wr(e)(l.map(d=>({type:Ee.handshake,fragment:d.serialize()})),++e.recordSequenceNumber);const f=u.map(d=>d.serialize());for(const d of f){r.send(d).catch(h=>nr(\"send failed\",h))}},\"flight2\");var Sm=P(\"webrtc/dtls/flight/server/flight4:log\");var Sf=class extends Dt{static{a(this,\"Flight4\")}constructor(e,t,s,n){super(e,t,4,6);this.cipher=s;this.srtp=n}async exec(e,t=false){if(this.dtls.flight===4){Sm(this.dtls.sessionId,\"flight4 twice\");this.send(this.dtls.lastMessage).catch(n=>Sm(\"send failed\",n));return}this.dtls.flight=4;this.dtls.sequenceNumber=1;this.dtls.bufferHandshakeCache([e],false,4);const s=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(n=>n);this.dtls.lastMessage=s;await this.transmit(s)}sendServerHello(){const e=[];if(this.srtp.srtpProfile){e.push(Bt.create([this.srtp.srtpProfile],Buffer.from([0])).extension)}if(this.dtls.options.extendedMasterSecret){e.push({type:Tr.type,data:Buffer.alloc(0)})}const t=xr.createEmpty();e.push(t.extension);const s=new Xi(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e);const n=this.createPacket([s]);return Buffer.concat(n.map(i=>i.serialize()))}sendCertificate(){const e=new zr([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerKeyExchange(){const e=this.cipher.generateKeySignature(\"sha256\");if(!this.cipher.signatureHashAlgorithm)throw new Error(\"not exist\");const t=new Ji(Xu.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e);const s=this.createPacket([t]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificateRequest(){const e=new Vi(pT,Yu,[]);Sm(this.dtls.sessionId,\"sendCertificateRequest\",e);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerHelloDone(){const e=new Yi;const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}};var xn=P(\"webrtc/dtls/flight/server/flight6\");var wf=class extends Dt{static{a(this,\"Flight6\")}constructor(e,t,s){super(e,t,6);this.cipher=s}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,5);const t=(()=>{switch(e.msg_type){case $.certificate_11:return zr.deSerialize(e.fragment);case $.certificate_verify_15:return Gi.deSerialize(e.fragment);case $.client_key_exchange_16:return Ki.deSerialize(e.fragment);case $.finished_20:return Sn.deSerialize(e.fragment)}})();if(t){const s=Rc[t.msgType];if(!s){return}s({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){xn(this.dtls.sessionId,\"flight6 twice\");this.send(this.dtls.lastMessage).catch(t=>xn(\"send failed\",t));return}this.dtls.flight=6;const e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e;await this.transmit(e)}sendChangeCipherSpec(){const e=zi.createEmpty().serialize();const t=wr(this.dtls)([{type:Ee.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(n=>n.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Sn(t);this.dtls.epoch=1;const[n]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const i=this.cipher.encryptPacket(n).serialize();return i}};var Rc={};Rc[$.client_key_exchange_16]=({cipher:r,dtls:e})=>t=>{r.remoteKeyPair={curve:r.namedCurve,publicKey:t.publicKey};if(!r.remoteKeyPair.publicKey||!r.localKeyPair||!r.remoteRandom||!r.localRandom)throw new Error(\"not exist\");const s=Qu(r.remoteKeyPair.publicKey,r.localKeyPair.privateKey,r.localKeyPair.curve);xn(e.sessionId,\"extendedMasterSecret\",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);const n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));r.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?tf(s,n):ef(s,r.remoteRandom.serialize(),r.localRandom.serialize());r.cipher=df(r.cipherSuite);r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize());xn(e.sessionId,\"setup cipher\",r.cipher.summary)};Rc[$.certificate_11]=({cipher:r,dtls:e})=>t=>{xn(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Rc[$.certificate_verify_15]=({cipher:r,dtls:e})=>t=>{if(!r.remoteCertificate){throw new Error(\"client certificate missing before certificate verify\")}xn(e.sessionId,\"certificate_verify\",t.algorithm)};Rc[$.finished_20]=({dtls:r})=>e=>{xn(r.sessionId,\"finished\",e)};var to=P(\"webrtc/dtls/server:log\");var _c=class extends Tn{static{a(this,\"DtlsServer\")}constructor(e){super(e,dt.SERVER);this.handleHandshakes=async t=>{to(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case $.client_hello_1:{if(this.connected){this.renegotiation()}const n=Hi.deSerialize(s.fragment);if(n.cookie.length===0){to(this.dtls.sessionId,\"send flight2\");dx(this.transport,this.dtls,this.cipher,this.srtp)(n)}else if(this.dtls.cookie&&n.cookie.equals(this.dtls.cookie)){to(this.dtls.sessionId,\"send flight4\");await new Sf(this.transport,this.dtls,this.cipher,this.srtp).exec(s,this.options.certificateRequest)}else{to(\"wrong state\",{dtlsCookie:this.dtls.cookie?.toString(\"hex\").slice(10),helloCookie:n.cookie.toString(\"hex\").slice(10)})}}break;case $.certificate_11:case $.certificate_verify_15:case $.client_key_exchange_16:{if(this.connected)return;this.flight6=new wf(this.transport,this.dtls,this.cipher);this.flight6.handleHandshake(s)}break;case $.finished_20:{await this.waitForReady(()=>!!this.flight6);this.flight6?.handleHandshake(s);const n=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(i=>typeof i===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(n));await this.flight6?.exec();this.connected=true;this.onConnect.execute();to(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;to(this.dtls.sessionId,\"start server\")}};var wm=2;var Em=3;var hx=0;var ro=50;var Tm=51;var xm=53;var Tf=56;var xf=57;var Rm=\"0.0.0.0\";var _m=9;var Ef={auto:\"actpass\",client:\"active\",server:\"passive\"};var Cm=Object.keys(Ef).reduce((r,e)=>{const t=Ef[e];r[t]=e;return r},{});var px=[\"apt\",\"max-fr\",\"max-fs\",\"maxplaybackrate\",\"minptime\",\"packetization-mode\",\"level-asymmetry-allowed\",\"stereo\",\"useinbandfec\"];var vm=[\"cname\",\"msid\",\"mslabel\",\"label\"];var Am={SRTP_AES128_CM_HMAC_SHA1_80:Si,SRTP_AEAD_AES_128_GCM:Cs};var Rn=[\"sendonly\",\"sendrecv\"];var mx=[\"sendrecv\",\"recvonly\"];var so=554869826;var gx=8;var yx=1398035790;var Gr=20;var Im=24;var Om=1;var km=2;var bx=6;var Sx=50;var ie;(function(r){r[r[\"REQUEST\"]=0]=\"REQUEST\";r[r[\"INDICATION\"]=16]=\"INDICATION\";r[r[\"RESPONSE\"]=256]=\"RESPONSE\";r[r[\"ERROR\"]=272]=\"ERROR\"})(ie||(ie={}));var Ge;(function(r){r[r[\"BINDING\"]=1]=\"BINDING\";r[r[\"SHARED_SECRET\"]=2]=\"SHARED_SECRET\";r[r[\"ALLOCATE\"]=3]=\"ALLOCATE\";r[r[\"REFRESH\"]=4]=\"REFRESH\";r[r[\"SEND\"]=6]=\"SEND\";r[r[\"DATA\"]=7]=\"DATA\";r[r[\"CREATE_PERMISSION\"]=8]=\"CREATE_PERMISSION\";r[r[\"CHANNEL_BIND\"]=9]=\"CHANNEL_BIND\"})(Ge||(Ge={}));function wx(r){if(r.length<Gr){return false}if((r[0]&192)!==0){return false}if(r.readUInt32BE(4)!==so){return false}const e=r.readUInt16BE(2);if(e%4!==0){return false}return r.length===Gr+e}a(wx,\"isStunMessage\");var Ex=3e3;function Tx(r){const e=Buffer.alloc(2);e.writeUInt16BE(r.length,0);return Buffer.concat([e,r])}a(Tx,\"encodeTcpFrame\");function xx(r){const e=[];let t=0;while(r.length-t>=2){const s=r.readUInt16BE(t);if(r.length-t<s+2){break}e.push(r.subarray(t+2,t+2+s));t+=2+s}return{frames:e,rest:r.subarray(t)}}a(xx,\"splitTcpFrames\");var Pf=require(\"node:net\");var Ic=require(\"node:crypto\");var no=require(\"node:net\");function Pm(r){if((0,no.isIPv4)(r)){const n=Buffer.allocUnsafe(4);const i=r.split(\".\");for(let o=0;o<4;o++){n[o]=Number(i[o])&255}return n}if(!(0,no.isIPv6)(r)){throw new Error(`Invalid ip address: ${r}`)}const e=r.split(\":\",8);for(let n=0;n<e.length;n++){let i;if((0,no.isIPv4)(e[n])){i=Pm(e[n]);e[n]=i.subarray(0,2).toString(\"hex\")}if(i&&++n<8){e.splice(n,0,i.subarray(2,4).toString(\"hex\"))}}if(e[0]===\"\"){while(e.length<8)e.unshift(\"0\")}else if(e[e.length-1]===\"\"){while(e.length<8)e.push(\"0\")}else if(e.length<8){let n=0;for(;n<e.length&&e[n]!==\"\";n++);const i=[];for(let o=9-e.length;o>0;o--){i.push(\"0\")}e.splice(n,1,...i)}const t=Buffer.allocUnsafe(16);let s=0;for(const n of e){const i=Number.parseInt(n,16)||0;t[s++]=i>>8&255;t[s++]=i&255}return t}a(Pm,\"ipAddressToBuffer\");function Nm(r){if(r.length===4){return`${r[0]}.${r[1]}.${r[2]}.${r[3]}`}if(r.length!==16){throw new Error(`Invalid ip address buffer length: ${r.length}`)}const e=[];for(let s=0;s<16;s+=2){e.push(r.readUInt16BE(s).toString(16))}let t=e.join(\":\");t=t.replace(/(^|:)0(:0)*:0(:|$)/,\"$1::$3\");t=t.replace(/:{3,4}/,\"::\");return t}a(Nm,\"bufferToIpAddress\");function Rx(r){return(0,no.isIPv4)(r)}a(Rx,\"isIpV4Address\");function _n(r){const[e]=r;const t=Rx(e)?Om:km;const s=Buffer.alloc(4);s.writeUInt8(0,0);s.writeUInt8(t,1);s.writeUInt16BE(r[1],2);return Buffer.concat([s,Pm(e)])}a(_n,\"packAddress\");function ZO(r){if(r.length<4){throw new Error(\"STUN error code is less than 4 bytes\")}const e=r.readUInt8(2);const t=r.readUInt8(3);const s=r.slice(4).toString(\"utf8\");return[e*100+t,s]}a(ZO,\"unpackErrorCode\");function Cn(r){if(r.length<4){throw new Error(\"STUN address length is less than 4 bytes\")}const e=r.readUInt8(1);const t=r.readUInt16BE(2);const s=r.slice(4);switch(e){case Om:if(s.length!==4){throw new Error(\"STUN address has invalid length for IPv4\")}return[Nm(s),t];case km:if(s.length!==16){throw new Error(\"STUN address has invalid length for IPv6\")}return[Nm(s),t];default:throw new Error(\"STUN address has unknown protocol\")}}a(Cn,\"unpackAddress\");var Lm=Buffer.alloc(6);Lm.writeUInt16BE(so>>16,0);Lm.writeUInt32BE(so,2);function vx(r,e){const t=[...Lm,...e];let s=r.slice(0,2);for(let n=2;n<r.length;n++){const i=r[n]^t[n-2];const o=Buffer.alloc(1);o.writeUIntBE(i,0,1);s=Buffer.concat([s,o])}return s}a(vx,\"xorAddress\");function Cc(r,e){return Cn(vx(r,e))}a(Cc,\"unpackXorAddress\");function QO(r){const e=Buffer.alloc(4);e.writeUInt16BE(0,0);e.writeUInt8(Math.floor(r[0]/100),2);e.writeUInt8(r[0]%100,3);const t=Buffer.from(r[1],\"utf8\");return Buffer.concat([e,t])}a(QO,\"packErrorCode\");function ek(r){const e=Buffer.alloc(r.length*2);r.forEach((t,s)=>{e.writeUInt16BE(t,s*2)});return e}a(ek,\"packUnknownAttributes\");function tk(r){if(r.length%2!==0){throw new Error(\"UNKNOWN-ATTRIBUTES must have an even length\")}const e=[];for(let t=0;t<r.length;t+=2){e.push(r.readUInt16BE(t))}return e}a(tk,\"unpackUnknownAttributes\");function vc(r,e){return vx(_n(r),e)}a(vc,\"packXorAddress\");var io=a(r=>{const e=Buffer.alloc(4);e.writeUInt32BE(r,0);return e},\"packUnsigned\");var oo=a(r=>r.readUInt32BE(0),\"unpackUnsigned\");var rk=a(r=>{const e=Buffer.alloc(4);e.writeUInt16BE(r,0);return e},\"packUnsignedShort\");var sk=a(r=>r.readUInt16BE(0),\"unpackUnsignedShort\");var _x=a(r=>{const e=Buffer.allocUnsafe(8);e.writeBigUInt64BE(r,0);return e},\"packUnsigned64\");var Cx=a(r=>r.readBigUInt64BE(0),\"unpackUnsigned64\");var _f=a(r=>Buffer.from(r,\"utf8\"),\"packString\");var Rf=a(r=>r.toString(\"utf8\"),\"unpackString\");var nk=a(r=>{if([...r].length>=128){throw new Error(\"SOFTWARE must be shorter than 128 characters\")}return _f(r)},\"packSoftware\");var Kr=a(r=>r,\"packBytes\");var Wr=a(r=>r,\"unpackBytes\");var ik=a(()=>Buffer.alloc(0),\"packNone\");var ok=a(()=>null,\"unpackNone\");var Ax=[[1,\"MAPPED-ADDRESS\",_n,Cn],[3,\"CHANGE-REQUEST\",io,oo],[4,\"SOURCE-ADDRESS\",_n,Cn],[5,\"CHANGED-ADDRESS\",_n,Cn],[6,\"USERNAME\",_f,Rf],[8,\"MESSAGE-INTEGRITY\",Kr,Wr],[9,\"ERROR-CODE\",QO,ZO],[10,\"UNKNOWN-ATTRIBUTES\",ek,tk],[12,\"CHANNEL-NUMBER\",rk,sk],[13,\"LIFETIME\",io,oo],[18,\"XOR-PEER-ADDRESS\",vc,Cc],[19,\"DATA\",Kr,Wr],[20,\"REALM\",_f,Rf],[21,\"NONCE\",Kr,Wr],[22,\"XOR-RELAYED-ADDRESS\",vc,Cc],[23,\"REQUESTED-ADDRESS-FAMILY\",io,oo],[24,\"EVEN-PORT\",Kr,Wr],[25,\"REQUESTED-TRANSPORT\",io,oo],[28,\"MESSAGE-INTEGRITY-SHA256\",Kr,Wr],[29,\"PASSWORD-ALGORITHM\",Kr,Wr],[30,\"USERHASH\",Kr,Wr],[32,\"XOR-MAPPED-ADDRESS\",vc,Cc],[34,\"RESERVATION-TOKEN\",Kr,Wr],[36,\"PRIORITY\",io,oo],[37,\"USE-CANDIDATE\",ik,ok],[32770,\"PASSWORD-ALGORITHMS\",Kr,Wr],[32771,\"ALTERNATE-DOMAIN\",_f,Rf],[32802,\"SOFTWARE\",nk,Rf],[32803,\"ALTERNATE-SERVER\",_n,Cn],[32808,\"FINGERPRINT\",io,oo],[32809,\"ICE-CONTROLLED\",_x,Cx],[32810,\"ICE-CONTROLLING\",_x,Cx],[32811,\"RESPONSE-ORIGIN\",_n,Cn],[32812,\"OTHER-ADDRESS\",_n,Cn]];var Ac=class{static{a(this,\"AttributeRepository\")}constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){const s=this.attributes.find(n=>n[0]===e);if(s){s[1]=t}else{this.attributes.push([e,t])}return this}getAttributeValue(e){const t=this.attributes.find(s=>s[0]===e);return t?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}removeAttribute(e){this.attributes=this.attributes.filter(t=>t[0]!==e);return this}clear(){this.attributes=[]}};var Ix=Ax.reduce((r,e)=>{r[e[0]]=e;return r},{});var Ox=Ax.reduce((r,e)=>{r[e[1]]=e;return r},{});function ir(r,e){if(!wx(r)){return void 0}const t=r.readUInt16BE(0);const s=Buffer.from(r.slice(Gr-12,Gr));const n=new Ac;const i=[];let o=false;for(let c=Gr;c<r.length;){if(c+4>r.length){return void 0}const l=r.readUInt16BE(c);const u=r.readUInt16BE(c+2);const f=c+4;const d=f+u;if(d>r.length){return void 0}const h=r.slice(f,d);const p=ao(u);if(d+p>r.length){return void 0}const m=Ix[l];if(m){const[,y,,w]=m;let S;try{S=w.name===Cc.name?w(h,s):w(h)}catch{return void 0}n.setAttribute(y,S);if(y===\"FINGERPRINT\"){const T=kx(r.slice(0,c));if(n.getAttributeValue(\"FINGERPRINT\")!==T){return void 0}}else if(y===\"MESSAGE-INTEGRITY\"&&e){const T=ck(r.slice(0,c),e);const _=n.getAttributeValue(\"MESSAGE-INTEGRITY\");if(!T.equals(_)){return void 0}o=true}}else{i.push({type:l,length:u,value:Buffer.from(h)})}c=d+p}if(e&&!o){return void 0}return new Ke(t&16111,t&272,s,n.getAttributes(),i)}a(ir,\"parseMessage\");var Ke=class extends Ac{static{a(this,\"Message\")}constructor(e,t,s=(0,Ic.randomBytes)(12),n=[],i=[]){super(n);this.messageMethod=e;this.messageClass=t;this.transactionId=s;this.rawAttributes=i}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(\"hex\")}appendRawAttribute(e,t){this.rawAttributes.push({type:e,value:Buffer.from(t)});return this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){const e=Buffer.concat(this.serializedAttributes.map(s=>ak(s.type,s.value)));const t=Buffer.alloc(8);t.writeUInt16BE(this.messageMethod|this.messageClass,0);t.writeUInt16BE(e.length,2);t.writeUInt32BE(so,4);return Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){this.removeAttribute(\"FINGERPRINT\").removeAttribute(\"MESSAGE-INTEGRITY\");this.setAttribute(\"MESSAGE-INTEGRITY\",this.messageIntegrity(e));return this}messageIntegrity(e){const t=Mm(this.bytes,this.bytes.length-Gr+Im);return Buffer.from((0,Ic.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}addFingerprint(){this.removeAttribute(\"FINGERPRINT\");this.setAttribute(\"FINGERPRINT\",kx(this.bytes));return this}get serializedAttributes(){const e=[];for(const t of this.attributesKeys){const s=this.getAttributeValue(t);const[n,,i]=Ox[t];const o=i.name===vc.name?i(s,this.transactionId):i(s);e.push({type:n,value:o})}e.push(...this.rawAttributes.map(t=>({type:t.type,value:Buffer.from(t.value)})));return e}};function ak(r,e){const t=e.length;const s=ao(t);const n=Buffer.alloc(4);n.writeUInt16BE(r,0);n.writeUInt16BE(t,2);return Buffer.concat([n,e,Buffer.alloc(s)])}a(ak,\"serializeAttribute\");var Mm=a((r,e)=>{const t=Buffer.alloc(r.length);r.copy(t,0,0,2);t.writeUInt16BE(e,2);r.copy(t,4,4);return t},\"setBodyLength\");function kx(r){const e=Mm(r,r.length-Gr+gx);return(Ww(e)^yx)>>>0}a(kx,\"messageFingerprint\");function ck(r,e){const t=Mm(r,r.length-Gr+Im);return Buffer.from((0,Ic.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}a(ck,\"messageIntegrity\");function ao(r){const e=r%4;return e===0?0:4-e}a(ao,\"paddingLength\");var Nx=require(\"node:dns\");var Dm=require(\"node:net\");var Cf=class extends Error{static{a(this,\"TransactionError\")}};var co=class extends Cf{static{a(this,\"TransactionFailed\")}constructor(e,t){super();this.response=e;this.addr=t}get str(){let e=\"STUN transaction failed\";const t=this.response.getAttributeValue(\"ERROR-CODE\");if(t){const[s,n]=t;e+=` (${s} - ${n})`}return e}};var Oc=class extends Cf{static{a(this,\"TransactionTimeout\")}get str(){return\"STUN transaction timed out\"}};var vf=class extends Error{static{a(this,\"AddressFamilyMismatch\")}constructor(e,t){super(`cannot reach ${e[0]}:${e[1]} from an IPv${t} socket`);this.addr=e;this.socketFamily=t}};var kc=P(\"webrtc/ice/stun/transaction\");async function Xr(r,e=0){const t=(0,Dm.isIP)(r[0]);if(t){if(e!==0&&t!==e){throw new vf(r,e)}return r}const s=await Nx.promises.lookup(r[0],{family:e});return[s.address,r[1]]}a(Xr,\"resolveRequestAddress\");function Lx(r,e){if(r!==null&&typeof r===\"object\"){return r}const t=typeof r===\"number\"?r:void 0;return{retransmissions:t,onRequestSent:e}}a(Lx,\"normalizeTransactionOptions\");function Bm(r,e){return r[1]===e[1]&&Px(r[0])===Px(e[0])}a(Bm,\"addressEquals\");function Px(r){if((0,Dm.isIP)(r)!==6)return r;return new URL(`http://[${r.split(\"%\")[0]}]/`).hostname.slice(1,-1)}a(Px,\"canonicalHost\");var Vr=class{static{a(this,\"Transaction\")}constructor(e,t,s,n,i){this.request=e;this.addr=t;this.protocol=s;this.ended=false;this.tries=0;this.onResponse=new O;this.responseReceived=(c,l)=>{if(this.ended||this.onResponse.length===0){return}if(!Bm(this.expectedAddr,l)){kc(\"ignore STUN response from unexpected address\",l,\"expected\",this.expectedAddr);return}if(this.integrityKey){const u=c.attributesKeys.includes(\"MESSAGE-INTEGRITY\")||c.attributesKeys.includes(\"MESSAGE-INTEGRITY-SHA256\");if(!u&&!Um(c)){kc(\"ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)\");return}}if(c.messageClass===ie.RESPONSE){this.onResponse.execute(c,l);this.onResponse.complete()}else{this.onResponse.error(new co(c,l))}};this.run=async()=>{try{if(this.signal?.aborted){throw new Oc}this.attachAbortListener();this.retry().catch(l=>{kc(\"retry failed\",l)});const c=await this.onResponse.asPromise();return c}finally{this.cancel()}};this.retry=async()=>{while(this.tries<this.triesMax&&!this.ended){this.onRequestSent?.(this.tries);this.protocol.sendStun(this.request,this.addr).catch(c=>{kc(\"send stun failed\",c);if(this.failOnSendError){this.fail(c)}});await this.wait(this.timeoutDelay);if(this.ended){break}this.timeoutDelay*=2;this.tries++}if(this.tries>=this.triesMax&&!this.ended){kc(`retry failed times:${this.tries} maxLimit:${this.triesMax}`);this.failWithTimeout()}};const o=Lx(n,i);this.triesMax=1+(o.retransmissions??bx);this.timeoutDelay=o.responseTimeout??Sx;this.onRequestSent=o.onRequestSent;this.signal=o.signal;this.failOnSendError=o.failOnSendError??false;this.expectedAddr=t;this.integrityKey=o.integrityKey}attachAbortListener(){if(!this.signal){return}this.onAbort=()=>{this.failWithTimeout()};this.signal.addEventListener(\"abort\",this.onAbort,{once:true})}failWithTimeout(){this.fail(new Oc)}fail(e){if(this.ended){return}this.ended=true;this.clearWait();if(this.onResponse.length>0){this.onResponse.error(e)}}clearWait(){if(this.waitTimer!==void 0){clearTimeout(this.waitTimer);this.waitTimer=void 0}const e=this.waitResolve;this.waitResolve=void 0;e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t;this.waitTimer=setTimeout(()=>{this.waitTimer=void 0;this.waitResolve=void 0;t()},e)})}cancel(){this.ended=true;this.clearWait();if(this.signal&&this.onAbort){this.signal.removeEventListener(\"abort\",this.onAbort);this.onAbort=void 0}}};function Um(r){if(r.messageClass!==ie.ERROR||!r.getAttributeValue(\"NONCE\")){return false}const[e]=r.getAttributeValue(\"ERROR-CODE\")??[];return e===401||e===438}a(Um,\"isChallenge\");function vn(r,e,t){const s=Lx(e,t);if(r&&!s.integrityKey){s.integrityKey=r}return s}a(vn,\"buildTransactionOptions\");var Af=P(\"webrtc/ice/stun/tcpProtocol\");function Pc(r){return`${r[0]}:${r[1]}`}a(Pc,\"socketKey\");function lk(r){return r.destroyed||r.writableEnded}a(lk,\"isSocketClosed\");function Dx(r){if(!r.remoteAddress||!r.remotePort){return}return[r.remoteAddress,r.remotePort]}a(Dx,\"addressFromSocket\");async function Mx(r,e,t){return await new Promise((s,n)=>{const i=a(c=>{r.off(\"listening\",o);n(c)},\"onError\");const o=a(()=>{r.off(\"error\",i);s()},\"onListening\");r.once(\"error\",i);r.once(\"listening\",o);r.listen({host:e,port:t??0,exclusive:true})})}a(Mx,\"waitForListening\");var If=class r{static{a(this,\"BaseTcpProtocol\")}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new O;this.onDataReceived=new O;this.onConnectionClosed=new O;this.sockets=new Map}static{this.type=\"tcp\"}rememberSocket(e){const t=e.remoteAddr;if(!t){return}this.sockets.set(Pc(t),e)}forgetSocket(e){const t=e.remoteAddr;if(!t){return false}const s=Pc(t);if(this.sockets.get(s)!==e){return false}this.sockets.delete(s);return true}getOpenSocket(e){const t=this.sockets.get(Pc(e));if(!t){return}if(lk(t.socket)){this.dropSocket(t);return}return t}dropSocket(e){e.socket.destroy();if(this.forgetSocket(e)&&e.remoteAddr){this.onConnectionClosed.execute(e.remoteAddr)}}registerSocket(e,t){const s={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};if(t){this.rememberSocket(s)}e.on(\"data\",n=>{s.buffer=Buffer.concat([s.buffer,n]);const{frames:i,rest:o}=xx(s.buffer);s.buffer=o;const c=s.remoteAddr??Dx(e);if(!s.remoteAddr&&c){s.remoteAddr=c;this.rememberSocket(s)}if(!c){return}for(const l of i){if(l.length===0){continue}this.handleFrame(l,c)}});e.on(\"close\",()=>{if(this.forgetSocket(s)&&s.remoteAddr){this.onConnectionClosed.execute(s.remoteAddr)}});e.on(\"error\",n=>{Af(\"tcp socket error\",n)});return s}handleFrame(e,t){try{const s=ir(e);if(!s){this.onDataReceived.execute(e);return}if((s.messageClass===ie.RESPONSE||s.messageClass===ie.ERROR)&&this.transactions[s.transactionIdHex]){const n=this.transactions[s.transactionIdHex];const i=n.integrityKey?ir(e,n.integrityKey):s;if(!i){Af(\"STUN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(i,t)}else if(s.messageClass===ie.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){Af(\"tcp frame parse error\",s)}}async sendFrame(e,t){const s=await this.getSocket(t);try{await new Promise((n,i)=>{s.socket.write(Tx(e),o=>{if(o){i(o);return}n()})})}catch(n){Af(\"tcp write failed\",t,n);this.dropSocket(s);throw n}}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,s,n,i){if(this.transactions[e.transactionIdHex]){throw new Error(\"already requested\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await Xr(t);const c={failOnSendError:true,...vn(s,n,i)};const l=new Vr(e,o,this,c);this.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(const[t,s]of this.sockets.entries()){if(e&&t===Pc(e)){continue}s.socket.destroy();this.sockets.delete(t)}}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.pruneForSelection();this.onRequestReceived.complete();this.onDataReceived.complete();this.onConnectionClosed.complete()}};var Of=class extends If{static{a(this,\"TcpActiveProtocol\")}constructor(){super(...arguments);this.pendingSockets=new Map}async connectionMade(e){this.localIp=e}async getSocket(e){const t=Pc(e);const s=this.getOpenSocket(e);if(s){return s}const n=this.pendingSockets.get(t);if(n){return await n}const i=new Promise((o,c)=>{const l=(0,Pf.connect)({host:e[0],port:e[1],localAddress:this.localIp});const u=this.registerSocket(l,e);const f=a(h=>{l.off(\"connect\",d);c(h)},\"onError\");const d=a(()=>{l.off(\"error\",f);o(u)},\"onConnect\");l.once(\"error\",f);l.once(\"connect\",d)});this.pendingSockets.set(t,i);try{return await i}finally{this.pendingSockets.delete(t)}}};var kf=class extends If{static{a(this,\"TcpPassiveProtocol\")}constructor(){super(...arguments);this.server=(0,Pf.createServer)(e=>{this.registerSocket(e,Dx(e))})}async connectionMade(e,t){this.localIp=e;if(t){let s;for(let n=t[0];n<=t[1];n++){try{await Mx(this.server,e,n);return}catch(i){s=i}}throw s??new Error(\"tcp port not found\")}await Mx(this.server,e)}async getSocket(e){const t=this.getOpenSocket(e);if(!t){throw new Error(\"tcp passive connection not established\")}return t}get listeningPort(){const e=this.server.address();if(!e||typeof e===\"string\"){throw new Error(\"tcp passive protocol is not listening\")}return e.port}async close(){await super.close();await new Promise(e=>{this.server.close(()=>e())})}};var jm=P(\"webrtc/ice/stun/protocol\");var An=class r{static{a(this,\"StunProtocol\")}static{this.type=\"stun\"}get transactionsKeys(){return Object.keys(this.transactions)}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new O;this.onDataReceived=new O;this.connectionMade=async(e,t,s)=>{if(e){this.transport=await en.init(\"udp4\",{portRange:t,interfaceAddresses:s})}else{this.transport=await en.init(\"udp6\",{portRange:t,interfaceAddresses:s})}this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}}}datagramReceived(e,t){try{const s=ir(e);if(!s){if(this.localCandidate){this.onDataReceived.execute(e)}return}if((s.messageClass===ie.RESPONSE||s.messageClass===ie.ERROR)&&this.transactionsKeys.includes(s.transactionIdHex)){const n=this.transactions[s.transactionIdHex];const i=n.integrityKey?ir(e,n.integrityKey):s;if(!i){jm(\"STUN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(i,t)}else if(s.messageClass===ie.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){jm(\"datagramReceived error\",s)}}getExtraInfo(){const{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed){return}const s=e.bytes;await this.transport.send(s,t).catch(()=>{jm(\"sendStun failed\",t,e)})}async sendData(e,t){if(this.transport.closed){return}await this.transport.send(e,t)}connectTo(e){this.transport?.connectTo(e)}disconnect(){this.transport?.disconnect()}async request(e,t,s,n,i){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error(\"already request ed\");if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await Xr(t,this.transport.addressFamily);const c=vn(s,n,i);const l=new Vr(e,o,this,c);this.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.transport.close();this.onRequestReceived.complete();this.onDataReceived.complete()}};var Gx=require(\"node:net\");var Kx=require(\"node:timers/promises\");var Bx=require(\"node:crypto\");function Ux(r,e,t){return(0,Bx.createHash)(\"md5\").update(Buffer.from([r,e,t].join(\":\"))).digest()}a(Ux,\"makeTurnIntegrityKey\");var $m=require(\"node:crypto\");function lo(r){return(0,$m.randomBytes)(r).toString(\"hex\").substring(0,r)}a(lo,\"randomString\");function jx(){return(0,$m.randomBytes)(12)}a(jx,\"randomTransactionId\");var Nc=class{static{a(this,\"PQueue\")}constructor(){this.queue=[];this.wait=new O}put(e){this.queue.push(e);if(this.queue.length===1){this.wait.execute(e)}}get(){const e=this.queue.shift();if(!e){return new Promise(t=>{this.wait.subscribe(s=>{void this.queue.shift();t(s)})})}return e}};var Lc=a(r=>{let e;let t;const s=new Promise((i,o)=>{e=i;t=o});s.then(()=>{n.execute(void 0);n.complete()}).catch(i=>{n.execute(i??new Error);n.complete()});const n=new O;r(e,t,n).catch(()=>{});return{awaitable:s,resolve:e,reject:t}},\"cancelable\");function Nf(r){return r.length>=4&&(r[0]&192)===64}a(Nf,\"isChannelData\");function $x(r,e){const t=Buffer.alloc(4);t.writeUInt16BE(r,0);t.writeUInt16BE(e.length,2);return Buffer.concat([t,e])}a($x,\"encodeChannelData\");function Fx(r){if(!Nf(r)||r.length<4){return void 0}const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);if(r.length<4+t){return void 0}return{channelNumber:e,data:r.subarray(4,4+t)}}a(Fx,\"decodeChannelData\");function Hx(r){const e=ao(r.length);return e>0?Buffer.concat([r,Buffer.alloc(e)]):r}a(Hx,\"padTurnFrame\");function qx(r){const e=[];let t=0;let s=false;while(r.length-t>=4){let n;if(Nf(r.subarray(t))){const i=r.readUInt16BE(t+2);n=4+i+ao(i)}else if((r[t]&192)===0){if(r.length-t<20){break}const i=r.readUInt16BE(t+2);n=20+i+ao(i)}else{s=true;break}if(r.length-t<n){break}e.push(r.subarray(t,t+n));t+=n}return{frames:e,malformed:s,rest:r.subarray(t)}}a(qx,\"splitTurnTcpFrames\");var Fe=P(\"webrtc/ice/turn/protocol\");var uk=500;var fk=1e3;var dk=600;var hk=285212672;function Lf(r){return r.type===\"tcp\"||r.type===\"tls\"}a(Lf,\"isStreamTransport\");function pk(r){return r[0]}a(pk,\"permissionKey\");function zx(r){return JSON.stringify(r)}a(zx,\"channelKey\");var Fm=class r{static{a(this,\"StunOverTurnProtocol\")}static{this.type=\"turn\"}constructor(e){this.turn=e;this.type=r.type;this.disposer=new hu;this.onRequestReceived=new O;this.onDataReceived=new O;this.handleStunMessage=(t,s)=>{try{const n=ir(t);if(!n){this.onDataReceived.execute(t);return}if(n.messageClass===ie.RESPONSE||n.messageClass===ie.ERROR){const i=this.turn.transactions[n.transactionIdHex];if(i){const o=i.integrityKey?ir(t,i.integrityKey):n;if(!o){Fe(\"STUN over TURN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(o,s)}}else if(n.messageClass===ie.REQUEST){this.onRequestReceived.execute(n,s,t)}}catch(n){Fe(\"datagramReceived error\",n)}};e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}async request(e,t,s,n,i){if(this.turn.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await Xr(t);const c=vn(s,n,i);const l=new Vr(e,o,this,c);this.turn.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){this.disposer.dispose();return this.turn.close()}};var Hm=class r{static{a(this,\"TurnProtocol\")}static{this.type=\"turn\"}constructor(e,t,s,n,i,o={}){this.server=e;this.username=t;this.password=s;this.lifetime=n;this.transport=i;this.options=o;this.type=r.type;this.onData=new O;this.onRequestReceived=new O;this.onDataReceived=new O;this.transactions={};this.expiresAt=0;this.channelNumber=16384;this.channelByAddr={};this.addrByChannel={};this.channelBindQueue=Promise.resolve();this.channelBindingByAddr=new Map;this.tcpBuffer=Buffer.alloc(0);this.permissionByAddr={};this.permissionQueue=Promise.resolve();this.creatingPermissionByAddr=new Map;this.refresh=c=>{this.refreshHandle=Lc(async(l,u,f)=>{const d=new AbortController;f.once(()=>{d.abort()});while(!d.signal.aborted){const h=5/6*c*1e3;Fe(\"refresh delay\",h,{exp:c});try{await(0,Kx.setTimeout)(h,void 0,{signal:d.signal})}catch(m){if(d.signal.aborted){return}throw m}if(d.signal.aborted){return}const p=new Ke(Ge.REFRESH,ie.REQUEST);p.setAttribute(\"LIFETIME\",c);try{const[m]=await this.requestWithRetry(p,this.server,d.signal);c=m.getAttributeValue(\"LIFETIME\");Fe(\"refresh\",{exp:c});this.expiresAt=Date.now()+c*1e3}catch(m){if(d.signal.aborted){return}Fe(\"refresh error\",m)}}})};this.channelRefreshTime=this.options.channelRefreshTime??uk}async connectionMade(){this.transport.onData=(n,i)=>{this.dataReceived(n,i)};const e=new Ke(Ge.ALLOCATE,ie.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime).setAttribute(\"REQUESTED-TRANSPORT\",hk);const[t]=await this.requestWithRetry(e,this.server).catch(n=>{Fe(\"connect error\",n);throw n});this.relayedAddress=t.getAttributeValue(\"XOR-RELAYED-ADDRESS\");this.mappedAddress=t.getAttributeValue(\"XOR-MAPPED-ADDRESS\");const s=t.getAttributeValue(\"LIFETIME\");Fe(\"connect\",this.relayedAddress,this.mappedAddress,{exp:s});this.expiresAt=Date.now()+s*1e3;this.refresh(s)}handleChannelData(e){const t=Fx(e);const s=t&&this.addrByChannel[t.channelNumber];if(s&&t){this.onData.execute(t.data,s)}}handleSTUNMessage(e,t){try{const s=ir(e);if(!s){throw new Error(\"not stun message\")}if(s.messageClass===ie.RESPONSE||s.messageClass===ie.ERROR){const n=this.transactions[s.transactionIdHex];if(n){const i=n.integrityKey&&!Um(s)?ir(e,n.integrityKey):s;if(!i){Fe(\"TURN STUN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(i,t)}}else if(s.messageClass===ie.REQUEST){this.onData.execute(e,t)}if(s.getAttributeValue(\"DATA\")){const n=s.getAttributeValue(\"DATA\");const i=s.getAttributeValue(\"XOR-PEER-ADDRESS\")??t;this.onData.execute(n,i)}}catch(s){Fe(\"parse error\",e.toString())}}dataReceived(e,t){const s=a((n,i)=>{if(n.length>=4&&Nf(n)){this.handleChannelData(n)}else{this.handleSTUNMessage(n,i)}},\"datagramReceived\");if(Lf(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);const{frames:n,rest:i}=qx(this.tcpBuffer);this.tcpBuffer=i;for(const o of n){s(o,t)}}else{s(e,t)}}async send(e,t){if(this.transport.closed){return}await this.transport.send(Lf(this.transport)?Hx(e):e,t)}async createPermission(e){const t=new Ke(Ge.CREATE_PERMISSION,ie.REQUEST);t.setAttribute(\"XOR-PEER-ADDRESS\",e).setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce);await this.requestWithRetry(t,this.server)}async request(e,t,s,n,i){if(this.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(this.integrityKey){e.setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint()}const o=await this.resolveRequestTarget(t);const c=vn(this.integrityKey,n,i);const l=new Vr(e,o,this,c);this.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.transactions[e.transactionIdHex]}}get serverEndpoint(){return this.pinnedServerEndpoint}async resolveRequestTarget(e){if(Lf(this.transport)||Bm(e,this.server)){return this.selectServerEndpoint()}return Xr(e,this.transport.addressFamily??0)}async serverDestination(){return this.pinnedServerEndpoint??this.selectServerEndpoint()}selectServerEndpoint(){this.serverEndpointSelection??=this.resolveServerEndpoint().then(e=>{this.pinnedServerEndpoint=e;return e},e=>{this.serverEndpointSelection=void 0;throw e});return this.serverEndpointSelection}async resolveServerEndpoint(){const e=this.transport;if(!Lf(e)){return Xr(this.server,e.addressFamily??0)}if(e.remoteAddress){return e.remoteAddress}if(e instanceof Ba||e instanceof Ua){throw new Error(`${e.type} transport has no remote address`)}return Xr(this.server)}async requestWithRetry(e,t,s){let n,i;try{[n,i]=await this.request(e,t,void 0,{signal:s})}catch(o){if(o instanceof co==false){Fe(\"requestWithRetry error\",o);throw o}const[c]=o.response.getAttributeValue(\"ERROR-CODE\");const l=o.response.getAttributeValue(\"NONCE\");const u=o.response.getAttributeValue(\"REALM\");if((c===401&&u||c===438&&this.realm)&&l){Fe(\"retry with nonce\",c);this.nonce=l;if(c===401){this.realm=u}this.integrityKey=yk(this.username,this.realm,this.password);e.transactionId=jx();[n,i]=await this.request(e,this.server,void 0,{signal:s})}else{throw o}}return[n,i]}async sendData(e,t){let s;try{s=await this.getChannel(t)}catch(n){Fe(\"channelBind error; falling back to Send Indication\",n)}if(!s){await this.getPermission(t);const n=new Ke(Ge.SEND,ie.INDICATION).setAttribute(\"DATA\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);await this.sendStun(n,await this.serverDestination());return}await this.send($x(s.number,e),await this.serverDestination())}async getPermission(e){const t=pk(e);if(this.permissionByAddr[t]){return}const s=this.creatingPermissionByAddr.get(t);if(s){return s}const n=this.permissionQueue.then(async()=>{if(this.permissionByAddr[t]){return}await this.createPermission(e);this.permissionByAddr[t]=true});this.permissionQueue=n.then(()=>void 0,()=>void 0);this.creatingPermissionByAddr.set(t,n);try{await n}catch(i){Fe(\"createPermission error\",i);throw i}finally{if(this.creatingPermissionByAddr.get(t)===n){this.creatingPermissionByAddr.delete(t)}}}async getChannel(e){const t=zx(e);const s=this.channelBindingByAddr.get(t);if(s){return s}const n=this.channelByAddr[t];const i=_s(Date.now()/1e3);if(n&&n.refreshAt>i){return n}const o=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=o.then(()=>void 0,()=>void 0);this.channelBindingByAddr.set(t,o);try{return await o}catch(c){Fe(\"channelBind error\",c);throw c}finally{if(this.channelBindingByAddr.get(t)===o){this.channelBindingByAddr.delete(t)}}}async ensureChannel(e){const t=zx(e);const s=_s(Date.now()/1e3);let n=this.channelByAddr[t];if(n&&n.refreshAt>s){return n}const i=!n;if(!n){n={number:this.channelNumber++,address:e,refreshAt:0};this.channelByAddr[t]=n;this.addrByChannel[n.number]=e}try{await this.channelBind(n.number,e);n.refreshAt=_s(Date.now()/1e3)+this.channelRefreshTime;Fe(i?\"channelBind\":\"channelBind refresh\",n);return n}catch(o){if(i){delete this.channelByAddr[t];delete this.addrByChannel[n.number]}throw o}}async channelBind(e,t){const s=new Ke(Ge.CHANNEL_BIND,ie.REQUEST);s.setAttribute(\"CHANNEL-NUMBER\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);const[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==Ge.CHANNEL_BIND){throw new Error(\"should be CHANNEL_BIND\")}}async sendStun(e,t){await this.send(e.bytes,t)}async refreshAllocation(){if(!this.expiresAt||this.transport.closed){return false}const e=new Ke(Ge.REFRESH,ie.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime);try{const[t]=await this.requestWithRetry(e,this.server);this.expiresAt=Date.now()+t.getAttributeValue(\"LIFETIME\")*1e3;return true}catch(t){Fe(\"refresh failed\",t);this.expiresAt=0;return false}}async close(){this.refreshHandle?.resolve?.();if(this.expiresAt>Date.now()&&!this.transport.closed){this.expiresAt=0;const e=new Ke(Ge.REFRESH,ie.REQUEST);e.setAttribute(\"LIFETIME\",0);await this.requestWithRetry(e,this.server,AbortSignal.timeout(fk)).catch(t=>{Fe(\"delete allocation\",t)})}await this.transport.close()}};function mk(r,e){const t=(0,Gx.isIP)(r[0]);if(t===4||t===6){if(e&&e!==t){Fe(\"udpFamily ignored for IP literal TURN server\",{address:r,udpFamily:e,literalFamily:t})}return t===6?\"udp6\":\"udp4\"}return(e??4)===6?\"udp6\":\"udp4\"}a(mk,\"selectTurnUdpSocketType\");async function gk({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,ssl:o,tlsOptions:c,transport:l,connectTimeoutMs:u,udpFamily:f}={}){s??=dk;l??=o?\"tls\":\"udp\";const d=l===\"udp\"?await en.init(mk(r,f),{portRange:n,interfaceAddresses:i}):l===\"tcp\"?await Ba.init(r,{connectTimeoutMs:u}):await Ua.init(r,c,{connectTimeoutMs:u});const h=new Hm(r,e,t,s,d);try{await h.connectionMade()}catch(p){try{await h.close()}catch(m){Fe(\"failed to close TURN client after allocation failure\",m)}throw p}return h}a(gk,\"createTurnClient\");async function Wx(r,e={}){const t=await gk(r,e);const s=new Fm(t);return s}a(Wx,\"createStunOverTurnClient\");function yk(r,e,t){return Ux(r,e,t)}a(yk,\"makeIntegrityKey\");var Mc=require(\"node:crypto\");var qm=require(\"node:net\");var it=class r{static{a(this,\"Candidate\")}constructor(e,t,s,n,i,o,c,l,u,f,d,h){this.foundation=e;this.component=t;this.transport=s;this.priority=n;this.host=i;this.port=o;this.type=c;this.relatedAddress=l;this.relatedPort=u;this.tcptype=f;this.generation=d;this.ufrag=h;this.id=(0,Mc.randomUUID)().toString()}refreshId(){this.id=(0,Mc.randomUUID)().toString()}static fromSdp(e){const t=e.split(\" \");if(t.length<8){throw new Error(\"SDP does not have enough properties\")}const s={foundation:t[0],component:Number(t[1]),transport:t[2],priority:Number(t[3]),host:t[4],port:Number(t[5]),type:t[7]};for(let d=8,h=t.length-1;d<h;d+=2){if(t[d]===\"raddr\"){s[\"related_address\"]=t[d+1]}else if(t[d]===\"rport\"){s[\"related_port\"]=Number(t[d+1])}else if(t[d]===\"tcptype\"){s[\"tcptype\"]=t[d+1]}else if(t[d]===\"generation\"){s[\"generation\"]=Number(t[d+1])}else if(t[d]===\"ufrag\"){s[\"ufrag\"]=t[d+1]}}const{foundation:n,component:i,transport:o,priority:c,host:l,port:u,type:f}=s;return new r(n,i,o,c,l,u,f,s[\"related_address\"],s[\"related_port\"],s[\"tcptype\"],s[\"generation\"],s[\"ufrag\"])}canPairWith(e){const t=(0,qm.isIPv4)(this.host);const s=(0,qm.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&Tk(this,e)&&t===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;if(this.relatedAddress)e+=` raddr ${this.relatedAddress}`;if(this.relatedPort!=void 0)e+=` rport ${this.relatedPort}`;if(this.tcptype)e+=` tcptype ${this.tcptype}`;if(this.generation!=void 0)e+=` generation ${this.generation}`;if(this.ufrag!=void 0)e+=` ufrag ${this.ufrag}`;return e}};var bk={host:126,prflx:110,srflx:100,relay:0};var Sk={host:105,prflx:90,srflx:80,relay:0};var wk={active:6,passive:4,so:2};var Ek={active:4,passive:2,so:6};function Mf(r){return r?.toLowerCase()??\"udp\"}a(Mf,\"normalizeTransport\");function zm(r){switch(r){case\"active\":case\"passive\":case\"so\":return r;default:return void 0}}a(zm,\"normalizeTcpType\");function Tk(r,e){if(Mf(r.transport)!==\"tcp\"){return true}const t=zm(r.tcptype);const s=zm(e.tcptype);if(!t||!s){return false}return t===\"active\"&&s===\"passive\"||t===\"passive\"&&s===\"active\"||t===\"so\"&&s===\"so\"}a(Tk,\"canPairTcpCandidates\");function xk({candidateType:r,transport:e=\"udp\",tcptype:t,otherPreference:s=8191}){if(Mf(e)!==\"tcp\"){return s}const n=zm(t)??\"active\";const i=r===\"srflx\"||r===\"prflx\"?Ek[n]:wk[n];return(1<<13)*i+s}a(xk,\"candidateLocalPreference\");function Rk(r,e=\"udp\"){const t=Mf(e)===\"tcp\"?Sk:bk;return t[r]??0}a(Rk,\"candidateTypePreference\");function In(r,e,t,s){const n=s===void 0?`${r}|${e}|${t}`:`${r}|${e}|${t}|${s}`;return(0,Mc.createHash)(\"md5\").update(n,\"ascii\").digest(\"hex\").slice(7)}a(In,\"candidateFoundation\");function Os(r,e=65535){const t=1;const s=typeof e===\"number\"?\"udp\":Mf(e.transport);const n=typeof e===\"number\"?e:e.localPreference??xk({candidateType:r,transport:s,tcptype:e.tcptype,otherPreference:e.otherPreference});const i=Rk(r,s);return(1<<24)*i+(1<<8)*n+(256-t)}a(Os,\"candidatePriority\");function Vx(r){switch(r){case\"passive\":return\"active\";case\"active\":return\"passive\";default:return\"so\"}}a(Vx,\"remoteTcpTypeForIncoming\");var dR=require(\"node:crypto\");var Wm=require(\"node:net\");var hR=Ye(require(\"node:timers/promises\"),1);var Zx=require(\"node:dgram\");var Qx=require(\"node:events\");var Xx=\"224.0.0.251\";var Yx=5353;var Dc={A:1,AAAA:28};function _k(r){const e=r.replace(/\\.$/,\"\").split(\".\").map(t=>{const s=Buffer.from(t,\"utf8\");return Buffer.concat([Buffer.from([s.length]),s])});return Buffer.concat([...e,Buffer.from([0])])}a(_k,\"encodeName\");function Jx(r,e){const t=[];let s=e;let n=-1;for(let i=0;i<64;i++){const o=r[s];if(o===void 0)throw new Error(\"truncated name\");if(o===0){s++;break}if((o&192)===192){if(n<0)n=s+2;s=(o&63)<<8|r[s+1];continue}t.push(r.toString(\"utf8\",s+1,s+1+o));s+=1+o}return[t.join(\".\"),n<0?s:n]}a(Jx,\"decodeName\");function Ck(r,e){if(r===Dc.A&&e.length===4)return Array.from(e).join(\".\");if(r===Dc.AAAA&&e.length===16){const t=[];for(let s=0;s<16;s+=2)t.push(e.readUInt16BE(s).toString(16));return t.join(\":\")}return e}a(Ck,\"formatAddress\");function vk(r){try{if(r.length<12||!(r[2]&128))return void 0;const e=r.readUInt16BE(4);const t=r.readUInt16BE(6)+r.readUInt16BE(8)+r.readUInt16BE(10);let s=12;for(let i=0;i<e;i++)s=Jx(r,s)[1]+4;const n=[];for(let i=0;i<t;i++){const[o,c]=Jx(r,s);const l=r.readUInt16BE(c);const u=r.readUInt32BE(c+4);const f=r.readUInt16BE(c+8);const d=r.subarray(c+10,c+10+f);s=c+10+f;const h=l===Dc.A?\"A\":l===Dc.AAAA?\"AAAA\":void 0;n.push({name:o,type:h??l,ttl:u,data:Ck(l,d)})}return n}catch{return void 0}}a(vk,\"parseMdnsResponse\");function Ak(r,e){const t=Buffer.alloc(12);t.writeUInt16BE(1,4);const s=Buffer.alloc(4);s.writeUInt16BE(Dc[e],0);s.writeUInt16BE(1,2);return Buffer.concat([t,_k(r),s])}a(Ak,\"encodeMdnsQuery\");var Df=class extends Qx.EventEmitter{static{a(this,\"MulticastDns\")}#e;#t;constructor(){super();this.#e=(0,Zx.createSocket)({type:\"udp4\",reuseAddr:true});this.#e.on(\"error\",e=>void this.emit(\"error\",e));this.#e.on(\"message\",(e,t)=>{const s=vk(e);if(s?.length)this.emit(\"response\",s,t)});this.#t=new Promise(e=>{this.#e.bind(Yx,()=>{try{this.#e.addMembership(Xx);this.#e.setMulticastTTL(255);this.#e.setMulticastLoopback(true)}catch(t){this.emit(\"error\",t)}e()})})}async query(e,t=\"A\"){await this.#t;await new Promise((s,n)=>{this.#e.send(Ak(e,t),Yx,Xx,i=>i?n(i):s())})}destroy(){try{this.#e.close()}catch{}}};var Bf=class{static{a(this,\"MdnsLookup\")}constructor(){this.cache=new Map;this.mdnsInstance=new Df;this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,s)=>{const n=a(()=>{this.mdnsInstance.removeListener(\"response\",o);clearTimeout(i)},\"cleanup\");const i=setTimeout(()=>{n();s(new Error(\"No mDNS response\"))},1e4);const o=a(c=>{const l=c.find(u=>u.type===\"A\"&&u.name.toLowerCase()===e.toLowerCase());if(!l){return}n();t(l.data)},\"l\");this.mdnsInstance.on(\"response\",o);this.mdnsInstance.query(e,\"A\").catch(c=>{n();s(c)})})}close(){this.mdnsInstance.destroy()}};var eR=require(\"node:crypto\");var Ik=P(\"webrtc/ice/iceBase:log\");var Bc=class{static{a(this,\"CandidatePair\")}get state(){return this._state}toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}constructor(e,t,s){this.protocol=e;this.remoteCandidate=t;this.iceControlling=s;this.id=(0,eR.randomUUID)().toString();this.nominated=false;this.remoteNominated=false;this._state=ae.FROZEN;this.packetsSent=0;this.packetsReceived=0;this.bytesSent=0;this.bytesReceived=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.requestsReceived=0;this.requestsSent=0;this.responsesReceived=0;this.responsesSent=0;this.retransmissionsReceived=0;this.retransmissionsSent=0;this.consentRequestsSent=0;this.requestTransactionIds=new Set}updateState(e){this._state=e}get localCandidate(){if(!this.protocol.localCandidate){throw new Error(\"localCandidate not exist\")}return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return Gm(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){const t=this.requestTransactionIds.has(e);if(!t){this.requestTransactionIds.add(e);return false}this.retransmissionsReceived++;return true}};var Uc=1;var uo=2;var tR=5;var rR=30;var Ok=1e3;var kk=500;function sR(r){if(r===void 0||!Number.isFinite(r)||r<=0){return Ok}return Math.max(kk,Math.round(r*1e3*2+200))}a(sR,\"consentResponseTimeoutMs\");var ae;(function(r){r[r[\"FROZEN\"]=0]=\"FROZEN\";r[r[\"WAITING\"]=1]=\"WAITING\";r[r[\"IN_PROGRESS\"]=2]=\"IN_PROGRESS\";r[r[\"SUCCEEDED\"]=3]=\"SUCCEEDED\";r[r[\"FAILED\"]=4]=\"FAILED\"})(ae||(ae={}));var nR={iceLite:false,useTcp:false,useIpv4:true,useIpv6:true};function Km(r){if(![\"host\",\"relay\",\"srflx\"].includes(r.type))throw new Error(`Unexpected candidate type \"${r.type}\"`);return r}a(Km,\"validateRemoteCandidate\");function iR(r,e){return r.sort((t,s)=>Gm(t.localCandidate,t.remoteCandidate,e)-Gm(s.localCandidate,s.remoteCandidate,e)).reverse()}a(iR,\"sortCandidatePairs\");function Gm(r,e,t){const s=t&&r.priority||e.priority;const n=t&&e.priority||r.priority;return(1<<32)*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}a(Gm,\"candidatePairPriority\");async function oR(r,e){const t=new Ke(Ge.BINDING,ie.REQUEST);try{const[s]=await r.request(t,e);const n=r.localCandidate;if(!n){throw new Error(\"not exist\")}const i=new it(In(\"srflx\",n.transport,n.host,e[0]),n.component,n.transport,Os(\"srflx\",{transport:n.transport,tcptype:n.tcptype}),s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[0],s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[1],\"srflx\",n.host,n.port,n.tcptype);return i}catch(s){Ik(\"error serverReflexiveCandidate\",s)}}a(oR,\"serverReflexiveCandidate\");function Uf(r){if(r&&Number.isNaN(r[1])){return[r[0],443]}return r}a(Uf,\"validateAddress\");var lR=Ye(require(\"node:os\"),1);function aR(r,e,t={},s){const n=[\"ipsec\",\"tun\",\"utun\",\"tap\"];const i=[\"vmnet\",\"veth\"];const{useLinkLocalAddress:o}=t;const c=Object.keys(r).map(l=>{for(const f of[...n,...i]){if(l.startsWith(f)){return{nic:l,addresses:[]}}}const u=(r[l]??[]).filter(f=>Qs(f.family)===e&&!f.internal&&(o?true:!s(f)));return{nic:l,addresses:u.map(f=>f.address)}}).filter(l=>!!l);c.sort((l,u)=>l.nic.localeCompare(u.nic));return Object.values(c).flatMap(l=>l.addresses)}a(aR,\"selectAddressesFromInterfaces\");var Pk=P(\"webrtc/ice/utils\");function Nk(r){return Qs(r.family)===4&&r.address?.startsWith(\"169.254.\")||Qs(r.family)===6&&r.address?.startsWith(\"fe80::\")}a(Nk,\"isLinkLocalAddress\");function cR(r,{useLinkLocalAddress:e}={}){const t=lR.networkInterfaces();Pk(t);return aR(t,r,{useLinkLocalAddress:e},Nk)}a(cR,\"nodeIpAddress\");function uR(r,e,t={}){const s=[];if(r){s.push(...cR(4,t))}if(e){s.push(...cR(6,t))}return s}a(uR,\"getHostAddresses\");var Y=P(\"webrtc/ice/ice:log\");var Lk=1e3;var Mk=3e4;var Dk={udp:65535,tcp:49151,tls:32767};function Bk(r){const e=[];if(r.turnServer&&r.turnUsername&&r.turnPassword){e.push({address:r.turnServer,username:r.turnUsername,password:r.turnPassword,transport:r.turnTransport})}e.push(...r.turnServers??[]);const t=new Map;for(const s of e){const n=Uf(s.address);if(!n||!s.username||!s.password)continue;const i=n[0].toLowerCase();let o=t.get(i);if(!o){o={key:i,attempts:[]};t.set(i,o)}const c=s.transport===void 0||s.transport===\"udp\"?[\"udp\",\"tcp\"]:[s.transport];for(const l of c){const u=o.attempts.some(f=>f.transport===l&&f.address[1]===n[1]&&f.username===s.username&&f.password===s.password);if(!u)o.attempts.push({address:n,transport:l,username:s.username,password:s.password})}}return[...t.values()]}a(Bk,\"relayServersOf\");function Uk(r){const e=[];for(const t of[r.stunServer,...r.stunServers??[]]){const s=Uf(t);if(s&&!e.some(([n,i])=>n===s[0]&&i===s[1]))e.push(s)}return e}a(Uk,\"stunServersOf\");var jf=class{static{a(this,\"Connection\")}constructor(e,t){this._iceControlling=e;this.localUsername=lo(4);this.localPassword=lo(22);this.remoteIsLite=false;this.remotePassword=\"\";this.remoteUsername=\"\";this.checkList=[];this.localCandidates=[];this.stunServers=[];this.relayServers=[];this.relays=new Map;this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.generation=-1;this.userHistory={};this.tieBreaker=(0,dR.randomBytes)(8).readBigUInt64BE(0);this.state=\"new\";this._remoteCandidates=[];this.nominating=false;this.checkListDone=false;this.checkListState=new Nc;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;this.protocols=[];this.consentFresh=false;this.consentSessionId=0;this.resolvingRemoteCandidates=0;this.noPairDeadline=0;this.onData=new O;this.stateChanged=new O;this.onIceCandidate=new O;this.queryConsent=()=>{if(this.iceLite){return}this.stopConsentLifecycle();const s=this.consentSessionId;this.consentFresh=true;const n=Lc(async(i,o,c)=>{let l=false;const u=new AbortController;const f=a(()=>{if(this.consentExpiryTimer===void 0){return}clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0},\"clearConsentExpiry\");const d=a(()=>{if(l||s!==this.consentSessionId){return}f();this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0;if(l||s!==this.consentSessionId){return}if(this.state===\"closed\"||this.state===\"failed\"){return}Y(\"Consent to send expired\");this.consentFresh=false;this.consentSessionId++;this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;if(this.queryConsentHandle===n){this.queryConsentHandle=void 0}l=true;u.abort();this.setState(\"failed\")},rR*1e3)},\"refreshConsentExpiry\");c.once(()=>{l=true;if(s===this.consentSessionId){f();this.consentRequestAbort?.abort();this.consentRequestAbort=void 0}u.abort();if(this.queryConsentHandle===n){this.queryConsentHandle=void 0}});d();const h=a(()=>tR*(.8+.4*Math.random())*1e3,\"randomizedConsentInterval\");let p=Date.now()+h();const m=a(()=>this.state===\"closed\"||this.state===\"failed\",\"isTerminalState\");try{while(!m()&&!l&&s===this.consentSessionId){await this.abortableDelay(Math.max(0,p-Date.now()),u.signal);if(l||m()||s!==this.consentSessionId){break}p=Date.now()+h();const y=this.nominated;if(!y){break}const w=y.id;const S=this.generation;const T=this.remotePassword;const{localUsername:_,remoteUsername:x,iceControlling:k}=this;const N=this.buildRequest({nominate:this.shouldNominateConsentRequest(y),localUsername:_,remoteUsername:x,iceControlling:k,localCandidate:y.localCandidate});this.consentRequestAbort?.abort();const A=new AbortController;this.consentRequestAbort=A;y.consentRequestsSent++;y.requestsSent++;const B=sR(y.rtt);const ee=performance.now();y.protocol.request(N,y.remoteAddr,Buffer.from(T,\"utf8\"),{retransmissions:0,responseTimeout:B,signal:A.signal,onRequestSent:a(fe=>{if(fe>0){y.retransmissionsSent++}},\"onRequestSent\")}).then(()=>{if(s!==this.consentSessionId||l){return}const fe=this.state;if(fe===\"closed\"||fe===\"failed\"){return}if(this.nominated?.id!==w){return}if(this.generation!==S){return}if(this.remotePassword!==T){return}const Rt=(performance.now()-ee)/1e3;y.rtt=Rt;y.totalRoundTripTime+=Rt;y.roundTripTimeMeasurements++;y.responsesReceived++;this.consentFresh=true;d();if(fe===\"disconnected\"){this.setState(\"connected\")}}).catch(fe=>{if(s===this.consentSessionId&&this.nominated?.id===w){Y(\"no stun response\",fe)}})}}catch(y){}finally{if(s===this.consentSessionId){f()}}});this.queryConsentHandle=n};this.send=async s=>{if(!this.canSendApplicationData()){return}const n=this.nominated;await n.protocol.sendData(s,n.remoteAddr);n.packetsSent++;n.bytesSent+=s.length};this.checkStart=s=>Lc(async n=>{Y(\"check start\",s.toJSON());s.updateState(ae.IN_PROGRESS);const i={};const{remotePassword:o,remoteUsername:c,generation:l}=this;const u=s.localCandidate.ufrag??this.localUsername;const f=false;const d=this.buildRequest({nominate:f,localUsername:u,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});const h=performance.now();try{s.requestsSent++;const[p,m]=await s.protocol.request(d,s.remoteAddr,Buffer.from(o,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++;const y=performance.now();const w=(y-h)/1e3;s.rtt=w;s.totalRoundTripTime+=w;s.roundTripTimeMeasurements++;Y(\"response received\",d.toJSON(),p.toJSON(),m,{localUsername:u,remoteUsername:c,remotePassword:o,generation:l,rtt:w});i.response=p;i.addr=m}catch(p){const m=p;Y(\"failure case\",d.toJSON(),m.response?JSON.stringify(m.response.toJSON(),null,2):p,{localUsername:u,remoteUsername:c,remotePassword:o,generation:l},s.remoteAddr);if(m.response?.getAttributeValue(\"ERROR-CODE\")[0]===487){if(d.attributesKeys.includes(\"ICE-CONTROLLED\")){this.switchRole(true)}else if(d.attributesKeys.includes(\"ICE-CONTROLLING\")){this.switchRole(false)}await this.checkStart(s).awaitable;n();return}if(m.response?.getAttributeValue(\"ERROR-CODE\")[0]===401){Y(\"retry 401\",s.toJSON());await this.checkStart(s).awaitable;n();return}else{Y(\"checkStart CandidatePairState.FAILED\",s.toJSON());s.updateState(ae.FAILED);this.checkComplete(s);n();return}}if(i.addr[0]!==s.remoteAddr[0]||i.addr[1]!==s.remoteAddr[1]){s.updateState(ae.FAILED);this.checkComplete(s);n();return}if(f||s.remoteNominated){s.nominated=true}else if(this.usesTcpRegularNomination(s)){}else if(this.iceControlling&&!this.nominating&&!this.nominated){this.nominating=true;const p=this.buildRequest({nominate:true,localUsername:u,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});try{s.requestsSent++;await s.protocol.request(p,s.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++}catch(m){this.nominating=false;s.updateState(ae.FAILED);this.checkComplete(s);return}s.nominated=true}s.updateState(ae.SUCCEEDED);this.checkComplete(s);n()});this.pairRemoteCandidate=s=>{for(const n of this.protocols){this.tryPair(n,s)}};this.options={...nR,...t};if(this.iceLite){this._iceControlling=false}this.applyStunTurnServersFromOptions();this.restart().catch(s=>Y(\"restart failed\",s));Y(\"new Connection\",this.options)}setIceServers(e){this.options={...this.options,stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:e.turnTransport,stunServers:e.stunServers,turnServers:e.turnServers};if(e.forceTurn!==void 0){this.options.forceTurn=e.forceTurn}if(e.useTcp!==void 0){this.options.useTcp=e.useTcp}if(e.turnTlsOptions!==void 0){this.options.turnTlsOptions=e.turnTlsOptions}if(e.turnUdpFamily!==void 0){this.options.turnUdpFamily=e.turnUdpFamily}this.applyStunTurnServersFromOptions();Y(\"Connection ice servers updated\",this.options)}applyStunTurnServersFromOptions(){this.stunServers=Uk(this.options);this.relayServers=Bk(this.options);this.stunServer=this.stunServers[0];this.turnServer=Uf(this.options.turnServer)??this.relayServers[0]?.attempts[0]?.address}get iceControlling(){return this._iceControlling}set iceControlling(e){if(this.iceLite){e=false}if(this.nominated){return}this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++;this.localUsername=lo(4);this.localPassword=lo(22);if(this.options.localPasswordPrefix){this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)}this.userHistory[this.localUsername]=this.localPassword;this.remoteUsername=\"\";this.remotePassword=\"\";this.localCandidates=[];this._remoteCandidates=[];this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.state=\"new\";this.lookup?.close?.();this.lookup=void 0;this.nominated=void 0;this.nominating=false;this.checkList=[];this.checkListDone=false;this.checkListState=new Nc;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;for(const e of this.protocols){e.disconnect?.();if(e.localCandidate){e.localCandidate.refreshId();e.localCandidate.generation=this.generation;e.localCandidate.ufrag=this.localUsername}}this.stopConsentLifecycle()}resetNominatedPair(){Y(\"resetNominatedPair\");for(const e of this.protocols)e.disconnect?.();this.nominated=void 0;this.nominating=false;this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:s}){Y(\"setRemoteParams\",{iceLite:e,usernameFragment:t,password:s});this.remoteIsLite=e;this.remoteUsername=t;this.remotePassword=s}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=true;const e=[...this.relays.values()];for(const i of this.protocols){if(i.localCandidate&&!e.includes(i)){i.localCandidate.generation=this.generation;i.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(i.localCandidate)}}let t=uR(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress});const{interfaceAddresses:s}=this.options;if(s){const i=t.filter(o=>Object.values(s).includes(o));if(i.length){t=i}}if(this.options.additionalHostAddresses){t=Array.from(new Set([...this.options.additionalHostAddresses,...t]))}const n=this.getCandidatePromises(t,this.options.stunGatherTimeout);await Promise.allSettled(n);this.localCandidatesEnd=true}this.setState(\"completed\")}appendLocalCandidate(e){this.localCandidates.push(e);this.onIceCandidate.execute(e)}isRedundant(e){const t=a(s=>s.type===\"host\"?`${s.host}|${s.port}`:`${s.relatedAddress}|${s.relatedPort}`,\"baseOf\");return this.localCandidates.some(s=>s.transport===e.transport&&s.host===e.host&&s.port===e.port&&s.type!==\"relay\"&&t(s)===t(e))}gatherRelayCandidates(e){for(const[t,s]of this.relays){if(!e.some(n=>n.key===t))this.dropRelay(t,s)}return e.map(async t=>{const s=this.relays.get(t.key);if(s){if(await s.turn.refreshAllocation()){if(this.relays.get(t.key)!==s)return;s.localCandidate.generation=this.generation;s.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(s.localCandidate);return s.localCandidate}this.dropRelay(t.key,s)}const{protocol:n,attempt:i}=await this.allocateRelay(t);if(this.state===\"closed\"||this.relays.has(t.key)){await n.close();return}this.ensureProtocol(n);this.protocols.push(n);this.relays.set(t.key,n);const o=n.turn.relayedAddress;const c=n.turn.mappedAddress;Y(\"turn candidateAddress\",o);n.localCandidate=new it(In(\"relay\",\"udp\",o[0],`${t.key}|${i.transport}`),1,\"udp\",Os(\"relay\",Dk[i.transport]),o[0],o[1],\"relay\",c[0],c[1],void 0,this.generation,this.localUsername);this.appendLocalCandidate(n.localCandidate);return n.localCandidate}).map(t=>t.catch(s=>{Y(\"query TURN server\",s)}))}allocateRelay(e){return new Promise((t,s)=>{let n=0;let i=0;let o=false;let c;const l=a(()=>{clearTimeout(c);if(o||n>=e.attempts.length)return;const u=e.attempts[n++];i++;c=setTimeout(l,Lk);Wx({address:u.address,username:u.username,password:u.password},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:u.transport,tlsOptions:this.options.turnTlsOptions,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1e3,udpFamily:this.options.turnUdpFamily}).then(f=>{i--;if(o){f.close().catch(d=>Y(\"close TURN relay\",d));return}o=true;clearTimeout(c);t({protocol:f,attempt:u})},f=>{i--;Y(\"TURN allocation failed\",u.transport,u.address,f);if(o)return;if(n<e.attempts.length){l()}else if(!i){o=true;s(f)}})},\"start\");l()})}dropRelay(e,t){this.relays.delete(e);this.protocols=this.protocols.filter(s=>s!==t);t.close().catch(s=>Y(\"close TURN relay\",s))}ensureProtocol(e){e.onRequestReceived.subscribe((t,s)=>{if(t.messageMethod!==Ge.BINDING){this.respondError(t,s,e,[400,\"Bad Request\"]);return}const n=t.getAttributeValue(\"USERNAME\");const{remoteUsername:i}=fR(n);const o=this.userHistory[i]??this.localPassword;const{iceControlling:c}=this;if(c&&t.attributesKeys.includes(\"ICE-CONTROLLING\")){if(this.tieBreaker>=t.getAttributeValue(\"ICE-CONTROLLING\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(false)}}else if(!c&&t.attributesKeys.includes(\"ICE-CONTROLLED\")){if(this.iceLite||this.tieBreaker<t.getAttributeValue(\"ICE-CONTROLLED\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(true);return}}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,s,e)){return}const l=new Ke(Ge.BINDING,ie.RESPONSE,t.transactionId);l.setAttribute(\"XOR-MAPPED-ADDRESS\",s).addMessageIntegrity(Buffer.from(o,\"utf8\")).addFingerprint();e.sendStun(l,s).catch(u=>{Y(\"sendStun error\",u)});if(this.checkList.length===0&&!this.earlyChecksDone){this.earlyChecks.push([t,s,e])}else{this.checkIncoming(t,s,e)}});e.onDataReceived.subscribe(t=>{try{const s=this.nominated;if(s&&s.protocol===e){s.packetsReceived++;s.bytesReceived+=t.length}this.onData.execute(t)}catch(s){Y(\"dataReceived\",s)}});e.onConnectionClosed?.subscribe(t=>{this.handleConnectionClosed(e,t)})}handleConnectionClosed(e,t){const s=this.nominated;if(!s||s.protocol!==e||s.remoteAddr[0]!==t[0]||s.remoteAddr[1]!==t[1]){return}if(this.state===\"closed\"||this.state===\"failed\"){return}Y(\"selected tcp connection closed\",s.toJSON());this.stopConsentLifecycle();this.setState(\"failed\")}getCandidatePromises(e,t=5){const s=[];const{stunServers:n,relayServers:i}=this;const o=this.iceLite;const c=!o&&this.options.forceTurn&&i.length>0;const l=this.protocols.filter(f=>f instanceof An&&!!f.localCandidate);e=e.filter(f=>{if(this.protocols.find(d=>d.localIp===f)){return false}return true});const u=c?[]:e.map(async f=>{const d=new An;this.ensureProtocol(d);try{await d.connectionMade((0,Wm.isIPv4)(f),this.options.portRange,this.options.interfaceAddresses);d.localIp=f;this.protocols.push(d);Y(\"protocol\",d.localIp);const h=[f,d.getExtraInfo()[1]];d.localCandidate=new it(In(\"host\",\"udp\",h[0]),1,\"udp\",Os(\"host\",{transport:\"udp\"}),h[0],h[1],\"host\",void 0,void 0,void 0,this.generation,this.localUsername);this.pairLocalProtocol(d);this.appendLocalCandidate(d.localCandidate);return d}catch(h){Y(\"error protocol STUN\",h)}});if(!c){s.push(...u.map(f=>f.then(d=>d?.localCandidate)))}if(!c&&this.options.useTcp){const f=e.map(async d=>{if(this.options.tcpPassive!==false){const h=new kf;this.ensureProtocol(h);await h.connectionMade(d,this.options.portRange);h.localIp=d;h.localCandidate=new it(In(\"host\",\"tcp\",d),1,\"tcp\",Os(\"host\",{transport:\"tcp\",tcptype:\"passive\"}),d,h.listeningPort,\"host\",void 0,void 0,\"passive\",this.generation,this.localUsername);this.protocols.push(h);this.appendLocalCandidate(h.localCandidate)}if(!o){const h=new Of;this.ensureProtocol(h);await h.connectionMade(d);h.localIp=d;h.localCandidate=new it(In(\"host\",\"tcp\",d),1,\"tcp\",Os(\"host\",{transport:\"tcp\",tcptype:\"active\"}),d,9,\"host\",void 0,void 0,\"active\",this.generation,this.localUsername);this.protocols.push(h);this.pairLocalProtocol(h);this.appendLocalCandidate(h.localCandidate)}});s.push(...f)}if(!o&&!c&&n.length){const f=[...l.map(h=>Promise.resolve(h)),...u];const d=f.flatMap(h=>n.map(async p=>{const m=await h;if(!m)return;const y=this.generation;const w=(async()=>{const _=m.localCandidate?.host;if(!_||!(0,Wm.isIPv4)(_))return;const x=await oR(m,p).catch(k=>{Y(\"error\",k)});if(!x||y!==this.generation||this.isRedundant(x))return;x.generation=this.generation;x.ufrag=this.localUsername;this.appendLocalCandidate(x);return x})();let S;const T=new Promise((_,x)=>{S=setTimeout(()=>x(new Error(\"STUN query timeout\")),t*1e3)});return Promise.race([w,T]).finally(()=>clearTimeout(S)).catch(_=>{Y(\"query STUN server\",_)})}));s.push(...d)}if(!o){s.push(...this.gatherRelayCandidates(i))}return s}async connect(){Y(\"start connect ice\");if(!this.localCandidatesEnd){if(!this.localCandidatesStart){throw new Error(\"Local candidates gathering was not performed\")}}if(!this.remoteUsername||!this.remotePassword){throw new Error(\"Remote username or password is missing\")}for(const t of this.remoteCandidates){this.pairRemoteCandidate(t)}this.sortCheckList();if(!this.iceLite){this.unfreezeInitial()}Y(\"earlyChecks\",this.localPassword,this.earlyChecks.length);for(const t of this.earlyChecks){this.checkIncoming(...t)}this.earlyChecks=[];this.earlyChecksDone=true;if(this.iceLite){if(!this.nominated){let t=uo;while(!this.checkListDone&&this.state!==\"closed\"){t=await this.checkListState.get();Y(\"checkListState\",t);if(t===Uc){break}}if(t!==Uc&&!this.nominated){throw new Error(\"ICE negotiation failed\")}}this.setState(\"connected\");return}this.noPairDeadline=Date.now()+Mk;for(;;){if(this.state===\"closed\")break;if(!this.schedulingChecks())break;await hR.setTimeout(20)}let e=uo;while(this.checkList.length>0&&e===uo&&this.state!==\"closed\"){e=await this.checkListState.get();Y(\"checkListState\",e)}for(const t of this.checkList){t.handle?.resolve?.()}if(e!==Uc){throw new Error(\"ICE negotiation failed\")}this.queryConsent();this.setState(\"connected\")}unfreezeInitial(){const[e]=this.checkList;if(!e)return;if(e.state===ae.FROZEN){e.updateState(ae.WAITING)}const t=new Set(e.localCandidate.foundation);for(const s of this.checkList){if(s.component===e.component&&!t.has(s.localCandidate.foundation)&&s.state===ae.FROZEN){s.updateState(ae.WAITING);t.add(s.localCandidate.foundation)}}}schedulingChecks(){if(this.nominating&&!this.nominated)return true;{const e=this.checkList.filter(t=>{if(this.options.forceTurn&&t.protocol.type===An.type)return false;return true}).find(t=>t.state===ae.WAITING);if(e){e.handle=this.checkStart(e);return true}}{const e=this.checkList.find(t=>t.state===ae.FROZEN);if(e){e.handle=this.checkStart(e);return true}}if(!this.remoteCandidatesEnd||this.resolvingRemoteCandidates>0||!this.checkList.length&&Date.now()<this.noPairDeadline){return!this.checkListDone}return false}stopConsentLifecycle(){this.consentSessionId++;this.consentFresh=false;if(this.consentExpiryTimer!==void 0){clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0}this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;const e=this.queryConsentHandle;this.queryConsentHandle=void 0;e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){if(!this.nominated){return false}if(this.state===\"closed\"||this.state===\"failed\"){return false}if(this.iceLite){return true}return this.consentFresh}abortableDelay(e,t){return new Promise((s,n)=>{if(t.aborted){n(new DOMException(\"The operation was aborted\",\"AbortError\"));return}const i=setTimeout(()=>{t.removeEventListener(\"abort\",o);s()},e);const o=a(()=>{clearTimeout(i);n(new DOMException(\"The operation was aborted\",\"AbortError\"))},\"onAbort\");t.addEventListener(\"abort\",o,{once:true})})}async close(){this.setState(\"closed\");this.stopConsentLifecycle();if(this.checkList&&!this.checkListDone){this.checkListState.put(new Promise(t=>{t(uo)}))}this.nominated=void 0;const e=this.protocols;this.protocols=[];this.relays.clear();await Promise.all(e.map(async t=>{await t.close?.()}));this.localCandidates=[];this.lookup?.close?.();this.lookup=void 0}setState(e){this.state=e;this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=true;return}if(e.host.includes(\".local\")){void this.resolveRemoteCandidate(e);return}this.addResolvedRemoteCandidate(e)}async resolveRemoteCandidate(e){const t=this.generation;this.resolvingRemoteCandidates++;try{if(!this.lookup){this.lookup=new Bf}e.host=await this.lookup.lookup(e.host)}catch{return}finally{this.resolvingRemoteCandidates--}if(t!==this.generation||this.state===\"closed\")return;this.addResolvedRemoteCandidate(e)}addResolvedRemoteCandidate(e){try{Km(e)}catch(t){return}if(this._remoteCandidates.some(t=>t.host===e.host&&t.port===e.port&&t.component===e.component&&t.type===e.type&&t.transport.toLowerCase()===e.transport.toLowerCase())){return}Y(\"addRemoteCandidate\",e);this._remoteCandidates.push(e);this.pairRemoteCandidate(e);this.sortCheckList()}getDefaultCandidate(){const e=this.localCandidates.sort((s,n)=>s.priority-n.priority);const[t]=e;return t}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw new Error(\"Cannot set remote candidates after end-of-candidates.\");this._remoteCandidates=[];for(const t of e){try{Km(t)}catch(s){continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=true}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){iR(this.checkList,this.iceControlling)}findPair(e,t){const s=this.checkList.find(n=>n.protocol===e&&n.remoteCandidate===t);return s}applyIceControlling(e){this._iceControlling=e;for(const t of this.checkList){t.iceControlling=e}}switchRole(e){Y(\"switch role\",e);if(this.iceLite){e=false}this.applyIceControlling(e);this.sortCheckList()}checkComplete(e){e.handle=void 0;if(e.state===ae.SUCCEEDED){if(e.nominated&&(e.remoteCandidate.ufrag==void 0||e.remoteCandidate.ufrag===this.remoteUsername)&&this.nominated==void 0){Y(\"nominated\",e.toJSON());this.nominated=e;this.nominating=false;this.pruneTcpConnections(e);e.protocol.connectTo?.(e.remoteAddr);if(!this.iceLite&&(this.state===\"connected\"||this.state===\"completed\")){this.queryConsent()}for(const t of this.checkList){if(t.component===e.component&&[ae.WAITING,ae.FROZEN].includes(t.state)){t.updateState(ae.FAILED)}}}if(this.nominated){if(!this.checkListDone){Y(\"ICE completed\");this.checkListState.put(new Promise(t=>t(Uc)));this.checkListDone=true}return}Y(\"not completed\",e.toJSON());for(const t of this.checkList){if(t.localCandidate.foundation===e.localCandidate.foundation&&t.state===ae.FROZEN){t.updateState(ae.WAITING)}}}this.nominateTcpPairIfReady();if(this.nominating){return}{const t=[ae.SUCCEEDED,ae.FAILED];if(this.checkList.find(({state:s})=>!t.includes(s))){return}}if(!this.iceControlling){const t=ae.SUCCEEDED;if(this.checkList.find(({state:s})=>s===t)){return}}if(!this.checkListDone){Y(\"ICE failed\");this.checkListState.put(new Promise(t=>{t(uo)}))}}isTcpPair(e){return e.localCandidate.transport.toLowerCase()===\"tcp\"}usesTcpRegularNomination(e){return this.iceControlling&&!this.remoteIsLite&&this.isTcpPair(e)}checkRequestOptions(e){const t=a(s=>{if(s>0){e.retransmissionsSent++}},\"onRequestSent\");if(this.isTcpPair(e)){return{retransmissions:0,responseTimeout:Ex,onRequestSent:t}}return{retransmissions:4,onRequestSent:t}}nominateTcpPairIfReady(){if(!this.iceControlling||this.remoteIsLite||this.nominated||this.nominating){return}for(const e of this.checkList){if(!this.isTcpPair(e)){continue}if(e.state===ae.SUCCEEDED){this.nominateTcpPair(e);return}if(e.state!==ae.FAILED){return}}}nominateTcpPair(e){this.nominating=true;const{generation:t}=this;const s=this.buildRequest({nominate:true,localUsername:e.localCandidate.ufrag??this.localUsername,remoteUsername:this.remoteUsername,iceControlling:this.iceControlling,localCandidate:e.localCandidate});e.requestsSent++;e.protocol.request(s,e.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(e)).then(()=>{if(this.isStaleNomination(e,t)){return}e.responsesReceived++;e.nominated=true;this.nominating=false;this.checkComplete(e)},n=>{if(this.isStaleNomination(e,t)){return}Y(\"tcp nomination failed\",e.toJSON(),n);this.nominating=false;e.updateState(ae.FAILED);this.checkComplete(e)})}isStaleNomination(e,t){return this.state===\"closed\"||this.generation!==t||!this.checkList.includes(e)}addPair(e){this.checkList.push(e);this.sortCheckList()}checkIncoming(e,t,s){const n=e.getAttributeValue(\"USERNAME\");const{remoteUsername:i}=fR(n);let o;const[c,l]=t;for(const f of this.remoteCandidates){if(f.host===c&&f.port===l){o=f;break}}if(!o){o=new it(lo(10),1,s.localCandidate?.transport??\"udp\",e.getAttributeValue(\"PRIORITY\"),c,l,\"prflx\",void 0,void 0,s.localCandidate?.transport===\"tcp\"?Vx(s.localCandidate.tcptype):void 0,void 0,void 0);this._remoteCandidates.push(o)}let u=this.findPair(s,o);if(!u){u=new Bc(s,o,this.iceControlling);u.updateState(ae.WAITING);this.addPair(u)}u.noteIncomingRequest(e.transactionIdHex);u.requestsReceived++;u.responsesSent++;u.localCandidate.ufrag=i;Y(\"Triggered Checks\",e.toJSON(),u.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation});if(this.iceLite){if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){u.remoteNominated=true;u.nominated=true;u.updateState(ae.SUCCEEDED);this.checkComplete(u)}return}if([ae.WAITING,ae.FAILED].includes(u.state)){u.handle=this.checkStart(u)}if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){u.remoteNominated=true;if(u.state===ae.SUCCEEDED){u.nominated=true;this.checkComplete(u)}}}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&!(e.localCandidate.transport.toLowerCase()===\"tcp\"&&e.localCandidate.tcptype===\"passive\"&&t.type!==\"prflx\")&&!this.findPair(e,t)){const s=new Bc(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(s)){return}s.updateState(ae.WAITING);this.addPair(s)}}pairLocalProtocol(e){for(const t of this.remoteCandidates){this.tryPair(e,t)}}buildRequest({nominate:e,remoteUsername:t,localUsername:s,iceControlling:n,localCandidate:i}){const o=jk({remoteUsername:t,localUsername:s});const c=new Ke(Ge.BINDING,ie.REQUEST);c.setAttribute(\"USERNAME\",o).setAttribute(\"PRIORITY\",Os(\"prflx\",{transport:i?.transport,tcptype:i?.tcptype}));if(n){c.setAttribute(\"ICE-CONTROLLING\",this.tieBreaker);if(e){c.setAttribute(\"USE-CANDIDATE\",null)}}else{c.setAttribute(\"ICE-CONTROLLED\",this.tieBreaker)}return c}pruneTcpConnections(e){for(const t of this.protocols){if(t.localCandidate?.transport.toLowerCase()!==\"tcp\"){continue}if(\"pruneForSelection\"in t&&typeof t.pruneForSelection===\"function\"){void t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}}}respondError(e,t,s,n){const i=new Ke(e.messageMethod,ie.ERROR,e.transactionId);i.setAttribute(\"ERROR-CODE\",n).addMessageIntegrity(Buffer.from(this.localPassword,\"utf8\")).addFingerprint();s.sendStun(i,t).catch(o=>{Y(\"sendStun error\",o)})}};var jk=a(({remoteUsername:r,localUsername:e})=>{return`${r}:${e}`},\"encodeTxUsername\");var fR=a(r=>{const[e,t]=r.split(\":\");return{remoteUsername:e,localUsername:t}},\"decodeTxUsername\");var bo=require(\"node:crypto\");var $f=class extends Map{static{a(this,\"RTCStatsReport\")}constructor(e){super();if(e){for(const t of e){this.set(t.id,t)}}}};function ue(r,...e){const t=e.filter(s=>s!==void 0);return`${r}_${t.join(\"_\")}`}a(ue,\"generateStatsId\");function fo(r,e,t){return ue(\"codec\",r,e,t)}a(fo,\"generateCodecStatsId\");function Qe(){return performance.timeOrigin+performance.now()}a(Qe,\"getStatsTimestamp\");function $k(r){const e=[];for(const[t,s]of Object.entries(r)){if(t===\"id\"){continue}if(t.endsWith(\"Id\")){if(typeof s===\"string\"){e.push(s)}continue}if(t.endsWith(\"Ids\")&&Array.isArray(s)){for(const n of s){if(typeof n===\"string\"){e.push(n)}}}}return e}a($k,\"getReferencedStatsIds\");function On(r,e){const t=new Map;for(const i of r){t.set(i.id,i)}if(!e){return new $f([...t.values()])}const s=new Set;const n=[...new Set(Array.from(e))];while(n.length>0){const i=n.shift();if(!i||s.has(i)){continue}const o=t.get(i);if(!o){continue}s.add(i);n.push(...$k(o))}return new $f([...s].map(i=>t.get(i)).filter(i=>!!i))}a(On,\"buildStatsReport\");var RR=require(\"node:crypto\");var gR=require(\"node:crypto\");var Jm=require(\"node:perf_hooks\");var pR=require(\"node:crypto\");var Ff=class{static{a(this,\"RTCRtpTransceiver\")}set codecs(e){this._codecs=e}get codecs(){return this._codecs}get codecPreferences(){return this._codecPreferences}setCodecPreferences(e){if(!Array.isArray(e)){throw rr(\"codecs must be an array\")}const t=e.length===0?void 0:e.map(ME);if(Fk(this._codecPreferences,t))return;this._codecPreferences=t;this.codecPreferencesNeedResolution=true;this._codecs=[];this.onCodecPreferencesChanged.execute()}constructor(e,t,s,n,i){this.kind=e;this.receiver=s;this.sender=n;this._direction=i;this.id=(0,pR.randomUUID)().toString();this.onTrack=new O;this.mid=null;this.usedForSender=false;this._codecs=[];this.headerExtensions=[];this.onCodecPreferencesChanged=new O;this.codecPreferencesNeedResolution=false;this.options={};this.stopping=false;this.stopped=false;this.rejected=false;this.pendingRejection=false;this.firedReceiving=false;this.addedByAddTrack=false;this.onStopRequested=new O;this.onRelease=new O;this.onDirectionChanged=new O;if(t){this.setDtlsTransport(t)}}get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){const t=e!==this._direction;this.setDirection(e);if(t)this.onDirectionChanged.execute()}setDirection(e){this._direction=e;if(this._currentDirection&&this._currentDirection!==\"stopped\"&&Rn.includes(this._currentDirection)){this.usedForSender=true}}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e;if(e&&e!==\"stopped\"&&Rn.includes(e)&&this.sender.track){this.usedForSender=true}}setDtlsTransport(e){this.receiver.setDtlsTransport(e);this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){const t=this.receiver.addTrack(e);if(t){this.onTrack.execute(e,this)}}get associated(){return this.mid!=null&&this.mLineIndex!=void 0}stop(){if(this.stopping){return}this.stopping=true;this.releaseMedia();if(!this.associated){this.markStopped()}this.onStopRequested.execute()}commitStopped({rejected:e}){if(e&&!this.stopping){this.rejected=true}this.pendingRejection=false;this.stopping=true;this.releaseMedia();this.markStopped()}markStopped(){this.stopped=true;this.setCurrentDirection(\"stopped\")}releaseMedia(){this.sender.stop({keepTrack:true});this.receiver.stop();this.receiver.endTracks();this.onRelease.execute()}forceStop(){if(this.stopped&&this.sender.stopped&&this.receiver.stopped){return}this.stopping=true;this.stopped=true;this.setCurrentDirection(\"stopped\");this.receiver.stop();this.sender.stop();this.onRelease.execute()}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){const e=Qe();return this.collectCodecStats(e)}collectCodecStats(e){const t=[];if(!this.dtlsTransport){return t}const s=ue(\"transport\",this.dtlsTransport.id);for(const n of this.codecs){const i={type:\"codec\",id:fo(s,n.payloadType,this.id),timestamp:e,payloadType:n.payloadType,transportId:s,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,sdpFmtpLine:n.parameters};t.push(i)}return t}};function Fk(r,e){if(r===e)return true;if(r==void 0||e==void 0||r.length!==e.length){return false}return Hf(r)===Hf(e)}a(Fk,\"sameCodecPreferences\");function Hf(r){if(Array.isArray(r)){return`[${r.map(Hf).join(\",\")}]`}if(r!=void 0&&typeof r===\"object\"){const e=Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[s])=>t.localeCompare(s));return`{${e.map(([t,s])=>`${JSON.stringify(t)}:${Hf(s)}`).join(\",\")}}`}return JSON.stringify(r)??\"undefined\"}a(Hf,\"stableCodecValue\");var Hk=\"inactive\";var Vm=\"sendonly\";var Xm=\"recvonly\";var Ym=\"sendrecv\";var qf=[Hk,Vm,Xm,Ym];var qk=P(\"webrtc/peer/utils\");function Zm(r,e){const t=a(i=>i.toUpperCase(),\"upper\");const s=a(i=>i.match(/(.{2})/g).join(\":\"),\"colon\");const n=(0,gR.createHash)(e).update(r).digest(\"hex\");return s(t(n))}a(Zm,\"fingerprint\");var zk={sha1:\"sha1\",\"sha-1\":\"sha1\",sha224:\"sha224\",\"sha-224\":\"sha224\",sha256:\"sha256\",\"sha-256\":\"sha256\",sha384:\"sha384\",\"sha-384\":\"sha384\",sha512:\"sha512\",\"sha-512\":\"sha512\"};function Qm(r){return zk[r.trim().toLowerCase()]}a(Qm,\"normalizeFingerprintAlgorithm\");function zf(r){return r.replace(/[^0-9a-f]/gi,\"\").toLowerCase()}a(zf,\"normalizeFingerprintValue\");function yR(r){const e=r[0];return e>19&&e<64}a(yR,\"isDtls\");var Gf=a((r,e)=>qf[qf.indexOf(r)&qf.indexOf(e)],\"andDirection\");function bR(r){if(r===\"sendonly\")return\"recvonly\";if(r===\"recvonly\")return\"sendonly\";return r}a(bR,\"reverseDirection\");var ho=Date.now;var Gk=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n;var SR=a(()=>{return Gk+process.hrtime.bigint()/1000n},\"microTime\");var po=a(()=>Date.now()/1e3,\"timestampSeconds\");var eg=Date.UTC(1900,0,1);var wR=a((r=Jm.performance.timeOrigin+Jm.performance.now())=>{const e=r-eg;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);return BigInt(t)<<32n|BigInt(s)},\"ntpTime\");var tg=a(r=>{const e=r-eg;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);const n=Buffer.allocUnsafe(3);n.writeUIntBE((t&63)<<18|s>>>14,0,3);return n},\"absSendTimeOf\");var ER=a(r=>{const e=Number(r>>32n);const t=Number(r&0xffffffffn);return e*1e3+t/2**32*1e3+eg},\"ntpTimeToEpochMs\");var Kf=a(r=>{return Number(r>>16n&0xffffffffn)},\"compactNtp\");function TR(r){const e={stunServers:[],turnServers:[]};for(const t of r){const s=Array.isArray(t.urls)?t.urls:[t.urls];for(const n of s){const i=Kk(n);if(!i){continue}if(i.kind===\"stun\"){e.stunServer??=i.address;e.stunServers.push(i.address)}if(i.kind===\"turn\"){if(!e.turnServer){e.turnServer=i.address;e.turnTransport=i.transport;e.turnUsername=t.username;e.turnPassword=t.credential}if(t.username&&t.credential){e.turnServers.push({address:i.address,username:t.username,password:t.credential,transport:i.transport})}}}}qk(\"iceOptions\",e);return e}a(TR,\"parseIceServers\");function rg({configuredTurnTransport:r,forceTurnTCP:e,parsedTurnTransport:t}){if(t){return t}if(r){return r}if(e){return\"tcp\"}return void 0}a(rg,\"resolveTurnTransport\");function Kk(r){const e=/^(stun|stuns|turn|turns):(.+)$/i.exec(r.trim());if(!e){return}const[,t,s]=e;const n=t.toLowerCase();const[i]=s.split(\"?\",1);const[,o=\"\"]=s.split(\"?\");const c=Xk(i,Vk(n));if(!c){return}if(n===\"stun\"||n===\"stuns\"){return{kind:\"stun\",address:c}}const l=new URLSearchParams(o);const u=l.get(\"transport\");const f=Wk({scheme:n,transportParam:u});if(f===\"invalid\"){return}return{kind:\"turn\",address:c,transport:f}}a(Kk,\"parseIceServerUrl\");function Wk({scheme:r,transportParam:e}){if(e==null){return r===\"turns\"?\"tls\":void 0}if(e===\"udp\"){return r===\"turns\"?\"invalid\":\"udp\"}if(e===\"tcp\"){return r===\"turns\"?\"tls\":\"tcp\"}return\"invalid\"}a(Wk,\"resolveParsedTurnTransport\");function Vk(r){if(r===\"stuns\"||r===\"turns\"){return 5349}return 3478}a(Vk,\"defaultPort\");function Xk(r,e){const t=r.startsWith(\"//\")?r.slice(2):r;if(!t){return}if(t.startsWith(\"[\")){const i=t.indexOf(\"]\");if(i===-1){return}const o=t.slice(1,i);const c=mR(t.slice(i+1),e);return[o,c]}const s=t.indexOf(\":\");const n=t.lastIndexOf(\":\");if(s!==-1&&s===n){return[t.slice(0,s),mR(t.slice(s+1),e)]}return[t,e]}a(Xk,\"parseAddress\");function mR(r,e){const t=r.startsWith(\":\")?r.slice(1):r;const s=Number.parseInt(t,10);return Number.isFinite(s)?s:e}a(mR,\"parsePort\");var VZ=Hr.createSelfSignedCertificateWithKey;var xR=a((r,e)=>{if(!r||typeof r!==\"object\"){if(e!==null&&typeof e===\"object\"){return e}else{return r}}if(!e||typeof e!==\"object\"){if(e==void 0){return r}return e}for(const t in e){if(Object.prototype.hasOwnProperty.call(e,t)){const s=e[t];if(s!=void 0){r[t]=s}}}return r},\"deepMerge\");var Yk=P(\"webrtc/peer/media/receiver/receiverTwcc\");var Jk=100;var Zk=500;var Qk=1<<15;function eP(r){const e=[];let t=0;while(t<r.length){let s=1;while(t+s<r.length&&r[t+s]===r[t]&&s<8191)s++;if(s>=7){e.push(new Ei({packetStatus:r[t],runLength:s}));t+=s;continue}const n=r.slice(t,t+14);const i=n.includes(Te.TypeTCCPacketReceivedLargeDelta)?r.slice(t,t+7):n;const o=i===n?14:7;e.push(new Ga({type:vs.TypeTCCStatusVectorChunk,symbolSize:o===14?0:1,symbolList:[...i,...Array(o-i.length).fill(Te.TypeTCCPacketNotReceived)]}));t+=o}return e}a(eP,\"packetChunksOf\");var Wf=class{static{a(this,\"ReceiverTWCC\")}constructor(e){this.dtlsTransport=e;this.arrivals=new Map;this.fbPktCount=0;this.rtcpSsrc=(0,RR.randomBytes)(4).readUInt32BE();this.mediaSourceSsrc=0}handleTWCC(e,t,s=Number(SR())){const n=this.unwrap(e);if(this.nextSequenceNumber!==void 0&&n<this.nextSequenceNumber)return;if(!this.arrivals.has(n))this.arrivals.set(n,s);if(this.arrivals.size>Qk){let i=n;for(const o of this.arrivals.keys())i=Math.min(i,o);this.arrivals.delete(i);this.nextSequenceNumber=i+1}this.mediaSourceSsrc=t;if(!this.timer){this.timer=setInterval(()=>this.sendTWCC(),Jk);this.timer.unref()}}stop(){clearInterval(this.timer);this.timer=void 0;this.arrivals.clear()}sendTWCC(){if(this.arrivals.size===0)return;let e=this.nextSequenceNumber??Infinity;if(e===Infinity){for(const s of this.arrivals.keys())e=Math.min(e,s)}const t=this.highestSequenceNumber;while(e<=t){const{feedback:s,next:n}=this.buildFeedback(e,t);this.dtlsTransport.sendRtcp([new nt({feedback:s})]).catch(i=>Yk(i));e=n}this.arrivals.clear();this.nextSequenceNumber=t+1}unwrap(e){if(this.highestSequenceNumber===void 0){this.highestSequenceNumber=e;return e}let t=e-this.highestSequenceNumber&65535;if(t>=32768)t-=65536;const s=this.highestSequenceNumber+t;if(s>this.highestSequenceNumber)this.highestSequenceNumber=s;return s}buildFeedback(e,t){let s=e;while(!this.arrivals.has(s))s++;const n=Math.floor(this.arrivals.get(s)/64e3);let i=n*64e3;const o=[];const c=[];let l=e;for(;l<=t&&o.length<Zk;l++){const f=this.arrivals.get(l);if(f===void 0){o.push(Te.TypeTCCPacketNotReceived);continue}const d=Math.round((f-i)/250);if(d<-32768||d>32767)break;const h=d>=0&&d<=255?Te.TypeTCCPacketReceivedSmallDelta:Te.TypeTCCPacketReceivedLargeDelta;o.push(h);c.push(new sn({type:h,delta:d*250}));i+=d*250}const u=new Mr({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:e&65535,packetStatusCount:o.length,referenceTime:n&16777215,fbPktCount:this.fbPktCount,packetChunks:eP(o),recvDeltas:c});this.fbPktCount=Vw(this.fbPktCount,1);return{feedback:u,next:l}}};var Vf=class{static{a(this,\"CumulativeResult\")}constructor(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}addPacket(e,t,s){if(this.numPackets===0){this.firstPacketSentAtMs=t;this.firstPacketReceivedAtMs=s;this.lastPacketSentAtMs=t;this.lastPacketReceivedAtMs=s}else{if(t<this.firstPacketSentAtMs)this.firstPacketSentAtMs=t;if(s<this.firstPacketReceivedAtMs)this.firstPacketReceivedAtMs=s;if(t>this.lastPacketSentAtMs)this.lastPacketSentAtMs=t;if(s>this.lastPacketReceivedAtMs)this.lastPacketReceivedAtMs=s}this.numPackets++;this.totalSize+=e}reset(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}get receiveBitrate(){const e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;const t=this.totalSize/e*8*1e3;return wi(t)}get sendBitrate(){const e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;const t=this.totalSize/e*8*1e3;return wi(t)}};var mo=20;var tP=10;var rP=8192;var Xf=class{static{a(this,\"SenderBandwidthEstimator\")}get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e;this.onCongestionScore.execute(e)}get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e;this.onAvailableBitrate.execute(e)}constructor(){this.congestion=false;this.onAvailableBitrate=new O;this.onCongestion=new O;this.onCongestionScore=new O;this.congestionCounter=0;this.cumulativeResult=new Vf;this.sentInfos=new Map;this._congestionScore=1;this._availableBitrate=0}receiveTWCC(e){const t=ho();const s=this.cumulativeResult.numPackets?t-this.cumulativeResult.firstPacketSentAtMs:0;if(s>1e3){this.cumulativeResult.reset();if(this.congestionCounter<mo){this.congestionCounter++}else if(this.congestionScore<tP){this.congestionScore++}if(this.congestionCounter>=mo&&!this.congestion){this.congestion=true;this.onCongestion.execute(this.congestion)}}for(const n of e.packetResults){if(!n.received)continue;const i=n.sequenceNumber;const o=this.sentInfos.get(i);if(!o)continue;if(!n.receivedAtMs)continue;this.cumulativeResult.addPacket(o.size,o.sendingAtMs,n.receivedAtMs)}if(s>=100&&this.cumulativeResult.numPackets>=20){this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate);this.cumulativeResult.reset();if(this.congestionCounter>-mo){const n=wi(mo/2)+1;const i=wi(mo/4)+1;const o=n-(n-i)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-o}if(this.congestionCounter<=-mo){if(this.congestionScore>1){this.congestionScore--;this.onCongestion.execute(false)}this.congestionCounter=0}if(this.congestionCounter<=0&&this.congestion){this.congestion=false;this.onCongestion.execute(this.congestion)}}}rtpPacketSent(e){this.sentInfos.delete(e.wideSeq-rP&65535);this.sentInfos.set(e.wideSeq,e)}};var Ut=P(\"webrtc/peer/transport/dtls\");var sP=a(()=>void 0,\"ignoreSendFailure\");function nP(r){if(!r){return}if(r.major===254&&r.minor===253){return\"DTLS 1.2\"}if(r.major===254&&r.minor===255){return\"DTLS 1.0\"}}a(nP,\"formatDtlsVersion\");function iP(r){switch(r){case 1:return\"AES_CM_128_HMAC_SHA1_80\";case 7:return\"AEAD_AES_128_GCM\";default:return}}a(iP,\"formatSrtpCipher\");var jc=class r{static{a(this,\"RTCDtlsTransport\")}#e;#t;constructor(e,t,s,n=[]){this.config=e;this.iceTransport=t;this.localCertificate=s;this.srtpProfiles=n;this.id=(0,bo.randomUUID)().toString();this.state=\"new\";this.role=\"auto\";this.srtpStarted=false;this.transportSequenceNumber=0;this.receiverTWCC=new Wf(this);this.senderBWE=new Xf;this.bytesSent=0;this.bytesReceived=0;this.packetsSent=0;this.packetsReceived=0;this.dataReceiver=()=>{};this.onStateChange=new O;this.onRtcp=new O;this.onRtp=new O;this.events=new kt;this.addEventListener=(i,o,c)=>{this.events.addEventListener(i,o,c)};this.removeEventListener=(i,o)=>{this.events.removeEventListener(i,o)};this.dispatchEvent=i=>this.events.dispatchEvent(i);this.sendData=async i=>{if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return}if(!this.dtls){throw new Error(\"dtls not established\")}await this.dtls.send(i)};this.localCertificate??=r.localCertificate;this.#e=lP(t.connection)}get localParameters(){return new yo(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){if(this.localCertificate){return this.localCertificate}if(this.localCertificatePromise){return this.localCertificatePromise}this.localCertificatePromise=(async()=>{const{certPem:e,keyPem:t,signatureHash:s}=await Hr.createSelfSignedCertificateWithKey({signature:Tt.ecdsa_3,hash:Ku.sha256_4},jr.secp256r1_23);this.localCertificate=new $c(t,e,s);return this.localCertificate})();return this.localCertificatePromise}setRemoteParams(e){const t=oP([...this.remoteParameters?.fingerprints??[],...e.fingerprints]);const s=e.role===\"auto\"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new yo(t,s)}async start(){if(this.#t){return await this.#t}if(this.state!==\"new\"){throw new Error(\"state must be new\")}this.#t=this.#r();await this.#t}async#r(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}if(this.role===\"auto\"){if(this.iceTransport.role===\"controlling\"){this.role=\"server\"}else{this.role=\"client\"}}this.setState(\"connecting\");await new Promise((e,t)=>{if(this.role===\"server\"){this.dtls=new _c({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true,certificateRequest:true})}else{this.dtls=new eo({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true})}this.dtls.onData.subscribe(s=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}this.dataReceiver(s)});this.dtls.onClose.subscribe(()=>{if(this.state!==\"failed\"){this.setState(\"closed\")}});this.dtls.onConnect.once(e);this.dtls.onError.once(s=>{this.setState(\"failed\");Ut(\"dtls failed\",s);t(s)});if(this.dtls instanceof eo){this.dtls.connect().catch(s=>{this.setState(\"failed\");Ut(\"dtls connect failed\",s);t(s)})}});try{this.verifyRemoteCertificateFingerprint()}catch(e){this.setState(\"failed\");this.dtls?.close();throw e}if(this.srtpProfiles.length>0){this.startSrtp()}this.setState(\"connected\");Ut(\"dtls connected\")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}const e=this.dtls?.remoteCertificate;if(!e){throw new Error(\"remote certificate not available\")}const t=this.remoteParameters.fingerprints.flatMap(({algorithm:c,value:l})=>{const u=Qm(c);if(!u){return[]}const f=zf(l);if(!f){throw new Error(\"remote fingerprint value is empty\")}return[{normalizedAlgorithm:u,normalizedValue:f}]});if(t.length===0){throw new Error(\"no supported remote fingerprint algorithms\")}const s=cP(t);const n=t.filter(({normalizedAlgorithm:c})=>c===s);const i=n.reduce((c,{normalizedAlgorithm:l})=>{if(!c.has(l)){c.set(l,zf(Zm(e,l)))}return c},new Map);const o=n.some(({normalizedAlgorithm:c,normalizedValue:l})=>i.get(c)===l);if(!o){throw new Error(\"remote certificate fingerprint mismatch\")}}updateSrtpSession(){if(!this.dtls)throw new Error;const e=this.dtls.srtp.srtpProfile;if(!e){throw new Error(\"need srtpProfile\")}Ut(\"selected SRTP Profile\",e);const{localKey:t,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(lE(e),uE(e));const o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new Ou(o);this.srtcp=new Au(o)}startSrtp(){if(this.srtpStarted)return;this.srtpStarted=true;this.updateSrtpSession();this.iceTransport.connection.onData.subscribe(e=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}if(!hE(e))return;this.bytesReceived+=e.length;this.packetsReceived++;if(mE(e)){let t;try{t=this.srtcp.decrypt(e)}catch(n){if(n instanceof Nt){Ut(\"dropping invalid SRTCP packet\",n);return}throw n}let s;try{s=bu.deSerialize(t)}catch(n){Ut(\"dropping malformed SRTCP packet\",n);return}for(const n of s){try{if(n instanceof nt&&n.feedback instanceof Mr){this.senderBWE.receiveTWCC(n.feedback);continue}this.onRtcp.execute(n)}catch(i){Ut(\"RTCP error\",i)}}}else{let t;try{t=this.srtp.decrypt(e)}catch(n){if(n instanceof Nt){Ut(\"dropping invalid SRTP packet\",n);return}throw n}let s;try{s=Le.deSerialize(t)}catch(n){Ut(\"dropping malformed SRTP packet\",n);return}try{this.onRtp.execute(s)}catch(n){Ut(\"RTP error\",n)}}})}async sendRtp(e,t){try{const s=this.srtp.encrypt(e,t);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return s.length}this.bytesSent+=s.length;this.packetsSent++;await this.iceTransport.connection.send(s).catch(sP);return s.length}catch(s){Ut(\"failed to send\",s);return 0}}async sendRtcp(e){if(!this.srtcp){return}const t=Buffer.concat(e.map(n=>n.serialize()));const s=this.srtcp.encrypt(t);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return s.length}this.bytesSent+=s.length;this.packetsSent++;await this.iceTransport.connection.send(s).catch(()=>{})}setState(e,t=true){if(e!=this.state){this.state=e;if(e===\"closed\"||e===\"failed\")this.receiverTWCC.stop();this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}async stop(){this.setState(\"closed\",false);this.dtls?.close();await this.iceTransport.stop()}async getStats(e=Qe()){const t=[];const s=ue(\"transport\",this.id);const n={type:\"transport\",id:s,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===\"unknown\"?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?ue(\"candidate-pair\",this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?ue(\"certificate\",this.id,\"local\"):void 0,remoteCertificateId:this.dtls?.remoteCertificate?ue(\"certificate\",this.id,\"remote\"):void 0,dtlsRole:this.role===\"auto\"?void 0:this.role,tlsVersion:nP(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:iP(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};t.push(n);if(this.localCertificate){const o=this.localCertificate.getFingerprints();if(o.length>0){const c={type:\"certificate\",id:ue(\"certificate\",this.id,\"local\"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(\"base64\")};t.push(c)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){const o={type:\"certificate\",id:ue(\"certificate\",this.id,\"remote\"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(\"base64\")};t.push(o)}const i=await this.iceTransport.getStats(e,s);t.push(...i);return t}};var $c=class{static{a(this,\"RTCCertificate\")}constructor(e,t,s){this.certPem=t;this.signatureHash=s;this.publicKey=new bo.X509Certificate(t).publicKey.export({type:\"spki\",format:\"pem\"});this.privateKey=(0,bo.createPrivateKey)(e).export({type:\"pkcs8\",format:\"pem\"})}getFingerprints(){return[new go(\"sha-256\",Zm(Ju(this.certPem),\"sha256\"))]}};var go=class{static{a(this,\"RTCDtlsFingerprint\")}constructor(e,t){this.algorithm=e;this.value=t}};var yo=class{static{a(this,\"RTCDtlsParameters\")}constructor(e=[],t){this.fingerprints=e;this.role=t}};var oP=a(r=>{const e=new Set;return r.filter(({algorithm:t,value:s})=>{const n=`${Qm(t)??t.trim().toLowerCase()}:${zf(s)}`;if(e.has(n)){return false}e.add(n);return true})},\"deduplicateFingerprints\");var aP=[\"sha512\",\"sha384\",\"sha256\",\"sha224\",\"sha1\"];var cP=a(r=>{return aP.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm},\"selectPreferredFingerprintAlgorithm\");var sg=class{static{a(this,\"IceTransport\")}#e;#t;constructor(e){this.ice=e;this.closed=false;this.#e=[];this.type=\"ice\";this.send=t=>{return this.ice.send(t)};e.onData.subscribe(t=>{if(!yR(t))return;if(this.#t)this.#t(t);else if(this.#e&&this.#e.length<16)this.#e.push(t)})}get onData(){return this.#t??(()=>void 0)}set onData(e){const t=this.#e;if(!t){this.#t=e;return}queueMicrotask(()=>{this.#e=void 0;this.#t=e;t.forEach(s=>e(s))})}get address(){return{}}async close(){this.closed=true;Ne(()=>this.ice.close(),e=>Ut(\"close failed\",e))}};var lP=a(r=>new sg(r),\"createIceTransport\");var _R=require(\"node:crypto\");var Yf=P(\"webrtc/peer/transport/ice\");function uP(r){switch(r){case 0:return\"frozen\";case 1:return\"waiting\";case 2:return\"in-progress\";case 3:return\"succeeded\";case 4:return\"failed\";default:return\"failed\"}}a(uP,\"mapCandidatePairState\");var Jf=class{static{a(this,\"RTCIceTransport\")}constructor(e){this.iceGather=e;this.id=(0,_R.randomUUID)().toString();this.state=\"new\";this.component=\"rtp\";this.iceRestarts=0;this.renominating=false;this.events=new kt;this.onStateChange=new O;this.onIceCandidate=new O;this.onNegotiationNeeded=new O;this.addEventListener=(t,s,n)=>{this.events.addEventListener(t,s,n)};this.removeEventListener=(t,s)=>{this.events.removeEventListener(t,s)};this.dispatchEvent=t=>this.events.dispatchEvent(t);this.addRemoteCandidate=async t=>{if(!this.connection.remoteCandidatesEnd){await this.connection.addRemoteCandidate(t?fP(t):void 0)}};this.connection=this.iceGather.connection;this.connection.stateChanged.subscribe(t=>{this.setState(t)});this.iceGather.onIceCandidate=t=>{this.onIceCandidate.execute(t)};this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.();this.events.emit(\"gatheringstatechange\")})}get role(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return\"unknown\"}if(this.connection.iceControlling)return\"controlling\";else return\"controlled\"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==\"prflx\").map(e=>Yr(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>Yr(e).toJSON())}getSelectedCandidatePair(){const e=this.connection.candidatePairs.find(t=>t.nominated)??this.connection.candidatePairs.find(t=>t.state===3);if(!e){return null}return{local:Yr(e.localCandidate).toJSON(),remote:Yr(e.remoteCandidate).toJSON()}}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return null}return new So({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=true){if(e!==this.state){this.state=e;this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}gather(){return this.iceGather.gather()}setIceServers(e){this.iceGather.setIceServers(e)}setRemoteParams(e,t=false){if(t){this.renominating=true}if(this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)){if(this.renominating){Yf(\"renomination\",e);this.connection.resetNominatedPair();this.checking=void 0;this.renominating=false}else{Yf(\"restart\",e);this.restart()}}this.connection.setRemoteParams(e)}restart(){this.iceRestarts++;this.connection.restart().catch(e=>Yf(\"restart failed\",e));this.setState(\"new\");this.iceGather.setGatheringState(\"new\");this.checking=void 0;this.onNegotiationNeeded.execute()}async start(){if(this.state===\"closed\"){throw new Error(\"RTCIceTransport is closed\")}if(!this.connection.remotePassword||!this.connection.remoteUsername){throw new Error(\"remoteParams missing\")}this.checking??=this.check();await this.checking}async check(){this.setState(\"checking\");try{await this.connection.connect()}catch(e){if(this.state!==\"closed\")this.setState(\"failed\");throw e}}async stop(){if(this.state!==\"closed\"){this.setState(\"closed\",false);await this.connection.close()}this.onStateChange.complete();this.onIceCandidate.complete();this.onNegotiationNeeded.complete()}async getStats(e=Qe(),t=ue(\"transport\",this.id)){const s=[];for(const i of this.connection.localCandidates){const o={type:\"local-candidate\",id:ue(\"local-candidate\",i.id),timestamp:e,transportId:t,address:i.host,port:i.port,protocol:i.transport,candidateType:i.type,priority:i.priority,foundation:i.foundation,relatedAddress:i.relatedAddress,relatedPort:i.relatedPort,usernameFragment:i.ufrag,tcpType:i.tcptype};s.push(o)}for(const i of this.connection.remoteCandidates){const o={type:\"remote-candidate\",id:ue(\"remote-candidate\",i.id),timestamp:e,transportId:t,address:i.host,port:i.port,protocol:i.transport,candidateType:i.type,priority:i.priority,foundation:i.foundation,relatedAddress:i.relatedAddress,relatedPort:i.relatedPort,usernameFragment:i.ufrag,tcpType:i.tcptype};s.push(o)}const n=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(i=>i.nominated),...this.connection.candidatePairs.filter(i=>!i.nominated)]:[];for(const i of n){const o={type:\"candidate-pair\",id:ue(\"candidate-pair\",i.id),timestamp:e,transportId:t,localCandidateId:ue(\"local-candidate\",i.localCandidate.id),remoteCandidateId:ue(\"remote-candidate\",i.remoteCandidate.id),state:uP(i.state),nominated:i.nominated,packetsSent:i.packetsSent,packetsReceived:i.packetsReceived,bytesSent:i.bytesSent,bytesReceived:i.bytesReceived,currentRoundTripTime:i.rtt,totalRoundTripTime:i.totalRoundTripTime,roundTripTimeMeasurements:i.roundTripTimeMeasurements,requestsReceived:i.requestsReceived,requestsSent:i.requestsSent,responsesReceived:i.responsesReceived,responsesSent:i.responsesSent,retransmissionsReceived:i.retransmissionsReceived,retransmissionsSent:i.retransmissionsSent,consentRequestsSent:i.consentRequestsSent};s.push(o)}return s}};var Zf=class{static{a(this,\"RTCIceGatherer\")}constructor(e={}){this.options=e;this.onIceCandidate=()=>{};this.gatheringState=\"new\";this.onGatheringStateChange=new O;this.connection=new jf(false,this.options);this.connection.onIceCandidate.subscribe(t=>{this.onIceCandidate(Yr(t))})}async gather(){if(this.gatheringState===\"new\"){this.setState(\"gathering\");await this.connection.gatherCandidates();this.onIceCandidate(void 0);this.setState(\"complete\")}}setIceServers(e){this.connection.setIceServers(e)}setGatheringState(e){this.setState(e)}get localCandidates(){return this.connection.localCandidates.map(Yr)}get localParameters(){const e=new So({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword});return e}setState(e){if(e!==this.gatheringState){this.gatheringState=e;this.onGatheringStateChange.execute(e)}}};function Yr(r){const e=new Fc(r.component,r.foundation,r.host,r.port,r.priority,r.transport,r.type,r.generation,r.ufrag);e.relatedAddress=r.relatedAddress;e.relatedPort=r.relatedPort;e.tcpType=r.tcptype;return e}a(Yr,\"candidateFromIce\");function fP(r){return new it(r.foundation,r.component,r.protocol,r.priority,r.ip,r.port,r.type,r.relatedAddress,r.relatedPort,r.tcpType,r.generation,r.ufrag)}a(fP,\"candidateToIce\");var ng=class{static{a(this,\"RTCIceCandidate\")}constructor(e){Object.assign(this,e)}static fromSdp(e){const t=it.fromSdp(e);const s=Yr(t);return s.toJSON()}static isThis(e){if(typeof e?.candidate===\"string\")return true}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};var Fc=class{static{a(this,\"IceCandidate\")}constructor(e,t,s,n,i,o,c,l,u){this.component=e;this.foundation=t;this.ip=s;this.port=n;this.priority=i;this.protocol=o;this.type=c;this.generation=l;this.ufrag=u}toJSON(){return new ng({candidate:ig(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate){throw new Error(\"candidate is required\")}const t=e.candidate.startsWith(\"candidate:\")?e.candidate.slice(\"candidate:\".length):e.candidate;const s=og(t);s.sdpMLineIndex=e.sdpMLineIndex??void 0;s.sdpMid=e.sdpMid??void 0;return s}catch(t){Yf(\"candidate not parsed\",t)}}};var So=class{static{a(this,\"RTCIceParameters\")}constructor(e={}){this.iceLite=false;Object.assign(this,e)}};var AR=require(\"node:crypto\");var CR=require(\"node:crypto\");var Qf=P(\"webrtc/peer/dataChannel\");function vR(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}a(vR,\"getDataChannelMessageSize\");var wo=class extends kt{static{a(this,\"RTCDataChannel\")}constructor(e,t,s=true){super();this.sctp=e;this.parameters=t;this.sendOpen=s;this.statsId=(0,CR.randomUUID)().toString();this.stateChange=new O;this.stateChanged=new O;this.onMessage=new O;this.error=new O;this.bufferedAmountLow=new O;this.bufferedAmountChanged=new O;this.isCreatedByRemote=false;this.readyState=\"connecting\";this.bufferedAmount=0;this._bufferedAmountLowThreshold=0;this.messagesSent=0;this.bytesSent=0;this.messagesReceived=0;this.bytesReceived=0;this.id=this.parameters.id;if(t.negotiated){if(this.id==void 0||this.id<0||this.id>65534){throw new Error(\"ID must be in range 0-65534 if data channel is negotiated out-of-band\")}this.sctp.dataChannelAddNegotiated(this)}else{if(s){this.sendOpen=false;this.sctp.dataChannelOpen(this)}}}get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){if(e<0||e>4294967295){throw new Error(\"bufferedAmountLowThreshold must be in range 0 - 4294967295\")}this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){this.readyState=e;this.stateChange.execute(e);this.stateChanged.execute(e);switch(e){case\"open\":if(this.onopen)Ne(()=>this.onopen(),t=>Qf(\"onopen failed\",t));this.emit(\"open\");break;case\"closed\":if(this.onclose)Ne(()=>this.onclose(),t=>Qf(\"onclose failed\",t));this.emit(\"close\");break;case\"closing\":if(this.onclosing)Ne(()=>this.onclosing(),t=>Qf(\"onclosing failed\",t));break}Qf(\"change state\",e)}}addBufferedAmount(e){const t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e;this.bufferedAmountChanged.execute();if(t){this.bufferedAmountLow.execute();this.emit(\"bufferedamountlow\")}}send(e){const t=this.sctp.datachannelSend(this,e);this.messagesSent++;this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}};var Eo=class{static{a(this,\"RTCDataChannelParameters\")}constructor(e={}){this.label=\"\";this.ordered=true;this.protocol=\"\";this.negotiated=false;Object.assign(this,e)}};var pt=P(\"webrtc/peer/transport/sctp\");var To=65536;var ed=class r{static{a(this,\"RTCSctpTransport\")}constructor(e=5e3,t=To,s={}){this.port=e;this.maxMessageSize=t;this.sctpOptions=s;this.onDataChannel=new O;this.id=(0,AR.randomUUID)().toString();this.bundled=false;this.dataChannels={};this.remoteMaxMessageSize=To;this.dataChannelQueue=[];this.eventDisposer=[];this.datachannelReceive=async(n,i,o)=>{if(i===ro&&o.length>0){pt(\"DCEP\",n,i,o);switch(o[0]){case Em:{if(o.length<12){pt(\"DATA_CHANNEL_OPEN data.length not enough\");return}if(!Object.keys(this.dataChannels).includes(n.toString())){const u=o.readUInt8(1);const f=o.readUInt32BE(4);const d=o.readUInt16BE(8);const h=o.readUInt16BE(10);let p=12;const m=o.slice(p,p+d).toString(\"utf8\");p+=d;const y=o.slice(p,p+h).toString(\"utf8\");pt(\"DATA_CHANNEL_OPEN\",{channelType:u,reliability:f,streamId:n,label:m,protocol:y});const w=(u&3)===1?f:void 0;const S=(u&3)===2?f:void 0;const T=new Eo({label:m,ordered:(u&128)===0,maxPacketLifeTime:S,maxRetransmits:w,protocol:y,id:n});const _=new wo(this,T,false);_.isCreatedByRemote=true;this.dataChannels[n]=_;this.onDataChannel.execute(_);_.setReadyState(\"open\")}else{pt(\"datachannel already opened\",\"retransmit ack\")}const c=this.dataChannels[n];const l=Buffer.allocUnsafe(1);l.writeUInt8(wm,0);this.dataChannelQueue.push([c,ro,l]);await this.dataChannelFlush()}break;case wm:{pt(\"DATA_CHANNEL_ACK\",n,i);const c=this.dataChannels[n];if(!c){throw new Error(\"channel not found\")}c.setReadyState(\"open\")}break}}else{const c=this.dataChannels[n];if(c){const l=(()=>{switch(i){case Tm:return o.toString(\"utf8\");case Tf:return\"\";case xm:return o;case xf:return Buffer.from([]);default:throw new Error}})();c.messagesReceived++;c.bytesReceived+=o.length;c.onMessage.execute(l);c.emit(\"message\",{data:l});if(c.onmessage){Ne(()=>c.onmessage({data:l}),u=>pt(\"onmessage failed\",u))}}}};this.datachannelSend=(n,i)=>{const o=vR(i);this.assertSendableMessageSize(o);n.addBufferedAmount(o);if(o===0){this.dataChannelQueue.push([n,typeof i===\"string\"?Tf:xf,Buffer.from([0])])}else{const c=Buffer.isBuffer(i)?i:Buffer.from(i);this.dataChannelQueue.push(typeof i===\"string\"?[n,Tm,c]:[n,xm,c])}if(this.sctp.associationState!==Q.ESTABLISHED){pt(\"sctp not established\",this.sctp.associationState)}this.dataChannelFlush().catch(c=>pt(\"flush failed\",c));return o}}get transport(){return this.dtlsTransport}setDtlsTransport(e){if(this.dtlsTransport&&this.dtlsTransport.id===e.id){return}this.eventDisposer.forEach(t=>t());this.dtlsTransport=e;this.sctp=new lc(new ag(this.dtlsTransport),this.port,this.sctpOptions);this.eventDisposer=[...[this.sctp.onReceive.subscribe(Vt(this.datachannelReceive,t=>pt(\"receive failed\",t))),this.sctp.onReconfigStreams.subscribe(t=>{t.forEach(s=>{const n=this.dataChannels[s];if(!n)return;n.setReadyState(\"closing\");n.setReadyState(\"closed\");delete this.dataChannels[s]})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{if(t.negotiated&&t.readyState!==\"open\"){t.setReadyState(\"open\")}});this.dataChannelFlush().catch(t=>pt(\"flush failed\",t))}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.setReadyState(\"closed\")});this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"closed\"){this.sctp.setState(Q.CLOSED)}})].map(t=>t.unSubscribe),()=>this.sctp.onSackReceived=async()=>{},()=>this.sctp.onSent=void 0];this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()};this.sctp.onSent=(t,s,n)=>{if(s===ro||s===Tf||s===xf){return}this.dataChannels[t]?.addBufferedAmount(-n)}}holdReceived(e){this.sctp.holdReceived(e)}releaseReceived(e){this.sctp.releaseReceived(e)}get isServer(){return this.dtlsTransport.iceTransport.role!==\"controlling\"}channelByLabel(e){return Object.values(this.dataChannels).find(t=>t.label===e)}dataChannelAddNegotiated(e){if(e.id==void 0){throw new Error}if(this.dataChannels[e.id]){throw new Error}this.dataChannels[e.id]=e;if(this.sctp.associationState===Q.ESTABLISHED){e.setReadyState(\"open\")}}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=hx;const s=0;let n=0;if(e.maxRetransmits!==null){t=1;n=e.maxRetransmits}else if(e.maxPacketLifeTime!==null){t=2;n=e.maxPacketLifeTime}if(!e.ordered){t|=128}const i=Buffer.allocUnsafe(12);i.writeUInt8(Em,0);i.writeUInt8(t,1);i.writeUInt16BE(s,2);i.writeUInt32BE(n,4);const o=Buffer.from(e.label,\"utf8\");const c=Buffer.from(e.protocol,\"utf8\");i.writeUInt16BE(o.length,8);i.writeUInt16BE(c.length,10);const l=Buffer.concat([i,o,c]);this.dataChannelQueue.push([e,ro,l]);this.dataChannelFlush().catch(u=>pt(\"flush failed\",u))}async dataChannelFlush(){if(this.sctp.associationState!=Q.ESTABLISHED)return;while(this.dataChannelQueue.length>0){const[e,t,s]=this.dataChannelQueue.shift();let n=e.id;if(n===void 0){n=this.dataChannelId;while(Object.keys(this.dataChannels).includes(n.toString())){n+=2}this.dataChannels[n]=e;e.setId(n)}if(t===ro){this.sctp.send(n,t,s,{ordered:true}).catch(i=>pt(\"send dcep failed\",i.message))}else{const i=e.maxPacketLifeTime!==null?Date.now()+e.maxPacketLifeTime/1e3:void 0;this.sctp.send(n,t,s,{expiry:i,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered}).catch(o=>pt(\"send data failed\",o.message))}}this.dataChannelQueue=[]}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize){throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}}getCapabilities(){return r.getCapabilities(this.maxMessageSize)}static getCapabilities(e=To){return new Hc(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??To}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.dataChannelId=this.dtlsTransport.role===\"server\"?1:0;this.sctp.isServer=this.isServer;await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{};await this.sctp.stop()}dataChannelClose(e){if(![\"closing\",\"closed\"].includes(e.readyState)){e.setReadyState(\"closing\");if(this.sctp.associationState===Q.ESTABLISHED){if(!this.sctp.reconfigQueue.includes(e.id)){this.sctp.reconfigQueue.push(e.id)}if(this.sctp.reconfigQueue.length===1){this.sctp.transmitReconfigRequest().catch(t=>pt(\"reconfig failed\",t))}}else{this.dataChannelQueue=this.dataChannelQueue.filter(t=>t[0].id!==e.id);this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id);if(e.id!==void 0){delete this.dataChannels[e.id]}e.setReadyState(\"closed\")}}}};var Hc=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};var ag=class{static{a(this,\"BridgeDtls\")}constructor(e){this.dtls=e;this.send=t=>{return this.dtls.sendData(t)}}set onData(e){this.dtls.dataReceiver=e}close(){}};var Jr=class r{static{a(this,\"SessionDescription\")}constructor(){this.version=0;this.name=\"-\";this.time=\"0 0\";this.group=[];this.extMapAllowMixed=true;this.msidSemantic=[];this.media=[];this.dtlsFingerprints=[]}static parse(e){const[t,s]=dP(e);const n=new r;t.forEach(c=>{if(c.startsWith(\"v=\")){n.version=Number.parseInt(c.slice(2),10)}else if(c.startsWith(\"o=\")){n.origin=c.slice(2)}else if(c.startsWith(\"s=\")){n.name=c.slice(2)}else if(c.startsWith(\"c=\")){n.host=cg(c.slice(2))}else if(c.startsWith(\"t=\")){n.time=c.slice(2)}else if(c.startsWith(\"a=\")){const[l,u]=lg(c);switch(l){case\"fingerprint\":{const[f,d]=u?.split(\" \")||[];n.dtlsFingerprints.push(new go(f,d))}break;case\"ice-lite\":n.iceLite=true;break;case\"ice-options\":n.iceOptions=u;break;case\"ice-pwd\":n.icePassword=u;break;case\"ice-ufrag\":n.iceUsernameFragment=u;break;case\"group\":ug(n.group,u);break;case\"msid-semantic\":ug(n.msidSemantic,u);break;case\"setup\":n.dtlsRole=Cm[u];break;case\"extmap-allow-mixed\":n.extMapAllowMixed=true;break}}});const i=n.group.find(c=>c.semantic===\"BUNDLE\");s.forEach(c=>{const l=c[0];const u=l.match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!u){throw new Error(\"m line not found\")}const f=u[1];const d=u[4].split(\" \");const h=[\"audio\",\"video\"].includes(f)?d.map(y=>Number(y)):void 0;const p=new kn(f,Number.parseInt(u[2]),u[3],h||d);p.dtlsParams=new yo([...n.dtlsFingerprints],n.dtlsRole);p.iceParams=new So({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword});p.iceOptions=n.iceOptions;n.media.push(p);c.slice(1).forEach(y=>{if(y.startsWith(\"c=\")){p.host=cg(y.slice(2))}else if(y.startsWith(\"a=\")){const[w,S]=lg(y);switch(w){case\"candidate\":if(!S)throw new Error;p.iceCandidates.push(og(S));break;case\"end-of-candidates\":p.iceCandidatesComplete=true;break;case\"extmap\":{let[T,_]=S.split(\" \");if(T.includes(\"/\")){[T]=T.split(\"/\")}p.rtp.headerExtensions.push(new Qt({id:Number.parseInt(T),uri:_}))}break;case\"fingerprint\":{if(!S)throw new Error;const[T,_]=S.split(\" \");p.dtlsParams?.fingerprints.push(new go(T,_))}break;case\"ice-options\":p.iceOptions=S;break;case\"ice-pwd\":p.iceParams.password=S;break;case\"ice-ufrag\":p.iceParams.usernameFragment=S;break;case\"ice-lite\":p.iceParams.iceLite=true;break;case\"max-message-size\":p.sctpCapabilities=new Hc(Number.parseInt(S,10));break;case\"mid\":p.rtp.muxId=S;break;case\"msid\":p.msids.push(S);break;case\"rtcp\":{const[T,_]=yr(S,\" \");p.rtcpPort=Number.parseInt(T);p.rtcpHost=cg(_)}break;case\"rtcp-mux\":p.rtcpMux=true;break;case\"bundle-only\":p.bundleOnly=true;break;case\"setup\":p.dtlsParams.role=Cm[S];break;case\"recvonly\":case\"sendonly\":case\"sendrecv\":case\"inactive\":p.direction=w;break;case\"rtpmap\":{const[T,_]=yr(S,\" \");const[x,k,N]=_.split(\"/\");let A;if(p.kind===\"audio\"){A=N?Number.parseInt(N):1}const B=new ft({mimeType:p.kind+\"/\"+x,channels:A,clockRate:Number.parseInt(k),payloadType:Number.parseInt(T)});p.rtp.codecs.push(B)}break;case\"sctpmap\":{if(!S)throw new Error;const[T,_]=yr(S,\" \");p.sctpMap[Number.parseInt(T)]=_;p.sctpPort=Number.parseInt(T)}break;case\"sctp-port\":if(!S)throw new Error;p.sctpPort=Number.parseInt(S);break;case\"ssrc\":{const[T,_]=yr(S,\" \");const x=Number.parseInt(T);const[k,N]=yr(_,\":\");let A=p.ssrc.find(B=>B.ssrc===x);if(!A){A=new xo({ssrc:x});p.ssrc.push(A)}if(vm.includes(k)){A[k]=N}}break;case\"ssrc-group\":ug(p.ssrcGroup,S);break;case\"rid\":{const[T,_]=yr(S,\" \");p.simulcastParameters.push(new Ii({rid:T,direction:_}))}break}}});if(!p.iceParams.usernameFragment||!p.iceParams.password){if(p.rtp.muxId&&i&&i.items.includes(p.rtp.muxId)){for(let y=0;y<i.items.length;y++){if(!i.items.includes(y.toString()))continue;const w=n.media[y];if(w.iceParams?.usernameFragment&&w.iceParams.password){p.iceParams={...w.iceParams};break}}}}if(!p.dtlsParams.role){p.dtlsParams=void 0}const m=a(y=>p.rtp.codecs.find(w=>w.payloadType===y),\"findCodec\");c.slice(1).forEach(y=>{if(y.startsWith(\"a=\")){const[w,S]=lg(y);if(w===\"fmtp\"){const[T,_]=yr(S,\" \");const x=m(Number(T));x.parameters=_}else if(w===\"rtcp-fb\"){const[T,_,x]=S.split(\" \");p.rtp.codecs.forEach(k=>{if([\"*\",k.payloadType.toString()].includes(T)){k.rtcpFeedback.push(new Lu({type:_,parameter:x}))}})}}})});const o=i?n.media.find(c=>c.rtp.muxId===i.items[0]):void 0;if(i&&o?.port){for(const c of n.media){if(c.port===0&&c.bundleOnly&&c.rtp.muxId&&i.items.includes(c.rtp.muxId))c.port=o.port}}return n}webrtcTrackId(e){if(e.msid?.includes(\" \")){const t=e.msid.split(\" \");for(const s of this.msidSemantic){if(s.semantic===\"WMS\"&&(s.items.includes(t[0])||s.items.includes(\"*\"))){return t[1]}}}return}get string(){const e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];if(this.host){e.push(`c=${fg(this.host)}`)}e.push(`t=${this.time}`);this.group.forEach(n=>e.push(`a=group:${n.str}`));if(this.extMapAllowMixed){e.push(`a=extmap-allow-mixed`)}this.msidSemantic.forEach(n=>e.push(`a=msid-semantic:${n.str}`));const t=this.media.map(n=>n.toString()).join(\"\");const s=e.join(\"\\r\\n\")+\"\\r\\n\"+t;return s}toJSON(){const e=this.string;if(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type){this.cachedJson=new dg(e,this.type)}return this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}};var kn=class{static{a(this,\"MediaDescription\")}constructor(e,t,s,n){this.kind=e;this.port=t;this.profile=s;this.fmt=n;this.msids=[];this.rtcpMux=false;this.bundleOnly=false;this.ssrc=[];this.ssrcGroup=[];this.rtp={codecs:[],headerExtensions:[]};this.sctpMap={};this.iceCandidates=[];this.iceCandidatesComplete=false;this.simulcastParameters=[]}get msid(){return this.msids[0]}set msid(e){this.msids=e?[e]:[]}toString(){const e=[];e.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(t=>t.toString()).join(\" \")}`);if(this.host){e.push(`c=${fg(this.host)}`)}this.iceCandidates.forEach(t=>{e.push(`a=candidate:${ig(t)}`)});if(this.iceCandidatesComplete){e.push(\"a=end-of-candidates\")}if(this.iceParams?.usernameFragment){e.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`)}if(this.iceParams?.password){e.push(`a=ice-pwd:${this.iceParams.password}`)}if(this.iceParams?.iceLite){e.push(`a=ice-lite`)}if(this.iceOptions){e.push(`a=ice-options:${this.iceOptions}`)}if(this.dtlsParams){this.dtlsParams.fingerprints.forEach(t=>{e.push(`a=fingerprint:${t.algorithm} ${t.value}`)});e.push(`a=setup:${Ef[this.dtlsParams.role]}`)}if(this.direction){e.push(`a=${this.direction}`)}if(this.rtp.muxId){e.push(`a=mid:${this.rtp.muxId}`)}this.msids.forEach(t=>e.push(`a=msid:${t}`));if(this.rtcpPort&&this.rtcpHost){e.push(`a=rtcp:${this.rtcpPort} ${fg(this.rtcpHost)}`);if(this.rtcpMux){e.push(\"a=rtcp-mux\")}}this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)});this.ssrc.forEach(t=>{vm.forEach(s=>{const n=t[s];if(n!==void 0){e.push(`a=ssrc:${t.ssrc} ${s}:${n}`)}})});this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`);t.rtcpFeedback.forEach(s=>{let n=s.type;if(s.parameter)n+=` ${s.parameter}`;e.push(`a=rtcp-fb:${t.payloadType} ${n}`)});if(t.parameters){e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)}});Object.keys(this.sctpMap).forEach(t=>{const s=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${s}`)});if(this.sctpPort){e.push(`a=sctp-port:${this.sctpPort}`)}if(this.sctpCapabilities){e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`)}this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`));if(this.simulcastParameters.length){this.simulcastParameters.forEach(i=>{e.push(`a=rid:${i.rid} ${i.direction}`)});let t=`a=simulcast:`;const s=this.simulcastParameters.filter(i=>i.direction===\"recv\");if(s.length){t+=`recv ${s.map(i=>i.rid).join(\";\")} `}const n=this.simulcastParameters.filter(i=>i.direction===\"send\");if(n.length){t+=`send ${n.map(i=>i.rid).join(\";\")}`}e.push(t)}return e.join(\"\\r\\n\")+\"\\r\\n\"}};var ks=class{static{a(this,\"GroupDescription\")}constructor(e,t){this.semantic=e;this.items=t}get str(){return`${this.semantic} ${this.items.join(\" \")}`}};function cg(r){const e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error(\"exception\");return e[2]}a(cg,\"ipAddressFromSdp\");function fg(r){const e=(0,OR.isIPv4)(r)?4:6;return`IN IP${e} ${r}`}a(fg,\"ipAddressToSdp\");function ig(r){let e=`${r.foundation} ${r.component} ${r.protocol} ${r.priority} ${r.ip} ${r.port} typ ${r.type}`;if(r.relatedAddress!=void 0){e+=` raddr ${r.relatedAddress}`}if(r.relatedPort!=void 0){e+=` rport ${r.relatedPort}`}if(r.tcpType!=void 0){e+=` tcptype ${r.tcpType}`}if(r.generation!=void 0){e+=` generation ${r.generation}`}if(r.ufrag!=void 0){e+=` ufrag ${r.ufrag}`}return e}a(ig,\"candidateToSdp\");function dP(r){const e=[];const t=[];let s=r.split(\"\\r\\n\");if(s.length===1){s=r.split(\"\\n\")}s.forEach(n=>{if(n.startsWith(\"m=\")){t.push([n])}else if(t.length>0){t[t.length-1].push(n)}else{e.push(n)}});return[e,t]}a(dP,\"groupLines\");function lg(r){if(r.includes(\":\")){const e=yr(r.slice(2),\":\");return[e[0],e[1]]}else{return[r.slice(2),void 0]}}a(lg,\"parseAttr\");function ug(r,e,t=s=>s.toString()){const s=e.split(\" \");if(s.length>0){r.push(new ks(s[0],s.slice(1).map(t)))}}a(ug,\"parseGroup\");function og(r){const e=it.fromSdp(r);const t=Yr(e);return t}a(og,\"candidateFromSdp\");var dg=class{static{a(this,\"RTCSessionDescription\")}constructor(e,t){Object.defineProperties(this,{sdp:{configurable:true,enumerable:true,value:e,writable:false},type:{configurable:true,enumerable:true,value:t,writable:false}})}static isThis(e){if(typeof e?.sdp===\"string\")return true}toSdp(){return{sdp:this.sdp,type:this.type}}};function hg(r,e){const t=\"-\";const s=(0,IR.randomBytes)(8).readBigUInt64BE(0).toString().slice(0,8);const n=0;e.origin=`${t} ${s} ${n} IN IP4 0.0.0.0`;e.msidSemantic.push(new ks(\"WMS\",[\"*\"]));e.type=r}a(hg,\"addSDPHeader\");function or(r){const e={};r.split(\";\").forEach(t=>{if(t.length===0)return;if(t.includes(\"=\")){const[s,n]=yr(t,\"=\");if(px.includes(s)){e[s]=Number(n)}else{e[s]=n}}else if(t.includes(\":\")){const[s,n]=t.split(\":\");e[s]=Number.isNaN(Number(n))?n:Number(n)}else{e[t]=void 0}});return e}a(or,\"codecParametersFromString\");var xo=class{static{a(this,\"SsrcDescription\")}constructor(e){Object.assign(this,e)}};function zc(r){return r.name.toLowerCase()}a(zc,\"codecName\");function td(r,e){return r==void 0||e==void 0||r===e}a(td,\"optionalEqual\");function kR(r){const e=or(r.parameters??\"\");return{packetizationMode:e[\"packetization-mode\"],profileLevelId:e[\"profile-level-id\"]?.toString().toLowerCase()}}a(kR,\"h264Parameters\");function Ro(r,e){if(r.mimeType.toLowerCase()!==e.mimeType.toLowerCase()){return false}if(r.clockRate!==e.clockRate)return false;if(!td(r.channels,e.channels))return false;if(zc(r)!==\"h264\")return true;const t=kR(r);const s=kR(e);if(!td(t.packetizationMode,s.packetizationMode)){return false}return td(t.profileLevelId,s.profileLevelId)}a(Ro,\"isCodecCompatible\");function Pn(r){return[\"rtx\",\"red\"].includes(zc(r))}a(Pn,\"isAuxiliary\");function rd(r,e,t){if(r!==\"audio\"||e==void 0||zc(e)!==\"red\"){return e}const[s]=pg(e);return t.find(n=>!Pn(n)&&n.payloadType===s)??t.find(n=>!Pn(n))??e}a(rd,\"deliveredTrackCodec\");function PR(r,e){return r.some(t=>!Pn(t)&&e.some(s=>s.mimeType.toLowerCase()===t.mimeType.toLowerCase()))}a(PR,\"hasCommonPrimaryMimeType\");function pg(r){const e=r.parameters??\"\";if(zc(r)===\"rtx\"){const t=Number(or(e).apt);return Number.isNaN(t)?[]:[t]}if(zc(r)===\"red\"){return e.split(\"/\").map(Number).filter(t=>!Number.isNaN(t))}return[]}a(pg,\"referencedPayloadTypes\");function NR(r,e){const t=new Set(e.map(n=>n.payloadType));const s=r.filter(n=>{if(!Pn(n))return false;const i=pg(n);return i.length>0&&i.every(o=>t.has(o))});return r.filter(n=>e.includes(n)||s.includes(n))}a(NR,\"withAuxiliaryCodecs\");function LR(r,e){const t=r.filter(s=>!Pn(s)&&e.some(n=>Ro(n,s)));return NR(r,t)}a(LR,\"intersectCodecs\");function hP(r,e){return r.mimeType.toLowerCase()===e.mimeType.toLowerCase()&&td(r.clockRate,e.clockRate)}a(hP,\"matchesPreference\");function MR(r,e){if(e==void 0)return r;const t=e.flatMap(c=>{const l=r.find(u=>hP(u,c));return l?[l]:[]});const s=[...new Set(t)];const n=new Set(s.filter(Pn).flatMap(pg));const i=r.filter(c=>!Pn(c)&&(s.includes(c)||n.has(c.payloadType)));const o=NR(r,i);return[...s.filter(c=>o.includes(c)),...o.filter(c=>!s.includes(c))]}a(MR,\"applyCodecPreferences\");function mg(r,e,t){return MR(e==void 0?r:LR(r,e),t)}a(mg,\"resolveCodecs\");function qc(r){return r?.map(e=>e.mimeType).join(\", \")||\"(none)\"}a(qc,\"list\");function Nn(r){const{kind:e,configured:t,source:s,preferences:n}=r;const i=s==void 0?t:LR(t,s);if(s!=void 0&&i.length===0){throw ne(\"NotSupportedError\",`Track codec ${qc(s)} is not supported by this RTCPeerConnection. Configured ${e} codecs: ${qc(t)}`)}const o=MR(i,n);if(o.length===0){throw ne(\"NotSupportedError\",`No codec remains after applying codec preferences. Source codecs: ${qc(s)} Configured codecs: ${qc(t)} Preferred codecs: ${qc(n)}`)}return o}a(Nn,\"assertCodecsSupported\");function gg(){return new Qt({uri:pe.sdesMid})}a(gg,\"useSdesMid\");function yg(){return new Qt({uri:pe.transportWideCC})}a(yg,\"useTransportWideCC\");function bg(){return new Qt({uri:pe.absSendTime})}a(bg,\"useAbsSendTime\");function DR(){return new Qt({uri:pe.audioLevelIndication})}a(DR,\"useAudioLevelIndication\");var UR=require(\"node:crypto\");var id=require(\"node:timers/promises\");var pP=P(\"webrtc/peer/media/receiver/nack\");var BR=30*5;var sd=class{static{a(this,\"NackHandler\")}constructor(e){this.receiver=e;this.newEstSeqNum=0;this._lost={};this.onPacketLost=new O;this.retryCount=10;this.closed=false;this.sendNack=()=>new Promise((t,s)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){const n=new Lr({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers});const i=new nt({feedback:n});this.receiver.dtlsTransport.sendRtcp([i]).then(t).catch(s);this.updateRetryCount();this.onPacketLost.execute(n)}})}get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t;if(this.nackLoop||this.closed){return}this.nackLoop=setInterval(Vt(async()=>{await this.sendNack();if(!Object.keys(this._lost).length){clearInterval(this.nackLoop);this.nackLoop=void 0}},s=>pP(\"failed to send nack\",s)),5)}removeLost(e){delete this._lost[e]}addPacket(e){const{sequenceNumber:t,ssrc:s}=e.header;this.mediaSourceSsrc=s;if(this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===$e(this.newEstSeqNum,1)){this.newEstSeqNum=t}else if(t>$e(this.newEstSeqNum,1)){for(let n=$e(this.newEstSeqNum,1);n<t;n=$e(n,1)){this.setLost(n,1)}this.newEstSeqNum=t;this.pruneLost()}}pruneLost(){if(this.lostSeqNumbers.length>BR){this._lost=Object.entries(this._lost).slice(-BR).reduce((e,[t,s])=>{e[t]=s;return e},{})}}close(){this.closed=true;clearInterval(this.nackLoop);this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{const t=this._lost[e]++;if(t>this.retryCount){this.removeLost(e);return e}})}};var nd=class{static{a(this,\"StreamStatistics\")}constructor(e){this.cycles=0;this.packets_received=0;this.bytesReceived=0;this.headerBytesReceived=0;this.jitter_q4=0;this.expected_prior=0;this.received_prior=0;this.clockRate=e}add(e,t=Date.now()/1e3){const s=this.max_seq==void 0||lu(e.header.sequenceNumber,this.max_seq);this.packets_received++;this.bytesReceived+=e.payload.length;this.headerBytesReceived+=e.header.serializeSize;this.lastPacketReceivedTimestamp=Qe();if(this.base_seq==void 0){this.base_seq=e.header.sequenceNumber}if(s){const n=_s(t*this.clockRate);if(this.max_seq!=void 0&&e.header.sequenceNumber<this.max_seq){this.cycles+=1<<16}this.max_seq=e.header.sequenceNumber;if(e.header.timestamp!==this.last_timestamp&&this.packets_received>1){const i=Math.abs(n-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=i-(this.jitter_q4+8>>4)}this.last_arrival=n;this.last_timestamp=e.header.timestamp}}get fraction_lost(){const e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;const t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;const s=e-t;if(e==0||s<=0){return 0}else{return Math.floor((s<<8)/e)}}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){const e=this.packets_expected-this.packets_received;return e<0?0:e}};var _o=P(\"webrtc/peer/media/rtpReceiver\");var Co=class{static{a(this,\"RTCRtpReceiver\")}get codecArray(){this.sortedCodecs??=Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType);return this.sortedCodecs}constructor(e,t,s){this.config=e;this.kind=t;this.rtcpSsrc=s;this.codecs={};this.ssrcByRtx={};this.nack=new sd(this);this.audioRedHandler=new Eu;this.type=\"receiver\";this.uuid=(0,UR.randomUUID)().toString();this.tracks=[];this.trackBySSRC={};this.trackByRID={};this.lastSRtimestamp={};this.receiveLastSRTimestamp={};this.onPacketLost=this.nack.onPacketLost;this.onRtcp=new O;this.stopped=false;this.remoteStreamIds=[];this.rtcpRunning=false;this.rtcpCancel=new AbortController;this.remoteStreams={};this.senderReportsReceivedBySsrc={};this.remoteTimestampsBySsrc={};this.remotePacketCountBySsrc={};this.remoteOctetCountBySsrc={};this.nackCountBySsrc={};this.pliCountBySsrc={};this.handleRtpBySsrc=(n,i)=>{const o=this.trackBySSRC[n.header.ssrc];this.handleRTP(n,i,o)};this.handleRtpByRid=(n,i,o)=>{const c=this.trackByRID[i];if(!this.trackBySSRC[n.header.ssrc]){this.trackBySSRC[n.header.ssrc]=c}this.handleRTP(n,o,c)};this.defaultTrack=new Zt({kind:t,remote:true});this.onPacketLost.subscribe(n=>{this.nackCountBySsrc[n.mediaSourceSsrc]=(this.nackCountBySsrc[n.mediaSourceSsrc]??0)+1})}get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===\"nack\")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===Nu().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===an().type)}prepareReceive(e){e.codecs.forEach(t=>{this.codecs[t.payloadType]=t});this.sortedCodecs=void 0;e.encodings.forEach(t=>{if(t.rtx){this.ssrcByRtx[t.rtx.ssrc]=t.ssrc}})}resyncCodecs(e){for(const s of Object.keys(this.codecs)){delete this.codecs[Number(s)]}this.sortedCodecs=void 0;for(const s of Object.keys(this.ssrcByRtx)){delete this.ssrcByRtx[Number(s)]}this.prepareReceive(e);const t=rd(this.kind,e.codecs[0],e.codecs);if(t){for(const s of this.tracks){s.codec=t}}}addTrack(e){const t=this.tracks.find(s=>{if(s.rid){return s.rid===e.rid}if(s.ssrc){return s.ssrc===e.ssrc}});if(t){return false}this.tracks.push(e);if(e.ssrc){this.trackBySSRC[e.ssrc]=e}if(e.rid){this.trackByRID[e.rid]=e}return true}stop(){this.stopped=true;this.rtcpRunning=false;this.rtcpCancel.abort();this.nack.close()}endTracks(){for(const e of[...this.tracks,this.defaultTrack]){e.stop()}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,id.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=Object.entries(this.remoteStreams).map(([s,n])=>{let i=0,o=0;if(this.lastSRtimestamp[s]){i=this.lastSRtimestamp[s];const c=po()-this.receiveLastSRTimestamp[s];if(c>0&&c<65536){o=_s(c*65536)}}return new rn({ssrc:Number(s),fractionLost:n.fraction_lost,packetsLost:n.packets_lost,highestSequence:n.max_seq,jitter:n.jitter,lsr:i,dlsr:o})});const t=new Yt({ssrc:this.rtcpSsrc,reports:e});try{if(this.config.debug.receiverReportDelay){await(0,id.setTimeout)(this.config.debug.receiverReportDelay)}await this.dtlsTransport.sendRtcp([t])}catch(s){_o(\"sendRtcp failed\",s);await(0,id.setTimeout)(500+Math.random()*1e3)}}}catch(e){_o(\"rtcp loop ended\",e)}}getInboundRtpStatsId(e){return ue(\"inbound-rtp\",e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return ue(\"remote-outbound-rtp\",e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e?true:t===e).filter(t=>t.ssrc).map(t=>this.getInboundRtpStatsId(t))}collectStats(e){const t=[];const s=this.dtlsTransport?ue(\"transport\",this.dtlsTransport.id):void 0;const n=this.codecArray[0];const i=new Set;for(const o of this.tracks){if(!o.ssrc)continue;const c=this.remoteStreams[o.ssrc];const l=this.remoteTimestampsBySsrc[o.ssrc]!==void 0;const u=this.lastSRtimestamp[o.ssrc]!==void 0||l?this.getRemoteOutboundRtpStatsId(o):void 0;const f=n&&s?fo(s,n.payloadType,o.id??o.uuid):void 0;if(n&&s&&f&&!i.has(f)){i.add(f);const h={type:\"codec\",id:f,timestamp:e,payloadType:n.payloadType,transportId:s,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,sdpFmtpLine:n.parameters};t.push(h)}const d={type:\"inbound-rtp\",id:this.getInboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:f,mid:this.sdesMid,trackIdentifier:o.id??o.uuid,packetsReceived:c?.packets_received??0,bytesReceived:c?.bytesReceived??0,headerBytesReceived:c?.headerBytesReceived??0,packetsLost:c?.packets_lost??0,jitter:c?.clockRate?c.jitter/c.clockRate:void 0,lastPacketReceivedTimestamp:c?.lastPacketReceivedTimestamp,remoteId:u,nackCount:this.nackCountBySsrc[o.ssrc]||void 0,pliCount:this.pliCountBySsrc[o.ssrc]||void 0};t.push(d);if(u){const h={type:\"remote-outbound-rtp\",id:this.getRemoteOutboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:d.codecId,localId:d.id,remoteTimestamp:this.remoteTimestampsBySsrc[o.ssrc],reportsSent:this.senderReportsReceivedBySsrc[o.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[o.ssrc],bytesSent:this.remoteOctetCountBySsrc[o.ssrc]};t.push(h)}}return t}async getStats(){const e=Qe();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return On(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){_o(\"pli not supported\",{mediaSsrc:e});return}if(this.stopped){return}_o(\"sendRtcpPLI\",{mediaSsrc:e});const t=new Xt({feedback:new Pr({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1;await this.dtlsTransport.sendRtcp([t])}catch(s){_o(s)}}handleRtcpPacket(e){switch(e.type){case Pt.type:{const t=e;this.lastSRtimestamp[t.ssrc]=Kf(t.senderInfo.ntpTimestamp);this.receiveLastSRTimestamp[t.ssrc]=po();this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1;this.remoteTimestampsBySsrc[t.ssrc]=ER(t.senderInfo.ntpTimestamp);this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount;this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;const s=this.trackBySSRC[e.ssrc];if(s){s.onReceiveRtcp.execute(e)}}break}this.onRtcp.execute(e)}handleRTP(e,t,s){if(this.stopped){return}const n=this.codecs[e.header.payloadType];if(!n){return}this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new nd(n.clockRate);this.remoteStreams[e.header.ssrc].add(e);if(this.twccEnabled){const o=t[pe.transportWideCC];if(o!==void 0){this.dtlsTransport.receiverTWCC.handleTWCC(o,e.header.ssrc)}}if(n.name.toLowerCase()===\"rtx\"){const o=this.ssrcByRtx[e.header.ssrc];const c=or(n.parameters??\"\");const l=this.codecs[c[\"apt\"]];if(e.payload.length<2)return;e=_E(e,l.payloadType,o);s=this.trackBySSRC[o]}let i;if(n.name.toLowerCase()===\"red\"){i=Ti.deSerialize(e.payload);if(!Object.keys(this.codecs).includes(i.header.fields[0].blockPT.toString())){return}}if(s?.kind===\"video\"&&this.nackEnabled){this.nack.addPacket(e)}if(s){if(i){if(s.kind===\"audio\"){const o=this.audioRedHandler.push(i,e);for(const c of o){s.onReceiveRtp.execute(c.clone(),t)}}}else{s.onReceiveRtp.execute(e.clone(),t)}}this.runRtcp().catch(o=>_o(\"rtcp failed\",o))}};var Gc=P(\"webrtc/peer/media/router\");var od=class{static{a(this,\"RtpRouter\")}constructor(){this.ssrcTable={};this.ridTable={};this.extIdUriMap={};this.routeRtp=e=>{const t=gE(e.header.extensions,this.extIdUriMap);let s=this.ssrcTable[e.header.ssrc];const n=t[pe.sdesRTPStreamID];if(typeof n===\"string\"){s=this.ridTable[n];if(s){s.latestRid=n;s.handleRtpByRid(e,n,t)}}else if(s){s.handleRtpBySsrc(e,t)}else{s=Object.values(this.ridTable).filter(c=>c instanceof Co).find(c=>c.trackBySSRC[e.header.ssrc]);if(s){Gc(\"simulcast register receiver by ssrc\",e.header.ssrc);this.registerRtpReceiver(s,e.header.ssrc);s.handleRtpBySsrc(e,t)}else{}}if(!s){Gc(\"ssrcReceiver not found\");return}const i=t[pe.sdesMid];if(typeof i===\"string\"){s.sdesMid=i}const o=t[pe.repairedRtpStreamId];if(typeof o===\"string\"){s.latestRepairedRid=o}};this.routeRtcp=e=>{const t=[];switch(e.type){case Pt.type:{e=e;t.push(this.ssrcTable[e.ssrc])}break;case Yt.type:{e=e;e.reports.forEach(s=>{t.push(this.ssrcTable[s.ssrc])})}break;case Dr.type:break;case nt.type:{const s=e;if(s.feedback){t.push(this.ssrcTable[s.feedback.mediaSourceSsrc])}}break;case Xt.type:{const s=e;switch(s.feedback.count){case Nr.count:{const n=s.feedback;t.push(this.ssrcTable[n.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[s.feedback.mediaSsrc]||this.ssrcTable[s.feedback.senderSsrc])}}break}t.filter(s=>s).forEach(s=>s.handleRtcpPacket(e))}}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){Gc(\"registerRtpReceiver\",t);this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){Gc(\"registerRtpReceiverBySsrc\",t);t.encodings.filter(s=>s.ssrc!=void 0).forEach((s,n)=>{this.registerRtpReceiver(e.receiver,s.ssrc);e.addTrack(new Zt({ssrc:s.ssrc,kind:e.kind,id:e.sender.trackId,remote:true,codec:rd(e.kind,t.codecs[n],t.codecs)}));if(s.rtx){this.registerRtpReceiver(e.receiver,s.rtx.ssrc)}});t.headerExtensions.forEach(s=>{this.extIdUriMap[s.id]=s.uri})}registerRtpReceiverByRid(e,t,s){const[n]=s.codecs;Gc(\"registerRtpReceiverByRid\",t);e.addTrack(new Zt({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:true,codec:n}));this.ridTable[t.rid]=e.receiver}unregisterTransceiver(e){const t=[e.sender,e.receiver];for(const[s,n]of Object.entries(this.ssrcTable)){if(t.includes(n)){delete this.ssrcTable[Number(s)]}}for(const[s,n]of Object.entries(this.ridTable)){if(t.includes(n)){delete this.ridTable[s]}}}};var Kc=require(\"node:crypto\");var wg=require(\"node:timers/promises\");var ad=class{static{a(this,\"SDPManager\")}constructor({cname:e,midSuffix:t,bundlePolicy:s,mLineReuse:n}){this.seenMid=new Set;this.cname=e;this.midSuffix=t??false;this.bundlePolicy=s;this.mLineReuse=n??\"compatible\"}get localDescription(){if(!this._localDescription){return void 0}return this._localDescription.toJSON()}get remoteDescription(){if(!this._remoteDescription){return void 0}return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(e=>e.direction===\"inactive\")}createMediaDescriptionForTransceiver(e,t){const s=new kn(e.kind,9,\"UDP/TLS/RTP/SAVPF\",e.codecs.map(n=>n.payloadType));s.direction=t;s.msids=e.msids;s.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0};s.rtcpHost=\"0.0.0.0\";s.rtcpPort=9;s.rtcpMux=true;s.ssrc=[new xo({ssrc:e.sender.ssrc,cname:this.cname})];if(e.options.simulcast){s.simulcastParameters=e.options.simulcast.map(n=>new Ii(n))}if(s.rtp.codecs.find(n=>n.name.toLowerCase()===\"rtx\")){s.ssrc.push(new xo({ssrc:e.sender.rtxSsrc,cname:this.cname}));s.ssrcGroup=[new ks(\"FID\",[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]}this.addTransportDescription(s,e.dtlsTransport);return s}createRejectedMediaDescription(e,t){const s=e.fmt[0]??e.codecs[0]?.payloadType??0;const n=new kn(e.kind,0,e.profile,[s]);n.host=Rm;n.direction=\"inactive\";n.rtp={codecs:e.codecs.filter(i=>i.payloadType?.toString()===s.toString()),headerExtensions:[],muxId:e.mid};n.rtcpMux=true;if(t){n.iceParams=t.iceTransport.localParameters;n.dtlsParams=t.localParameters}return n}createMediaDescriptionForSctp(e){const t=new kn(\"application\",_m,\"UDP/DTLS/SCTP\",[\"webrtc-datachannel\"]);t.sctpPort=e.port;t.rtp.muxId=e.mid;t.sctpCapabilities=e.getCapabilities();this.addTransportDescription(t,e.dtlsTransport);return t}addTransportDescription(e,t){const s=t.iceTransport;e.iceCandidates=s.localCandidates;e.iceCandidatesComplete=s.gatheringState===\"complete\";e.iceParams=s.localParameters;e.iceOptions=\"trickle\";e.host=Rm;e.port=_m;if(e.direction===\"inactive\"){if(this.mLineReuse===\"aggressive\"){e.port=0}e.msids=[]}if(!e.dtlsParams){e.dtlsParams=t.localParameters;if(!e.dtlsParams.fingerprints){e.dtlsParams.fingerprints=t.localParameters.fingerprints}}}allocateMid(e=\"\"){let t;for(let s=0;;){t=(s++).toString()+e;if(!this.seenMid.has(t))break}this.seenMid.add(t);return t}parseSdp({sdp:e,isLocal:t,signalingState:s,type:n}){const i=Jr.parse(e);this.validateDescription({description:i,isLocal:t,signalingState:s,type:n});i.type=n;return i}validateDescription({isLocal:e,signalingState:t,type:s}){if(e){if(s===\"offer\"){if(![\"stable\",\"have-local-offer\"].includes(t))throw ne(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}else{if(s===\"offer\"){if(![\"stable\",\"have-remote-offer\",\"have-local-offer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-local-offer\",\"have-remote-pranswer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}}buildOfferSdp(e,t){const s=new Jr;hg(\"offer\",s);const n=this.findLiveDtlsTransport(e,t);const i=this.currentLocalDescription?.media??[];const o=new Set;i.forEach((c,l)=>{const u=c.rtp.muxId;if(!u){return}if(c.kind===\"application\"){if(!t){throw new Error(\"sctpTransport not found\")}t.mLineIndex=l;s.media.push(this.createMediaDescriptionForSctp(t))}else{const f=e.find(d=>d.mid===u);if(!f){o.add(l);s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:u},n));return}f.mLineIndex=l;if(f.stopping||f.stopped){s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:u},this.liveTransportOr(f.dtlsTransport,n)));return}s.media.push(this.createMediaDescriptionForTransceiver(f,f.direction))}});for(const c of e.filter(l=>!l.stopping&&!l.stopped&&!s.media.find(u=>u.rtp.muxId===l.mid))){if(c.mid==void 0){c.mid=this.allocateMid(this.midSuffix?\"av\":\"\")}const l=this.createMediaDescriptionForTransceiver(c,c.direction);const u=c.mLineIndex;if(u!=void 0&&o.has(u)&&s.media[u]?.kind===c.kind){o.delete(u);s.media[u]=l}else{c.mLineIndex=s.media.length;s.media.push(l)}}if(t&&!s.media.find(c=>c.kind===\"application\")){t.mLineIndex=s.media.length;if(t.mid==void 0){t.mid=this.allocateMid(this.midSuffix?\"dc\":\"\")}s.media.push(this.createMediaDescriptionForSctp(t))}if(this.bundlePolicy!==\"disable\"){const c=s.media.filter(l=>l.port!==0).map(l=>l.rtp.muxId).filter(l=>l);if(c.length){const l=new ks(\"BUNDLE\",jR(c,this.negotiatedBundleTag));s.group.push(l)}}return s}liveTransportOr(e,t){return e&&e.state!==\"closed\"?e:t}findLiveDtlsTransport(e,t){return[...e.filter(s=>!s.stopped&&!s.pendingRejection).map(s=>s.dtlsTransport),t?.dtlsTransport,...e.map(s=>s.dtlsTransport)].find(s=>!!s&&s.state!==\"closed\")}get negotiatedBundleTag(){const e=[this.currentLocalDescription,this.currentRemoteDescription].find(t=>t?.type===\"answer\");return e?.group.find(t=>t.semantic===\"BUNDLE\")?.items[0]}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:s}){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(s)){throw new Error(\"createAnswer failed\")}if(!this._remoteDescription){throw new Error(\"wrong state\")}const n=new Jr;hg(\"answer\",n);const i=this._remoteDescription;const o=this.findLiveDtlsTransport(e,t);for(const c of i.media){let l;let u;let f=true;if([\"audio\",\"video\"].includes(c.kind)){const d=e.find(h=>h.mid!=void 0&&h.mid===c.rtp.muxId);if(!d&&c.port!==0){throw new Error(`Transceiver with mid=${c.rtp.muxId} not found`)}if(!d||c.port===0||d.stopped||d.pendingRejection){f=false;l=this.liveTransportOr(d?.dtlsTransport,o);u=this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:c.rtp.muxId},l)}else{u=this.createMediaDescriptionForTransceiver(d,d.stopping?\"inactive\":Gf(d.direction,d.offerDirection));l=d.dtlsTransport}}else if(c.kind===\"application\"){if(!t||!t.mid){throw new Error(\"sctpTransport not found\")}u=this.createMediaDescriptionForSctp(t);l=t.dtlsTransport}else{throw new Error(\"invalid kind\")}if(u.dtlsParams&&l){if(l.role===\"auto\"){u.dtlsParams.role=\"client\"}else{u.dtlsParams.role=l.role}}if(f&&c.simulcastParameters&&c.simulcastParameters.length>0){u.simulcastParameters=c.simulcastParameters.map(d=>({...d,direction:d.direction===\"send\"?\"recv\":\"send\"}))}n.media.push(u)}if(this.bundlePolicy!==\"disable\"){n.group.push(...this.buildAnswerBundleGroups(i,n))}return n}buildAnswerBundleGroups(e,t){const s=new Set(t.media.filter(i=>i.port!==0&&i.rtp.muxId).map(i=>i.rtp.muxId));const n=this.negotiatedBundleTag;return e.group.filter(i=>i.semantic===\"BUNDLE\").map(i=>i.items.filter((o,c,l)=>{return s.has(o)&&l.indexOf(o)===c})).filter(i=>i.length>0).map(i=>new ks(\"BUNDLE\",jR(i,n)))}assertRemoteAnswerCodecs(e){if(![\"answer\",\"pranswer\"].includes(e.type)){return}const t=this.pendingLocalDescription;if(!t){return}e.media.forEach((s,n)=>{if(![\"audio\",\"video\"].includes(s.kind)||s.port===0){return}const i=t.media[n];if(!i||i.port===0||i.kind!==s.kind){return}const o=s.rtp.codecs.some(c=>c.name.toLowerCase()!==\"rtx\"&&i.rtp.codecs.some(l=>l.mimeType.toLowerCase()===c.mimeType.toLowerCase()));if(!o){throw ne(\"InvalidAccessError\",`No common codec for m-line ${n} (mid=${s.rtp.muxId}) in remote ${e.type}`)}})}assertBundlePreserved(e){if(e.type!==\"offer\"||this.bundlePolicy===\"disable\"){return}const t=[this.currentLocalDescription,this.currentRemoteDescription].find(n=>n?.type===\"answer\")?.group.filter(n=>n.semantic===\"BUNDLE\")??[];const s=e.group.filter(n=>n.semantic===\"BUNDLE\");for(const n of t){let i;for(const o of n.items){const c=e.media.find(u=>u.rtp.muxId===o);if(!c||c.port===0){continue}const l=s.find(u=>u.items.includes(o));if(!l){throw ne(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be preserved by the remote offer`)}i??=l;if(l!==i){throw ne(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be split into another BUNDLE group by the remote offer`)}}}}setLocalDescription(e){if(e.type===\"offer\"||e.type===\"pranswer\"){this.pendingLocalDescription=e;return}this.currentLocalDescription=e;if(this.pendingRemoteDescription){this.currentRemoteDescription=this.pendingRemoteDescription}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type){throw new Error(\"invalid sessionDescription\")}if(e.type===\"rollback\"){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot rollback remote description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0;return}if(!e.sdp){throw new Error(\"invalid sessionDescription\")}const s=this.parseSdp({sdp:e.sdp,isLocal:false,signalingState:t,type:e.type});this.assertRemoteAnswerCodecs(s);this.assertBundlePreserved(s);if(s.type===\"offer\"||s.type===\"pranswer\"){this.pendingRemoteDescription=s}else{if(this.pendingLocalDescription){this.currentLocalDescription=this.pendingLocalDescription}this.currentRemoteDescription=s;this.pendingRemoteDescription=void 0;this.pendingLocalDescription=void 0}return s}rollbackLocalDescription(e){if(![\"have-local-offer\",\"have-local-pranswer\"].includes(e)){throw ne(\"InvalidStateError\",\"Cannot rollback local description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){const e=this._remoteDescription;if(!e){return void 0}const t=e.group.find(s=>s.semantic===\"BUNDLE\"&&this.bundlePolicy!==\"disable\");return t}setLocal(e,t,s){const n=new Map(t.map(c=>[c?.mLineIndex,c]));const i=t.find(c=>c?.dtlsTransport)?.dtlsTransport??s?.dtlsTransport;e.media.forEach((c,l)=>{if(![\"audio\",\"video\"].includes(c.kind)){return}const u=t.find(h=>h?.mid!=void 0&&h.mid===c.rtp.muxId)??n.get(l);if(c.port===0){const h=u&&!u.stopping&&!u.stopped&&!u.pendingRejection;if(!h){return}}const f=u?.dtlsTransport??i;if(!f){throw new Error(`dtls transport not found for media index ${l}`)}const d=c.port;this.addTransportDescription(c,f);if(d===0){c.port=0}});const o=e.media.find(c=>c.kind===\"application\");if(s&&o){this.addTransportDescription(o,s.dtlsTransport)}this.setLocalDescription(e)}};function jR(r,e){if(!e||!r.includes(e)){return r}return[e,...r.filter(t=>t!==e)]}a(jR,\"orderBundleMids\");var Ln=P(\"webrtc/peer/media/rtpSender\");var $R=128;var Sg=256;var FR=.85;function mP(r){if(r===true){return{enabled:true,maxLength:Sg}}if(r==void 0||r===false){return{enabled:false,maxLength:Sg}}const e=typeof r.maxLength===\"number\"&&Number.isFinite(r.maxLength)&&r.maxLength>=1?Math.floor(r.maxLength):Sg;return{enabled:r.enabled??true,maxLength:e}}a(mP,\"resolvePendingRtpOptions\");function gP(r,e,t,s,n){return{seqOffset:$e($e(r,1),-t),timestampOffset:gr(gr(e,n),-s)}}a(gP,\"freezeRtpContinuityOffsets\");var cd=class{static{a(this,\"RTCRtpSender\")}constructor(e,t={}){this.trackOrKind=e;this.type=\"sender\";this.ssrc=(0,Kc.randomBytes)(4).readUInt32BE(0);this.rtxSsrc=(0,Kc.randomBytes)(4).readUInt32BE(0);this.trackId=(0,Kc.randomUUID)().toString();this.onReady=new O;this.onRtcp=new O;this.onPictureLossIndication=new O;this.onGenericNack=new O;this.onStreamsChanged=new O;this.rtxSequenceNumber=Lp();this._redDistance=2;this.redEncoder=new wu(this._redDistance);this.headerExtensions=[];this.sendEncodings=[{}];this.rtpTimestamp=0;this.octetCount=0;this.packetCount=0;this.headerBytesSent=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.retransmittedPacketsSent=0;this.retransmittedBytesSent=0;this.nackCount=0;this.pliCount=0;this.firCount=0;this.receiverEstimatedMaxBitrate=0n;this.timestampOffset=0;this.seqOffset=0;this.rtpContinuityPending=false;this.pendingTimestampStep=1;this.rtpCache=[];this.pendingRtp=[];this.drainingPendingRtp=false;this.negotiatedCodecs=[];this.dtlsDisposer=[];this.track=null;this.streamIds=[];this.stopped=false;this.rtcpRunning=false;this.rtcpCancel=new AbortController;const s=mP(t.pendingRtp);this.pendingRtpEnabled=s.enabled;this.pendingRtpMaxLength=s.maxLength;this.kind=typeof this.trackOrKind===\"string\"?this.trackOrKind:this.trackOrKind.kind;if(typeof e!==\"string\"){this.registerTrack(e)}}get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){if(this.dtlsTransport){this.dtlsDisposer.forEach(t=>t())}this.dtlsTransport=e;this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"connected\"){this.onReady.execute();void this.drainPendingRtp()}}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e;this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname;this.mid=e.muxId;this.headerExtensions=e.headerExtensions;this.rtpStreamId=e.rtpStreamId??this.rtpStreamId;this.repairedRtpStreamId=e.repairedRtpStreamId;this.negotiatedCodecs=[...e.codecs];this.selectCodec(this.track?br(this.track):void 0);if(this.track){this.track.codec=this.codec}void this.drainPendingRtp()}selectCodec(e){const t=this.negotiatedCodecs;const s=a(o=>{if(o?.name.toLowerCase()!==\"red\")return o;const c=Number((o.parameters??\"\").split(\"/\")[0]);return t.find(l=>![\"red\",\"rtx\"].includes(l.name.toLowerCase())&&l.payloadType===c)},\"primaryOf\");const n=a(o=>{const c=s(o);return!!c&&(!e||e.some(l=>Ro(l,c)))},\"compatible\");const i=t.find(o=>o.name.toLowerCase()!==\"rtx\")??t[0];this.codec=t.find(o=>o.name.toLowerCase()!==\"rtx\"&&n(o))??i;this.sendPrimaryCodec=s(this.codec);this.rtxPayloadType=void 0;this.redRedundantPayloadType=void 0;t.forEach(o=>{const c=or(o.parameters??\"\");if(o.name.toLowerCase()===\"rtx\"&&this.sendPrimaryCodec?.payloadType===c[\"apt\"]){this.rtxPayloadType=o.payloadType}});if(this.codec?.name.toLowerCase()===\"red\"&&this.sendPrimaryCodec!=void 0){this.redRedundantPayloadType=this.sendPrimaryCodec.payloadType}}canSendRtp(){return!this.stopped&&this.dtlsTransport?.state===\"connected\"&&!!this.codec}settlePendingRtp(e,t){if(t==void 0){e.resolve();return}e.reject(t)}discardPendingRtp(){const e=this.pendingRtp.splice(0);for(const t of e){this.settlePendingRtp(t)}}enqueuePendingRtp(e,t,s){const n=Buffer.isBuffer(e)?Le.deSerialize(e):e.clone();this.pendingRtp.push({packet:n,resolve:t,reject:s});while(this.pendingRtp.length>this.pendingRtpMaxLength){const i=this.pendingRtp.shift();if(i){this.settlePendingRtp(i)}}}async drainPendingRtp(){if(this.drainingPendingRtp){return}this.drainingPendingRtp=true;try{while(this.pendingRtp.length>0&&this.canSendRtp()){const e=this.pendingRtp.shift();if(!this.canSendRtp()){this.settlePendingRtp(e);continue}try{await this.dispatchRtp(e.packet);this.settlePendingRtp(e)}catch(t){this.settlePendingRtp(e,t)}}}finally{this.drainingPendingRtp=false}if(this.pendingRtp.length>0&&this.canSendRtp()){await this.drainPendingRtp()}}registerTrack(e){if(e.stopped)throw new Error(\"track is ended\");on(e);if(this.disposeTrack){this.disposeTrack()}e.id=this.trackId;const{unSubscribe:t}=e.onReceiveRtp.subscribe(Vt((n,i)=>e.remote?this.sendRtp(this.relayedRtp(n,i),true):this.sendRtp(n),n=>Ln(\"send rtp failed\",n)));const{unSubscribe:s}=e.onSourceChanged.subscribe(n=>{this.replaceRTP(n)});this.track=e;this.disposeTrack=()=>{t();s()};if(this.codec){e.codec=this.codec}}relayedRtp(e,t={}){const s=e.clone();s.header.extensions=this.headerExtensions.flatMap(n=>{switch(n.uri){case pe.audioLevelIndication:{const i=t[n.uri];return i?[{id:n.id,payload:Buffer.from([(i.v?128:0)|i.level&127])}]:[]}case pe.videoOrientation:{const i=t[n.uri];return i?[{id:n.id,payload:Buffer.from([i.c<<3|i.f<<2|i.r1<<1|i.r0])}]:[]}default:return[]}});return s}setStreams(e=[]){const t=[...new Set(e.map(n=>n.id))];const s=t.join(\"\\n\")!==(this.streamIds??[]).join(\"\\n\");this.streamIds=t;if(s)this.onStreamsChanged.execute()}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(s=>({...s})):[{}];const t=this.sendEncodings.find(s=>typeof s.rid===\"string\")?.rid;if(typeof t===\"string\"){this.rtpStreamId=t}}async replaceTrack(e){if(e===null){this.detachTrack();return}if(e.stopped)throw new Error(\"track is ended\");on(e);const t=br(e);if(this.sendPrimaryCodec!=void 0&&t!=void 0&&!this.negotiatedCodecs.some(s=>![\"red\",\"rtx\"].includes(s.name.toLowerCase())&&t.some(n=>Ro(n,s)))){throw ne(\"InvalidModificationError\",`Track codec ${t.map(s=>s.mimeType).join(\", \")} is incompatible with negotiated codecs ${this.negotiatedCodecs.map(s=>s.mimeType).join(\", \")}`)}if(this.negotiatedCodecs.length)this.selectCodec(t);if(this.sequenceNumber!=void 0){this.scheduleRtpContinuity()}this.registerTrack(e);Ln(\"replaceTrack\",\"ssrc\",e.ssrc,\"rid\",e.rid)}detachTrack(){this.rtpContinuityPending=false;this.discardPendingRtp();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}this.track=null}stop({keepTrack:e=false}={}){this.stopped=true;this.rtpContinuityPending=false;this.discardPendingRtp();this.rtcpRunning=false;this.rtcpCancel.abort();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}if(!e){this.track=null}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,wg.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=this.sentAtEpochMs===void 0?0n:wR(this.sentAtEpochMs);const t=[new Pt({ssrc:this.ssrc,senderInfo:new Va({ntpTimestamp:e,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=Kf(e);this.lastSentSRTimestamp=po();if(this.cname){t.push(new Dr({chunks:[new Ka({source:this.ssrc,items:[new Wa({type:1,text:this.cname})]})]}))}try{await this.dtlsTransport.sendRtcp(t)}catch(s){Ln(\"sendRtcp failed\",s);await(0,wg.setTimeout)(500+Math.random()*1e3)}}}catch(e){Ln(\"rtcp loop ended\",e)}}async sendRtp(e,t=false){if(this.stopped){return}if(!this.pendingRtpEnabled){if(!this.canSendRtp()){return}await this.dispatchRtp(e,t);return}await new Promise((s,n)=>{this.enqueuePendingRtp(e,s,n);void this.drainPendingRtp()})}replaceRTP(e,t=false,s=1){this.scheduleRtpContinuity(s);Ln(\"replaceRTP\",this.sequenceNumber,e.sequenceNumber,t,s)}scheduleRtpContinuity(e=1){this.rtpContinuityPending=true;this.pendingTimestampStep=e;this.rtpCache=[]}async dispatchRtp(e,t=false){if(!this.canSendRtp()){return}const s=this.codec;if(!s){return}e=Buffer.isBuffer(e)?Le.deSerialize(e):t?e:e.clone();const{header:n,payload:i}=e;const o=n.sequenceNumber;const c=n.timestamp;if(this.rtpContinuityPending){if(this.sequenceNumber!=void 0&&this.timestamp!=void 0){const m=gP(this.sequenceNumber,this.timestamp,o,c,this.pendingTimestampStep);this.seqOffset=m.seqOffset;this.timestampOffset=m.timestampOffset}this.rtpContinuityPending=false;this.pendingTimestampStep=1}n.ssrc=this.ssrc;n.payloadType=s.payloadType;n.timestamp=gr(n.timestamp,this.timestampOffset);n.sequenceNumber=$e(n.sequenceNumber,this.seqOffset);this.timestamp=n.timestamp;this.sequenceNumber=n.sequenceNumber;const l=performance.timeOrigin+performance.now();let u;const f=[];for(const m of this.headerExtensions){let y;switch(m.uri){case pe.sdesMid:if(this.mid)y=yE(this.mid);break;case pe.sdesRTPStreamID:if(this.rtpStreamId)y=bE(this.rtpStreamId);break;case pe.repairedRtpStreamId:if(this.repairedRtpStreamId)y=SE(this.repairedRtpStreamId);break;case pe.transportWideCC:u=this.nextTransportSequenceNumber();y=Kp(u);break;case pe.absSendTime:y=tg(l);break}if(y)f.push({id:m.id,payload:y})}for(const m of n.extensions){let y;for(const w of f){if(w.id===m.id){y=w;break}}if(y){y.payload=m.payload}else{f.push(m)}}for(let m=1;m<f.length;m++){if(f[m-1].id>f[m].id){f.sort((y,w)=>y.id-w.id);break}}n.extensions=f;this.sentAtEpochMs=l;this.rtpTimestamp=n.timestamp;this.octetCount+=i.length;this.headerBytesSent+=n.serializeSize;this.packetCount=gr(this.packetCount,1);this.rtpCache[n.sequenceNumber%$R]=e;let d=i;if(this.redRedundantPayloadType){this.redEncoder.push({block:d,timestamp:n.timestamp,blockPT:this.redRedundantPayloadType});const m=this.redEncoder.build();d=m.serialize()}const h=ho();const p=await this.dtlsTransport.sendRtp(d,n);if(!this.rtcpRunning&&!this.stopped)this.runRtcp().catch(m=>Ln(\"rtcp failed\",m));if(u!==void 0){this.packetSent(u,p,h)}}nextTransportSequenceNumber(){this.dtlsTransport.transportSequenceNumber=$e(this.dtlsTransport.transportSequenceNumber,1);return this.dtlsTransport.transportSequenceNumber}packetSent(e,t,s){const n={wideSeq:e,size:t,sendingAtMs:s,sentAtMs:ho()};this.dtlsTransport.senderBWE.rtpPacketSent(n)}async resendRtp(e){let t;const s=e.header.extensions.map(c=>{const l=this.headerExtensions.find(u=>u.id===c.id)?.uri;switch(l){case pe.transportWideCC:t=this.nextTransportSequenceNumber();return{id:c.id,payload:Kp(t)};case pe.absSendTime:return{id:c.id,payload:tg(performance.timeOrigin+performance.now())};default:return c}});let n=new Le(new Xe({...e.header,extensions:s}),e.payload);if(this.rtxPayloadType!=void 0){n=CE(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc);this.rtxSequenceNumber=$e(this.rtxSequenceNumber,1)}this.retransmittedPacketsSent++;this.retransmittedBytesSent+=n.payload.length;this.headerBytesSent+=n.header.serializeSize;const i=ho();const o=await this.dtlsTransport.sendRtp(n.payload,n.header);if(t!==void 0){this.packetSent(t,o,i)}}handleRtcpPacket(e){switch(e.type){case Pt.type:case Yt.type:{const t=e;t.reports.filter(s=>s.ssrc===this.ssrc).forEach(s=>{this.remotePacketsLost=s.packetsLost;this.remoteFractionLost=s.fractionLost/256;if(this.lastSRtimestamp===s.lsr&&s.dlsr){if(this.lastSentSRTimestamp){const n=po()-this.lastSentSRTimestamp-s.dlsr/65536;this.totalRoundTripTime+=n;this.roundTripTimeMeasurements++;if(this.rtt===void 0){this.rtt=n}else{this.rtt=FR*this.rtt+(1-FR)*n}}}})}break;case nt.type:{const t=e;switch(t.feedback.count){case Lr.count:{const s=t.feedback;this.nackCount++;s.lost.forEach(Vt(async n=>{const i=this.rtpCache[n%$R];if(i&&i.header.sequenceNumber===n){await this.resendRtp(i)}},n=>Ln(\"retransmission failed\",n)));this.onGenericNack.execute(s)}break}}break;case Xt.type:{const t=e;switch(t.feedback.count){case Nr.count:{const s=t.feedback;this.receiverEstimatedMaxBitrate=s.bitrate}break;case Pr.count:{this.pliCount++;this.onPictureLossIndication.execute()}break}}break}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){if(e.encodings){this.setSendEncodings(e.encodings)}}get outboundRtpStatsId(){return ue(\"outbound-rtp\",this.trackId)}get mediaSourceStatsId(){return ue(\"media-source\",this.trackId)}get remoteInboundRtpStatsId(){return ue(\"remote-inbound-rtp\",this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){const t=[];const s=this.dtlsTransport?ue(\"transport\",this.dtlsTransport.id):void 0;const n=this.codec&&s?fo(s,this.codec.payloadType,this.trackId):void 0;const i={type:\"outbound-rtp\",id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:n,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};t.push(i);if(this.track){const o={type:\"media-source\",id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(o)}if(this.codec&&s){const o={type:\"codec\",id:n,timestamp:e,payloadType:this.codec.payloadType,transportId:s,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(o)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){const o={type:\"remote-inbound-rtp\",id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:i.codecId,localId:i.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(o)}return t}async getStats(){const e=Qe();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return On(t,this.getStatsRootIds())}};var HR=P(\"webrtc/peer/transceiverManager\");function yP(r){if(!r||r.length<2){return void 0}const e=r.map(t=>t.rid).filter(t=>typeof t===\"string\"&&t.length>0);if(e.length<2){return void 0}return e.map(t=>({rid:t,direction:\"send\"}))}a(yP,\"simulcastFromSendEncodings\");var ld=class{static{a(this,\"TransceiverManager\")}constructor(e,t,s){this.cname=e;this.config=t;this.router=s;this.transceivers=[];this.watched=new WeakSet;this.stableState=new Map;this.onTransceiverAdded=new O;this.onRemoteTransceiverAdded=new O;this.onTrack=new O;this.onNegotiationNeeded=new O}getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.watchTransceiver(e);this.transceivers.push(e)}replaceTransceiver(e,t){this.watchTransceiver(e);this.transceivers[t]=e}unwatchTransceiver(e){this.watched.delete(e);e.onRelease.allUnsubscribe();e.onStopRequested.allUnsubscribe();e.onDirectionChanged.allUnsubscribe();e.sender.onStreamsChanged.allUnsubscribe()}watchTransceiver(e){if(this.watched.has(e)){return}this.watched.add(e);e.onRelease.subscribe(()=>{this.router.unregisterTransceiver(e)});e.onStopRequested.subscribe(()=>{if(!e.stopped){this.onNegotiationNeeded.execute()}});e.onDirectionChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()});e.sender.onStreamsChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()})}findReusableTransceiver(e){return this.transceivers.find(t=>t.stopped&&t.kind===e&&t.mLineIndex!=void 0&&!this.transceivers.some(s=>s!==t&&s.mLineIndex===t.mLineIndex))}takeOverMLine(e,t){const s=this.transceivers.indexOf(e);t.mLineIndex=e.mLineIndex;e.mid=null;e.mLineIndex=void 0;this.unwatchTransceiver(e);this.replaceTransceiver(t,s)}associateMLine(e,t){const s=this.transceivers.find(n=>n!==e&&n.stopped&&n.mLineIndex===t);if(!s){return}this.transceivers.splice(this.transceivers.indexOf(e),1);this.takeOverMLine(s,e)}releaseUnassociatedReservations(e,t){for(const s of this.transceivers){if(!e.has(s)&&s.mid==null&&s.mLineIndex!=void 0&&s.mLineIndex<t){s.mLineIndex=void 0}}}addTransceiver(e,t,s={},{remoteMLineIndex:n}={}){const i=typeof e===\"string\"?e:e.kind;const o=s.direction||\"sendrecv\";if(typeof e!==\"string\"){on(e);Nn({kind:i,configured:this.filterCodecsByDirection(i,o),source:br(e),preferences:void 0})}const c=new cd(e,{pendingRtp:this.config.pendingRtp});const l=new Co(this.config,i,c.ssrc);const u=new Ff(i,t,l,c,o);u.onCodecPreferencesChanged.subscribe(()=>{this.onNegotiationNeeded.execute()});u.options={...s,simulcast:s.simulcast??yP(s.sendEncodings)};u.sender.setStreams(s.streams??[]);u.sender.setSendEncodings((s.sendEncodings??[]).map(d=>({...d})));this.router.registerRtpSender(u.sender);const f=n==void 0?this.findReusableTransceiver(i):this.transceivers.find(d=>d.stopped&&d.mLineIndex===n);if(f){this.takeOverMLine(f,u)}else{this.pushTransceiver(u)}if(n!=void 0){this.remoteOfferSnapshot?.remoteCreated.add(u)}this.onTransceiverAdded.execute(u);return u}reusableForTrack(e,t){return e.sender.track==void 0&&e.kind===t&&!e.usedForSender&&!e.stopping&&!e.stopped&&!e.rejected&&!e.pendingRejection}addTrack(e,t=[],s){if(this.getSenders().find(c=>c.track?.uuid===e.uuid)){throw ne(\"InvalidAccessError\",\"Track already added\")}const n=a(c=>this.reusableForTrack(c,e.kind)&&(s===void 0||c===s),\"reusableForTrack\");const i=s===null?void 0:this.transceivers.find(c=>n(c)&&Rn.includes(c.direction));if(i){this.validateTrackForTransceiver(e,i);const c=i.sender;c.setStreams(t);c.registerTrack(e);i.options={...i.options,streams:t};i.codecs=[];return i}const o=s===null?void 0:this.transceivers.find(c=>n(c)&&!Rn.includes(c.direction));if(o){const c=o.direction===\"recvonly\"?\"sendrecv\":o.direction===\"inactive\"?\"sendonly\":o.direction;this.validateTrackForTransceiver(e,o,c);const l=o.sender;l.setStreams(t);l.registerTrack(e);o.options={...o.options,streams:t};switch(o.direction){case\"recvonly\":o.setDirection(\"sendrecv\");break;case\"inactive\":o.setDirection(\"sendonly\");break}o.codecs=[];return o}else{const c=this.addTransceiver(e,void 0,{direction:\"sendrecv\",streams:t});c.addedByAddTrack=true;return c}}removeTrack(e){if(!this.getSenders().find(({ssrc:s})=>e.ssrc===s)){throw ne(\"InvalidAccessError\",\"Sender does not exist\")}const t=this.transceivers.find(({sender:{ssrc:s}})=>e.ssrc===s);if(!t)throw new Error(\"No matching transceiver found\");if(t.stopping||t.stopped){return false}if(e.track==void 0){return false}e.detachTrack();if(t.direction===\"sendrecv\"){t.setDirection(\"recvonly\")}else if(t.direction===\"sendonly\"){t.setDirection(\"inactive\")}return true}assignTransceiverCodecs(e){const t=this.filterCodecsByDirection(e.kind,e.direction);e.codecs=Nn({kind:e.kind,configured:t,source:br(e.sender.track),preferences:e.codecPreferences});e.codecPreferencesNeedResolution=false}filterCodecsByDirection(e,t){return this.config.codecs[e].filter(s=>{switch(s.direction){case\"recvonly\":{if(mx.includes(t))return true;return false}case\"sendonly\":{if(Rn.includes(t))return true;return false}case\"sendrecv\":{if([Ym,Xm,Vm].includes(t))return true;return false}case\"all\":{return true}default:return false}})}validateTrackForTransceiver(e,t,s=t.direction){on(e);Nn({kind:e.kind,configured:this.filterCodecsByDirection(e.kind,s),source:br(e),preferences:t.codecPreferences})}getLocalRtpParams(e){if(e.mid==void 0)throw new Error(\"mid not assigned\");const t={codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:true}};return t}getRemoteRtpParams(e,t){const s={muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((n,i)=>{if(i.name.toLowerCase()===\"rtx\"){const o=or(i.parameters??\"\");const c=n[o[\"apt\"]];if(c&&e.ssrc.length===2){c.rtx=new Mu({ssrc:e.ssrc[1].ssrc})}return n}n[i.payloadType]=new Du({ssrc:e.ssrc[0]?.ssrc,payloadType:i.payloadType});return n},{}))};return s}resyncAnswerCodecs(e,t){this.refreshAnswerCodecs(e,t);const s=this.getLocalRtpParams(e);e.sender.prepareSend(s);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const n=this.getRemoteRtpParams(t,e);for(const i of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,i,n)}e.receiver.resyncCodecs(n);this.router.registerRtpReceiverBySsrc(e,n)}}resolveRemoteCodecSet(e,t,s,n){const i=a(f=>f.name.toLowerCase(),\"codecName\");const o=a(f=>(f.parameters??\"\").split(\"/\").map(Number).filter(d=>!Number.isNaN(d)),\"redPayloadTypes\");const c=new Map;const l=new Set;for(const f of e){if([\"red\",\"rtx\"].includes(i(f)))continue;const d=t.rtp.codecs.find(h=>!l.has(h)&&h.mimeType.toLowerCase()===f.mimeType.toLowerCase()&&(n==void 0||n.some(p=>Ro(p,h))));if(d){c.set(f,d);l.add(d)}}const u=e.flatMap(f=>{if(i(f)===\"red\"){const y=o(f).flatMap(S=>{const T=e.find(x=>x.payloadType===S);const _=T?c.get(T):void 0;return _?[_.payloadType]:[]});const w=t.rtp.codecs.find(S=>{if(i(S)!==\"red\"||l.has(S))return false;const T=o(S);return T.length===y.length&&T.every((_,x)=>_===y[x])});if(!w)return[];l.add(w);return[w]}if(i(f)!==\"rtx\"){const y=c.get(f);return y?[y]:[]}const d=or(f.parameters??\"\").apt;const h=e.find(y=>y.payloadType===d);if(!h)return[];const p=c.get(h);if(!p)return[];const m=t.rtp.codecs.find(y=>{if(i(y)!==\"rtx\"||l.has(y)){return false}return or(y.parameters??\"\").apt===p.payloadType});if(!m)return[];l.add(m);return[m]});if(s===\"remote\"){const f=new Map(t.rtp.codecs.map((d,h)=>[d,h]));u.sort((d,h)=>f.get(d)-f.get(h))}if(u.length===0){throw ne(\"NotSupportedError\",\"No compatible codec remains after remote negotiation.\")}return u}refreshAnswerCodecs(e,t){const s=this.config.codecs[t.kind]||[];const n=br(e.sender.track);Nn({kind:t.kind,configured:s,source:n,preferences:e.codecPreferences});const i=mg(s,n,e.codecPreferences);e.codecs=this.resolveRemoteCodecSet(i,t,\"local\",n);e.codecPreferencesNeedResolution=false;HR(\"negotiated codecs\",e.codecs)}planRemoteRtpCodecs(e,t){const s=new Map;const n=e.type===\"offer\";for(const[i,o]of e.media.entries()){if(![\"audio\",\"video\"].includes(o.kind))continue;const c=t(o,i);if(o.port===0||c?.stopped||c?.stopping){s.set(i,[]);continue}const l=br(c?.sender.track);const u=this.config.codecs[o.kind]||[];const f=n?u:c?.pendingLocalOfferCodecs||[];if(!PR(f,o.rtp.codecs)){s.set(i,[]);continue}if(n){Nn({kind:o.kind,configured:u,source:l,preferences:c?.codecPreferences})}const d=this.resolveRemoteCodecSet(n?mg(u,l,c?.codecPreferences):f,o,n?\"local\":\"remote\",l);if(l!=void 0){Nn({kind:o.kind,configured:d,source:l,preferences:void 0})}s.set(i,d)}return s}setRemoteRTP(e,t,s,n,i){if(!e.mid){e.mid=t.rtp.muxId??null}e.mLineIndex=n;if(s===\"answer\")e.pendingLocalOfferCodecs=void 0;if(e.stopped){return false}if(e.stopping){if(s===\"answer\"&&t.port===0){e.commitStopped({rejected:false})}return false}HR(\"negotiated codecs\",i);if(t.port===0||i.length===0){if(s===\"answer\"){e.commitStopped({rejected:true})}else{e.pendingRejection=true}return false}e.pendingRejection=false;e.codecs=i;e.headerExtensions=t.rtp.headerExtensions.filter(u=>(this.config.headerExtensions[t.kind]||[]).find(f=>f.uri===u.uri));const o=t.direction??\"inactive\";const c=bR(o);if([\"answer\",\"pranswer\"].includes(s)){e.setCurrentDirection(c)}else{e.offerDirection=c}const l=this.getLocalRtpParams(e);e.sender.prepareSend(l);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const u=this.getRemoteRtpParams(t,e);for(const f of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,f,u)}e.receiver.resyncCodecs(u);this.router.registerRtpReceiverBySsrc(e,u)}if([\"sendonly\",\"sendrecv\"].includes(o)){const u=[...new Set(t.msids.map(d=>d.split(\" \")[0]))];const f=t.msids[0]?.split(\" \")[1];e.receiver.remoteStreamId=u[0];e.receiver.remoteStreamIds=u;e.receiver.remoteTrackId=f;if(!e.firedReceiving){e.firedReceiving=true;this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:u.map(d=>new Br({id:d,tracks:[e.receiver.track]}))})}}else{e.firedReceiving=false}return true}markStable(){this.stableState=new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex}]))}rollbackLocalOffer(){for(const e of this.transceivers){const t=this.stableState.get(e);e.mid=t?.mid??null;e.mLineIndex=t?.mLineIndex}}beginRemoteOffer(){if(this.remoteOfferSnapshot){return}this.remoteOfferSnapshot={transceivers:[...this.transceivers],remoteCreated:new Set,states:new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex,pendingRejection:e.pendingRejection,firedReceiving:e.firedReceiving}]))}}commitRemoteOffer(){this.remoteOfferSnapshot=void 0;for(const e of this.transceivers){if(e.pendingRejection){e.commitStopped({rejected:true})}}}rollbackRemoteOffer(){const e=this.remoteOfferSnapshot;this.remoteOfferSnapshot=void 0;if(!e){return}for(const t of this.transceivers){if(e.states.has(t)){continue}if(!e.remoteCreated.has(t)||t.sender.track){t.mid=null;t.mLineIndex=void 0;e.transceivers.push(t);continue}t.forceStop();this.unwatchTransceiver(t)}this.transceivers.splice(0,this.transceivers.length,...e.transceivers);e.transceivers.forEach(t=>this.watchTransceiver(t));for(const[t,s]of e.states){t.mid=s.mid;t.mLineIndex=s.mLineIndex;t.pendingRejection=s.pendingRejection;t.firedReceiving=s.firedReceiving}}settleStoppingTransceivers(e){for(const t of this.transceivers){if(!t.stopping||t.stopped){continue}if(t.mid==void 0||!e.has(t.mid)){t.commitStopped({rejected:false})}}return this.transceivers.some(t=>t.stopping&&!t.stopped)}collectStats(e){const t=[];for(const s of this.transceivers){if(s.sender){t.push(...s.sender.collectStats(e))}if(s.receiver){t.push(...s.receiver.collectStats(e))}const n=s.collectCodecStats(e);if(n){t.push(...n)}}return t}getStatsRootIds(e){if(!e){return[]}const t=[];for(const s of this.transceivers){if(s.sender.track===e){t.push(...s.sender.getStatsRootIds())}if(s.receiver.tracks.includes(e)){t.push(...s.receiver.getStatsRootIds(e))}}return t}close(){for(const e of this.transceivers){e.forceStop();this.unwatchTransceiver(e)}this.onTransceiverAdded.allUnsubscribe();this.onRemoteTransceiverAdded.allUnsubscribe();this.onTrack.allUnsubscribe();this.onNegotiationNeeded.allUnsubscribe()}};var bP=P(\"webrtc/peer/sctpManager\");var ud=class{static{a(this,\"SctpTransportManager\")}constructor(){this.dataChannelsOpened=0;this.dataChannelsClosed=0;this.dataChannels=[];this.onDataChannel=new O}createSctpTransport(e,t){const s=new ed(5e3,e,t);s.mid=void 0;s.onDataChannel.subscribe(n=>{this.dataChannelsOpened++;this.dataChannels.push(n);this.onDataChannel.execute(n)});this.sctpTransport=s;return s}createDataChannel(e,t={}){const s=qR(t.maxPacketLifeTime,\"maxPacketLifeTime\");const n=qR(t.maxRetransmits,\"maxRetransmits\");const i={protocol:\"\",ordered:true,negotiated:false};const o={...i,...t,maxPacketLifeTime:s,maxRetransmits:n};if(o.maxPacketLifeTime!=null&&o.maxRetransmits!=null){throw rr(\"maxPacketLifeTime and maxRetransmits cannot both be set\")}if(!this.sctpTransport){this.sctpTransport=this.createSctpTransport()}const c=new Eo({id:o.id,label:e,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits,negotiated:o.negotiated,ordered:o.ordered,protocol:o.protocol});const l=new wo(this.sctpTransport,c);this.dataChannelsOpened++;this.dataChannels.push(l);l.stateChange.subscribe(u=>{if(u===\"closed\"){this.dataChannelsClosed++;const f=this.dataChannels.indexOf(l);if(f!==-1){this.dataChannels.splice(f,1)}}});return l}async connectSctp(){if(!this.sctpTransport||!this.sctpRemotePort){return}await this.sctpTransport.start(this.sctpRemotePort);await this.sctpTransport.sctp.stateChanged.connected.asPromise();bP(\"sctp connected\")}setRemoteSCTP(e,t){if(!this.sctpTransport){return}this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize);this.sctpRemotePort=e.sctpPort;if(!this.sctpRemotePort){throw new Error(\"sctpRemotePort not exist\")}this.sctpTransport.setRemotePort(this.sctpRemotePort);this.sctpTransport.mLineIndex=t;if(!this.sctpTransport.mid){this.sctpTransport.mid=e.rtp.muxId}}async close(){if(this.sctpTransport){await this.sctpTransport.stop();await new Promise(e=>setImmediate(e))}this.onDataChannel.allUnsubscribe()}async getStats(e=Qe()){const t=[];for(const s of this.dataChannels){const n={type:\"data-channel\",id:ue(\"data-channel\",s.id??s.statsId),timestamp:e,label:s.label,protocol:s.protocol,dataChannelIdentifier:s.id??void 0,state:s.readyState,messagesSent:s.messagesSent||0,bytesSent:s.bytesSent||0,messagesReceived:s.messagesReceived||0,bytesReceived:s.bytesReceived||0};t.push(n)}return t}};function qR(r,e){if(r===void 0){return void 0}const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw rr(`${e} must be an unsigned short`)}return t}a(qR,\"coerceUnsignedShortOption\");var Eg=P(\"webrtc/peer/secureTransportManager\");var fd=class{static{a(this,\"SecureTransportManager\")}constructor({config:e,transceiverManager:t,sctpManager:s}){this.connectionState=\"new\";this.iceConnectionState=\"new\";this.iceGatheringState=\"new\";this.iceGatheringStateChange=new O;this.iceConnectionStateChange=new O;this.onIceCandidate=new O;this.connectionStateChange=new O;this.createdTransports=new Set;this.config=e;this.transceiverManager=t;this.sctpManager=s;if(this.config.dtls){const{keys:n}=this.config.dtls;if(this.config.certificates[0]){this.certificate=this.config.certificates[0]}else if(n){this.setupCertificate(n)}}}get dtlsTransports(){return Tg([...this.transceiverManager.getTransceivers().filter(e=>!e.stopped).map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get allDtlsTransports(){return Tg([...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new $c(e.keyPem,e.certPem,e.signatureHash)}resolveIceServerOptions(){const e=TR(this.config.iceServers);const t=rg({parsedTurnTransport:e.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP});return{stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:t,stunServers:e.stunServers,turnServers:e.turnServers.map(s=>({...s,transport:rg({parsedTurnTransport:s.transport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP})}))}}updateIceServers(){const e={...this.resolveIceServerOptions(),forceTurn:this.config.iceTransportPolicy===\"relay\",useTcp:this.config.iceUseTcp,turnUdpFamily:this.config.turnUdpFamily};for(const t of this.iceTransports){if(t.gatheringState===\"new\"){t.setIceServers(e)}}}createTransport({inheritCredentials:e=true}={}){const t=e?this.iceTransports.find(o=>o.state!==\"closed\"):void 0;const s=new Zf({...this.resolveIceServerOptions(),iceLite:this.config.iceLite,forceTurn:this.config.iceTransportPolicy===\"relay\",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,useTcp:this.config.iceUseTcp,tcpPassive:this.config.iceTcpPassive,stunGatherTimeout:this.config.iceStunGatherTimeout,turnConnectTimeout:this.config.iceTurnConnectTimeout,turnTlsOptions:this.config.turnTlsOptions,turnUdpFamily:this.config.turnUdpFamily,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});if(t){s.connection.localUsername=t.connection.localUsername;s.connection.localPassword=t.connection.localPassword}s.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()});this.updateIceGatheringState();const n=new Jf(s);n.onStateChange.subscribe(()=>{this.updateIceConnectionState()});const i=new jc(this.config,n,this.certificate,SP);this.createdTransports.add(i);return i}handleNewIceCandidate({candidate:e,sdpMid:t,sdpMLineIndex:s}){e.sdpMid=t;e.sdpMLineIndex=s;if(e.foundation&&!e.foundation.startsWith(\"candidate:\")){e.foundation=\"candidate:\"+e.foundation}this.onIceCandidate.execute(e);return e}async addIceCandidate(e,t){const s=t?.candidate;const n=t?.sdpMid;const i=t?.sdpMLineIndex;const o=t?.usernameFragment;const c=t==null||s==null||s===\"\";const l=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:c,sdpMid:n,sdpMLineIndex:i,usernameFragment:o});if(c){const p=l.map(m=>this.getTransportByMLineIndex(e,m)).filter(m=>!!m).reduce((m,y)=>{if(!m.find(({id:w})=>w===y.id)){m.push(y)}return m},[]);await Promise.all(p.map(m=>m.addRemoteCandidate(void 0)));return{kind:\"end-of-candidates\",mediaIndices:l}}const u=Fc.fromJSON(t);if(!u){throw ne(\"OperationError\",\"Failed to parse ICE candidate\")}const f=l[0];const d=e.media[f];if(!d){throw ne(\"OperationError\",\"ICE media section not found\")}u.sdpMid=d.rtp.muxId??void 0;u.sdpMLineIndex=f;const h=this.getTransportByMLineIndex(e,f);if(!h){if(this.isRejectedMedia(d)){return{kind:\"candidate\",candidate:u,mediaIndices:[f]}}throw ne(\"OperationError\",\"ICE transport not found for candidate\")}await h.addRemoteCandidate(u);return{kind:\"candidate\",candidate:u,mediaIndices:[f]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:s,sdpMLineIndex:n,usernameFragment:i}){let o;if(typeof s===\"string\"){const c=e.media.findIndex(l=>l.rtp.muxId===s);if(c<0){throw ne(\"OperationError\",\"Media section for sdpMid was not found\")}o=[c]}else if(typeof n===\"number\"){if(n<0||n>=e.media.length){throw ne(\"OperationError\",\"Media section for sdpMLineIndex was not found\")}o=[n]}else if(t){o=e.media.map((c,l)=>l)}else{throw rr(\"sdpMid or sdpMLineIndex must be provided with a candidate\")}if(typeof i===\"string\"){const c=o.filter(l=>e.media[l]?.iceParams?.usernameFragment===i);if(c.length===0){throw ne(\"OperationError\",\"No media section matched the ICE usernameFragment\")}o=c}return o}isRejectedMedia(e){if(e.port===0){return true}if(![\"audio\",\"video\"].includes(e.kind)){return false}const t=this.transceiverManager.getTransceivers().find(s=>s.mid!=void 0&&s.mid===e.rtp.muxId);return!t||t.stopped||t.stopping||t.pendingRejection}getTransportByMid(e){if(!e){return}let t;const s=this.transceiverManager.getTransceivers().find(n=>n.mid===e);if(s){t=s.dtlsTransport?.iceTransport}else if(!t&&this.sctpManager.sctpTransport?.mid===e){t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport}if(t?.state===\"closed\"){return}return t}getTransportByMLineIndex(e,t){const s=e.media[t];if(!s){return}const n=this.getTransportByMid(s.rtp.muxId);return n}restartIce(){for(const e of this.iceTransports){e.restart()}this.updateIceGatheringState()}setLocalRole({type:e,role:t,roleOfTransport:s}){for(const n of this.dtlsTransports){const i=n.iceTransport;if(i.state===\"new\"){if(i.connection.iceLite){i.connection.iceControlling=false}else if(i.connection.remoteIsLite){i.connection.iceControlling=true}else{i.connection.iceControlling=e===\"offer\"}}if(e===\"answer\"){const o=s?.get(n)??t;if(o){n.role=o}}}}updateIceGatheringState(){const e=this.iceTransports;function t(...n){return e.filter(i=>n.includes(i.gatheringState)).length===e.length}a(t,\"allMatch\");let s;if(e.length&&t(\"complete\")){s=\"complete\"}else if(!e.length||t(\"new\",\"complete\")){s=\"new\"}else if(e.map(n=>n.gatheringState).includes(\"gathering\")){s=\"gathering\"}else{s=\"new\"}if(this.iceGatheringState===s){return}this.iceGatheringState=s;this.iceGatheringStateChange.execute(s)}updateIceConnectionState(){const e=this.iceTransports;let t;function s(...i){return e.filter(o=>i.includes(o.state)).length===e.length}a(s,\"allMatch\");function n(...i){return e.some(o=>i.includes(o.state))}a(n,\"anyMatch\");if(this.connectionState===\"closed\"){t=\"closed\"}else if(n(\"failed\")){t=\"failed\"}else if(n(\"disconnected\")){t=\"disconnected\"}else if(s(\"new\",\"closed\")){t=\"new\"}else if(n(\"new\",\"checking\")){t=\"checking\"}else if(s(\"completed\",\"closed\")){t=\"completed\"}else if(s(\"connected\",\"completed\",\"closed\")){t=\"connected\"}else{t=\"new\"}if(this.iceConnectionState===t){return}Eg(\"iceConnectionStateChange\",t);this.iceConnectionState=t;this.iceConnectionStateChange.execute(t);if(t===\"failed\"&&this.connectionState!==\"closed\"){this.setConnectionState(\"failed\")}else if(t===\"disconnected\"&&this.connectionState===\"connected\"){this.setConnectionState(\"disconnected\")}}async gatherCandidates(){await Promise.allSettled(this.iceTransports.filter(e=>e.state!==\"closed\").map(e=>e.gather())).catch(e=>{Eg(\"gatherCandidates failed\",e)})}setConnectionState(e){if(this.connectionState===e||this.connectionState===\"closed\"){return}Eg(\"connectionStateChange\",e);this.connectionState=e;this.connectionStateChange.execute(e)}async getStats(e){const t=[];for(const s of this.dtlsTransports){const n=await s.getStats(e);if(n){t.push(...n)}}return t}async ensureCerts(){if(!this.certificate){this.certificate=await jc.SetupCertificate()}for(const e of this.dtlsTransports){e.localCertificate=this.certificate}}async close(){this.setConnectionState(\"closed\");await Promise.allSettled(Tg([...this.allDtlsTransports,...this.createdTransports]).map(e=>e.stop()));this.createdTransports.clear();this.iceGatheringStateChange.allUnsubscribe();this.iceConnectionStateChange.allUnsubscribe();this.onIceCandidate.allUnsubscribe();this.connectionStateChange.allUnsubscribe()}};function Tg(r){return r.reduce((e,t)=>{if(t&&!e.map(s=>s.id).includes(t.id)){e.push(t)}return e},[])}a(Tg,\"uniqueTransports\");var SP=[Am.SRTP_AEAD_AES_128_GCM,Am.SRTP_AES128_CM_HMAC_SHA1_80];var ye=P(\"webrtc/peer/peerConnection\");var dd=class extends kt{static{a(this,\"RTCPeerConnection\")}get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super();this.id=(0,xg.randomUUID)().toString();this.cname=(0,xg.randomUUID)().toString();this.config=GR();this.signalingState=\"stable\";this.negotiationneeded=false;this.negotiationneededScheduled=false;this.negotiationChangeSeq=0;this.negotiatedChangeSeq=0;this.lastCreatedOfferChangeSeq=0;this.needRestart=false;this.router=new od;this.isClosed=false;this.shouldNegotiationneeded=false;this.pendingRemoteCandidates=[];this.iceGatheringStateChange=new O;this.iceConnectionStateChange=new O;this.signalingStateChange=new O;this.connectionStateChange=new O;this.onDataChannel=new O;this.onRemoteTransceiverAdded=new O;this.onTransceiverAdded=new O;this.onIceCandidate=new O;this.onNegotiationneeded=new O;this.onTrack=new O;this.eventHandlers={};this.needNegotiation=()=>{this.negotiationChangeSeq++;this.scheduleNegotiationneeded()};this.setConfiguration(e);this.sdpManager=new ad({cname:this.cname,bundlePolicy:this.config.bundlePolicy,mLineReuse:this.config.mLineReuse});this.transceiverManager=new ld(this.cname,this.config,this.router);this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);this.transceiverManager.onTrack.subscribe(({track:t,streams:s,transceiver:n})=>{const i=new Rg({track:t,streams:s,transceiver:n,receiver:n.receiver});this.onTrack.execute(t);this.emit(\"track\",i);if(this.ontrack){Ne(()=>this.ontrack(i),o=>ye(\"event handler failed\",o))}});this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation());this.sctpManager=new ud;this.sctpManager.onDataChannel.subscribe(t=>{this.onDataChannel.execute(t);const s={type:\"datachannel\",channel:t};if(this.ondatachannel)Ne(()=>this.ondatachannel(s),n=>ye(\"event handler failed\",n));this.emit(\"datachannel\",s)});this.secureManager=new fd({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager});this.secureManager.iceGatheringStateChange.subscribe(t=>{this.iceGatheringStateChange.execute(t);if(this.onicegatheringstatechange){Ne(()=>this.onicegatheringstatechange(new globalThis.Event(\"icegatheringstatechange\")),s=>ye(\"event handler failed\",s))}this.emit(\"icegatheringstatechange\")});this.secureManager.iceConnectionStateChange.subscribe(t=>{if(t===\"closed\"){this.close().catch(s=>ye(\"close failed\",s))}this.iceConnectionStateChange.execute(t);if(this.oniceconnectionstatechange)Ne(()=>this.oniceconnectionstatechange(),s=>ye(\"event handler failed\",s));this.emit(\"iceconnectionstatechange\")});this.secureManager.connectionStateChange.subscribe(t=>{this.connectionStateChange.execute(t);if(this.onconnectionstatechange)Ne(()=>this.onconnectionstatechange(),s=>ye(\"event handler failed\",s));this.emit(\"connectionstatechange\")});this.secureManager.onIceCandidate.subscribe(t=>{const s=t?t.toJSON():void 0;this.onIceCandidate.execute(s);const n={type:\"icecandidate\",candidate:s};if(this.onicecandidate)Ne(()=>this.onicecandidate(n),i=>ye(\"event handler failed\",i));this.emit(\"icecandidate\",n)})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctp(){return this.sctpTransport??null}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){const e=this.sdpManager._remoteDescription;if(!e){return null}const t=[e.iceOptions,...e.media.map(s=>s.iceOptions)].filter(s=>!!s).join(\" \");return t.split(/\\s+/).includes(\"trickle\")}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(e){const t=EP(e);const s=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==\"require\"){throw new Error(\"rtcpMuxPolicy must be require\")}if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0)){throw new Error(\"iceCandidatePoolSize must be a non-negative integer\")}if(s&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy){throw new Error(\"bundlePolicy cannot be changed\")}if(t.mLineReuse!==void 0&&!zR.includes(t.mLineReuse)){throw rr(`mLineReuse must be one of ${zR.join(\", \")}`)}if(s&&t.mLineReuse!==void 0&&t.mLineReuse!==this.config.mLineReuse){throw ne(\"InvalidModificationError\",\"mLineReuse cannot be changed\")}if(s&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy){throw new Error(\"rtcpMuxPolicy cannot be changed\")}if(s&&t.certificates!==void 0&&!xP(t.certificates,this.config.certificates)){throw new Error(\"certificates cannot be changed\")}if(s&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize){throw new Error(\"iceCandidatePoolSize cannot be changed after setLocalDescription\")}if((t.iceCandidatePoolSize??0)>0){throw new Error(\"iceCandidatePoolSize > 0 is not supported\")}if(t.sctp!==void 0){const o=t.sctp.mtu??ji;Gu(o);if(this.sctpManager?.sctpTransport&&o!==this.config.sctp.mtu){throw new Error(\"sctp.mtu cannot be changed after SCTP transport creation\")}}xR(this.config,t);this.config.sctp={mtu:this.config.sctp?.mtu??ji};if(this.config.icePortRange){const[o,c]=this.config.icePortRange;if(o===c)throw new Error(\"should not be same value\");if(o>=c)throw new Error(\"The min must be less than max\")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0){throw new Error(\"maxMessageSize must be a non-negative integer\")}if(this.sctpManager?.sctpTransport){this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize}wP(this.config);const n=new Map;const i=[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]];i.forEach(o=>{if(!n.has(o.uri))n.set(o.uri,n.size+1);o.id=n.get(o.uri)});if(s&&this.secureManager&&(t.iceServers!==void 0||t.turnUdpFamily!==void 0)){this.secureManager.updateIceServers()}}getConfiguration(){return RP(this.config)}headerExtensionsFor(e){const t=new Map;for(const n of this.transceiverManager.getTransceivers()){for(const i of n.headerExtensions)t.set(i.uri,i.id)}const s=new Set(t.values());return(this.config.headerExtensions[e]??[]).flatMap(n=>{let i=t.get(n.uri);if(i===void 0){i=s.has(n.id)?Array.from({length:14},(o,c)=>c+1).find(o=>!s.has(o)):n.id;if(i===void 0)return[];s.add(i);t.set(n.uri,i)}return[new Qt({uri:n.uri,id:i})]})}async createOffer({iceRestart:e}={}){if(e||this.needRestart){this.needRestart=false;this.secureManager.restartIce()}await this.secureManager.ensureCerts();for(const n of this.transceiverManager.getTransceivers()){if(n.codecs.length===0||n.codecPreferencesNeedResolution){this.transceiverManager.assignTransceiverCodecs(n)}if(n.headerExtensions.length===0){n.headerExtensions=this.headerExtensionsFor(n.kind)}}const t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);const s=t.toJSON();this.lastCreatedOffer=s;this.lastCreatedOfferChangeSeq=this.negotiationChangeSeq;return s}createSctpTransport(){const e=this.sctpManager.createSctpTransport(this.config.maxMessageSize,this.config.sctp);const t=this.findOrCreateTransport();e.setDtlsTransport(t);return e}createDataChannel(e,t={}){if(!this.sctpTransport){this.createSctpTransport();this.needNegotiation()}const s=this.sctpManager.createDataChannel(e,t);if(!s.sctp.dtlsTransport){const n=this.findOrCreateTransport();s.sctp.setDtlsTransport(n)}return s}removeTrack(e){if(this.isClosed){throw ne(\"InvalidStateError\",\"peer closed\")}if(this.transceiverManager.removeTrack(e)){this.needNegotiation()}}scheduleNegotiationneeded(){this.invalidateLastCreatedDescriptions();this.shouldNegotiationneeded=true;if(this.negotiationneeded||this.negotiationneededScheduled||this.signalingState!==\"stable\"){return}this.shouldNegotiationneeded=false;this.negotiationneededScheduled=true;setImmediate(()=>{this.negotiationneededScheduled=false;if(this.negotiatedChangeSeq>=this.negotiationChangeSeq){return}if(this.signalingState!==\"stable\"){this.shouldNegotiationneeded=true;return}this.negotiationneeded=true;this.onNegotiationneeded.execute();if(this.onnegotiationneeded){Ne(()=>this.onnegotiationneeded(new globalThis.Event(\"negotiationneeded\")),e=>ye(\"event handler failed\",e))}this.emit(\"negotiationneeded\")})}invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0;this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed();await Promise.resolve();if(this.isClosed){await new Promise(()=>void 0)}}findOrCreateTransport(){const e=this.dtlsTransports.find(t=>t.state!==\"closed\");if(this.sdpManager.bundlePolicy===\"max-bundle\"||this.sdpManager.bundlePolicy!==\"disable\"&&this.remoteIsBundled){if(e){return e}}return this.createDtlsTransport()}createDtlsTransport({inheritCredentials:e=true}={}){const t=this.secureManager.createTransport({inheritCredentials:e});t.onRtp.subscribe(n=>{this.router.routeRtp(n)});t.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});const s=t.iceTransport;s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()});s.onIceCandidate.subscribe(n=>{if(!this.localDescription){ye(\"localDescription not found when ice candidate was gathered\");return}if(!n){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport);this.onIceCandidate.execute(void 0);if(this.onicecandidate){Ne(()=>this.onicecandidate({candidate:void 0}),o=>ye(\"event handler failed\",o))}this.emit(\"icecandidate\",{candidate:void 0});return}if(!this._localDescription){ye(\"localDescription not found when ice candidate was gathered\");return}const i=this.resolveLocalCandidateOwner(s);if(!i){ye(\"no accepted m-line owns the ice transport\",s.id);return}this.secureManager.handleNewIceCandidate({candidate:n,sdpMid:i.mid,sdpMLineIndex:i.index})});return t}resolveLocalCandidateOwner(e){const t=this._localDescription;if(!t){return}const s=t.media.map((o,c)=>({media:o,index:c})).filter(({media:o})=>{if(o.port===0){return false}const c=o.rtp.muxId;if(o.kind===\"application\"){return!!this.sctpTransport&&this.sctpTransport.mid===c&&this.sctpTransport.dtlsTransport?.iceTransport.id===e.id}const l=this.transceiverManager.getTransceivers().find(u=>u.mid!=void 0&&u.mid===c);return!!l&&!l.stopped&&l.dtlsTransport?.iceTransport.id===e.id});const n=t.group.filter(o=>o.semantic===\"BUNDLE\").map(o=>o.items[0]);const i=s.find(({media:o})=>n.includes(o.rtp.muxId))??s[0];if(!i){return}return{mid:i.media.rtp.muxId,index:i.index}}settleStoppingTransceivers(){const e=new Set((this.sdpManager.currentLocalDescription?.media??[]).filter(s=>s.port!==0&&s.rtp.muxId).map(s=>s.rtp.muxId));const t=this.transceiverManager.settleStoppingTransceivers(e);this.closeIdleTransports();return t}closeIdleTransports(e=this.transceiverManager.getTransceivers().filter(t=>t.stopped).map(t=>t.dtlsTransport)){const t=new Set(this.dtlsTransports.map(s=>s.id));for(const s of new Set(e)){if(!s||s.state===\"closed\"||t.has(s.id)){continue}s.stop().catch(n=>{ye(\"failed to close idle transport\",n)})}}async setLocalDescription(e){const t=[\"stable\",\"have-local-offer\",\"have-remote-pranswer\"];await this.waitForPendingDescriptionTask();if(e?.type===\"rollback\"){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const d of this.transceiverManager.getTransceivers()){d.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}const s=!e?.type||!e.sdp||e.sdp.length===0;const n=s?e?.type===\"offer\"?this.lastCreatedOffer??await this.createOffer():e?.type===\"answer\"||e?.type===\"pranswer\"?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;e={type:e?.type??n.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:n.sdp};if(e.type===\"offer\"&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp){throw ne(\"InvalidModificationError\",\"setLocalDescription must use the latest created offer\")}const i=e.type;const o=e.sdp;const c=this.sdpManager.parseSdp({sdp:o,isLocal:true,signalingState:this.signalingState,type:i});if(c.type===\"offer\"){this.pendingOfferChangeSeq=this.lastCreatedOffer?.sdp===e.sdp?this.lastCreatedOfferChangeSeq:void 0;this.setSignalingState(\"have-local-offer\")}else if(c.type===\"answer\"){this.setSignalingState(\"stable\")}else if(c.type===\"pranswer\"){this.setSignalingState(\"have-local-pranswer\")}if(c.type===\"answer\"){this.transceiverManager.commitRemoteOffer();for(const d of c.media){if(![\"audio\",\"video\"].includes(d.kind)||d.port!==0){continue}const h=this.transceiverManager.getTransceivers().find(p=>p.mid===d.rtp.muxId&&!p.stopped);h?.commitStopped({rejected:true})}this.closeIdleTransports()}for(const[d,h]of Fp(c.media)){const p=h.rtp.muxId;this.sdpManager.registerMid(p);if([\"audio\",\"video\"].includes(h.kind)&&h.port!==0){const m=this.transceiverManager.getTransceivers().find(y=>y.mLineIndex===d&&!y.stopped&&y.kind===h.kind&&(y.mid==null||y.mid===p));if(m){m.mid=p;if(c.type===\"offer\"){m.pendingLocalOfferCodecs=[...h.rtp.codecs]}}}if(h.kind===\"application\"&&this.sctpTransport){this.sctpTransport.mid=p}}const l=c.media.find(d=>d.dtlsParams)?.dtlsParams?.role;const u=new Map;for(const d of c.media){const h=d.rtp.muxId;const p=d.dtlsParams?.role;if(d.port===0||h==void 0||!p){continue}const m=d.kind===\"application\"?this.sctpTransport?.mid===h?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(y=>y.mid===h&&!y.stopped);if(m?.dtlsTransport&&!u.has(m.dtlsTransport)){u.set(m.dtlsTransport,p)}}this.secureManager.setLocalRole({type:c.type===\"offer\"?\"offer\":\"answer\",role:l,roleOfTransport:u});if([\"answer\",\"pranswer\"].includes(c.type)){for(const d of c.media){const h=this.transceiverManager.getTransceivers().find(m=>m.mid!=void 0&&m.mid===d.rtp.muxId);if(!h||h.stopped||h.pendingRejection){continue}const p=h.stopping?\"inactive\":Gf(h.direction,h.offerDirection);h.setCurrentDirection(p)}}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);await this.gatherCandidates().catch(d=>{ye(\"gatherCandidates failed\",d)});if(c.type===\"answer\"){this.connect().catch(d=>{ye(\"connect failed\",d);this.secureManager.setConnectionState(\"failed\")})}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);const f=c.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||f){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return c}async gatherCandidates(){await this.secureManager.gatherCandidates()}async addIceCandidate(e={}){if(this.isClosed){throw ne(\"InvalidStateError\",\"is closed\")}if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){const t=this.sdpManager._remoteDescription;if(!t){return}const s=await this.secureManager.addIceCandidate(t,e);const n=this.sdpManager._remoteDescription;if(!n||!s){return}if(s.kind===\"end-of-candidates\"){for(const i of s.mediaIndices){const o=n.media[i];if(o){o.iceCandidatesComplete=true}}return}for(const i of s.mediaIndices){const o=n.media[i];if(!o){continue}o.iceCandidates.push(s.candidate)}}async flushPendingRemoteCandidates(){while(this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription){const e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){ye(\"start connect\");const e=await Promise.allSettled(this.dtlsTransports.map(async t=>{const{iceTransport:s}=t;if(s.state===\"connected\"){return}if(!s.connection.remoteUsername||!s.connection.remotePassword){return}const n=a(()=>t.state===\"connected\",\"checkDtlsConnected\");if(n()){if(!s.connection.nominated){await s.start().catch(i=>{ye(\"iceTransport.start failed\",i);throw i})}return}this.secureManager.setConnectionState(\"connecting\");await s.start().catch(i=>{ye(\"iceTransport.start failed\",i);throw i});if(n()){return}await t.start().catch(i=>{ye(\"dtlsTransport.start failed\",i);throw i});if(this.sctpTransport&&this.sctpTransport.dtlsTransport.id===t.id){await this.sctpManager.connectSctp()}}));if(e.find(t=>t.status===\"rejected\")){this.secureManager.setConnectionState(\"failed\")}else{this.secureManager.setConnectionState(\"connected\")}}restartIce(){this.needRestart=true;this.needNegotiation()}async setRemoteDescription(e){if(e instanceof Jr){e=e.toSdp()}await this.waitForPendingDescriptionTask();const t=e.type===\"offer\"&&[\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState);if(t){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const S of this.transceiverManager.getTransceivers()){S.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.shouldNegotiationneeded=true;this.setSignalingState(\"stable\");await Promise.resolve()}let s=new Map;if(e.type&&e.type!==\"rollback\"&&e.sdp){const S=this.sdpManager.parseSdp({sdp:e.sdp,isLocal:false,signalingState:this.signalingState,type:e.type});const T=new Set;s=this.transceiverManager.planRemoteRtpCodecs(S,(_,x)=>{const k=this.findTransceiverForRemoteMedia(_,x,T,e.type===\"offer\");if(k)T.add(k);return k})}this.assertAnswerKeepsSharedTransports(e);const n=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!n){const S=this.transceiverManager.getTransceivers().map(T=>T.dtlsTransport);this.transceiverManager.rollbackRemoteOffer();this.closeIdleTransports(S);this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}if(n.type===\"offer\"){this.transceiverManager.beginRemoteOffer()}const i=this.config.bundlePolicy===\"disable\"?[]:n.group.filter(S=>S.semantic===\"BUNDLE\");const o=a(S=>S==void 0?void 0:i.find(T=>T.items.includes(S)),\"groupOfMid\");const c=new Set;const l=n.media.map((S,T)=>{if([\"audio\",\"video\"].includes(S.kind)){let _=this.findTransceiverForRemoteMedia(S,T,c,n.type===\"offer\");if(!_){if(S.port===0){return{remoteMedia:S,index:T}}_=this.addRemoteTransceiver(S,T)}else if(_.mid==null){this.transceiverManager.associateMLine(_,T)}c.add(_);return{remoteMedia:S,index:T,transceiver:_}}else if(S.kind===\"application\"){let _=this.sctpTransport;if(!_){_=this.createSctpTransport();_.mid=S.rtp.muxId}return{remoteMedia:S,index:T,sctpTransport:_}}else{throw new Error(\"invalid media kind\")}});if(n.type===\"offer\"){this.transceiverManager.releaseUnassociatedReservations(c,n.media.length)}const u=a(S=>S.transceiver??S.sctpTransport,\"ownerOf\");const f=n.type===\"offer\";const d=a(S=>!!S&&S.state!==\"closed\",\"liveTransport\");const h=new Map;const p=new Set;for(const S of i){const T=l.filter(x=>!!u(x)&&S.items.includes(x.remoteMedia.rtp.muxId));if(T.length===0){continue}let _=T.map(x=>u(x).dtlsTransport).find(x=>d(x)&&(!f||!p.has(x)));if(!_){_=this.createDtlsTransport({inheritCredentials:false})}h.set(S,_);p.add(_);for(const x of T){const k=u(x);if(k.dtlsTransport!==_){k.setDtlsTransport(_)}}}if(f){for(const S of l){const T=u(S);if(!T||S.remoteMedia.port===0||o(S.remoteMedia.rtp.muxId)){continue}if(!d(T.dtlsTransport)||p.has(T.dtlsTransport)){T.setDtlsTransport(this.createDtlsTransport({inheritCredentials:false}))}p.add(T.dtlsTransport)}}const m=new Set;for(const S of l){const{remoteMedia:T,index:_}=S;if(S.transceiver){if(this.transceiverManager.setRemoteRTP(S.transceiver,T,n.type,_,s.get(_)??[])){m.add(S)}}else if(S.sctpTransport){this.sctpManager.setRemoteSCTP(T,_);m.add(S)}}const y=new Map;for(const S of i){for(const T of S.items){const _=l.find(x=>x.remoteMedia.rtp.muxId===T&&x.remoteMedia.port!==0&&m.has(x));if(_){y.set(S,_);break}}}for(const S of l){const{remoteMedia:T}=S;const _=u(S);if(!_){continue}const x=m.has(S);const k=_.dtlsTransport;const N=o(T.rtp.muxId);if(T.port===0||!k||k.state===\"closed\"||!x&&!N){continue}const A=k.iceTransport;const B=!N||y.get(N)===S;if(B){if(T.iceParams){const ee=!!this.sdpManager.inactiveRemoteMedia;A.setRemoteParams(T.iceParams,ee);if(T.iceParams.iceLite&&!A.connection.iceLite){A.connection.iceControlling=true}}if(T.dtlsParams){k.setRemoteParams(T.dtlsParams)}}for(const ee of T.iceCandidates){A.addRemoteCandidate(ee).catch(fe=>ye(\"add candidate failed\",fe))}if(T.iceCandidatesComplete){A.addRemoteCandidate(void 0).catch(ee=>ye(\"end of candidates failed\",ee))}if(n.type===\"answer\"&&T.dtlsParams?.role){k.role=T.dtlsParams.role===\"client\"?\"server\":\"client\"}}if(n.type===\"answer\"){for(const S of this.transceiverManager.getTransceivers()){if(!c.has(S)&&S.mid!=void 0&&!S.stopped){S.commitStopped({rejected:true})}}this.closeIdleTransports()}if(n.type===\"offer\"){this.setSignalingState(\"have-remote-offer\")}else if(n.type===\"answer\"){this.setSignalingState(\"stable\")}else if(n.type===\"pranswer\"){this.setSignalingState(\"have-remote-pranswer\")}await this.flushPendingRemoteCandidates();if(n.type===\"answer\"){ye(\"caller start connect\");this.connect().catch(S=>{ye(\"connect failed\",S);this.secureManager.setConnectionState(\"failed\")})}this.negotiationneeded=false;if(n.type===\"answer\"&&this.pendingOfferChangeSeq!=void 0){this.negotiatedChangeSeq=Math.max(this.negotiatedChangeSeq,this.pendingOfferChangeSeq);this.pendingOfferChangeSeq=void 0}const w=n.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||w){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions()}assertAnswerKeepsSharedTransports(e){if(![\"answer\",\"pranswer\"].includes(e.type??\"\")||![\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState)||!e.sdp||this.config.bundlePolicy===\"disable\"){return}const t=Jr.parse(e.sdp);const s=t.group.filter(i=>i.semantic===\"BUNDLE\");const n=new Map;for(const i of t.media){const o=i.rtp.muxId;if(i.port===0||o==void 0){continue}const c=i.kind===\"application\"?this.sctpTransport?.mid===o?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(h=>h.mid===o&&!h.stopped);const l=c?.dtlsTransport;if(!l){continue}const u={group:s.find(h=>h.items.includes(o)),credentials:`${i.iceParams?.usernameFragment}:${i.iceParams?.password}`};const f=n.get(l);if(!f){n.set(l,u);continue}const d=!!u.group&&u.group===f.group;if(!d&&u.credentials!==f.credentials){throw ne(\"InvalidAccessError\",`mid=${o} shares a transport in the local offer but the remote ${e.type} moves it out of that BUNDLE group`)}}}findTransceiverForRemoteMedia(e,t,s,n){const i=this.transceiverManager.getTransceivers().filter(u=>!s.has(u)&&u.kind===e.kind);const o=e.rtp.muxId;const c=o!=void 0?i.find(u=>u.mid===o):void 0;if(c){return c}if(e.port===0){return}const l=i.filter(u=>u.mid==null&&!u.stopping&&!u.stopped&&(!n||u.addedByAddTrack&&[\"sendrecv\",\"recvonly\"].includes(e.direction??\"sendrecv\")));return l.find(u=>u.mLineIndex===t)??l[0]}addRemoteTransceiver(e,t){const s=this.findOrCreateTransport();const n=this.transceiverManager.addTransceiver(e.kind,s,{direction:\"recvonly\"},{remoteMLineIndex:t});n.mid=e.rtp.muxId??null;this.secureManager.updateIceConnectionState();this.onRemoteTransceiverAdded.execute(n);return n}addTransceiver(e,t={}){const s=this.findOrCreateTransport();const n=this.transceiverManager.addTransceiver(e,s,t);this.secureManager.updateIceConnectionState();this.needNegotiation();return n}addTrack(e,...t){return this.addTrackOn(void 0,e,...t)}reusableForTrack(e){return this.transceiverManager.reusableForTrack(e,e.kind)}addTrackOn(e,t,...s){if(this.isClosed){throw ne(\"InvalidStateError\",\"is closed\")}const n=this.transceiverManager.addTrack(t,s,e);if(!n.dtlsTransport){const i=this.findOrCreateTransport();n.setDtlsTransport(i)}this.needNegotiation();return n.sender}async createAnswer(){this.assertNotClosed();await this.secureManager.ensureCerts();for(const s of this.transceiverManager.getTransceivers()){if(s.codecs.length!==0&&!s.codecPreferencesNeedResolution){continue}if(s.pendingRejection||s.stopping||s.stopped){continue}const n=this.sdpManager._remoteDescription;const i=n?.media.find(o=>o.rtp.muxId!=void 0&&o.rtp.muxId===s.mid&&o.kind===s.kind)??(s.mLineIndex!=void 0?n?.media[s.mLineIndex]:void 0);if(i&&[\"audio\",\"video\"].includes(i.kind)){this.transceiverManager.resyncAnswerCodecs(s,i)}else{this.transceiverManager.assignTransceiverCodecs(s)}if(s.headerExtensions.length===0){s.headerExtensions=this.headerExtensionsFor(s.kind)}}const e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState});const t=e.toJSON();this.lastCreatedAnswer=t;return t}assertNotClosed(){if(this.isClosed){throw ne(\"InvalidStateError\",\"RTCPeerConnection is closed\")}}markStable(){this.transceiverManager.markStable();const e=this.sctpTransport;this.stableSctp=e?{mid:e.mid,mLineIndex:e.mLineIndex}:void 0}rollbackLocalOffer(){this.transceiverManager.rollbackLocalOffer();const e=this.sctpTransport;if(e){e.mid=this.stableSctp?.mid;e.mLineIndex=this.stableSctp?.mLineIndex}}setSignalingState(e){if(this.signalingState===e){return}ye(\"signalingStateChange\",e);this.signalingState=e;if(e===\"stable\")this.markStable();this.signalingStateChange.execute(e);if(this.onsignalingstatechange){Ne(()=>this.onsignalingstatechange(new globalThis.Event(\"signalingstatechange\")),t=>ye(\"event handler failed\",t))}this.emit(\"signalingstatechange\")}createPeerConnectionStats(e){return{type:\"peer-connection\",id:ue(\"peer-connection\",this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){const t=Qe();const s=[];if(!e){s.push(this.createPeerConnectionStats(t))}s.push(...this.transceiverManager.collectStats(t));const n=await this.secureManager.getStats(t);s.push(...n);if(!e&&this.sctpTransport){const i=await this.sctpManager.getStats(t);if(i){s.push(...i)}}if(!e){return On(s)}return On(s,this.transceiverManager.getStatsRootIds(e))}async close(){this.closing??=this.closeOnce();return this.closing}async closeOnce(){this.isClosed=true;this.pendingRemoteCandidates.length=0;this.setSignalingState(\"closed\");this.transceiverManager.close();await this.sctpManager.close();await this.secureManager.close();this.completePeerEvents();ye(\"peerConnection closed\")}completePeerEvents(){const e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(const t of e){if(!t.ended){t.complete()}}}};var zR=[\"compatible\",\"aggressive\"];function wP(r){for(const[e,t]of Fp([...r.codecs.audio||[],...r.codecs.video||[]])){if(t.payloadType!=void 0){continue}t.payloadType=96+e;switch(t.name.toLowerCase()){case\"rtx\":{t.parameters=`apt=${t.payloadType-1}`}break;case\"red\":{if(t.contentType===\"audio\"){const s=t.payloadType+1;t.parameters=`${s}/${s}`;t.payloadType=63}}break}}}a(wP,\"assignDynamicPayloadTypes\");function GR(){return{codecs:LE(),headerExtensions:{audio:[],video:[]},iceTransportPolicy:\"all\",iceLite:false,iceServers:[],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:true,iceUseIpv6:true,iceUseTcp:false,iceTcpPassive:true,iceStunGatherTimeout:void 0,iceTurnConnectTimeout:void 0,turnTransport:void 0,turnTlsOptions:void 0,turnUdpFamily:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:\"max-compat\",rtcpMuxPolicy:\"require\",iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:false,forceTurnTCP:false,maxMessageSize:To,sctp:{mtu:ji},pendingRtp:false,mLineReuse:\"compatible\"}}a(GR,\"generateDefaultPeerConfig\");var rre=GR();function EP(r){const e=Object(r??{});const t={...e};if(e.sctp!==void 0){t.sctp={...e.sctp}}if(e.bundlePolicy===\"balanced\"){t.bundlePolicy=\"max-compat\"}if(\"certificates\"in e){if(e.certificates===void 0){t.certificates=void 0}else if(!Array.isArray(e.certificates)||e.certificates.some(s=>s==null)){throw rr(\"certificates must be an array of RTCCertificate\")}else{t.certificates=[...e.certificates]}}if(\"iceCandidatePoolSize\"in e){t.iceCandidatePoolSize=TP(e.iceCandidatePoolSize,\"iceCandidatePoolSize\")}return t}a(EP,\"normalizePeerConfiguration\");function TP(r,e){const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw rr(`${e} must be an unsigned short`)}return t}a(TP,\"coerceUnsignedShort\");function xP(r,e){return r.length===e.length&&r.every((t,s)=>t===e[s])}a(xP,\"hasSameCertificates\");function RP(r){return{...r,codecs:{audio:r.codecs.audio?[...r.codecs.audio]:void 0,video:r.codecs.video?[...r.codecs.video]:void 0},headerExtensions:{audio:r.headerExtensions.audio?[...r.headerExtensions.audio]:void 0,video:r.headerExtensions.video?[...r.headerExtensions.video]:void 0},iceServers:r.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:r.icePortRange?[...r.icePortRange]:void 0,iceAdditionalHostAddresses:r.iceAdditionalHostAddresses?[...r.iceAdditionalHostAddresses]:void 0,dtls:{...r.dtls},certificates:[...r.certificates],debug:{...r.debug},sctp:{...r.sctp},pendingRtp:typeof r.pendingRtp===\"object\"&&r.pendingRtp!=void 0?{...r.pendingRtp}:r.pendingRtp}}a(RP,\"clonePeerConfiguration\");var Rg=class{static{a(this,\"RTCTrackEvent\")}constructor(e){this.type=\"track\";this.track=e.track;this.streams=[...e.streams];this.transceiver=e.transceiver;this.receiver=e.receiver}};function KR(r){const e={iceServers:r.iceServers,iceTransportPolicy:r.iceTransportPolicy,iceUseIpv4:r.iceUseIpv4,iceUseIpv6:r.iceUseIpv6,codecs:jE(r.codecs),maxMessageSize:262144};if(r.icePortRange)e.icePortRange=r.icePortRange;if(r.iceAdditionalHostAddresses)e.iceAdditionalHostAddresses=r.iceAdditionalHostAddresses;if(r.headerExtensions){e.headerExtensions={audio:[DR(),bg(),yg(),gg()],video:[bg(),yg(),gg()]};for(const t of[...e.codecs.audio,...e.codecs.video])t.rtcpFeedback.push(Nu())}return e}a(KR,\"engineConfigOf\");var _g=new WeakMap;function Cg(r){return _g.get(r)}a(Cg,\"engineConnectionOf\");var vg=new WeakMap;function WR(r){return vg.get(r)}a(WR,\"engineChannelOf\");var VR=require(\"node:events\");var vo=class{static{a(this,\"Events\")}#e=new EventTarget;#t=new VR.EventEmitter;#r=new Map;#s;constructor(e){this.#s=e;this.#t.setMaxListeners(0)}fire(e,t,...s){const n=e===\"message\"?new MessageEvent(\"message\",{data:t.data}):new Event(e);for(const[o,c]of Object.entries(t)){if(o!==\"data\")Object.defineProperty(n,o,{value:c,enumerable:true})}Object.defineProperty(n,\"currentTarget\",{value:this.#s});this.#e.dispatchEvent(n);const i=this.#r.get(e);if(i)i.call(this.#s,n);if(e!==\"error\"||this.#t.listenerCount(\"error\"))this.#t.emit(e,...s)}dispatch(e,...t){const s=this.#e.dispatchEvent(e);this.#r.get(e.type)?.call(this.#s,e);if(e.type!==\"error\"||this.#t.listenerCount(\"error\"))this.#t.emit(e.type,...t);return s&&!e.defaultPrevented}addEventListener(e,t,s){this.#e.addEventListener(e,t,s)}removeEventListener(e,t,s){this.#e.removeEventListener(e,t,s)}on(e,t){this.#t.on(e,t)}once(e,t){this.#t.once(e,t)}off(e,t){this.#t.off(e,t)}handler(e){return this.#r.get(e)??null}setHandler(e,t){if(t){this.#r.set(e,t)}else{this.#r.delete(e)}}};var hd=class{static{a(this,\"PeerChannel\")}#e;#t=new vo(this);#r=\"nodebuffer\";constructor(e){this.#e=e;vg.set(this,e);e.stateChanged.subscribe(t=>{this.#t.fire(t===\"closed\"?\"close\":t,{})});e.onMessage.subscribe(t=>{const s=typeof t===\"string\"||this.#r===\"nodebuffer\"?t:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.#t.fire(\"message\",{data:s},s)});e.bufferedAmountLow.subscribe(()=>this.#t.fire(\"bufferedamountlow\",{}));e.error.subscribe(t=>this.#t.fire(\"error\",{error:t},t))}get label(){return this.#e.label}get id(){return this.#e.id??null}get protocol(){return this.#e.protocol}get ordered(){return this.#e.ordered}get maxRetransmits(){return this.#e.maxRetransmits??null}get maxPacketLifeTime(){return this.#e.maxPacketLifeTime??null}get negotiated(){return this.#e.negotiated}get readyState(){return this.#e.readyState}get bufferedAmount(){return this.#e.bufferedAmount}get bufferedAmountLowThreshold(){return this.#e.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this.#e.bufferedAmountLowThreshold=e}get binaryType(){return this.#r}set binaryType(e){if(e!==\"nodebuffer\"&&e!==\"arraybuffer\")throw new TypeError(`Unsupported binaryType: ${e}`);this.#r=e}get onopen(){return this.#t.handler(\"open\")}set onopen(e){this.#t.setHandler(\"open\",e)}get onmessage(){return this.#t.handler(\"message\")}set onmessage(e){this.#t.setHandler(\"message\",e)}get onclosing(){return this.#t.handler(\"closing\")}set onclosing(e){this.#t.setHandler(\"closing\",e)}get onclose(){return this.#t.handler(\"close\")}set onclose(e){this.#t.setHandler(\"close\",e)}get onbufferedamountlow(){return this.#t.handler(\"bufferedamountlow\")}set onbufferedamountlow(e){this.#t.setHandler(\"bufferedamountlow\",e)}get onerror(){return this.#t.handler(\"error\")}set onerror(e){this.#t.setHandler(\"error\",e)}send(e){if(this.#e.readyState!==\"open\")throw new DOMException(`The channel ${this.label} is ${this.#e.readyState}`,\"InvalidStateError\");if(typeof e===\"string\")return this.#e.send(e);const t=ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);this.#e.send(t)}close(){if(this.#e.readyState===\"closing\"||this.#e.readyState===\"closed\")return;this.#e.close()}addEventListener(e,t,s){this.#t.addEventListener(e,t,s)}removeEventListener(e,t,s){this.#t.removeEventListener(e,t,s)}dispatchEvent(e){return this.#t.dispatch(e,...e instanceof MessageEvent?[e.data]:[])}on(e,t){this.#t.on(e,t);return this}once(e,t){this.#t.once(e,t);return this}off(e,t){this.#t.off(e,t);return this}};var ZR=new WeakMap;var Ag=class{static{a(this,\"RtpSender\")}#e;constructor(e){this.#e=e;ZR.set(this,e)}get track(){return this.#e.track?cn(this.#e.track):null}async replaceTrack(e){await this.#e.replaceTrack(e?er(e):null)}setStreams(...e){this.#e.setStreams(e.map(t=>new Br({id:t})))}};var Ig=class{static{a(this,\"RtpReceiver\")}#e;constructor(e){this.#e=e}get track(){return cn(this.#e.track,this.#e)}};var XR=new WeakMap;var YR=new WeakMap;var JR=new WeakMap;var Og=class{static{a(this,\"RtpTransceiver\")}#e;constructor(e){this.#e=e}get mid(){return this.#e.mid}get kind(){return this.#e.kind}get direction(){return this.#e.direction}set direction(e){this.#e.direction=e}get currentDirection(){return this.#e.currentDirection}get sender(){return pd(this.#e.sender)}get receiver(){return md(this.#e.receiver)}stop(){this.#e.stop()}};function pd(r){let e=XR.get(r);if(!e){e=new Ag(r);XR.set(r,e)}return e}a(pd,\"senderOf\");function Wc(r){return ZR.get(r)}a(Wc,\"engineSenderOf\");function md(r){let e=YR.get(r);if(!e){e=new Ig(r);YR.set(r,e)}return e}a(md,\"receiverOf\");function gd(r){let e=JR.get(r);if(!e){e=new Og(r);JR.set(r,e)}return e}a(gd,\"transceiverOf\");var Rr=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Zr=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var kg=class{static{a(this,\"IceCandidate\")}constructor(e){this.candidate=e.candidate;this.sdpMid=e.sdpMid??null;this.sdpMLineIndex=e.sdpMLineIndex??null;this.usernameFragment=e.usernameFragment??null}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};function yd(r){return r?{type:r.type,sdp:r.sdp}:null}a(yd,\"plainDescription\");var xt=class Nre extends Ys{static{a(this,\"PeerConnection\")}#e=new vo(this);#t=new WeakMap;#r;#s=false;async init(){const e={iceServers:this.iceServers,iceTransportPolicy:this.iceTransportPolicy,iceUseIpv4:this.iceUseIpv4,iceUseIpv6:this.iceUseIpv6,codecs:this.codecs,headerExtensions:this.headerExtensions,...this.icePortRange?{icePortRange:this.icePortRange}:{},...this.iceAdditionalHostAddresses?{iceAdditionalHostAddresses:this.iceAdditionalHostAddresses}:{}};let t;if(this.threads){t=await(await this.getObject(this.threads)).open(e)}else{t=new dd(KR(e));_g.set(this,t)}this.#r=t;t.onIceCandidate.subscribe(s=>{const n=s?new kg(s):null;this.#n(\"icecandidate\",{candidate:n},n?n.toJSON():null)});t.onDataChannel.subscribe(s=>{const n=this.#u(s);this.#n(\"datachannel\",{channel:n},n)});t.on(\"track\",s=>{const n=cn(s.track,s.receiver);const i=s.streams.map(c=>c.id);const o=gd(s.transceiver);this.#n(\"track\",{track:n,streams:i.map(c=>({id:c})),receiver:md(s.receiver),transceiver:o},n,i,o)});t.onTransceiverAdded.subscribe(s=>{s.sender.onPictureLossIndication.subscribe(()=>{if(s.sender.track)WE(cn(s.sender.track))})});t.onNegotiationneeded.subscribe(()=>this.#n(\"negotiationneeded\",{}));t.connectionStateChange.subscribe(s=>this.#n(\"connectionstatechange\",{},s));t.iceConnectionStateChange.subscribe(s=>this.#n(\"iceconnectionstatechange\",{},s));t.iceGatheringStateChange.subscribe(s=>this.#n(\"icegatheringstatechange\",{},s));t.signalingStateChange.subscribe(s=>this.#n(\"signalingstatechange\",{},s))}async destroy(){this.#s=true;await this.#r?.close()}get connectionState(){return this.#r.connectionState}get iceConnectionState(){return this.#r.iceConnectionState}get iceGatheringState(){return this.#r.iceGatheringState}get signalingState(){return this.#r.signalingState}get localDescription(){return yd(this.#r.localDescription)}get remoteDescription(){return yd(this.#r.remoteDescription)}get sctp(){const e=this.#r.sctpTransport;return e?{maxMessageSize:e.remoteMaxMessageSize}:null}get onicecandidate(){return this.#e.handler(\"icecandidate\")}set onicecandidate(e){this.#e.setHandler(\"icecandidate\",e)}get ondatachannel(){return this.#e.handler(\"datachannel\")}set ondatachannel(e){this.#e.setHandler(\"datachannel\",e)}get ontrack(){return this.#e.handler(\"track\")}set ontrack(e){this.#e.setHandler(\"track\",e)}get onnegotiationneeded(){return this.#e.handler(\"negotiationneeded\")}set onnegotiationneeded(e){this.#e.setHandler(\"negotiationneeded\",e)}get onconnectionstatechange(){return this.#e.handler(\"connectionstatechange\")}set onconnectionstatechange(e){this.#e.setHandler(\"connectionstatechange\",e)}get oniceconnectionstatechange(){return this.#e.handler(\"iceconnectionstatechange\")}set oniceconnectionstatechange(e){this.#e.setHandler(\"iceconnectionstatechange\",e)}get onicegatheringstatechange(){return this.#e.handler(\"icegatheringstatechange\")}set onicegatheringstatechange(e){this.#e.setHandler(\"icegatheringstatechange\",e)}get onsignalingstatechange(){return this.#e.handler(\"signalingstatechange\")}set onsignalingstatechange(e){this.#e.setHandler(\"signalingstatechange\",e)}async createOffer(e={}){return yd(await this.#r.createOffer(e))}async createAnswer(){return yd(await this.#r.createAnswer())}async setLocalDescription(e){await this.#r.setLocalDescription(e)}async setRemoteDescription(e){await this.#r.setRemoteDescription(e)}async addIceCandidate(e){if(!e?.candidate)return;await this.#r.addIceCandidate({candidate:e.candidate,sdpMid:e.sdpMid??void 0,sdpMLineIndex:e.sdpMLineIndex??void 0,usernameFragment:e.usernameFragment??void 0})}createDataChannel(e,t={}){return this.#u(this.#r.createDataChannel(e,t))}addTrack(e,...t){const s=t.map(n=>new Br({id:n}));return pd(this.#r.addTrack(er(e),...s))}removeTrack(e){this.#r.removeTrack(Wc(e))}addTransceiver(e,t={}){const s=(t.streams??[]).map(n=>new Br({id:n}));return gd(this.#r.addTransceiver(typeof e===\"string\"?e:er(e),{direction:t.direction??\"sendrecv\",streams:s}))}getTransceivers(){return this.#r.getTransceivers().map(gd)}getSenders(){return this.#r.getSenders().map(pd)}getReceivers(){return this.#r.getReceivers().map(md)}restartIce(){this.#r.restartIce()}getConfiguration(){const e=this.#r.getConfiguration();return{iceServers:e.iceServers,iceTransportPolicy:e.iceTransportPolicy}}setConfiguration(e){const t={};if(e.iceServers)t.iceServers=e.iceServers;if(e.iceTransportPolicy)t.iceTransportPolicy=e.iceTransportPolicy;this.#r.setConfiguration(t)}close(){if(this.#s)return;this.#s=true;this.#r.close().catch(()=>void 0);void this.dispose().catch(()=>void 0)}addEventListener(e,t,s){this.#e.addEventListener(e,t,s)}removeEventListener(e,t,s){this.#e.removeEventListener(e,t,s)}on(e,t){this.#e.on(e,t);return this}once(e,t){this.#e.once(e,t);return this}off(e,t){this.#e.off(e,t);return this}#u(e){let t=this.#t.get(e);if(!t){t=new hd(e);this.#t.set(e,t)}return t}#n(e,t,...s){if(this.#s&&e!==\"connectionstatechange\"&&e!==\"iceconnectionstatechange\"&&e!==\"signalingstatechange\")return;this.#e.fire(e,t,...s)}};Rr([Ve(I.Array().items(I.Object({urls:I.Alternatives(I.String(),I.Array().items(I.String())).required(),username:I.String().optional(),credential:I.String().optional()})).optional().default([])),Zr(\"design:type\",Array)],xt.prototype,\"iceServers\",void 0);Rr([Ve(I.String().valid(\"all\",\"relay\").optional().default(\"all\")),Zr(\"design:type\",String)],xt.prototype,\"iceTransportPolicy\",void 0);Rr([Ve(I.Array().items(I.Number().port()).length(2).optional()),Zr(\"design:type\",Array)],xt.prototype,\"icePortRange\",void 0);Rr([Ve(I.Array().items(I.String()).optional()),Zr(\"design:type\",Array)],xt.prototype,\"iceAdditionalHostAddresses\",void 0);Rr([Ve(I.Boolean().optional().default(true)),Zr(\"design:type\",Boolean)],xt.prototype,\"iceUseIpv4\",void 0);Rr([Ve(I.Boolean().optional().default(true)),Zr(\"design:type\",Boolean)],xt.prototype,\"iceUseIpv6\",void 0);Rr([Ve(I.Array().items(I.String().valid(...$u).insensitive()).optional().default(BE)),Zr(\"design:type\",Array)],xt.prototype,\"codecs\",void 0);Rr([Ve(I.Boolean().optional().default(false)),Zr(\"design:type\",Boolean)],xt.prototype,\"headerExtensions\",void 0);Rr([Ve(I.String().optional()),Zr(\"design:type\",String)],xt.prototype,\"threads\",void 0);xt=Rr([sm(),fa()],xt);var _P=5e3;function bd(r,e=_P){if(r.iceGatheringState===\"complete\")return Promise.resolve();return new Promise(t=>{const s=a(()=>{clearTimeout(i);r.off(\"icegatheringstatechange\",n);t()},\"done\");const n=a(o=>{if(o===\"complete\")s()},\"changed\");const i=setTimeout(s,e);r.on(\"icegatheringstatechange\",n)})}a(bd,\"gathered\");function CP(r){const e={candidates:[]};for(const t of r.split(/^(?=m=)/m)){const s=t.split(/\\r?\\n/);const n=s.find(i=>i.startsWith(\"a=mid:\"))?.slice(\"a=mid:\".length).trim();for(const i of s){if(i.startsWith(\"a=ice-ufrag:\"))e.ufrag??=i.slice(\"a=ice-ufrag:\".length).trim();else if(i.startsWith(\"a=ice-pwd:\"))e.pwd??=i.slice(\"a=ice-pwd:\".length).trim();else if(i.startsWith(\"a=candidate:\"))e.candidates.push({candidate:i.slice(2).trim(),...n===void 0?{}:{sdpMid:n}})}}return e}a(CP,\"iceOf\");async function Pg(r,e,t){const s=CP(e);const n=r.remoteDescription?.sdp??\"\";const i=[...n.matchAll(/^a=mid:(\\S+)/gm)].map(u=>u[1]);const o=a(async()=>{for(const{candidate:u,sdpMid:f}of s.candidates)await r.addIceCandidate({candidate:u,sdpMid:f??i[0]??null})},\"add\");const c=!!s.ufrag&&s.ufrag!==/^a=ice-ufrag:(\\S+)/m.exec(n)?.[1];if(c&&!t)return null;if(!c){if(!s.ufrag&&!s.candidates.length&&!/^a=end-of-candidates/m.test(e))throw new Error(\"The fragment has no ICE\");await o();return void 0}if(!s.pwd)throw new Error(\"The fragment of an ICE restart has no password\");const l=n.replace(/^a=ice-ufrag:.*$/gm,`a=ice-ufrag:${s.ufrag}`).replace(/^a=ice-pwd:.*$/gm,`a=ice-pwd:${s.pwd}`).replace(/^a=(candidate:.*|end-of-candidates)\\r?\\n/gm,\"\");await r.setRemoteDescription({type:\"offer\",sdp:l});await r.setLocalDescription();await o();await bd(r);return vP(r.localDescription?.sdp??\"\")}a(Pg,\"patchConnection\");function vP(r){const e=(r.split(/^(?=m=)/m)[1]??\"\").split(/\\r?\\n/);return[`a=ice-ufrag:${/^a=ice-ufrag:(\\S+)/m.exec(r)?.[1]??\"\"}`,`a=ice-pwd:${/^a=ice-pwd:(\\S+)/m.exec(r)?.[1]??\"\"}`,...e[0]?[e[0],...e.filter(t=>t.startsWith(\"a=mid:\")),...e.filter(t=>t.startsWith(\"a=candidate:\")),\"a=end-of-candidates\"]:[]].join(\"\\r\\n\")+\"\\r\\n\"}a(vP,\"fragmentOf\");var Vc={peerJoined:\"webrtc:peer-joined\",peerLeft:\"webrtc:peer-left\",signal:\"webrtc:signal\"};var Xc={label:\"webrtc.control\",id:1023};var Sd=class{static{a(this,\"Emitter\")}#e=new Map;on(e,t){let s=this.#e.get(e);if(!s){s=new Set;this.#e.set(e,s)}s.add(t);return this}once(e,t){const s=a((...n)=>{this.off(e,s);t(...n)},\"wrapper\");return this.on(e,s)}off(e,t){this.#e.get(e)?.delete(t);return this}emit(e,...t){const s=this.#e.get(e);if(!s?.size)return false;for(const n of[...s]){try{n(...t)}catch(i){queueMicrotask(()=>{throw i})}}return true}listened(e){return!!this.#e.get(e)?.size}};function QR(r){r.unref?.();return r}a(QR,\"unrefTimer\");var AP=200;function e_(r){return new Set([...(r??\"\").matchAll(/^a=ice-ufrag:(\\S+)/gm)].map(e=>e[1]))}a(e_,\"ufragsOf\");var IP=5e3;var Yc=class extends Sd{static{a(this,\"Peer\")}#e;#t;#r;#s;#u;#n;#a=false;#o=false;#c=false;#i=[];#f=0;#m=[];#l=false;#d=false;#h=false;#g;#w;#E;#y=new Set;#I;#L=new Promise(e=>{this.#I=e});constructor(e,t,s,n){super();this.#e=e;this.id=t;this.#t=s;this.#r=n;this.polite=e.polite??e.localId<t;this.#n=this.#u=this.#P()}get connection(){return this.#s}get metadata(){return this.#t}get session(){return this.#r}get away(){return this.#d}get closed(){return this.#l}get ready(){return this.#u}get negotiated(){return this.#L}createDataChannel(e,t){if(!this.#e.relay)return this.#s.createDataChannel(e,t);if(t?.negotiated||t?.protocol)throw new TypeError(\"A channel through the media server has no protocol of its own and is not negotiated\");return this.#O(this.#s.createDataChannel(e,{...t,protocol:this.id}))}pause(e){this.#b(e,false)}resume(e){this.#b(e,true)}restartIce(){if(this.#l)return;if(this.#e.relay)return this.#e.relay.restartIce();if(!this.#e.signalingUp){this.#h=true;return}this.#h=false;this.#s.restartIce()}close(){if(this.#l)return;this.#l=true;clearTimeout(this.#g);if(this.#e.relay){if(this.#w)this.#E?.off(\"connectionstatechange\",this.#w);for(const e of[...this.#y]){try{e.close()}catch{}}this.#y.clear()}else{try{this.#s?.close()}catch{}}this.emit(\"close\");this.#e.closed(this)}receive(e){if(this.#e.relay)return;this.#T(()=>this.#_(e))}#T(e){this.#n=this.#n.then(e).catch(t=>this.#A(t))}rejoined(e){this.#d=false;this.#t=e;this.emit(\"metadata\",e)}left(){if(!this.#e.relay&&this.#s?.connectionState===\"connected\"){this.#d=true}else{this.close()}}async#p(e){this.#E=e;await e.ready;await e.negotiated;if(this.#l)return;this.#s=e.connection;this.#w=t=>void this.emit(\"connectionstatechange\",t);e.on(\"connectionstatechange\",this.#w)}#O(e){this.#y.add(e);e.addEventListener(\"close\",()=>this.#y.delete(e));return e}signalingUp(){if(this.#h)this.restartIce()}relayedTrack(e){if(!this.#l)this.emit(\"track\",e)}relayedChannel(e){if(this.#l)return e.close();this.emit(\"datachannel\",this.#O(e))}#b(e,t){if(this.#l||!this.#s)return;const s=this.#s.getTransceivers().find(o=>o.receiver.track===e);if(!s)return;if(this.#e.relay){if(s.mid!==null)this.#e.control?.({type:t?\"resume\":\"pause\",mid:s.mid});return}const n=s.direction===\"sendrecv\"||s.direction===\"sendonly\";const i=t?n?\"sendrecv\":\"recvonly\":n?\"sendonly\":\"inactive\";if(s.direction!==\"stopped\"&&s.direction!==i)s.direction=i}async#P(){if(this.#e.relay)return await this.#p(this.#e.relay);const e=await this.#e.create();this.#s=e;if(this.#l){e.close();return}e.addEventListener(\"negotiationneeded\",()=>this.#T(()=>this.#R()));e.addEventListener(\"icecandidate\",t=>{const s=t.candidate;if(!s?.candidate)return;const n=typeof s.toJSON===\"function\"?s.toJSON():s;const i={candidate:n.candidate,sdpMid:n.sdpMid??null,sdpMLineIndex:n.sdpMLineIndex??null,usernameFragment:n.usernameFragment??null};if(this.#f){this.#m.push(i)}else{void this.#k({candidate:i})}});e.addEventListener(\"connectionstatechange\",()=>this.#M());e.addEventListener(\"datachannel\",t=>void this.emit(\"datachannel\",t.channel));e.addEventListener(\"track\",t=>void this.emit(\"track\",t))}#k(e){return this.#e.send(this.id,e).catch(t=>this.#A(t))}async#x(){this.#f++;try{await this.#s.setLocalDescription();const e=this.#s.localDescription;if(e)await this.#k({description:{type:e.type,sdp:e.sdp}})}finally{this.#f--;if(!this.#f)for(const e of this.#m.splice(0))void this.#k({candidate:e})}}async#R(){if(this.#l)return;if(this.#s.signalingState!==\"stable\"){this.#a=true;return}this.#a=false;try{this.#o=true;await this.#x()}catch(e){this.#A(e)}finally{this.#o=false}}async#_(e){if(this.#l)return;const t=this.#s;if(e.description){const s=e.description;const n=s.type===\"offer\"&&(this.#o||t.signalingState!==\"stable\");this.#c=!this.polite&&n;if(this.#c)return;await t.setRemoteDescription(s);const i=e_(s.sdp);const o=this.#i;this.#i=[];for(const c of o){if(!c.usernameFragment||i.has(c.usernameFragment)){await this.#C(c)}else{this.#i.push(c)}}if(s.type===\"offer\")await this.#x();if(t.signalingState===\"stable\"){this.#I();if(this.#a)await this.#R()}}else if(e.candidate){const s=t.remoteDescription;const n=e.candidate.usernameFragment;if(!s||n&&!e_(s.sdp).has(n)){if(!this.#c){this.#i.push(e.candidate);if(this.#i.length>AP)this.#i.shift()}return}await this.#C(e.candidate)}}async#C(e){try{await this.#s.addIceCandidate(e)}catch(t){if(!this.#c)throw t}}#M(){if(this.#l)return;const e=this.#s.connectionState;clearTimeout(this.#g);this.emit(\"connectionstatechange\",e);if(e===\"failed\"){this.#v()}else if(e===\"disconnected\"){this.#g=QR(setTimeout(()=>{if(this.#s.connectionState===\"disconnected\")this.#v()},IP))}else if(e===\"closed\"){this.close()}}#v(){if(this.#d)return this.close();this.restartIce()}#A(e){if(!this.#l)this.emit(\"error\",e)}};function Ps(r,e){return JSON.stringify([r,e])}a(Ps,\"trackKey\");var OP=5e3;var kP=1e3;function PP(r){try{const e=JSON.parse(r);return Array.isArray(e)&&e.length===2&&e.every(t=>typeof t===\"string\")?e:void 0}catch{return void 0}}a(PP,\"routeOf\");var wd=1024*1024;function t_(r,e,t=[]){const s=WR(r).sctp;const n=r.maxRetransmits===null&&r.maxPacketLifeTime===null;const i=[];let o=0;let c=0;e.bufferedAmountLowThreshold=wd/2;const l=a(()=>{while(i.length&&e.readyState===\"open\"&&e.bufferedAmount<wd){const{data:f,size:d}=i.shift();c-=d;e.send(f);if(n){o-=d;s.releaseReceived(d)}}},\"drain\");const u=a(f=>{const d=typeof f===\"string\"||Buffer.isBuffer(f)?f:Buffer.from(f);if(e.readyState===\"closing\"||e.readyState===\"closed\")return;if(!i.length&&e.readyState===\"open\"&&e.bufferedAmount<wd)return e.send(d);const h=typeof d===\"string\"?Buffer.byteLength(d):d.length;if(!n&&(e.readyState===\"open\"||c+h>wd))return;i.push({data:d,size:h});c+=h;if(n){o+=h;s.holdReceived(h)}},\"relayed\");t.forEach(u);r.on(\"message\",u);e.on(\"open\",l);e.on(\"bufferedamountlow\",l);e.on(\"close\",()=>{i.length=0;c=0;if(o)s.releaseReceived(o);o=0})}a(t_,\"relay\");function r_(r,e){const t=Cg(r);return e.mid===null?void 0:t.getTransceivers().find(s=>s.mid===e.mid)}a(r_,\"engineTransceiverOf\");var Ed=class{static{a(this,\"SFURoom\")}#e;#t=new Map;#r=new Map;#s=new Set;#u=new WeakSet;#n=new Map;#a=new Map;#o=new Map;#c=new Set;#i=false;constructor(e,t){this.#e=e;this.name=t;this.ready=this.#d()}get empty(){return!this.members.length&&!this.#r.size}get viewers(){return this.#r.size}get closed(){return this.#i}get members(){return[...this.#t.values()].filter(e=>!e.cascade).map(e=>e.id)}get tracks(){return[...this.#s].filter(e=>!e.remote).map(e=>e.track)}track(e,t){for(const o of this.#s){if(!o.remote&&o.track.peerId===e&&o.track.id===t)return o.media}const s=Ps(e,t);const n=this.#z(s);if(!n)return void 0;let i=this.#o.get(s);if(!i){const o=n.codec??{mimeType:n.track.codec,clockRate:n.track.kind===\"audio\"?48e3:9e4};const c=VE(n.track.kind,new ft(o),t,{requestKeyFrame:a(()=>this.#F(s)?.media.requestKeyFrame(),\"requestKeyFrame\"),wanted:a(l=>{const u=this.#o.get(s);if(!u)return;u.wanted=l;this.#U(s);this.#S()},\"wanted\")});i={track:c.track,receive:c.receive,wanted:false};this.#o.set(s,i)}return i.track}cascades(){return Object.fromEntries([...this.#t.values()].filter(e=>!!e.cascade).map(e=>[e.id,{sends:e.subscriptions.size,receives:e.publications.size}]))}async close(){if(this.#i)return;this.#i=true;for(const e of[...this.#t.values()])this.#p(e);for(const e of[...this.#r.values()])this.#l(e);for(const e of[...this.#o.keys()])this.#j(e);for(const e of[...this.#c])e.channel.close();await this.#e.signaling.leave(this.#e.id,this.name).catch(()=>void 0)}async play(e,t,s){const n=await this.#e.connect();const i=[];let o=false;const c={connection:n,ready:Promise.resolve(),get closed(){return o},close:a(()=>{if(o)return;o=true;n.close();for(const u of i.splice(0))u()},\"close\")};const l={id:e,leg:c,transceivers:new Map,attached:new Map,select:s,feeding:Promise.resolve()};n.on(\"connectionstatechange\",u=>{if(u===\"failed\"||u===\"closed\")this.#l(l)});try{await n.setRemoteDescription(t);for(const u of n.getTransceivers()){if(l.transceivers.has(u.kind))continue;l.transceivers.set(u.kind,u);u.direction=\"sendonly\"}if(!l.transceivers.size)throw new Error(\"The offer has no audio and no video\");await n.setLocalDescription();await bd(n);if(o)throw new Error(`The connection is ${n.connectionState}`)}catch(u){c.close();throw u}this.#r.set(e,l);this.#e.changed?.(this);await this.#f(l);return{answer:n.localDescription,patch:a((u,f)=>Pg(n,u,f),\"patch\"),ended:a(u=>o?u():i.push(u),\"ended\"),close:a(()=>this.#l(l),\"close\"),source:a(()=>l.source,\"source\")}}#f(e){e.feeding=e.feeding.then(()=>this.#m(e)).catch(()=>void 0);return e.feeding}async#m(e){if(e.leg.closed)return;const t=[...this.tracks,...[...this.#D()].map(c=>c.track)];const s=e.select?await e.select(t):void 0;if(e.leg.closed)return;const n=[...new Set(t.map(c=>c.peerId))];const i=s??n.filter(c=>c.startsWith(\"whip:\")).at(-1)??n[0];const o=e.source;e.source=i!==void 0&&n.includes(i)?i:void 0;if(e.source!==o){this.#e.sourced?.(e.id,e.source);this.#S()}for(const[c,l]of e.transceivers){const u=e.source===void 0?void 0:[...this.#s].find(f=>f.track.peerId===e.source&&f.track.kind===c);if(e.attached.get(c)===u)continue;e.attached.delete(c);try{await l.sender.replaceTrack(u?.media??null)}catch{this.#e.emit(\"unsupported\",this.name,e.id,u.track);await l.sender.replaceTrack(null).catch(()=>void 0);continue}if(!u)continue;e.attached.set(c,u);if(c===\"video\")u.media.requestKeyFrame()}}#l(e){if(this.#r.get(e.id)!==e)return e.leg.close();this.#r.delete(e.id);e.leg.close();if(!this.#i)this.#e.changed?.(this);if(!this.#i&&this.empty)this.#e.emptied(this)}async publish(e,t){const s=await this.#e.connect();const n=[];let i=false;const o={connection:s,ready:Promise.resolve(),get closed(){return i},close:a(()=>{if(i)return;i=true;s.close();for(const l of n.splice(0))l()},\"close\")};const c={id:e,leg:o,metadata:void 0,publications:new Map,subscriptions:new Map,streams:new Map,streamIds:new Map,transceivers:new Set};this.#t.set(e,c);this.#e.changed?.(this);s.addEventListener(\"track\",l=>this.#x(c,l));s.on(\"connectionstatechange\",l=>{if(l===\"failed\"||l===\"closed\")this.#p(c)});s.on(\"signalingstatechange\",l=>{if(l===\"stable\")setImmediate(()=>this.#v(c))});try{await s.setRemoteDescription(t);await s.setLocalDescription();await bd(s);if(i)throw new Error(`The connection is ${s.connectionState}`);await this.#e.signaling.join(e,this.name,{role:\"whip\",receive:a(()=>void 0,\"receive\")})}catch(l){this.#p(c);throw l}return{answer:s.localDescription,patch:a((l,u)=>Pg(s,l,u),\"patch\"),ended:a(l=>i?l():n.push(l),\"ended\"),close:a(()=>this.#p(c),\"close\")}}async#d(){const e=await this.#e.signaling.join(this.#e.id,this.name,{role:\"sfu\",receive:a((t,s)=>this.#w(t,s),\"receive\")});for(const t of e.peers){if(this.#g(t))this.#E(t.peerId,t.metadata,t.session);else this.#h(t)}}#h(e){if(e.role===\"sfu\"){if(e.peerId!==this.#e.id&&!this.#t.has(e.peerId))this.#$(e.peerId)}else if(!e.role&&e.sfu){this.#n.set(e.peerId,e.sfu)}this.#T()}#g(e){return!e.role&&e.sfu===this.#e.id}#w(e,t){if(this.#i)return;switch(e){case Vc.peerJoined:{const s=t;const n=this.#t.get(s.peerId);if(!this.#g(s)){if(!s.role&&n?.peer)this.#p(n);this.#h(s);return}this.#n.delete(s.peerId);if(n&&s.session!==void 0&&n.session!==s.session)this.#p(n);if(n&&this.#t.get(s.peerId)===n){const i=JSON.stringify(n.metadata)!==JSON.stringify(s.metadata);n.metadata=s.metadata;if(i)this.#G(n);return}this.#E(s.peerId,s.metadata,s.session);return}case Vc.peerLeft:{const s=t.peerId;this.#n.delete(s);const n=this.#t.get(s);if(n)this.#p(n);return}case Vc.signal:{const s=t;let n=this.#t.get(s.from);if(!n){if(this.#n.has(s.from))return;n=s.from.startsWith(\"sfu:\")?this.#$(s.from):this.#E(s.from,void 0,s.session)}if(n.cascade)for(const o of s.streams??[])n.cascade.received.set(o.id,o);const i={};if(s.description)i.description=s.description;if(s.candidate)i.candidate=s.candidate;n.peer?.receive(i);return}}}#E(e,t,s){const n={localId:this.#e.id,create:a(()=>this.#e.connect(),\"create\"),send:a((c,l)=>this.#O(o,l),\"send\"),signalingUp:true,closed:a(()=>void 0,\"closed\"),polite:false};const i=new Yc(n,e,t,s);const o={id:e,leg:i,peer:i,metadata:t,session:s,publications:new Map,subscriptions:new Map,streams:new Map,streamIds:new Map,transceivers:new Set};this.#t.set(e,o);this.#e.changed?.(this);this.#B();this.#T();i.on(\"error\",()=>void 0);i.on(\"track\",c=>this.#x(o,c));i.on(\"datachannel\",c=>this.#y(o,c));i.ready.then(async()=>{if(i.closed)return;const c=i.connection;c.on(\"signalingstatechange\",h=>{if(h===\"stable\")setImmediate(()=>this.#v(o))});c.on(\"connectionstatechange\",h=>{if(h===\"connected\")this.#K(o)});const l=o.metadata;const u=new Map([...this.#s].map(h=>[h,this.#P(o,h)]));const f=[...u.values()].some(h=>h instanceof Promise)?await this.#k(u):new Map;if(i.closed||this.#t.get(o.id)!==o)return;const d=c.createDataChannel(Xc.label,{negotiated:true,id:Xc.id});d.on(\"message\",h=>this.#A(o,h));o.control=d;for(const[h,p]of u){if(!this.#s.has(h))continue;if(o.metadata===l)this.#b(o,h,f.get(h)??p);else this.#b(o,h)}},()=>this.#p(o));return o}#y(e,t){let s=e.id;let n=t.protocol;if(e.cascade){const c=PP(t.protocol);if(!c)return t.close();[s,n]=c}const i=[];const o=a(c=>i.push(c),\"keep\");t.on(\"message\",o);this.#I({member:e,channel:t,source:s,target:n,early:i,keep:o})}#I(e){const{member:t,channel:s,source:n,target:i,early:o,keep:c}=e;if(s.readyState===\"closing\"||s.readyState===\"closed\")return;const l=this.#t.get(i);let u;let f;if(l?.cascade||i.startsWith(\"sfu:\"))return s.close();if(l){if(l===t||!l.peer||l.leg.closed)return s.close();u=l;f=n}else{const h=this.#n.get(i);if(t.cascade&&h!==void 0)return s.close();u=t.cascade||h===void 0?void 0:this.#t.get(h);f=JSON.stringify([n,i])}if(!u)return this.#L(e);const d=u;d.leg.ready.then(()=>d.cascade?d.peer.negotiated:void 0).then(()=>{s.off(\"message\",c);if(d.leg.closed||s.readyState===\"closed\")return s.close();const h=d.leg.connection.createDataChannel(s.label,{protocol:f,ordered:s.ordered,...s.maxRetransmits!==null?{maxRetransmits:s.maxRetransmits}:{},...s.maxPacketLifeTime!==null?{maxPacketLifeTime:s.maxPacketLifeTime}:{}});t_(s,h,o);t_(h,s);s.on(\"close\",()=>h.close());h.on(\"close\",()=>s.close())},()=>s.close())}#L(e){if(this.#c.has(e))return;this.#c.add(e);e.timer=setTimeout(()=>{this.#c.delete(e);e.channel.close()},OP);e.timer.unref();e.channel.on(\"close\",()=>{clearTimeout(e.timer);this.#c.delete(e)})}#T(){for(const e of[...this.#c]){const t=this.#t.has(e.target)||this.#t.has(this.#n.get(e.target)??\"\");if(!t)continue;this.#c.delete(e);clearTimeout(e.timer);this.#I(e)}}#p(e){if(this.#t.get(e.id)!==e)return;this.#t.delete(e.id);for(const t of[...e.publications.values()])this.#R(t);e.leg.close();if(!e.peer)this.#e.signaling.leave(e.id,this.name).catch(()=>void 0);if(e.cascade){for(const t of e.cascade.offered.keys())this.#j(t);for(const t of[...this.#c])if(this.#n.get(t.target)===e.id)t.channel.close();if(!this.#i)this.#H()}else{this.#a.delete(e.id);if(!this.#i)this.#S()}if(!this.#i)this.#e.changed?.(this);if(!this.#i&&this.empty)this.#e.emptied(this)}async#O(e,t){await this.#e.signaling.signal(this.#e.id,this.name,e.id,{...t,...t.description?{streams:[...e.streams.values()]}:{}})}#b(e,t,s=this.#P(e,t)){if(e===t.publisher||!e.peer||e.leg.closed)return;if(e.cascade){if(!t.remote&&e.cascade.wanted.has(Ps(t.track.peerId,t.track.id)))this.#_(e,t).catch(()=>void 0);return}const n=s;if(n===void 0)return;if(typeof n===\"boolean\"){if(n)this.#_(e,t).catch(()=>void 0);return}n.then(i=>i&&this.#t.get(e.id)===e&&!e.leg.closed&&this.#s.has(t)?this.#_(e,t):void 0).catch(()=>void 0)}#P(e,t){if(e===t.publisher||!e.peer||e.leg.closed||e.cascade)return void 0;return this.#e.select({peerId:e.id,metadata:e.metadata,session:e.session},t.track)}async#k(e){const t=new Map;const s=[];for(const[i,o]of e){if(o instanceof Promise)s.push(o.then(c=>void t.set(i,c),()=>void t.set(i,false)))}if(!s.length)return t;let n;await Promise.race([Promise.all(s),new Promise(i=>{n=setTimeout(i,kP)})]);clearTimeout(n);return t}#x(e,t){const s=e.publications.get(t.transceiver);if(s)this.#R(s);const n=r_(e.leg.connection,t.transceiver);let i=e.id;let o=t.streams[0]?.id??\"\";if(e.cascade){const u=e.cascade.received.get(o);if(!u)return;i=u.peerId;o=u.stream}const c={room:this.name,peerId:i,id:n?.receiver.remoteTrackId??t.transceiver.mid??t.track.id,kind:t.track.kind,codec:t.track.codec??\"\",stream:o};const l={track:c,media:t.track,transceiver:t.transceiver,publisher:e,remote:!!e.cascade};e.publications.set(t.transceiver,l);this.#s.add(l);if(l.remote){this.#U(Ps(c.peerId,c.id))}else{this.#e.emit(\"publish\",c);this.#N()}for(const u of this.#t.values())this.#b(u,l);for(const u of this.#r.values())void this.#f(u)}#R(e){if(!this.#s.delete(e))return;if(e.publisher.publications.get(e.transceiver)===e)e.publisher.publications.delete(e.transceiver);for(const t of this.#t.values())this.#C(t,e);if(e.remote){this.#U(Ps(e.track.peerId,e.track.id))}else{this.#e.emit(\"unpublish\",e.track);this.#N()}for(const t of this.#r.values())void this.#f(t)}async#_(e,t){if(e.subscriptions.has(t))return;const s=e.leg.connection;const n=this.#M(e,t.track);const i=new Set([...e.subscriptions.values()].map(c=>c.transceiver));const o=s.getTransceivers().find(c=>e.transceivers.has(c)&&!i.has(c)&&!c.sender.track&&c.direction===\"inactive\"&&c.currentDirection===\"inactive\"&&c.kind===t.track.kind&&r_(s,c)?.sender.codec?.mimeType.toLowerCase()===t.track.codec.toLowerCase());if(!o){const c=s.addTransceiver(t.media,{direction:\"sendonly\",streams:[n]});if(e.cascade)Wc(c.sender).trackId=t.track.id;e.transceivers.add(c);e.subscriptions.set(t,{transceiver:c,started:false,paused:false});return}e.subscriptions.set(t,{transceiver:o,started:false,paused:false});if(e.cascade)Wc(o.sender).trackId=t.track.id;await o.sender.replaceTrack(t.media);o.sender.setStreams(n);o.direction=\"sendonly\"}#C(e,t){const s=e.subscriptions.get(t);if(!s)return;e.subscriptions.delete(t);if(e.leg.closed)return;try{s.transceiver.direction=\"inactive\";s.transceiver.sender.replaceTrack(null).catch(()=>void 0)}catch{}}#M(e,t){const s=JSON.stringify([t.peerId,t.stream||t.id]);let n=e.streamIds.get(s);if(!n){n=`s${e.streamIds.size+1}`;e.streamIds.set(s,n);e.streams.set(n,{id:n,peerId:t.peerId,stream:t.stream})}return n}#v(e){if(e.leg.closed||e.leg.connection.signalingState!==\"stable\")return;for(const t of[...e.publications.values()]){const s=t.transceiver.currentDirection;if(s===\"inactive\"||s===\"sendonly\"||s===\"stopped\")this.#R(t)}for(const[t,s]of[...e.subscriptions]){const n=s.transceiver.currentDirection;if(n===\"stopped\"){e.subscriptions.delete(t);this.#e.emit(\"unsupported\",this.name,e.id,t.track)}else if(!s.started&&(n===\"sendonly\"||n===\"sendrecv\")){s.started=true;if(t.track.kind===\"video\")t.media.requestKeyFrame()}}}#A(e,t){let s;try{s=JSON.parse(typeof t===\"string\"?t:Buffer.from(t).toString())}catch{return}if(e.cascade)return this.#q(e,e.cascade,s);if(s?.type!==\"pause\"&&s?.type!==\"resume\")return;for(const[n,i]of e.subscriptions){if(i.transceiver.mid!==s.mid)continue;const o=s.type===\"pause\";if(i.paused===o)return;i.paused=o;i.transceiver.sender.replaceTrack(o?null:n.media).catch(()=>void 0);if(!o&&n.track.kind===\"video\")n.media.requestKeyFrame();return}}#$(e){const t={localId:this.#e.id,create:a(()=>this.#e.connect(),\"create\"),send:a((o,c)=>this.#O(i,c),\"send\"),signalingUp:true,closed:a(()=>void 0,\"closed\"),polite:this.#e.id>e};const s=new Yc(t,e,void 0,void 0);const n={offered:new Map,wanted:new Set,received:new Map};const i={id:e,leg:s,peer:s,metadata:void 0,publications:new Map,subscriptions:new Map,streams:new Map,streamIds:new Map,transceivers:new Set,cascade:n};this.#t.set(e,i);this.#T();s.on(\"error\",()=>void 0);s.on(\"track\",o=>this.#x(i,o));s.on(\"datachannel\",o=>this.#y(i,o));s.ready.then(()=>s.polite?s.negotiated:void 0).then(()=>{if(s.closed)return;const o=s.connection;o.on(\"signalingstatechange\",l=>{if(l===\"stable\")setImmediate(()=>this.#v(i))});const c=o.createDataChannel(Xc.label,{negotiated:true,id:Xc.id});c.on(\"message\",l=>this.#A(i,l));c.on(\"open\",()=>{n.toldTracks=void 0;n.toldWants=void 0;this.#N();this.#S()});i.control=c},()=>this.#p(i));return i}#q(e,t,s){if(!t.heard){t.heard=true;t.toldTracks=void 0;t.toldWants=void 0;this.#N();this.#S()}if(s?.type===\"tracks\"&&Array.isArray(s.tracks)){const n=t.offered;t.offered=new Map(s.tracks.filter(i=>typeof i?.track?.peerId===\"string\"&&typeof i.track.id===\"string\").map(i=>[Ps(i.track.peerId,i.track.id),{track:{...i.track,room:this.name},...i.codec?{codec:i.codec}:{}}]));for(const i of n.keys())if(!t.offered.has(i))this.#j(i);this.#H();this.#B();for(const i of this.#r.values())void this.#f(i)}else if(s?.type===\"want\"&&Array.isArray(s.keys)){t.wanted=new Set(s.keys.filter(n=>typeof n===\"string\"));for(const n of[...this.#s]){if(n.remote)continue;if(t.wanted.has(Ps(n.track.peerId,n.track.id)))this.#b(e,n);else this.#C(e,n)}}}*#D(){for(const e of this.#t.values())if(e.cascade)yield*e.cascade.offered.values()}#z(e){for(const t of this.#t.values()){const s=t.cascade?.offered.get(e);if(s)return s}return void 0}#F(e){for(const t of this.#s){if(t.remote&&Ps(t.track.peerId,t.track.id)===e)return t}return void 0}#H(){this.#e.known?.(this,[...this.#D()])}#N(){const e=[...this.#s].filter(s=>!s.remote).map(s=>{const n=er(s.media).codec;return{track:s.track,...n?{codec:{payloadType:n.payloadType,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,parameters:n.parameters}}:{}}});const t=JSON.stringify({type:\"tracks\",tracks:e});for(const s of this.#t.values()){if(!s.cascade||s.control?.readyState!==\"open\"||s.cascade.toldTracks===t)continue;s.cascade.toldTracks=t;s.control.send(t)}}#S(){if(this.#i)return;const e=new Set([...this.#r.values()].map(t=>t.source).filter(t=>t!==void 0));for(const t of this.#t.values()){const s=t.cascade;if(!s||t.control?.readyState!==\"open\")continue;const n=[];for(const[o,{track:c}]of s.offered){const l=[...this.#t.values()].some(u=>!!u.peer&&!u.cascade&&!u.leg.closed&&u.id!==c.peerId&&this.#a.get(u.id)?.get(o)===true);if(l||e.has(c.peerId)||this.#o.get(o)?.wanted)n.push(o)}const i=JSON.stringify({type:\"want\",keys:n.sort()});if(s.toldWants===i)continue;s.toldWants=i;t.control.send(i)}}#G(e){if(!e.peer||e.cascade)return;this.#a.delete(e.id);this.#B();if(!e.control)return;const t={peerId:e.id,metadata:e.metadata,session:e.session};for(const s of[...this.#s]){if(s.publisher===e)continue;const n=a(o=>{if(this.#t.get(e.id)!==e||e.leg.closed||!this.#s.has(s))return;if(o)this.#_(e,s).catch(()=>void 0);else this.#C(e,s)},\"apply\");const i=this.#e.select(t,s.track);if(typeof i===\"boolean\")n(i);else i.then(n,()=>void 0)}}#B(){for(const e of this.#t.values()){if(!e.peer||e.cascade)continue;let t=this.#a.get(e.id);if(!t){t=new Map;this.#a.set(e.id,t)}const s=t;for(const n of this.#D()){const i=Ps(n.track.peerId,n.track.id);if(s.has(i)||n.track.peerId===e.id)continue;const o=this.#e.select({peerId:e.id,metadata:e.metadata,session:e.session},n.track);if(typeof o===\"boolean\"){s.set(i,o);continue}s.set(i,false);o.then(c=>{if(!c||this.#a.get(e.id)!==s)return;s.set(i,true);this.#S()},()=>void 0)}}this.#S()}#U(e){const t=this.#o.get(e);if(!t)return;const s=t.wanted?this.#F(e):void 0;if(t.source===s)return;t.unpipe?.();t.unpipe=void 0;t.source=s;if(!s)return;t.unpipe=er(s.media).onReceiveRtp.subscribe((n,i)=>t.receive(n,i)).unSubscribe;if(s.track.kind===\"video\")s.media.requestKeyFrame()}#j(e){const t=this.#o.get(e);if(!t)return;this.#o.delete(e);t.unpipe?.();t.track.stop()}#K(e){const t=Cg(e.leg.connection).dtlsTransports[0];if(!t||this.#u.has(t))return;this.#u.add(t);t.senderBWE.onCongestion.subscribe(s=>{if(!e.leg.closed)this.#e.emit(\"congestion\",this.name,e.id,s,t.senderBWE.availableBitrate)})}};var Td=class{static{a(this,\"SFUWorkerChannel\")}#e;#t=new Map;#r=1;#s;constructor(e,t){this.#e=e;e.on(\"message\",s=>{const n=s;if(n.type===\"reply\"){const{reply:o,result:c,error:l}=n;const u=this.#t.get(o);this.#t.delete(o);if(l===void 0)u?.resolve(c);else u?.reject(new Error(l));return}const i=n.request;if(i===void 0){try{const o=t(n);if(o instanceof Promise)o.catch(()=>void 0)}catch{}return}Promise.resolve().then(()=>t(n)).then(o=>this.#u({type:\"reply\",reply:i,result:o}),o=>this.#u({type:\"reply\",reply:i,error:o instanceof Error?o.message:String(o)}))})}request(e){if(this.#s)return Promise.reject(this.#s);const t=this.#r++;return new Promise((s,n)=>{this.#t.set(t,{resolve:s,reject:n});try{this.#e.postMessage({...e,request:t})}catch(i){this.#t.delete(t);n(i)}})}post(e,t){if(!this.#s)this.#e.postMessage(e,t)}close(e){this.#s??=e;for(const{reject:t}of this.#t.values())t(e);this.#t.clear()}#u(e){if(this.#s)return;try{this.#e.postMessage(e)}catch(t){this.#e.postMessage({type:\"reply\",reply:e.reply,error:t.message})}}};function Jc(...r){return r.join(\"\\n\")}a(Jc,\"keyOf\");function n_(){if(!Zc.parentPort)throw new Error(\"The media server forwards in a worker thread only\");const r=Zc.workerData;const e=new Wt;const t=new Map;const s=new Map;const n=new Map;const i=new Map;const o=new Td(Zc.parentPort,h=>d(h));const c=a(h=>{const p=t.get(h);if(!p)throw new Error(\"The room is not served any more\");return p},\"roomOf\");const l=a((h,p)=>{n.set(h,p);p.ended(()=>{if(n.get(h)===p)n.delete(h);o.post({type:\"ended\",leg:h})})},\"keep\");const u=a((h,p,m,y)=>{const w=Jc(h,p,m);i.get(w)?.();i.delete(w);const S=y?t.get(h)?.track(p,m):void 0;if(!S)return;i.set(w,er(S).onReceiveRtp.subscribe((T,_)=>{const x=new Uint8Array(T.serialize());o.post({type:\"rtp\",ref:h,peerId:p,trackId:m,packet:x,extensions:_},[x.buffer])}).unSubscribe)},\"stream\");const f=a((h,p)=>({id:p,signaling:{join:a(async(m,y,w)=>{s.set(Jc(h,m),w.receive);try{return await o.request({type:\"join\",ref:h,peerId:m,role:w.role})}catch(S){s.delete(Jc(h,m));throw S}},\"join\"),leave:a(async m=>{s.delete(Jc(h,m));await o.request({type:\"leave\",ref:h,peerId:m})},\"leave\"),signal:a((m,y,w,S)=>o.request({type:\"signal\",ref:h,peerId:m,to:w,signal:S}),\"signal\")},connect:a(()=>e.get(xt,r.connection),\"connect\"),select:r.select?(m,y)=>o.request({type:\"select\",subscriber:m,track:y}):()=>true,emit:a((m,...y)=>{const w=m===\"publish\"||m===\"unpublish\"?y[0]:void 0;let S;const T=m===\"publish\"&&w?t.get(h)?.track(w.peerId,w.id):void 0;if(T){const _=er(T).codec;S={id:T.id,..._?{codec:{payloadType:_.payloadType,mimeType:_.mimeType,clockRate:_.clockRate,channels:_.channels,parameters:_.parameters}}:{}}}if(m===\"unpublish\"&&w)u(h,w.peerId,w.id,false);o.post({type:\"emit\",ref:h,event:m,args:y,...S?{media:S}:{}})},\"emit\"),emptied:a(()=>o.post({type:\"emptied\",ref:h}),\"emptied\"),changed:a(m=>o.post({type:\"state\",ref:h,members:m.members,viewers:m.viewers}),\"changed\"),sourced:a((m,y)=>o.post({type:\"source\",leg:m,source:y}),\"sourced\"),known:a((m,y)=>o.post({type:\"known\",ref:h,tracks:y}),\"known\")}),\"hostOf\");const d=a(async h=>{switch(h.type){case\"open\":{const p=new Ed(f(h.ref,h.id),h.room);t.set(h.ref,p);try{await p.ready}catch(m){if(t.get(h.ref)===p)t.delete(h.ref);throw m}return void 0}case\"close\":{const p=t.get(h.ref);t.delete(h.ref);await p?.close();return void 0}case\"publish\":{const p=await c(h.ref).publish(h.peerId,h.offer);l(h.peerId,p);return{answer:p.answer}}case\"play\":{const p=h.viewerId;const m=await c(h.ref).play(p,h.offer,h.select?y=>o.request({type:\"choose\",leg:p,tracks:y}):void 0);l(p,m);return{answer:m.answer,source:m.source()}}case\"patch\":{const p=n.get(h.leg);if(!p)throw new Error(\"There is no such session\");return await p.patch(h.fragment,h.restart)}case\"end\":return n.get(h.leg)?.close();case\"receive\":return s.get(Jc(h.ref,h.peerId))?.(h.event,h.payload);case\"stream\":return u(h.ref,h.peerId,h.trackId,h.wanted);case\"keyframe\":return t.get(h.ref)?.track(h.peerId,h.trackId)?.requestKeyFrame();case\"debug\":return Fw(h.enabled?(p,m)=>o.post({type:\"log\",namespace:p,message:`[thread ${r.thread}] ${(0,s_.format)(...m)}`}):void 0);case\"stop\":{const p=[...t.values()];t.clear();await Promise.all(p.map(m=>m.close()));await e.destroy();return void 0}}},\"handle\");o.post({type:\"ready\"})}a(n_,\"runSFUWorker\");n_();\n";
1
+ export const sfuWorkerCode = "var S_=Object.create;var tl=Object.defineProperty;var w_=Object.getOwnPropertyDescriptor;var E_=Object.getOwnPropertyNames;var T_=Object.getPrototypeOf;var x_=Object.prototype.hasOwnProperty;var a=(r,e)=>tl(r,\"name\",{value:e,configurable:true});var R_=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var __=(r,e)=>{for(var t in e)tl(r,t,{get:e[t],enumerable:true})};var C_=(r,e,t,s)=>{if(e&&typeof e===\"object\"||typeof e===\"function\"){for(let n of E_(e))if(!x_.call(r,n)&&n!==t)tl(r,n,{get:()=>e[n],enumerable:!(s=w_(e,n))||s.enumerable})}return r};var Ye=(r,e,t)=>(t=r!=null?S_(T_(r)):{},C_(e||!r||!r.__esModule?tl(t,\"default\",{value:r,enumerable:true}):t,r));var Bn=R_(()=>{/*! *****************************************************************************\nCopyright (C) Microsoft. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */var zg;(function(r){(function(e){var t=typeof globalThis===\"object\"?globalThis:typeof global===\"object\"?global:typeof self===\"object\"?self:typeof this===\"object\"?this:c();var s=n(r);if(typeof t.Reflect!==\"undefined\"){s=n(t.Reflect,s)}e(s,t);if(typeof t.Reflect===\"undefined\"){t.Reflect=r}function n(l,u){return function(f,d){Object.defineProperty(l,f,{configurable:true,writable:true,value:d});if(u)u(f,d)}}a(n,\"makeExporter\");function i(){try{return Function(\"return this;\")()}catch(l){}}a(i,\"functionThis\");function o(){try{return(void 0,eval)(\"(function() { return this; })()\")}catch(l){}}a(o,\"indirectEvalThis\");function c(){return i()||o()}a(c,\"sloppyModeThis\")})(function(e,t){var s=Object.prototype.hasOwnProperty;var n=typeof Symbol===\"function\";var i=n&&typeof Symbol.toPrimitive!==\"undefined\"?Symbol.toPrimitive:\"@@toPrimitive\";var o=n&&typeof Symbol.iterator!==\"undefined\"?Symbol.iterator:\"@@iterator\";var c=typeof Object.create===\"function\";var l={__proto__:[]}instanceof Array;var u=!c&&!l;var f={create:c?function(){return Cd(Object.create(null))}:l?function(){return Cd({__proto__:null})}:function(){return Cd({})},has:u?function(E,R){return s.call(E,R)}:function(E,R){return R in E},get:u?function(E,R){return s.call(E,R)?E[R]:void 0}:function(E,R){return E[R]}};var d=Object.getPrototypeOf(Function);var h=typeof Map===\"function\"&&typeof Map.prototype.entries===\"function\"?Map:p_();var p=typeof Set===\"function\"&&typeof Set.prototype.entries===\"function\"?Set:m_();var m=typeof WeakMap===\"function\"?WeakMap:g_();var y=n?Symbol.for(\"@reflect-metadata:registry\"):void 0;var w=f_();var S=d_(w);function T(E,R,C,L){if(!z(C)){if(!Dg(E))throw new TypeError;if(!Ae(R))throw new TypeError;if(!Ae(L)&&!z(L)&&!Mn(L))throw new TypeError;if(Mn(L))L=void 0;C=ar(C);return xd(E,R,C,L)}else{if(!Dg(E))throw new TypeError;if(!Bg(R))throw new TypeError;return Qc(E,R)}}a(T,\"decorate\");e(\"decorate\",T);function _(E,R){function C(L,F){if(!Ae(L))throw new TypeError;if(!z(F)&&!l_(F))throw new TypeError;Oo(E,R,L,F)}a(C,\"decorator\");return C}a(_,\"metadata\");e(\"metadata\",_);function x(E,R,C,L){if(!Ae(C))throw new TypeError;if(!z(L))L=ar(L);return Oo(E,R,C,L)}a(x,\"defineMetadata\");e(\"defineMetadata\",x);function k(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return Ao(E,R,C)}a(k,\"hasMetadata\");e(\"hasMetadata\",k);function N(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return _t(E,R,C)}a(N,\"hasOwnMetadata\");e(\"hasOwnMetadata\",N);function A(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return Ns(E,R,C)}a(A,\"getMetadata\");e(\"getMetadata\",A);function B(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);return Io(E,R,C)}a(B,\"getOwnMetadata\");e(\"getOwnMetadata\",B);function ee(E,R){if(!Ae(E))throw new TypeError;if(!z(R))R=ar(R);return el(E,R)}a(ee,\"getMetadataKeys\");e(\"getMetadataKeys\",ee);function fe(E,R){if(!Ae(E))throw new TypeError;if(!z(R))R=ar(R);return Ng(E,R)}a(fe,\"getOwnMetadataKeys\");e(\"getOwnMetadataKeys\",fe);function Rt(E,R,C){if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);if(!Ae(R))throw new TypeError;if(!z(C))C=ar(C);var L=ko(R,C,false);if(z(L))return false;return L.OrdinaryDeleteMetadata(E,R,C)}a(Rt,\"deleteMetadata\");e(\"deleteMetadata\",Rt);function Qc(E,R){for(var C=E.length-1;C>=0;--C){var L=E[C];var F=L(R);if(!z(F)&&!Mn(F)){if(!Bg(F))throw new TypeError;R=F}}return R}a(Qc,\"DecorateConstructor\");function xd(E,R,C,L){for(var F=E.length-1;F>=0;--F){var Ie=E[F];var De=Ie(R,C,L);if(!z(De)&&!Mn(De)){if(!Ae(De))throw new TypeError;L=De}}return L}a(xd,\"DecorateProperty\");function Ao(E,R,C){var L=_t(E,R,C);if(L)return true;var F=_d(R);if(!Mn(F))return Ao(E,F,C);return false}a(Ao,\"OrdinaryHasMetadata\");function _t(E,R,C){var L=ko(R,C,false);if(z(L))return false;return Mg(L.OrdinaryHasOwnMetadata(E,R,C))}a(_t,\"OrdinaryHasOwnMetadata\");function Ns(E,R,C){var L=_t(E,R,C);if(L)return Io(E,R,C);var F=_d(R);if(!Mn(F))return Ns(E,F,C);return void 0}a(Ns,\"OrdinaryGetMetadata\");function Io(E,R,C){var L=ko(R,C,false);if(z(L))return;return L.OrdinaryGetOwnMetadata(E,R,C)}a(Io,\"OrdinaryGetOwnMetadata\");function Oo(E,R,C,L){var F=ko(C,L,true);F.OrdinaryDefineOwnMetadata(E,R,C,L)}a(Oo,\"OrdinaryDefineOwnMetadata\");function el(E,R){var C=Ng(E,R);var L=_d(E);if(L===null)return C;var F=el(L,R);if(F.length<=0)return C;if(C.length<=0)return F;var Ie=new p;var De=[];for(var W=0,M=C;W<M.length;W++){var D=M[W];var U=Ie.has(D);if(!U){Ie.add(D);De.push(D)}}for(var j=0,J=F;j<J.length;j++){var D=J[j];var U=Ie.has(D);if(!U){Ie.add(D);De.push(D)}}return De}a(el,\"OrdinaryMetadataKeys\");function Ng(E,R){var C=ko(E,R,false);if(!C){return[]}return C.OrdinaryOwnMetadataKeys(E,R)}a(Ng,\"OrdinaryOwnMetadataKeys\");function Lg(E){if(E===null)return 1;switch(typeof E){case\"undefined\":return 0;case\"boolean\":return 2;case\"string\":return 3;case\"symbol\":return 4;case\"number\":return 5;case\"object\":return E===null?1:6;default:return 6}}a(Lg,\"Type\");function z(E){return E===void 0}a(z,\"IsUndefined\");function Mn(E){return E===null}a(Mn,\"IsNull\");function i_(E){return typeof E===\"symbol\"}a(i_,\"IsSymbol\");function Ae(E){return typeof E===\"object\"?E!==null:typeof E===\"function\"}a(Ae,\"IsObject\");function o_(E,R){switch(Lg(E)){case 0:return E;case 1:return E;case 2:return E;case 3:return E;case 4:return E;case 5:return E}var C=R===3?\"string\":R===5?\"number\":\"default\";var L=Ug(E,i);if(L!==void 0){var F=L.call(E,C);if(Ae(F))throw new TypeError;return F}return a_(E,C===\"default\"?\"number\":C)}a(o_,\"ToPrimitive\");function a_(E,R){if(R===\"string\"){var C=E.toString;if(Dn(C)){var L=C.call(E);if(!Ae(L))return L}var F=E.valueOf;if(Dn(F)){var L=F.call(E);if(!Ae(L))return L}}else{var F=E.valueOf;if(Dn(F)){var L=F.call(E);if(!Ae(L))return L}var Ie=E.toString;if(Dn(Ie)){var L=Ie.call(E);if(!Ae(L))return L}}throw new TypeError}a(a_,\"OrdinaryToPrimitive\");function Mg(E){return!!E}a(Mg,\"ToBoolean\");function c_(E){return\"\"+E}a(c_,\"ToString\");function ar(E){var R=o_(E,3);if(i_(R))return R;return c_(R)}a(ar,\"ToPropertyKey\");function Dg(E){return Array.isArray?Array.isArray(E):E instanceof Object?E instanceof Array:Object.prototype.toString.call(E)===\"[object Array]\"}a(Dg,\"IsArray\");function Dn(E){return typeof E===\"function\"}a(Dn,\"IsCallable\");function Bg(E){return typeof E===\"function\"}a(Bg,\"IsConstructor\");function l_(E){switch(Lg(E)){case 3:return true;case 4:return true;default:return false}}a(l_,\"IsPropertyKey\");function Rd(E,R){return E===R||E!==E&&R!==R}a(Rd,\"SameValueZero\");function Ug(E,R){var C=E[R];if(C===void 0||C===null)return void 0;if(!Dn(C))throw new TypeError;return C}a(Ug,\"GetMethod\");function jg(E){var R=Ug(E,o);if(!Dn(R))throw new TypeError;var C=R.call(E);if(!Ae(C))throw new TypeError;return C}a(jg,\"GetIterator\");function $g(E){return E.value}a($g,\"IteratorValue\");function Fg(E){var R=E.next();return R.done?false:R}a(Fg,\"IteratorStep\");function Hg(E){var R=E[\"return\"];if(R)R.call(E)}a(Hg,\"IteratorClose\");function _d(E){var R=Object.getPrototypeOf(E);if(typeof E!==\"function\"||E===d)return R;if(R!==d)return R;var C=E.prototype;var L=C&&Object.getPrototypeOf(C);if(L==null||L===Object.prototype)return R;var F=L.constructor;if(typeof F!==\"function\")return R;if(F===E)return R;return F}a(_d,\"OrdinaryGetPrototypeOf\");function u_(){var E;if(!z(y)&&typeof t.Reflect!==\"undefined\"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata===\"function\"){E=h_(t.Reflect)}var R;var C;var L;var F=new m;var Ie={registerProvider:De,getProvider:M,setProvider:U};return Ie;function De(j){if(!Object.isExtensible(Ie)){throw new Error(\"Cannot add provider to a frozen registry.\")}switch(true){case E===j:break;case z(R):R=j;break;case R===j:break;case z(C):C=j;break;case C===j:break;default:if(L===void 0)L=new p;L.add(j);break}}a(De,\"registerProvider\");function W(j,J){if(!z(R)){if(R.isProviderFor(j,J))return R;if(!z(C)){if(C.isProviderFor(j,J))return R;if(!z(L)){var be=jg(L);while(true){var Oe=Fg(be);if(!Oe){return void 0}var jt=$g(Oe);if(jt.isProviderFor(j,J)){Hg(be);return jt}}}}}if(!z(E)&&E.isProviderFor(j,J)){return E}return void 0}a(W,\"getProviderNoCache\");function M(j,J){var be=F.get(j);var Oe;if(!z(be)){Oe=be.get(J)}if(!z(Oe)){return Oe}Oe=W(j,J);if(!z(Oe)){if(z(be)){be=new h;F.set(j,be)}be.set(J,Oe)}return Oe}a(M,\"getProvider\");function D(j){if(z(j))throw new TypeError;return R===j||C===j||!z(L)&&L.has(j)}a(D,\"hasProvider\");function U(j,J,be){if(!D(be)){throw new Error(\"Metadata provider not registered.\")}var Oe=M(j,J);if(Oe!==be){if(!z(Oe)){return false}var jt=F.get(j);if(z(jt)){jt=new h;F.set(j,jt)}jt.set(J,be)}return true}a(U,\"setProvider\")}a(u_,\"CreateMetadataRegistry\");function f_(){var E;if(!z(y)&&Ae(t.Reflect)&&Object.isExtensible(t.Reflect)){E=t.Reflect[y]}if(z(E)){E=u_()}if(!z(y)&&Ae(t.Reflect)&&Object.isExtensible(t.Reflect)){Object.defineProperty(t.Reflect,y,{enumerable:false,configurable:false,writable:false,value:E})}return E}a(f_,\"GetOrCreateMetadataRegistry\");function d_(E){var R=new m;var C={isProviderFor:a(function(D,U){var j=R.get(D);if(z(j))return false;return j.has(U)},\"isProviderFor\"),OrdinaryDefineOwnMetadata:De,OrdinaryHasOwnMetadata:F,OrdinaryGetOwnMetadata:Ie,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:M};w.registerProvider(C);return C;function L(D,U,j){var J=R.get(D);var be=false;if(z(J)){if(!j)return void 0;J=new h;R.set(D,J);be=true}var Oe=J.get(U);if(z(Oe)){if(!j)return void 0;Oe=new h;J.set(U,Oe);if(!E.setProvider(D,U,C)){J.delete(U);if(be){R.delete(D)}throw new Error(\"Wrong provider for target.\")}}return Oe}a(L,\"GetOrCreateMetadataMap\");function F(D,U,j){var J=L(U,j,false);if(z(J))return false;return Mg(J.has(D))}a(F,\"OrdinaryHasOwnMetadata\");function Ie(D,U,j){var J=L(U,j,false);if(z(J))return void 0;return J.get(D)}a(Ie,\"OrdinaryGetOwnMetadata\");function De(D,U,j,J){var be=L(j,J,true);be.set(D,U)}a(De,\"OrdinaryDefineOwnMetadata\");function W(D,U){var j=[];var J=L(D,U,false);if(z(J))return j;var be=J.keys();var Oe=jg(be);var jt=0;while(true){var qg=Fg(Oe);if(!qg){j.length=jt;return j}var y_=$g(qg);try{j[jt]=y_}catch(b_){try{Hg(Oe)}finally{throw b_}}jt++}}a(W,\"OrdinaryOwnMetadataKeys\");function M(D,U,j){var J=L(U,j,false);if(z(J))return false;if(!J.delete(D))return false;if(J.size===0){var be=R.get(U);if(!z(be)){be.delete(j);if(be.size===0){R.delete(be)}}}return true}a(M,\"OrdinaryDeleteMetadata\")}a(d_,\"CreateMetadataProvider\");function h_(E){var R=E.defineMetadata,C=E.hasOwnMetadata,L=E.getOwnMetadata,F=E.getOwnMetadataKeys,Ie=E.deleteMetadata;var De=new m;var W={isProviderFor:a(function(M,D){var U=De.get(M);if(!z(U)&&U.has(D)){return true}if(F(M,D).length){if(z(U)){U=new p;De.set(M,U)}U.add(D);return true}return false},\"isProviderFor\"),OrdinaryDefineOwnMetadata:R,OrdinaryHasOwnMetadata:C,OrdinaryGetOwnMetadata:L,OrdinaryOwnMetadataKeys:F,OrdinaryDeleteMetadata:Ie};return W}a(h_,\"CreateFallbackProvider\");function ko(E,R,C){var L=w.getProvider(E,R);if(!z(L)){return L}if(C){if(w.setProvider(E,R,S)){return S}throw new Error(\"Illegal state.\")}return void 0}a(ko,\"GetMetadataProvider\");function p_(){var E={};var R=[];var C=(function(){function W(M,D,U){this._index=0;this._keys=M;this._values=D;this._selector=U}a(W,\"MapIterator\");W.prototype[\"@@iterator\"]=function(){return this};W.prototype[o]=function(){return this};W.prototype.next=function(){var M=this._index;if(M>=0&&M<this._keys.length){var D=this._selector(this._keys[M],this._values[M]);if(M+1>=this._keys.length){this._index=-1;this._keys=R;this._values=R}else{this._index++}return{value:D,done:false}}return{value:void 0,done:true}};W.prototype.throw=function(M){if(this._index>=0){this._index=-1;this._keys=R;this._values=R}throw M};W.prototype.return=function(M){if(this._index>=0){this._index=-1;this._keys=R;this._values=R}return{value:M,done:true}};return W})();var L=(function(){function W(){this._keys=[];this._values=[];this._cacheKey=E;this._cacheIndex=-2}a(W,\"Map\");Object.defineProperty(W.prototype,\"size\",{get:a(function(){return this._keys.length},\"get\"),enumerable:true,configurable:true});W.prototype.has=function(M){return this._find(M,false)>=0};W.prototype.get=function(M){var D=this._find(M,false);return D>=0?this._values[D]:void 0};W.prototype.set=function(M,D){var U=this._find(M,true);this._values[U]=D;return this};W.prototype.delete=function(M){var D=this._find(M,false);if(D>=0){var U=this._keys.length;for(var j=D+1;j<U;j++){this._keys[j-1]=this._keys[j];this._values[j-1]=this._values[j]}this._keys.length--;this._values.length--;if(Rd(M,this._cacheKey)){this._cacheKey=E;this._cacheIndex=-2}return true}return false};W.prototype.clear=function(){this._keys.length=0;this._values.length=0;this._cacheKey=E;this._cacheIndex=-2};W.prototype.keys=function(){return new C(this._keys,this._values,F)};W.prototype.values=function(){return new C(this._keys,this._values,Ie)};W.prototype.entries=function(){return new C(this._keys,this._values,De)};W.prototype[\"@@iterator\"]=function(){return this.entries()};W.prototype[o]=function(){return this.entries()};W.prototype._find=function(M,D){if(!Rd(this._cacheKey,M)){this._cacheIndex=-1;for(var U=0;U<this._keys.length;U++){if(Rd(this._keys[U],M)){this._cacheIndex=U;break}}}if(this._cacheIndex<0&&D){this._cacheIndex=this._keys.length;this._keys.push(M);this._values.push(void 0)}return this._cacheIndex};return W})();return L;function F(W,M){return W}a(F,\"getKey\");function Ie(W,M){return M}a(Ie,\"getValue\");function De(W,M){return[W,M]}a(De,\"getEntry\")}a(p_,\"CreateMapPolyfill\");function m_(){var E=(function(){function R(){this._map=new h}a(R,\"Set\");Object.defineProperty(R.prototype,\"size\",{get:a(function(){return this._map.size},\"get\"),enumerable:true,configurable:true});R.prototype.has=function(C){return this._map.has(C)};R.prototype.add=function(C){return this._map.set(C,C),this};R.prototype.delete=function(C){return this._map.delete(C)};R.prototype.clear=function(){this._map.clear()};R.prototype.keys=function(){return this._map.keys()};R.prototype.values=function(){return this._map.keys()};R.prototype.entries=function(){return this._map.entries()};R.prototype[\"@@iterator\"]=function(){return this.keys()};R.prototype[o]=function(){return this.keys()};return R})();return E}a(m_,\"CreateSetPolyfill\");function g_(){var E=16;var R=f.create();var C=L();return(function(){function M(){this._key=L()}a(M,\"WeakMap\");M.prototype.has=function(D){var U=F(D,false);return U!==void 0?f.has(U,this._key):false};M.prototype.get=function(D){var U=F(D,false);return U!==void 0?f.get(U,this._key):void 0};M.prototype.set=function(D,U){var j=F(D,true);j[this._key]=U;return this};M.prototype.delete=function(D){var U=F(D,false);return U!==void 0?delete U[this._key]:false};M.prototype.clear=function(){this._key=L()};return M})();function L(){var M;do M=\"@@WeakMap@@\"+W();while(f.has(R,M));R[M]=true;return M}a(L,\"CreateUniqueKey\");function F(M,D){if(!s.call(M,C)){if(!D)return void 0;Object.defineProperty(M,C,{value:f.create()})}return M[C]}a(F,\"GetOrCreateWeakMapTable\");function Ie(M,D){for(var U=0;U<D;++U)M[U]=Math.random()*255|0;return M}a(Ie,\"FillRandomBytes\");function De(M){if(typeof Uint8Array===\"function\"){var D=new Uint8Array(M);if(typeof crypto!==\"undefined\"){crypto.getRandomValues(D)}else if(typeof msCrypto!==\"undefined\"){msCrypto.getRandomValues(D)}else{Ie(D,M)}return D}return Ie(new Array(M),M)}a(De,\"GenRandomBytes\");function W(){var M=De(E);M[6]=M[6]&79|64;M[8]=M[8]&191|128;var D=\"\";for(var U=0;U<E;++U){var j=M[U];if(U===4||U===6||U===8)D+=\"-\";if(j<16)D+=\"0\";D+=j.toString(16).toLowerCase()}return D}a(W,\"CreateUUID\")}a(g_,\"CreateWeakMapPolyfill\");function Cd(E){E.__=void 0;delete E.__;return E}a(Cd,\"MakeDictionary\")})})(zg||(zg={}))});var s_=require(\"node:util\");var Zc=require(\"node:worker_threads\");var Iz=Ye(Bn(),1);var Xg=require(\"node:util\");function v(r){return r}a(v,\"As\");var vd=class extends Error{static{a(this,\"Warning\")}get name(){return this.constructor.name}};function _r(r){return process.emit(\"warning\",new vd(r))}a(_r,\"throwWarning\");function Un(r){return process.env[r]}a(Un,\"variable\");function rl(r){const e=r?.trim().toLowerCase();return e===\"development\"||e===\"production\"?e:void 0}a(rl,\"modeOf\");function Gg(r){const e=rl(Un(\"MODE\"));if(e)return e;if(Un(\"MODE\")?.trim())_r(`The MODE environment variable \"${Un(\"MODE\")}\" is not a mode (development, production), it is ignored`);return rl(Un(\"NODE_ENV\"))??r??\"development\"}a(Gg,\"resolveMode\");function Ad(){return rl(Un(\"MODE\"))??rl(Un(\"NODE_ENV\"))??\"development\"}a(Ad,\"currentMode\");function v_(r){try{new Intl.DateTimeFormat(\"en-US\",{timeZone:r});return true}catch{return false}}a(v_,\"isTimezone\");function A_(r){const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!v_(r)){_r(`The passed time zone \"${r}\" is invalid, use the default time zone \"${e}\"`);return e}return r}a(A_,\"validateTimezone\");function Kg(r){process.env.appId=r.appId;process.env.appName=r.appName;const e=r.timezone===\"auto\"?Intl.DateTimeFormat().resolvedOptions().timeZone:r.timezone;process.env.TZ=A_(e);process.env.NODE_ENV=r.mode;process.env.MODE=r.mode;return Id()}a(Kg,\"setBasicInfo\");function jn(){return process.env.appId||\"Unknown\"}a(jn,\"getAppId\");function Qr(){return process.env.appName||\"Unknown\"}a(Qr,\"getAppName\");function Id(){return{appId:jn(),appName:Qr(),timezone:v(process.env.TZ),mode:Ad()}}a(Id,\"getBasicInfo\");var Wg=a(r=>r.replace(/&/g,\"&amp;\").replace(/\"/g,\"&quot;\").replace(/'/g,\"&#39;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\"),\"_htmlEscape\");function I_(r,...e){if(typeof r===\"string\"){return Wg(r)}let t=r[0];for(const[s,n]of e.entries()){t=t+Wg(String(n))+r[s+1]}return t}a(I_,\"htmlEscape\");var Od=class extends Error{static{a(this,\"MissingValueError\")}constructor(e){super(`Missing a value for ${e?`the placeholder: ${e}`:\"a placeholder\"}`);this.name=\"MissingValueError\";this.key=e}};function Vg(r,e,{ignoreMissing:t=false,transform:s=a(({value:n})=>n,\"transform\")}={}){if(typeof r!==\"string\"){throw new TypeError(`Expected a \\`string\\` in the first argument, got \\`${typeof r}\\``)}if(typeof e!==\"object\"){throw new TypeError(`Expected an \\`object\\` or \\`Array\\` in the second argument, got \\`${typeof e}\\``)}const n=a((l,u)=>{let f=e;for(const h of u.split(\".\")){f=f?f[h]:void 0}const d=s({value:f,key:u});if(d===void 0){if(t){return l}throw new Od(u)}return String(d)},\"replace\");const i=a(l=>(...u)=>I_(l(...u)),\"composeHtmlEscape\");const o=/{{(\\d+|[a-z$_][\\w\\-$]*?(?:\\.[\\w\\-$]*?)*?)}}/gi;if(o.test(r)){r=r.replace(o,i(n))}const c=/{(\\d+|[a-z$_][\\w\\-$]*?(?:\\.[\\w\\-$]*?)*?)}/gi;return r.replace(c,n)}a(Vg,\"templating\");function $t(...r){return void 0}a($t,\"DevNull\");var O_=\"sdifjoOc\";function k_(r,...e){if(!e.length)return r;let t=\"\";let s=0;let n=0;for(let i=0;i<r.length-1;i++){if(r[i]!==\"%\")continue;const o=r[++i];if(n<e.length&&O_.includes(o)){let c;try{c=o===\"c\"?\"\":(0,Xg.format)(`%${o}`,e[n])}catch{c=`%${o}`}t+=r.slice(s,i-1)+c;n++;s=i+1}else if(o===\"%\"){t+=r.slice(s,i);s=i+1}}return t+r.slice(s)}a(k_,\"format\");var P_=Symbol(\"EXCEPTION.PARAMS\");var Z=class extends Error{static{a(this,\"Exception\")}constructor(e,...t){super();this.appId=jn();this.appName=Qr();this.statusCode=500;if(t.length){const n=e;const i=t.length>1||typeof t[0]!==\"object\"||t[0]===null?t:t[0];Object.defineProperty(this,P_,{value:i,enumerable:false});try{this.message=Vg(n,i,{ignoreMissing:true})}catch(o){this.message=n;$t(o)}this.message=k_(this.message,...t)}else if(e){if(typeof e===\"string\"){this.message=e}else{this.message=v(e).message}}else{const n=this.name.replace(/([a-z\\d])([A-Z])/g,\"$1 $2\").replace(/([A-Z]+)([A-Z][a-z])/g,\"$1 $2\").split(/[\\s_-]+/).filter(i=>!!i).map(i=>/^[A-Z\\d]{2,}$/.test(i)?i:i.toLowerCase()).join(\" \");this.message=`${n.charAt(0).toUpperCase()}${n.slice(1)}`}let s=this.message;Object.defineProperty(this,\"message\",{configurable:true,enumerable:true,get:a(()=>s,\"get\"),set:a(n=>{s=n;v(this).errMsg=n},\"set\")});this.errMsg=s;this.err=this.name}get name(){return this.constructor.name}};var pB=Ye(Bn(),1);var Ub=require(\"node:util/types\");var Ls=class extends Error{static{a(this,\"AssertError\")}constructor(e,t){super(e||\"Unknown error\");this.name=\"AssertError\";if(typeof Error.captureStackTrace===\"function\")Error.captureStackTrace(this,t)}};function Po(...r){try{return JSON.stringify(...r)}catch(e){return\"[Cannot display object: \"+e.message+\"]\"}}a(Po,\"stringify\");function te(r,...e){if(r)return;if(e.length===1&&e[0]instanceof Error)throw e[0];const t=e.filter(s=>s!==\"\").map(s=>typeof s===\"string\"?s:s instanceof Error?s.message:Po(s));throw new Ls(t.join(\" \"),te)}a(te,\"assert\");function No(r,e={}){return e.symbols!==false?Reflect.ownKeys(r):Object.getOwnPropertyNames(r)}a(No,\"keys\");function ce(r){return Array.isArray(r)}a(ce,\"isArray\");function N_(r){if(r instanceof Set)return\"set\";if(r instanceof Map)return\"map\";return void 0}a(N_,\"iterables\");function et(r,e,t){if(e===false||e===null||e===void 0)return r;const s=typeof t===\"string\"?{separator:t}:t||{};const n=ce(e);te(!n||!s.separator,\"Separator option is not valid for array-based chain\");const i=ce(e)?e:e.split(s.separator||\".\");let o=r;for(let c=0;c<i.length;++c){let l=i[c];const u=s.iterables?N_(o):void 0;if(ce(o)||u===\"set\"){const f=Number(l);if(Number.isInteger(f))l=f<0?Number(o.length)+f:f}if(!o||typeof o===\"function\"&&s.functions===false||!u&&o[l]===void 0){te(!s.strict||c+1===i.length,\"Missing segment\",l,\"in reach path \",e);te(typeof o===\"object\"||s.functions===true||typeof o!==\"function\",\"Invalid segment\",l,\"in reach path \",e);o=s.default;break}if(!u){o=o[l]}else if(u===\"set\"){o=[...o][l]}else{o=o.get(l)}}return o}a(et,\"reach\");var K={array:Array.prototype,buffer:Buffer.prototype,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,url:URL.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype};var L_=new Map([[\"[object Error]\",K.error],[\"[object Map]\",K.map],[\"[object Promise]\",K.promise],[\"[object Set]\",K.set],[\"[object URL]\",K.url],[\"[object WeakMap]\",K.weakMap],[\"[object WeakSet]\",K.weakSet]]);function Ms(r){if(Array.isArray(r))return K.array;if(r instanceof Buffer)return K.buffer;if(r instanceof Date)return K.date;if(r instanceof RegExp)return K.regex;if(r instanceof Error)return K.error;const e=Object.prototype.toString.call(r);return L_.get(e)||K.generic}a(Ms,\"getInternalProto\");var Yg=new Set([K.set,K.map,K.weakSet,K.weakMap]);function G(r,e={},t=null){return kd(r,e,t)}a(G,\"clone\");function kd(r,e,t){if(typeof r!==\"object\"||r===null)return r;let s=kd;let n=t;if(e.shallow){if(e.shallow!==true)return M_(r,e);s=a(u=>u,\"cloner\")}else if(n){const u=n.get(r);if(u)return u}else{n=new Map}const i=Ms(r);switch(i){case K.buffer:return Buffer.from(r);case K.date:return new Date(r.getTime());case K.regex:return new RegExp(r);case K.url:return new URL(r)}const o=D_(r,i,e);if(o===r)return r;if(n)n.set(r,o);if(i===K.set){for(const u of r)o.add(s(u,e,n))}else if(i===K.map){for(const[u,f]of r)o.set(u,s(f,e,n))}const c=r;const l=o;for(const u of No(r,e)){if(u===\"__proto__\")continue;if(i===K.array&&u===\"length\"){o.length=r.length;continue}if(i===K.error&&u===\"stack\")continue;const f=Object.getOwnPropertyDescriptor(r,u);if(f){if(f.get||f.set){Object.defineProperty(o,u,f)}else if(f.enumerable){l[u]=s(c[u],e,n)}else{Object.defineProperty(o,u,{enumerable:false,writable:true,configurable:true,value:s(c[u],e,n)})}}else{Object.defineProperty(o,u,{enumerable:true,writable:true,configurable:true,value:s(c[u],e,n)})}}return o}a(kd,\"cloneValue\");function M_(r,e){const t=e.shallow;const s={...e,shallow:false};const n=new Map;for(const i of t){const o=et(r,i);if(typeof o===\"object\"||typeof o===\"function\")n.set(o,o)}return kd(r,s,n)}a(M_,\"cloneWithShallow\");function D_(r,e,t){if(t.prototype===false){if(Yg.has(e))return new e.constructor;return e===K.array?[]:{}}const s=Object.getPrototypeOf(r);if(s&&s.isImmutable)return r;if(e===K.array){const n=[];if(s!==e)Object.setPrototypeOf(n,s);return n}if(e===K.error&&s&&(s===e||Object.prototype.isPrototypeOf.call(Error,s.constructor))){const n=structuredClone(r);if(Object.getPrototypeOf(n)!==s)Object.setPrototypeOf(n,s);return n}if(Yg.has(e)){const n=new s.constructor;if(s!==e)Object.setPrototypeOf(n,s);return n}return Object.create(s)}a(D_,\"base\");function Ft(r,e,t){te(r&&typeof r===\"object\",\"Invalid target value: must be an object\");te(e===null||e===void 0||typeof e===\"object\",\"Invalid source value: must be null, undefined, or an object\");if(!e)return r;const s={nullOverride:true,mergeArrays:true,...t};if(ce(e)){te(ce(r),\"Cannot merge array onto an object\");if(!s.mergeArrays)r.length=0;for(let c=0;c<e.length;++c)r.push(G(e[c],{symbols:s.symbols}));return r}const n=r;const i=e;const o=No(e,s);for(let c=0;c<o.length;++c){const l=o[c];if(l===\"__proto__\"||!Object.prototype.propertyIsEnumerable.call(e,l))continue;const u=i[l];if(u&&typeof u===\"object\"){if(n[l]===u)continue;const f=n[l];if(!f||typeof f!==\"object\"||ce(f)!==ce(u)||u instanceof Date||Buffer.isBuffer(u)||u instanceof RegExp){n[l]=G(u,{symbols:s.symbols})}else{Ft(f,u,s)}}else{if(u!==null&&u!==void 0){n[l]=u}else if(s.nullOverride){n[l]=u}}}return r}a(Ft,\"merge\");function Pd(r,e,t={}){te(r&&typeof r===\"object\",\"Invalid defaults value: must be an object\");te(!e||e===true||typeof e===\"object\",\"Invalid source value: must be true, falsy or an object\");te(typeof t===\"object\",\"Invalid options: must be an object\");if(!e)return null;if(t.shallow)return B_(r,e,t);const s=G(r);if(e===true)return s;const n=t.nullOverride!==void 0?t.nullOverride:false;return Ft(s,e,{nullOverride:n,mergeArrays:false})}a(Pd,\"applyToDefaults\");function B_(r,e,t){const s=t.shallow;te(ce(s),\"Invalid keys\");const n=new Map;const i=e===true?null:new Set;for(const l of s){const u=ce(l)?l:l.split(\".\");const f=et(r,u);if(f&&typeof f===\"object\"){n.set(f,i&&et(e,u)||f)}else if(i){i.add(u)}}const o=G(r,{},n);if(!i)return o;for(const l of i)U_(o,e,l);const c=t.nullOverride!==void 0?t.nullOverride:false;return Ft(o,e,{nullOverride:c,mergeArrays:false})}a(B_,\"applyToDefaultsWithShallow\");function U_(r,e,t){let s=e;for(const o of t){if(!(o in s))return;const c=s[o];if(typeof c!==\"object\"||c===null)return;s=c}const n=s;let i=r;for(let o=0;o<t.length-1;++o){const c=t[o];if(typeof i[c]!==\"object\")i[c]={};i=i[c]}i[t[t.length-1]]=n}a(U_,\"reachCopy\");var Nd=Symbol(\"mismatched\");var Ld=class{static{a(this,\"SeenEntry\")}constructor(e,t){this.obj=e;this.ref=t}isSame(e,t){return this.obj===e&&this.ref===t}};function Ct(r,e,t){return!!es(r,e,{prototype:true,...t},[])}a(Ct,\"deepEqual\");function es(r,e,t,s){if(r===e)return r!==0||1/r===1/e;const n=typeof r;if(n!==typeof e)return false;if(r===null||e===null)return false;if(n===\"function\"){if(!t.deepFunction||sl(r)!==sl(e))return false}else if(n!==\"object\"){return r!==r&&e!==e}const i=r;const o=e;const c=j_(i,o,!!t.prototype);switch(c){case K.buffer:return Buffer.prototype.equals.call(r,e);case K.promise:return r===e;case K.regex:case K.url:return sl(r)===sl(e);case Nd:return false}for(let l=s.length-1;l>=0;--l){if(s[l].isSame(i,o))return true}s.push(new Ld(i,o));try{return!!F_(c,i,o,t,s)}finally{s.pop()}}a(es,\"isDeepEqual\");function sl(r){return r.toString()}a(sl,\"toStringOf\");function j_(r,e,t){if(t){if(Object.getPrototypeOf(r)!==Object.getPrototypeOf(e))return Nd;return Ms(r)}const s=Ms(r);if(s!==Ms(e))return Nd;return s}a(j_,\"getSharedType\");function Jg(r){const e=r.valueOf;if(e===void 0)return r;try{return e.call(r)}catch(t){return t}}a(Jg,\"valueOf\");function Lo(r,e){return Object.prototype.propertyIsEnumerable.call(r,e)}a(Lo,\"hasOwnEnumerableProperty\");function $_(r,e){for(const t of Set.prototype.values.call(r)){if(!Set.prototype.has.call(e,t))return false}return true}a($_,\"isSetSimpleEqual\");function F_(r,e,t,s,n){const i=e;const o=t;if(r===K.array){const d=e;const h=t;if(s.part){for(const p of d){for(const m of h){if(es(p,m,s,n))return true}}}else{if(d.length!==h.length)return false;for(let p=0;p<d.length;++p){if(!es(d[p],h[p],s,n))return false}return true}}else if(r===K.set){const d=e;const h=t;if(d.size!==h.size)return false;if(!$_(d,h)){const p=new Set(Set.prototype.values.call(h));for(const m of Set.prototype.values.call(d)){if(p.delete(m))continue;let y=false;for(const w of p){if(es(m,w,s,n)){p.delete(w);y=true;break}}if(!y)return false}}}else if(r===K.map){const d=e;const h=t;if(d.size!==h.size)return false;for(const[p,m]of Map.prototype.entries.call(d)){if(m===void 0&&!Map.prototype.has.call(h,p))return false;if(!es(m,Map.prototype.get.call(h,p),s,n))return false}}else if(r===K.error){if(e.name!==t.name||e.message!==t.message)return false}const c=Jg(e);const l=Jg(t);if((e!==c||t!==l)&&!es(c,l,s,n))return false;const u=Object.keys(e);if(!s.part&&u.length!==Object.keys(t).length&&!s.skip)return false;let f=0;for(const d of u){if(s.skip&&s.skip.includes(d)){if(o[d]===void 0)++f;continue}if(!Lo(t,d))return false;if(!es(i[d],o[d],s,n))return false}if(!s.part&&u.length-f!==Object.keys(t).length)return false;if(s.symbols!==false){const d=Object.getOwnPropertySymbols(e);const h=new Set(Object.getOwnPropertySymbols(t));for(const p of d){if(!s.skip?.includes(p)){if(Lo(e,p)){if(!Lo(t,p))return false;if(!es(i[p],o[p],s,n))return false}else if(Lo(t,p)){return false}}h.delete(p)}for(const p of h){if(Lo(t,p))return false}}return true}a(F_,\"isDeepEqualObj\");var H_=new Map([[38,\"&amp;\"],[60,\"&lt;\"],[62,\"&gt;\"],[34,\"&quot;\"],[160,\"&nbsp;\"],[162,\"&cent;\"],[163,\"&pound;\"],[164,\"&curren;\"],[169,\"&copy;\"],[174,\"&reg;\"]]);var q_=(()=>{const r=new Set;for(let e=32;e<123;++e){if(e>=97||e>=65&&e<=90||e>=48&&e<=57||e===32||e===46||e===44||e===45||e===58||e===95){r.add(e)}}return r})();function z_(r){const e=H_.get(r);if(e)return e;if(r>=256)return\"&#\"+r+\";\";const t=r.toString(16).padStart(2,\"0\");return`&#x${t};`}a(z_,\"escapeHtmlChar\");function Md(r){if(!r)return\"\";let e=\"\";for(let t=0;t<r.length;++t){const s=r.charCodeAt(t);e+=q_.has(s)?r[t]:z_(s)}return e}a(Md,\"escapeHtml\");function mt(r){return r.replace(/[\\^\\$\\.\\*\\+\\-\\?\\=\\!\\:\\|\\\\\\/\\(\\)\\[\\]\\{\\}\\,]/g,\"\\\\$&\")}a(mt,\"escapeRegex\");function ts(...r){}a(ts,\"ignore\");var rs=class extends Z{static{a(this,\"SchemaException\")}};var nl=class extends rs{static{a(this,\"SchemaDefinitionException\")}constructor(){super(...arguments);this.errno=\"E_SCHEMA_DEFINITION\"}};function $n(r,e,t){const s=new nl(r||\"Unknown error\");if(typeof Error.captureStackTrace===\"function\")Error.captureStackTrace(s,e);if(t!==void 0)s.cause=t;return s}a($n,\"definitionException\");function ss(r,e){r.message=e;if(r instanceof Z)r.errMsg=e}a(ss,\"setMessage\");function g(r,...e){if(r)return;if(e.length===1&&e[0]instanceof Error)throw e[0];const t=e.filter(s=>s!==\"\").map(s=>typeof s===\"string\"?s:s instanceof Error?s.message:Po(s));throw $n(t.join(\" \"),g)}a(g,\"assert\");function Fn(r){try{return r()}catch(e){if(e instanceof Ls)throw $n(e.message,Fn,e);throw e}}a(Fn,\"definition\");var gt={messages:void 0,template:void 0,schemas:void 0};var Dd;var Bd;var G_=/^(?:[-+]\\d{2})?(?:\\d{4}(?!\\d{2}\\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\\1(?:[12]\\d|0[1-9]|3[01]))?|W(?:[0-4]\\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[1-6])))(?![T]$|[T][\\d]+Z$)(?:[T\\s](?:(?:(?:[01]\\d|2[0-3])(?:(:?)[0-5]\\d)?|24\\:?00)(?:[.,]\\d+(?!:))?)(?:\\2[0-5]\\d(?:[.,]\\d+)?)?(?:[Z]|(?:[+-])(?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?)?$/;var ns=\"1.0.0\";var is={abortEarly:true,allowUnknown:false,artifacts:false,cache:true,context:null,convert:true,dateFormat:\"iso\",errors:{escapeHtml:false,label:\"path\",language:null,render:true,stack:false,wrap:{label:'\"',array:\"[]\"}},externals:true,messages:{},nonEnumerables:false,noDefaults:false,presence:\"optional\",skipFunctions:false,stripUnknown:false,warnings:false};var H={any:Symbol.for(\"@lakutata/validation/schema\"),arraySingle:Symbol(\"arraySingle\"),deepDefault:Symbol(\"deepDefault\"),errors:Symbol(\"errors\"),literal:Symbol(\"literal\"),override:Symbol(\"override\"),parent:Symbol(\"parent\"),prefs:Symbol(\"prefs\"),ref:Symbol(\"ref\"),template:Symbol(\"template\"),values:Symbol(\"values\")};function il(r,e){return r[e]}a(il,\"symbolOf\");function re(r,e,t=\"Options\"){g(r&&typeof r===\"object\"&&!ce(r),\"Options must be of type object\");const s=Object.keys(r).filter(n=>!e.includes(n));g(s.length===0,`${t} contain unknown keys: ${s}`)}a(re,\"assertOptions\");function Mo(r){Bd=Bd||gt.schemas();const e=Bd.preferences.validate(r);if(e.error)throw $n(String([e.error.details[0].message]),Mo)}a(Mo,\"checkPreferences\");function ot(r,e,t){const s=r;const n=e;switch(t){case\"=\":return r===e;case\">\":return s>n;case\"<\":return s<n;case\">=\":return s>=n;case\"<=\":return s<=n}}a(ot,\"compare\");function Ds(r,e){return r===void 0?e:r}a(Ds,\"defaultValue\");function ol(r){return G_.test(r)}a(ol,\"isIsoDate\");function Ud(r){return typeof r===\"number\"&&!isNaN(r)}a(Ud,\"isNumber\");function tt(r){if(!r)return false;return!!(il(r,H.ref)||il(r,H.template))}a(tt,\"isResolvable\");function oe(r,e={}){const t=r?il(r,H.any):void 0;if(!t)return false;g(e.legacy||t.version===ns,\"Cannot mix different versions of validation schemas\");return true}a(oe,\"isSchema\");function Zg(r){return!!il(r,H.values)}a(Zg,\"isValues\");function Cr(r){return Number.isSafeInteger(r)&&r>=0}a(Cr,\"limit\");function Ht(r,e){Dd=Dd||gt.messages;const t=r||{};const s=e||{};const n=Object.assign({},t,s);if(s.errors&&t.errors){n.errors=Object.assign({},t.errors,s.errors);n.errors.wrap=Object.assign({},t.errors.wrap,s.errors.wrap)}if(s.messages)n.messages=Dd.compile(s.messages,t.messages);delete n[H.prefs];return n}a(Ht,\"preferences\");function os(r,e,t={}){try{return r()}catch(s){const n=s;if(n.path!==void 0){n.path=e+\".\"+n.path}else{n.path=String(e)}if(t.append)ss(n,`${n.message} (${n.path})`);throw s}}a(os,\"tryWithPath\");function al(r,e,{assert:t,message:s}){if(oe(t)){const n=t.validate(r);if(!n.error)return;return n.error.message}else if(!t(r)){return e?`${e} ${s}`:s}}a(al,\"validateArg\");function Be(r,e){for(const t of r)g(!ce(t),\"Method no longer accepts array arguments:\",e)}a(Be,\"verifyFlat\");var jd=Symbol(\"annotations\");function Qg(r){if(!this._original||typeof this._original!==\"object\")return this.details[0].message;const e=r?\"\":\"\\x1B[31m\";const t=r?\"\":\"\\x1B[41m\";const s=r?\"\":\"\\x1B[0m\";const n=G(this._original);for(let c=this.details.length-1;c>=0;--c){const l=c+1;const u=this.details[c];const f=u.path;let d=n;for(let h=0;;++h){const p=f[h];if(oe(d))d=d.clone();if(h+1<f.length&&typeof d[p]!==\"string\"){d=d[p]}else{const m=d[jd]||{errors:{},missing:{}};d[jd]=m;const y=p||u.context?.key;if(d[p]!==void 0){m.errors[y]=m.errors[y]||[];m.errors[y].push(l)}else{m.missing[y]=l}break}}}const i={key:/_\\$key\\$_([, \\d]+)_\\$end\\$_\"/g,missing:/\"_\\$miss\\$_([^|]+)\\|(\\d+)_\\$end\\$_\": \"__missing__\"/g,arrayIndex:/\\s*\"_\\$idx\\$_([, \\d]+)_\\$end\\$_\",?\\n(.*)/g,specials:/\"\\[(NaN|Symbol.*|-?Infinity|function.*|\\(.*)]\"/g};let o=K_(n,2).replace(i.key,(c,l)=>`\" ${e}[${l}]${s}`).replace(i.missing,(c,l,u)=>`${t}\"${l}\"${s}${e} [${u}]: -- missing --${s}`).replace(i.arrayIndex,(c,l,u)=>`\n${u} ${e}[${l}]${s}`).replace(i.specials,(c,l)=>l);o=`${o}\n${e}`;for(let c=0;c<this.details.length;++c){const l=c+1;o=`${o}\n[${l}] ${this.details[c].message}`}o=o+s;return o}a(Qg,\"error\");function K_(r,e){return JSON.stringify(r,W_(),e)}a(K_,\"safeStringify\");function W_(){const r=[];const e=[];const t=a((s,n)=>{if(e[0]===n)return\"[Circular ~]\";return\"[Circular ~.\"+r.slice(0,e.indexOf(n)).join(\".\")+\"]\"},\"cycleReplacer\");return function(s,n){if(e.length>0){const i=e.indexOf(this);if(~i){e.length=i+1;r.length=i+1;r[i]=s}else{e.push(this);r.push(s)}if(~e.indexOf(n))n=t.call(this,s,n)}else{e.push(n)}if(n){const i=n[jd];if(i){if(ce(n)){const o=[];for(let c=0;c<n.length;++c){if(i.errors[c])o.push(`_$idx$_${i.errors[c].sort().join(\", \")}_$end$_`);o.push(n[c])}n=o}else{const o=n;for(const c in i.errors){o[`${c}_$key$_${i.errors[c].sort().join(\", \")}_$end$_`]=o[c];o[c]=void 0}for(const c in i.missing){o[`_$miss$_${c}|${i.missing[c]}_$end$_`]=\"__missing__\"}}return n}}if(n===Infinity||n===-Infinity||Number.isNaN(n)||typeof n===\"function\"||typeof n===\"symbol\"){return\"[\"+n.toString()+\"]\"}return n}}a(W_,\"serializer\");var qt=class r extends rs{static{a(this,\"SchemaValidationException\")}constructor(e,t,s){super(e);this.errno=\"E_SCHEMA_VALIDATION\";this.statusCode=400;if(this.message!==e){this.message=e;this.errMsg=e}this._original=s;this.details=t}annotate(e){return Qg.call(this,e)}static isError(e){return e instanceof r}};var V_=1e3;var X_=new Set([\"undefined\",\"boolean\",\"number\",\"string\"]);var $d=class{static{a(this,\"List\")}constructor(){this.tail=null;this.head=null}unshift(e){e.next=null;e.prev=this.head;if(this.head)this.head.next=e;this.head=e;if(!this.tail)this.tail=e;return e}first(e){if(e===this.head)return;this._remove(e);this.unshift(e)}pop(){return this._remove(this.tail)}_remove(e){const{next:t,prev:s}=e;t.prev=s;if(s)s.next=t;if(e===this.tail)this.tail=t;e.prev=null;e.next=null;return e}};var Fd=class{static{a(this,\"Cache\")}constructor(e={}){re(e,[\"max\"]);g(e.max===void 0||e.max&&e.max>0&&isFinite(e.max),\"Invalid max cache size\");this._max=e.max||V_;this._map=new Map;this._list=new $d}get length(){return this._map.size}set(e,t){if(e!==null&&!X_.has(typeof e))return;const s=e;let n=this._map.get(s);if(n){n.value=t;this._list.first(n);return}n=this._list.unshift({key:s,value:t,next:null,prev:null});this._map.set(s,n);this._compact()}get(e){const t=this._map.get(e);if(t){this._list.first(t);return G(t.value)}}_compact(){if(this._map.size>this._max){const e=this._list.pop();this._map.delete(e.key)}}};var cl={provision(r){return new Fd(r)}};var Hd;var qd={adjust:null,in:false,iterables:null,map:null,separator:\".\",type:\"value\"};var Do=class r{static{a(this,\"Ref\")}constructor(e){g(typeof e===\"object\",\"Invalid reference construction\");re(e,[\"adjust\",\"ancestor\",\"in\",\"iterables\",\"map\",\"path\",\"render\",\"separator\",\"type\",\"depth\",\"key\",\"root\",\"display\"]);g([false,void 0].includes(e.separator)||typeof e.separator===\"string\"&&e.separator.length===1,\"Invalid separator\");g(!e.adjust||typeof e.adjust===\"function\",\"options.adjust must be a function\");g(!e.map||ce(e.map),\"options.map must be an array\");g(!e.map||!e.adjust,\"Cannot set both map and adjust options\");Object.assign(this,qd,e);g(this.type===\"value\"||this.ancestor===void 0,\"Non-value references cannot reference ancestors\");if(ce(this.map))this.map=new Map(this.map);this.depth=this.path.length;this.key=this.path.length?this.path.join(this.separator):null;this.root=this.path[0];this.updateDisplay()}resolve(e,t,s,n,i={}){g(!this.in||i.in,\"Invalid in() reference usage\");if(this.type===\"global\")return this._resolve(s.context,t,i);if(this.type===\"local\")return this._resolve(n,t,i);if(!this.ancestor)return this._resolve(e,t,i);if(this.ancestor===\"root\")return this._resolve(t.ancestors[t.ancestors.length-1],t,i);g(this.ancestor<=t.ancestors.length,\"Invalid reference exceeds the schema root:\",this.display);return this._resolve(t.ancestors[this.ancestor-1],t,i)}_resolve(e,t,s){let n;if(this.type===\"value\"&&t.mainstay.shadow&&s.shadow!==false){n=t.mainstay.shadow.get(this.absolute(t))}if(n===void 0)n=et(e,this.path,{iterables:!!this.iterables,functions:true});if(this.adjust)n=this.adjust(n);if(this.map){const i=this.map.get(n);if(i!==void 0)n=i}if(t.mainstay)t.mainstay.tracer.resolve(t,this,n);return n}toString(){return this.display}absolute(e){return[...e.path.slice(0,-this.ancestor),...this.path]}clone(){return new r(this)}describe(){const e={path:this.path};if(this.type!==\"value\")e.type=this.type;if(this.separator!==\".\")e.separator=this.separator;if(this.type===\"value\"&&this.ancestor!==1)e.ancestor=this.ancestor;if(this.map)e.map=[...this.map];if(this.adjust!==null&&this.adjust!==void 0)e.adjust=this.adjust;if(this.iterables!==null&&this.iterables!==void 0)e.iterables=this.iterables;if(this.render!==null&&this.render!==void 0)e.render=this.render;if(this.in!==false)e.in=true;return{ref:e}}updateDisplay(){const e=this.key!==null?this.key:\"\";if(this.type!==\"value\"){this.display=`ref:${this.type}:${e}`;return}if(!this.separator){this.display=`ref:${e}`;return}if(!this.ancestor){this.display=`ref:${this.separator}${e}`;return}if(this.ancestor===\"root\"){this.display=`ref:root:${e}`;return}if(this.ancestor===1){this.display=`ref:${e||\"..\"}`;return}const t=new Array(this.ancestor+1).fill(this.separator).join(\"\");this.display=`ref:${t}${e||\"\"}`}};Object.defineProperty(Do.prototype,H.ref,{value:true,writable:true,enumerable:true,configurable:true});function Y_(r,e,t={}){r=r.trim();if(t){const s=t.global===void 0?\"$\":t.global;if(s!==e&&r.startsWith(s))return{key:r.slice(s.length),type:\"global\"};const n=t.local===void 0?\"#\":t.local;if(n!==e&&r.startsWith(n))return{key:r.slice(n.length),type:\"local\"};const i=t.root===void 0?\"/\":t.root;if(i!==e&&r.startsWith(i))return{key:r.slice(i.length),type:\"value\",root:true}}return{key:r,type:\"value\"}}a(Y_,\"context\");function J_(r,e){if(!e)return[1,0];if(r[0]!==e)return[1,0];if(r[1]!==e)return[0,1];let t=2;while(r[t]===e)++t;return[t-1,t]}a(J_,\"ancestor\");function as(r,e={}){g(typeof r===\"string\",\"Invalid reference key:\",r);re(e,[\"adjust\",\"ancestor\",\"in\",\"iterables\",\"map\",\"prefix\",\"render\",\"separator\"]);g(!e.prefix||typeof e.prefix===\"object\",\"options.prefix must be of type object\");const t=Object.assign({},qd,e);delete t.prefix;const s=t.separator;const n=Y_(r,s,e.prefix);t.type=n.type;let i=n.key;if(t.type===\"value\"){if(n.root){g(!s||i[0]!==s,\"Cannot specify relative path with root prefix\");t.ancestor=\"root\";if(!i)i=null}if(s&&s===i){i=null;t.ancestor=0}else{if(t.ancestor!==void 0){g(!s||!i||i[0]!==s,\"Cannot combine prefix with ancestor option\")}else{const[o,c]=J_(i,s);if(c){i=i.slice(c);if(i===\"\")i=null}t.ancestor=o}}}t.path=s?i===null?[]:i.split(s):[i];return new Do(t)}a(as,\"create\");function rt(r){return r?!!r[H.ref]:false}a(rt,\"isRef\");function ty(r,e={}){return as(r,{...e,in:true})}a(ty,\"inRef\");function zd(r){const e=Object.assign({},qd,r);if(e.type===\"value\"&&e.ancestor===void 0)e.ancestor=1;return new Do(e)}a(zd,\"build\");var ul=0;var Z_=1;var ll=class r{static{a(this,\"Manager\")}constructor(){this.refs=[]}register(e,t){if(!e)return;const s=t===void 0?Z_:t;if(ce(e)){for(const n of e)this.register(n,s);return}if(oe(e)){for(const n of e._refs.refs){if(n.ancestor-s>=0)this.refs.push({ancestor:n.ancestor-s,root:n.root})}return}if(rt(e)&&e.type===\"value\"&&e.ancestor-s>=0){this.refs.push({ancestor:e.ancestor-s,root:e.root})}Hd=Hd||gt.template;if(Hd.isTemplate(e))this.register(e.refs(),s)}get length(){return this.refs.length}clone(){const e=new r;e.refs=G(this.refs);return e}reset(){this.refs=[]}roots(){return this.refs.filter(e=>!e.ancestor).map(e=>e.root)}};function Kd(r,e,t={}){re(t,[\"appendPath\",\"override\"]);try{return Q_(r,e,t)}catch(s){if(t.appendPath&&s.path!==void 0)ss(s,`${s.message} (${s.path})`);throw s}}a(Kd,\"schema\");function Q_(r,e,t){g(e!==void 0,\"Invalid undefined schema\");if(Array.isArray(e)){g(e.length,\"Invalid empty array schema\");if(e.length===1)e=e[0]}const s=a((n,...i)=>{if(t.override!==false)return n.valid(r.override,...i);return n.valid(...i)},\"valid\");if(sy(e))return s(r,e);if(typeof e===\"function\")return r.custom(e);g(typeof e===\"object\",\"Invalid schema content:\",typeof e);if(tt(e))return s(r,e);if(oe(e))return e;if(Array.isArray(e)){for(const n of e){if(!sy(n))return r.alternatives().try(...e)}return s(r,...e)}if(e instanceof RegExp)return r.string().regex(e);if(e instanceof Date)return s(r.date(),e);g(Object.getPrototypeOf(e)===Object.getPrototypeOf({}),\"Schema can only contain plain objects\");return r.object().keys(e)}a(Q_,\"compileSchema\");function cr(r,e){return rt(r)?r:as(r,e)}a(cr,\"ref\");function fl(r,e,t={}){re(t,[\"legacy\"]);const s=e?e[H.any]:void 0;if(s){g(t.legacy||s.version===ns,\"Cannot mix different versions of validation schemas:\",s.version,ns);return e}if(typeof e!==\"object\"||!t.legacy)return ry(r,e);const n=Gd(e);if(!n)return ry(r,e);return n.compile(n.root,e)}a(fl,\"compile\");function ry(r,e){return Kd(r,e,{appendPath:true})}a(ry,\"compileRoot\");function Gd(r){if(typeof r!==\"object\")return null;if(Array.isArray(r)){for(const s of r){const n=Gd(s);if(n)return n}return null}const e=r;const t=e[H.any];if(t)return{root:e[t.root],compile:t.compile};g(Object.getPrototypeOf(r)===Object.getPrototypeOf({}),\"Schema can only contain plain objects\");for(const s in e){const n=Gd(e[s]);if(n)return n}return null}a(Gd,\"walk\");function sy(r){return r===null||[\"boolean\",\"string\",\"number\"].includes(typeof r)}a(sy,\"simple\");function dl(r,e,t){if(t===void 0){g(e&&typeof e===\"object\",\"Missing options\");t=e;e=as(\".\")}if(Array.isArray(t))t={switch:t};re(t,[\"is\",\"not\",\"then\",\"otherwise\",\"switch\",\"break\"]);if(oe(e)){g(t.is===void 0,'\"is\" can not be used with a schema condition');g(t.not===void 0,'\"not\" can not be used with a schema condition');g(t.switch===void 0,'\"switch\" can not be used with a schema condition');return ny(r,{is:e,then:t.then,otherwise:t.otherwise,break:t.break})}g(rt(e)||typeof e===\"string\",\"Invalid condition:\",e);g(t.not===void 0||t.is===void 0,'Cannot combine \"is\" with \"not\"');if(t.switch===void 0){let n=t;if(t.not!==void 0)n={is:t.not,then:t.otherwise,otherwise:t.then,break:t.break};let i=n.is!==void 0?r.$_compile(n.is):r.$_root.invalid(null,false,0,\"\").required();g(n.then!==void 0||n.otherwise!==void 0,'options must have at least one of \"then\", \"otherwise\", or \"switch\"');g(n.break===void 0||n.then===void 0||n.otherwise===void 0,\"Cannot specify then, otherwise, and break all together\");if(t.is!==void 0&&!rt(t.is)&&!oe(t.is))i=i.required();return ny(r,{ref:cr(e),is:i,then:n.then,otherwise:n.otherwise,break:n.break})}g(Array.isArray(t.switch),'\"switch\" must be an array');g(t.is===void 0,'Cannot combine \"switch\" with \"is\"');g(t.not===void 0,'Cannot combine \"switch\" with \"not\"');g(t.then===void 0,'Cannot combine \"switch\" with \"then\"');const s={ref:cr(e),switch:[],break:t.break};for(let n=0;n<t.switch.length;++n){const i=t.switch[n];const o=n===t.switch.length-1;re(i,o?[\"is\",\"then\",\"otherwise\"]:[\"is\",\"then\"]);g(i.is!==void 0,'Switch statement missing \"is\"');g(i.then!==void 0,'Switch statement missing \"then\"');const c={is:r.$_compile(i.is),then:r.$_compile(i.then)};if(!rt(i.is)&&!oe(i.is))c.is=c.is.required();if(o){g(t.otherwise===void 0||i.otherwise===void 0,'Cannot specify \"otherwise\" inside and outside a \"switch\"');const l=t.otherwise!==void 0?t.otherwise:i.otherwise;if(l!==void 0){g(s.break===void 0,\"Cannot specify both otherwise and break\");c.otherwise=r.$_compile(l)}}s.switch.push(c)}return s}a(dl,\"when\");function ny(r,e){for(const t of[\"then\",\"otherwise\"]){if(e[t]===void 0){delete e[t]}else{e[t]=r.$_compile(e[t])}}return e}a(ny,\"conditionOf\");var Wd=Symbol(\"settings\");var cy=Symbol(\"expression\");var iy=[\"!\",\"^\",\"*\",\"/\",\"%\",\"+\",\"-\",\"<\",\"<=\",\">\",\">=\",\"==\",\"!=\",\"&&\",\"||\",\"??\"];var oy=[\"!\",\"^\",\"*\",\"/\",\"%\",\"+\",\"-\",\"<\",\"=\",\">\",\"&\",\"|\",\"?\"];var eC=[[\"^\"],[\"*\",\"/\",\"%\"],[\"+\",\"-\"],[\"<\",\"<=\",\">\",\">=\"],[\"==\",\"!=\"],[\"&&\"],[\"||\",\"??\"]];var ay=[\"!\",\"n\"];var hl={'\"':'\"',\"`\":\"`\",\"'\":\"'\",\"[\":\"]\"};var tC=/^(?:[0-9]*(\\.[0-9]*)?){1}$/;var rC=/^[\\w\\$\\#\\.\\@\\:\\{\\}]+$/;var Bo=class r{static{a(this,\"Parser\")}constructor(e,t={}){this.single=null;this._parts=null;if(!t[Wd]&&t.constants){for(const s in t.constants){const n=t.constants[s];if(n!==null&&![\"boolean\",\"number\",\"string\"].includes(typeof n)){throw new Error(`Expression constant ${s} contains invalid ${typeof n} value type`)}}}this.settings=t[Wd]?t:{[Wd]:true,constants:{},functions:{},...t};this._parse(e)}_parse(e){let t=[];let s=\"\";let n=0;let i=false;const o=a(l=>{if(n)throw new Error(\"Expression missing closing parenthesis\");const u=t.length?t[t.length-1]:null;if(!i&&!s&&!l)return;if(u&&u.type===\"reference\"&&l===\")\"){t[t.length-1]={type:\"function\",value:this._subExpression(s,u.value)};s=\"\";return}if(l===\")\"){const f=new r(s,this.settings);t.push({type:\"segment\",value:f})}else if(i){if(i===\"]\"){t.push({type:\"reference\",value:s});s=\"\";return}t.push({type:\"literal\",value:s})}else if(oy.includes(s)){if(u&&u.type===\"operator\"&&iy.includes(u.value+s)){u.value+=s}else{t.push({type:\"operator\",value:s})}}else if(s.match(tC)){t.push({type:\"constant\",value:parseFloat(s)})}else if(this.settings.constants[s]!==void 0){t.push({type:\"constant\",value:this.settings.constants[s]})}else{if(!s.match(rC))throw new Error(`Expression contains invalid token: ${s}`);t.push({type:\"reference\",value:s})}s=\"\"},\"flush\");for(const l of e){if(i){if(l===i){o();i=false}else{s+=l}}else if(n){if(l===\"(\"){s+=l;++n}else if(l===\")\"){--n;if(!n){o(l)}else{s+=l}}else{s+=l}}else if(l in hl){i=hl[l]}else if(l===\"(\"){o();++n}else if(oy.includes(l)){o();s=l;o()}else if(l!==\" \"){s+=l}else{o()}}o();t=t.map((l,u)=>{if(l.type!==\"operator\"||l.value!==\"-\"||u&&t[u-1].type!==\"operator\")return l;return{type:\"operator\",value:\"n\"}});let c=false;for(const l of t){if(l.type===\"operator\"){if(ay.includes(l.value))continue;if(!c)throw new Error(\"Expression contains an operator in invalid position\");if(!iy.includes(l.value))throw new Error(`Expression contains an unknown operator ${l.value}`)}else if(c){throw new Error(\"Expression missing expected operator\")}c=!c}if(!c)throw new Error(\"Expression contains invalid trailing operator\");if(t.length===1&&[\"reference\",\"literal\",\"constant\"].includes(t[0].type)){this.single={type:t[0].type===\"reference\"?\"reference\":\"value\",value:t[0].value}}this._parts=t.map(l=>{if(l.type===\"operator\")return ay.includes(l.value)?l:l.value;if(l.type!==\"reference\")return l.value;if(this.settings.tokenRx&&!this.settings.tokenRx.test(l.value))throw new Error(`Expression contains invalid reference ${l.value}`);if(this.settings.reference)return this.settings.reference(l.value);return nC(l.value)})}_subExpression(e,t){const s=this.settings.functions[t];if(typeof s!==\"function\")throw new Error(`Expression contains unknown function ${t}`);const n=[];if(e){let o=\"\";let c=0;let l=false;const u=a(()=>{if(!o)throw new Error(`Expression contains function ${t} with invalid arguments ${e}`);n.push(o);o=\"\"},\"flush\");for(let f=0;f<e.length;++f){const d=e[f];if(l){o+=d;if(d===l)l=false}else if(d in hl&&!c){o+=d;l=hl[d]}else if(d===\",\"&&!c){u()}else{o+=d;if(d===\"(\"){++c}else if(d===\")\"){--c}}}u()}const i=n.map(o=>new r(o,this.settings));return function(o){const c=[];for(const l of i)c.push(l.evaluate(o));return s.call(o,...c)}}evaluate(e){const t=this._parts.slice();for(let s=t.length-2;s>=0;--s){const n=t[s];if(sC(n)){const i=t[s+1];t.splice(s+1,1);const o=pl(i,e);t[s]=iC(n.value,o)}}eC.forEach(s=>{for(let n=1;n<t.length-1;){if(s.includes(t[n])){const i=t[n];const o=pl(t[n-1],e);const c=pl(t[n+1],e);t.splice(n,2);const l=oC(i,o,c);t[n-1]=l===0?0:l}else{n+=2}}});return pl(t[0],e)}};Object.defineProperty(Bo.prototype,cy,{value:true,writable:true,enumerable:true,configurable:true});function sC(r){return!!r&&r.type===\"operator\"}a(sC,\"isPrefixOperator\");function nC(r){return function(e){return e&&e[r]!==void 0?e[r]:null}}a(nC,\"reference\");function pl(r,e){if(r===null)return null;if(typeof r===\"function\")return r(e);if(r[cy])return r.evaluate(e);return r}a(pl,\"evaluatePart\");function iC(r,e){if(r===\"!\")return e?false:true;const t=-e;if(t===0)return 0;return t}a(iC,\"single\");function Vd(r){return r!==null&&r!==void 0}a(Vd,\"exists\");function oC(r,e,t){if(r===\"??\")return Vd(e)?e:t;const s=e;const n=t;if(typeof e===\"string\"||typeof t===\"string\"){if(r===\"+\")return(Vd(e)?e:\"\")+(Vd(t)?t:\"\")}else{switch(r){case\"^\":return Math.pow(s,n);case\"*\":return s*n;case\"/\":return s/n;case\"%\":return s%n;case\"+\":return s+n;case\"-\":return s-n}}switch(r){case\"<\":return s<n;case\"<=\":return s<=n;case\">\":return s>n;case\">=\":return s>=n;case\"==\":return e===t;case\"!=\":return e!==t;case\"&&\":return e&&t;case\"||\":return e||t}return null}a(oC,\"calculate\");var vt=class{static{a(this,\"Report\")}constructor(e,t,s,n,i,o,c){this.code=e;this.flags=n;this.messages=i;this.path=o.path;this.prefs=c;this.state=o;this.value=t;this.message=null;this.template=null;this.local=s||{};this.local.label=Uo(this.flags,this.state,this.prefs,this.messages);if(this.value!==void 0&&!Object.prototype.hasOwnProperty.call(this.local,\"value\"))this.local.value=this.value;if(this.path.length){const l=this.path[this.path.length-1];if(typeof l!==\"object\")this.local.key=l}}_setTemplate(e){this.template=e;if(!this.flags.label&&this.path.length===0){const t=this._template(this.template,\"root\");if(t)this.local.label=t}}toString(){if(this.message)return this.message;const e=this.code;if(!this.prefs.errors.render)return this.code;const t=this._template(this.template)||this._template(this.prefs.messages)||this._template(this.messages);if(t===void 0)return`Error code \"${e}\" is not defined, your custom type is missing the correct messages definition`;this.message=t.render(this.value,this.state,this.prefs,this.local,{errors:this.prefs.errors,messages:[this.prefs.messages,this.messages]});if(!this.prefs.errors.label)this.message=this.message.replace(/^\"\" /,\"\").trim();return this.message}_template(e,t){return qn(this.value,e,t||this.code,this.state,this.prefs)}};function Xd(r){let e=\"\";for(const t of r){if(typeof t===\"object\")continue;if(typeof t===\"string\"){if(e)e+=\".\";e+=t}else{e+=`[${t}]`}}return e}a(Xd,\"path\");function qn(r,e,t,s,n){if(!e)return;if(se.isTemplate(e))return t!==\"root\"?e:null;let i=n.errors.language;if(tt(i))i=i.resolve(r,s,n,void 0);const o=e;if(i&&o[i]){const c=o[i];if(c[t]!==void 0)return c[t];if(c[\"*\"]!==void 0)return c[\"*\"]}if(!o[t])return o[\"*\"];return o[t]}a(qn,\"template\");function Uo(r,e,t,s){const n=t.errors;if(!n.label)return\"\";if(r.label)return r.label;let i=e.path;if(n.label===\"key\"&&e.path.length>1)i=e.path.slice(-1);const o=Xd(i);if(o)return o;return qn(null,t.messages,\"root\",e,t)||s&&qn(null,s,\"root\",e,t)||\"value\"}a(Uo,\"label\");function Yd(r,e,t){if(!r)return null;const{override:s,message:n,details:i}=lr(r);if(s)return s;if(t.errors.stack)return new qt(n,i,e);const o=Error.stackTraceLimit;Error.stackTraceLimit=0;const c=new qt(n,i,e);Error.stackTraceLimit=o;return c}a(Yd,\"process\");function lr(r,e={}){let t=[];const s=[];for(const n of r){if(n instanceof Error){if(e.override!==false)return{override:n};const o=n.toString();t.push(o);s.push({message:o,type:\"override\",context:{error:n}});continue}const i=n.toString();t.push(i);s.push({message:i,path:n.path.filter(o=>typeof o!==\"object\"),type:n.code,context:n.local})}if(t.length>1)t=[...new Set(t)];return{message:t.join(\". \"),details:s}}a(lr,\"detailsOf\");var aC=new Array(1e3).join(\"\\0\");var cC=new Array(1e3).join(\"\u0001\");var lC={date:Date.prototype.toDateString,iso:Date.prototype.toISOString,string:Date.prototype.toString,time:Date.prototype.toTimeString,utc:Date.prototype.toUTCString};var uC={true:true,false:false,null:null,second:1e3,minute:60*1e3,hour:60*60*1e3,day:24*60*60*1e3};var ly={if(r,e,t){return r?e:t},length(r){if(typeof r===\"string\")return r.length;if(!r||typeof r!==\"object\")return null;if(ce(r))return r.length;return Object.keys(r).length},msg(r){const[e,t,s,n,i]=this;const o=i.messages;if(!o)return\"\";const c=qn(e,o[0],r,t,s)||qn(e,o[1],r,t,s);if(!c)return\"\";return c.render(e,t,s,n,i)},number(r){if(typeof r===\"number\")return r;if(typeof r===\"string\")return parseFloat(r);if(typeof r===\"boolean\")return r?1:0;if(r instanceof Date)return r.getTime();return null}};function fC(r){return r.replace(/\\\\(\\{+)/g,(e,t)=>aC.slice(0,t.length)).replace(/\\\\(\\}+)/g,(e,t)=>cC.slice(0,t.length))}a(fC,\"encode\");function Jd(r){return r.replace(/\\u0000/g,\"{\").replace(/\\u0001/g,\"}\")}a(Jd,\"decode\");function dC(r){const e=[];let t=\"\";for(let s=0;s<r.length;++s){const n=r[s];if(n===\"{\"){let i=\"\";while(s+1<r.length&&r[s+1]===\"{\"){i+=\"{\";++s}e.push(t);t=i}else{t+=n}}e.push(t);return e}a(dC,\"split\");function Zd(r,e){if(!e)return r;if(e.length===1)return`${e}${r}${e}`;return`${e[0]}${r}${e[1]}`}a(Zd,\"wrap\");function Qd(r,e,t,s,n,i={}){const o=typeof r;const c=s&&s.errors&&s.errors.wrap||{};let l=false;if(rt(r)&&r.render){l=r.in;r=r.resolve(e,t,s,n,{in:r.in,...i})}if(r===null)return\"null\";if(o===\"string\")return Zd(r,i.arrayItems&&c.string);if(o===\"number\"||o===\"function\"||o===\"symbol\")return r.toString();if(o!==\"object\")return JSON.stringify(r);if(r instanceof Date)return se.date(r,s);if(r instanceof Map){const f=[];for(const[d,h]of r.entries())f.push(`${d.toString()} -> ${h.toString()}`);r=f}if(!ce(r))return r.toString();const u=[];for(const f of r)u.push(Qd(f,e,t,s,n,{arrayItems:true,...i}));return Zd(u.join(\", \"),!l&&c.array)}a(Qd,\"stringify\");var se=class r{static{a(this,\"Template\")}constructor(e,t){g(typeof e===\"string\",\"Template source must be a string\");g(!e.includes(\"\\0\")&&!e.includes(\"\u0001\"),\"Template source cannot contain reserved control characters\");this.source=e;this.rendered=e;this._template=null;if(t){const{functions:s,...n}=t;this._settings=Object.keys(n).length?G(n):void 0;this._functions=s;if(this._functions){g(Object.keys(this._functions).every(i=>typeof i===\"string\"),\"Functions keys must be strings\");g(Object.values(this._functions).every(i=>typeof i===\"function\"),\"Functions values must be functions\")}}else{this._settings=void 0;this._functions=void 0}this._parse()}_parse(){if(!this.source.includes(\"{\"))return;const e=fC(this.source);const t=dC(e);let s=false;const n=[];const i=t.shift();if(i)n.push(i);for(const o of t){const c=o[0]!==\"{\";const l=c?\"}\":\"}}\";const u=o.indexOf(l);if(u===-1||o[1]===\"{\"){n.push(`{${Jd(o)}`);continue}let f=o.slice(c?0:1,u);const d=f[0]===\":\";if(d)f=f.slice(1);const h=this._ref(Jd(f),{raw:c,wrapped:d});n.push(h);if(typeof h!==\"string\")s=true;const p=o.slice(u+l.length);if(p)n.push(Jd(p))}if(!s){this.rendered=n.join(\"\");return}this._template=n}static date(e,t){return lC[t.dateFormat].call(e)}describe(e={}){if(!this._settings&&e.compact)return this.source;const t={template:this.source};if(this._settings)t.options=this._settings;if(this._functions)t.functions=this._functions;return t}static build(e){return new r(e.template,e.options||e.functions?{...e.options,functions:e.functions}:void 0)}isDynamic(){return!!this._template}static isTemplate(e){return e?!!e[H.template]:false}refs(){if(!this._template)return;const e=[];for(const t of this._template){if(typeof t!==\"string\")e.push(...t.refs)}return e}resolve(e,t,s,n){if(this._template&&this._template.length===1)return this._part(this._template[0],[e,t,s,n,{}]);return this.render(e,t,s,n)}_part(e,t){if(e.ref)return e.ref.resolve(...t);return e.expression.evaluate(t)}render(e,t,s,n,i={}){if(!this.isDynamic())return this.rendered;const o=[];for(const c of this._template){if(typeof c===\"string\"){o.push(c)}else{const l=this._part(c,[e,t,s,n,i]);const u=Qd(l,e,t,s,n,i);if(u!==void 0){const f=c.raw||(i.errors&&i.errors.escapeHtml)===false?u:Md(u);o.push(Zd(f,c.wrapped&&s.errors.wrap.label))}}}return o.join(\"\")}_ref(e,{raw:t,wrapped:s}){const n=[];const i=a(c=>{const l=as(c,this._settings);n.push(l);return u=>{const f=l.resolve(...u);return f!==void 0?f:null}},\"reference\");let o;try{const c=this._functions?{...ly,...this._functions}:ly;o=new Bo(e,{reference:i,functions:c,constants:uC})}catch(c){throw $n(`Invalid template variable \"${e}\" fails due to: ${c.message}`,r.prototype._ref,c)}if(o.single){if(o.single.type===\"reference\"){const c=n[0];return{ref:c,raw:t,refs:n,wrapped:s||c.type===\"local\"&&c.key===\"label\"}}return Qd(o.single.value)}return{expression:o,raw:t,refs:n}}toString(){return this.source}};Object.defineProperty(se.prototype,H.template,{value:true,writable:true,enumerable:true,configurable:true});Object.defineProperty(se.prototype,\"isImmutable\",{value:true,writable:true,enumerable:true,configurable:true});gt.template=se;function jo(r,e){if(typeof r===\"string\"){g(!e,\"Cannot set single message string\");return new se(r)}if(se.isTemplate(r)){g(!e,\"Cannot set single message template\");return r}g(typeof r===\"object\"&&!ce(r),\"Invalid message options\");const t=e?G(e):{};for(const s in r){const n=r[s];if(s===\"root\"||se.isTemplate(n)){t[s]=n;continue}if(typeof n===\"string\"){t[s]=new se(n);continue}g(typeof n===\"object\"&&!ce(n),\"Invalid message for\",s);const i=s;t[i]=t[i]||{};const o=t[i];for(const c in n){const l=n[c];if(c===\"root\"||se.isTemplate(l)){o[c]=l;continue}g(typeof l===\"string\",\"Invalid message for\",c,\"in\",i);o[c]=new se(l)}}return t}a(jo,\"compile\");function uy(r){const e={};for(const t in r){const s=r[t];if(t===\"root\"){e.root=s;continue}if(se.isTemplate(s)){e[t]=s.describe({compact:true});continue}const n=t;const i={};e[n]=i;for(const o in s){const c=s[o];if(o===\"root\"){i.root=c;continue}i[o]=c.describe({compact:true})}}return e}a(uy,\"decompile\");function ml(r,e){if(!r)return jo(e);if(!e)return r;if(typeof e===\"string\")return new se(e);if(se.isTemplate(e))return e;const t=G(r);for(const s in e){const n=e[s];if(s===\"root\"||se.isTemplate(n)){t[s]=n;continue}if(typeof n===\"string\"){t[s]=new se(n);continue}g(typeof n===\"object\"&&!ce(n),\"Invalid message for\",s);const i=s;t[i]=t[i]||{};const o=t[i];for(const c in n){const l=n[c];if(c===\"root\"||se.isTemplate(l)){o[c]=l;continue}g(typeof l===\"string\",\"Invalid message for\",c,\"in\",i);o[c]=new se(l)}}return t}a(ml,\"merge\");gt.messages={compile:a((r,e)=>jo(r,e),\"compile\")};function yl(r,e){const t=Object.getPrototypeOf(r);const s=G(t);const n=r._assign(Object.create(s));const i=Object.assign({},e);delete i.base;const o=i;s._definition=o;const c=t._definition||{};o.messages=ml(c.messages,i.messages);o.properties=Object.assign({},c.properties,i.properties);n.type=i.type;o.flags=Object.assign({},c.flags,i.flags);const l=Object.assign({},c.terms);if(i.terms){for(const h in i.terms){const p=i.terms[h];g(n.$_terms[h]===void 0,\"Invalid term override for\",i.type,h);n.$_terms[h]=p.init;l[h]=p}}o.terms=l;if(!i.args)o.args=c.args;o.prepare=mC(i.prepare,c.prepare);if(i.coerce){if(typeof i.coerce===\"function\")i.coerce={method:i.coerce};if(i.coerce.from&&!Array.isArray(i.coerce.from))i.coerce={method:i.coerce.method,from:[].concat(i.coerce.from)}}o.coerce=pC(i.coerce,c.coerce);o.validate=yC(i.validate,c.validate);const u=Object.assign({},c.rules);if(i.rules){for(const h in i.rules){const p=i.rules[h];g(typeof p===\"object\",\"Invalid rule definition for\",i.type,h);let m=p.method;if(m===void 0){m=a(function(){return this.$_addRule(h)},\"method\")}if(m){g(!s[h],\"Rule conflict in\",i.type,h);s[h]=m}g(!u[h],\"Rule conflict in\",i.type,h);u[h]=p;if(p.alias){const y=[].concat(p.alias);for(const w of y)s[w]=p.method}if(p.args){const y=new Map;p.argsByName=y;p.args=p.args.map(w=>{if(typeof w===\"string\")w={name:w};g(!y.has(w.name),\"Duplicated argument name\",w.name);if(oe(w.assert))w.assert=w.assert.strict().label(w.name);y.set(w.name,w);return w})}}}o.rules=u;const f=Object.assign({},c.modifiers);if(i.modifiers){for(const h in i.modifiers){g(!s[h],\"Rule conflict in\",i.type,h);const p=i.modifiers[h];g(typeof p===\"function\",\"Invalid modifier definition for\",i.type,h);const m=a(function(y){return this.rule({[h]:y})},\"method\");s[h]=m;f[h]=p}}o.modifiers=f;if(i.overrides){s._super=t;n.$_super={};for(const h in i.overrides){const p=t[h];g(p,\"Cannot override missing\",h);i.overrides[h][H.parent]=p;n.$_super[h]=p.bind(n)}Object.assign(s,i.overrides)}o.cast=Object.assign({},c.cast,i.cast);const d=Object.assign({},c.manifest,i.manifest);d.build=hC(i.manifest&&i.manifest.build,c.manifest&&c.manifest.build);o.manifest=d;o.rebuild=gC(i.rebuild,c.rebuild);return n}a(yl,\"type\");function hC(r,e){if(!r||!e)return r||e;return function(t,s){return e(r(t,s),s)}}a(hC,\"build\");function pC(r,e){if(!r||!e)return r||e;return{from:r.from&&e.from?[...new Set([...r.from,...e.from])]:null,method(t,s){let n;if(!e.from||e.from.includes(typeof t)){n=e.method(t,s);if(n){if(n.errors||n.value===void 0)return n;t=n.value}}if(!r.from||r.from.includes(typeof t)){const i=r.method(t,s);if(i)return i}return n}}}a(pC,\"coerce\");function mC(r,e){if(!r||!e)return r||e;return function(t,s){const n=r(t,s);if(n){if(n.errors||n.value===void 0)return n;t=n.value}return e(t,s)||n}}a(mC,\"prepare\");function gC(r,e){if(!r||!e)return r||e;return function(t){e(t);r(t)}}a(gC,\"rebuild\");function yC(r,e){if(!r||!e)return r||e;return function(t,s){const n=e(t,s);if(n){if(n.errors&&(!Array.isArray(n.errors)||n.errors.length))return n;t=n.value}return r(t,s)||n}}a(yC,\"validate\");var eh;function rh(r){const e=r._definition;const t={type:r.type,flags:{},rules:[]};const s=t.flags;const n=t.rules;for(const i in r._flags){if(i[0]!==\"_\")s[i]=zn(r._flags[i])}if(!Object.keys(s).length)delete t.flags;if(r._preferences){const i=G(r._preferences,{shallow:[\"messages\"]});t.preferences=i;delete i[H.prefs];if(i.messages)i.messages=uy(i.messages)}if(r._valids)t.allow=r._valids.describe();if(r._invalids)t.invalid=r._invalids.describe();for(const i of r._rules){const o=e.rules[i.name];if(o.manifest===false)continue;const c={name:i.name};for(const l in e.modifiers){if(i[l]!==void 0)c[l]=zn(i[l])}if(i.args){const l={};c.args=l;for(const u in i.args){const f=i.args[u];if(u===\"options\"&&!Object.keys(f).length)continue;l[u]=zn(f,{assign:u})}if(!Object.keys(l).length)delete c.args}n.push(c)}if(!n.length)delete t.rules;for(const i in r.$_terms){if(i[0]===\"_\")continue;g(!t[i],\"Cannot describe schema due to internal name conflict with\",i);const o=r.$_terms[i];if(!o)continue;if(o instanceof Map){if(o.size)t[i]=[...o.entries()];continue}if(Zg(o)){t[i]=o.describe();continue}g(e.terms[i],\"Term\",i,\"missing configuration\");const c=e.terms[i].manifest;const l=typeof c===\"object\";const u=o;if(!u.length&&!l)continue;const f=[];for(const d of u)f.push(zn(d));if(l){const{from:d,to:h}=c.mapped;const p={};t[i]=p;for(const m of f)p[m[h]]=m[d];continue}if(c===\"single\"){g(f.length===1,\"Term\",i,\"contains more than one item\");t[i]=f[0];continue}t[i]=f}py(r.$_root,t);return t}a(rh,\"describe\");function zn(r,e={}){if(Array.isArray(r))return r.map(n=>zn(n));if(r===H.deepDefault)return{special:\"deep\"};if(typeof r!==\"object\"||r===null)return r;if(e.assign===\"options\")return G(r);if(Buffer&&Buffer.isBuffer(r))return{buffer:r.toString(\"binary\")};if(r instanceof Date)return r.toISOString();if(r instanceof Error)return r;if(r instanceof RegExp){if(e.assign===\"regex\")return r.toString();return{regex:r.toString()}}const t=r;if(t[H.literal])return{function:t.literal};if(typeof t.describe===\"function\"){const n=t.describe;if(e.assign===\"ref\")return n.call(r).ref;return n.call(r)}const s={};for(const n in t){const i=t[n];if(i===void 0)continue;s[n]=zn(i,{assign:n})}return s}a(zn,\"describeItem\");function sh(r,e){const t=new th(r);return t.parse(e)}a(sh,\"build\");var th=class{static{a(this,\"Builder\")}constructor(e){this.engine=e}parse(e){py(this.engine,e);let t=this.engine[e.type].call(this.engine)._bare();const s=t._definition;if(e.flags){for(const i in e.flags){const o=s.flags[i]&&s.flags[i].setter||i;g(typeof t[o]===\"function\",\"Invalid flag\",i,\"for type\",e.type);t=dy(t,o,this.build(e.flags[i]))}}if(e.preferences)t=t.preferences(this.build(e.preferences));if(e.allow)t=t.allow(...this.build(e.allow));if(e.invalid)t=t.invalid(...this.build(e.invalid));if(e.rules){for(const i of e.rules){g(typeof t[i.name]===\"function\",\"Invalid rule\",i.name,\"for type\",e.type);const o=[];if(i.args){const l={};for(const d in i.args)l[d]=this.build(i.args[d],{assign:d});const u=Object.keys(l);const f=s.rules[i.name].args;if(f){g(u.length<=f.length,\"Invalid number of arguments for\",e.type,i.name,\"(expected up to\",f.length,\", found\",u.length,\")\");for(const{name:d}of f)o.push(l[d])}else{g(u.length===1,\"Invalid number of arguments for\",e.type,i.name,\"(expected up to 1, found\",u.length,\")\");o.push(l[u[0]])}}t=dy(t,i.name,...o);const c={};for(const l in s.modifiers){if(i[l]!==void 0)c[l]=this.build(i[l])}if(Object.keys(c).length)t=t.rule(c)}}const n={};for(const i in e){if([\"allow\",\"flags\",\"invalid\",\"whens\",\"preferences\",\"rules\",\"type\"].includes(i))continue;g(s.terms[i],\"Term\",i,\"missing configuration\");const o=s.terms[i].manifest;if(o===\"schema\"){n[i]=e[i].map(c=>this.parse(c));continue}if(o===\"values\"){n[i]=e[i].map(c=>this.build(c));continue}if(o===\"single\"){n[i]=this.build(e[i]);continue}if(typeof o===\"object\"){const c={};n[i]=c;const l=e[i];for(const u in l){const f=l[u];c[u]=this.parse(f)}continue}n[i]=this.build(e[i])}if(e.whens)n.whens=e.whens.map(i=>this.build(i));t=s.manifest.build(t,n);t.$_temp.ruleset=false;return t}build(e,t={}){if(e===null)return null;if(Array.isArray(e))return e.map(i=>this.build(i));if(e instanceof Error)return e;if(t.assign===\"options\")return G(e);if(t.assign===\"regex\")return hy(e);if(t.assign===\"ref\")return zd(e);if(typeof e!==\"object\")return e;const s=e;if(Object.keys(s).length===1){if(s.buffer){g(Buffer,\"Buffers are not supported\");return Buffer&&Buffer.from(s.buffer,\"binary\")}if(s.function)return{[H.literal]:true,literal:s.function};if(s.override)return H.override;if(s.ref)return zd(s.ref);if(s.regex)return hy(s.regex);if(s.special){g([\"deep\"].includes(s.special),\"Unknown special value\",s.special);return H.deepDefault}if(s.value)return G(s.value)}if(s.type)return this.parse(s);if(s.template)return se.build(s);const n={};for(const i in s)n[i]=this.build(s[i],{assign:i});return n}};function dy(r,e,...t){return r[e].call(r,...t)}a(dy,\"call\");function hy(r){const e=r.lastIndexOf(\"/\");const t=r.slice(1,e);const s=r.slice(e+1);return new RegExp(t,s)}a(hy,\"regex\");function py(r,e){eh=eh||gt.schemas();r.assert(e,eh.description)}a(py,\"validate\");function nh(r=0){const e=Error.prepareStackTrace;Error.prepareStackTrace=(n,i)=>i;const t={};Error.captureStackTrace(t);const s=t.stack[r+1];Error.prepareStackTrace=e;return{filename:s.getFileName(),line:s.getLineNumber()}}a(nh,\"location\");var bC={error:1,pass:2,full:3};var SC={0:\"never used\",1:\"always error\",2:\"always pass\"};function ch(r){const e=a(function(){r._tracer=r._tracer||new oh;return r._tracer},\"trace\");r.trace=e;r.untrace=()=>{r._tracer=null}}a(ch,\"setup\");function lh(r){return r.$_setFlag(\"_tracerLocation\",nh(2))}a(lh,\"location\");var oh=class{static{a(this,\"Tracer\")}constructor(){this.name=\"lakutata\";this._schemas=new Map}_register(e){const t=this._schemas.get(e);if(t)return t.store;const s=new ah(e);const{filename:n,line:i}=e._flags._tracerLocation||nh(5);this._schemas.set(e,{filename:n,line:i,store:s});return s}_combine(e,t){for(const{store:s}of this._schemas.values())s._combine(e,t)}report(e){const t=[];for(const{filename:s,line:n,store:i}of this._schemas.values()){if(e&&e!==s)continue;const o=[];const c=[];for(const[l,u]of i._sources.entries()){if(TC(u.paths,c))continue;if(!u.entry){o.push({status:\"never reached\",paths:[...u.paths]});c.push(...u.paths);continue}for(const d of[\"valid\",\"invalid\"]){const h=l[`_${d}s`];if(!h)continue;const p=new Set(h._values);const m=new Set(h._refs);for(const{value:y,ref:w}of u[d]){p.delete(y);m.delete(w)}if(p.size||m.size){o.push({status:[...p,...[...m].map(y=>y.display)],rule:`${d}s`})}}const f=l._rules.map(d=>d.name);for(const d of[\"default\",\"failover\"]){if(l._flags[d]!==void 0)f.push(d)}for(const d of f){const h=SC[u.rule[d]||0];if(h){const p={rule:d,status:h};if(u.paths.size)p.paths=[...u.paths];o.push(p)}}}if(o.length){t.push({filename:s,line:n,missing:o,severity:\"error\",message:`Schema missing tests for ${o.map(wC).join(\", \")}`})}}return t.length?t:null}};var ah=class{static{a(this,\"Store\")}constructor(e){this.active=true;this._sources=new Map;this._combos=new Map;this._scan(e)}debug(e,t,s,n){e.mainstay.debug&&e.mainstay.debug.push({type:t,name:s,result:n,path:e.path})}entry(e,t){ih(t,{type:\"entry\"});this._record(e,s=>{s.entry=true})}filter(e,t,s,n){ih(t,{type:s,...n});this._record(e,i=>{i[s].add(n)})}log(e,t,s,n,i){ih(t,{type:s,name:n,result:i===\"full\"?\"pass\":i});this._record(e,o=>{o[s][n]=o[s][n]||0;o[s][n]|=bC[i]})}resolve(e,t,s){if(!e.mainstay.debug)return;const n={type:\"resolve\",ref:t.display,to:s,path:e.path};e.mainstay.debug.push(n)}value(e,t,s,n,i){if(!e.mainstay.debug||Ct(s,n))return;const o={type:\"value\",by:t,from:s,to:n,path:e.path};if(i)o.name=i;e.mainstay.debug.push(o)}_record(e,t){const s=this._sources.get(e);if(s){t(s);return}const n=this._combos.get(e);for(const i of n)this._record(i,t)}_scan(e,t){const s=t||[];let n=this._sources.get(e);if(!n){n={paths:new Set,entry:false,rule:{},valid:new Set,invalid:new Set};this._sources.set(e,n)}if(s.length)n.paths.add(s);const i=a((o,c)=>{const l=EC(o,c);this._scan(o,s.concat(l))},\"each\");e.$_modify({each:i,ref:false})}_combine(e,t){this._combos.set(e,t)}};function wC(r){const e=r.paths?Xd(r.paths[0])+(r.rule?\":\":\"\"):\"\";return`${e}${r.rule||\"\"} (${r.status})`}a(wC,\"message\");function EC(r,{source:e,name:t,path:s,key:n}){if(r._flags.id)return r._flags.id;if(n)return n;t=`@${t}`;if(e===\"terms\")return[t,s[Math.min(s.length-1,1)]];return t}a(EC,\"id\");function TC(r,e){for(const t of r){for(const s of e){if(Ct(t.slice(0,s.length),s))return true}}return false}a(TC,\"sub\");function ih(r,e){if(r.mainstay.debug){e.path=r.debug?[...r.path,r.debug]:r.path;r.mainstay.debug.push(e)}}a(ih,\"debug\");var bl=class r{static{a(this,\"Ids\")}constructor(){this._byId=new Map;this._byKey=new Map;this._schemaChain=false}clone(){const e=new r;e._byId=new Map(this._byId);e._byKey=new Map(this._byKey);e._schemaChain=this._schemaChain;return e}concat(e){if(e._schemaChain)this._schemaChain=true;for(const[t,s]of e._byId.entries()){g(!this._byKey.has(t),\"Schema id conflicts with existing key:\",t);this._byId.set(t,s)}for(const[t,s]of e._byKey.entries()){g(!this._byId.has(t),\"Schema key conflicts with existing id:\",t);this._byKey.set(t,s)}}fork(e,t,s){const n=this._collect(e);n.push({schema:s});const i=n.shift();let o={id:i.id,schema:t(i.schema)};g(oe(o.schema),\"adjuster function failed to return a schema\");for(const c of n)o={id:c.id,schema:xC(c.schema,o.id,o.schema)};return o.schema}labels(e,t=[]){const s=e[0];const n=this._get(s);if(!n)return[...t,...e].join(\".\");const i=e.slice(1);t=[...t,n.schema._flags.label||s];if(!i.length)return t.join(\".\");return n.schema._ids.labels(i,t)}reach(e,t=[]){const s=e[0];const n=this._get(s);g(n,\"Schema does not contain path\",[...t,...e].join(\".\"));const i=e.slice(1);if(!i.length)return n.schema;return n.schema._ids.reach(i,[...t,s])}register(e,{key:t}={}){if(!e||!oe(e))return;const s=e;if(s.$_property(\"schemaChain\")||s._ids._schemaChain)this._schemaChain=true;const n=s._flags.id;if(n){const i=this._byId.get(n);g(!i||i.schema===s,\"Cannot add different schemas with the same id:\",n);g(!this._byKey.has(n),\"Schema id conflicts with existing key:\",n);this._byId.set(n,{schema:s,id:n})}if(t){g(!this._byKey.has(t),\"Schema already contains key:\",t);g(!this._byId.has(t),\"Schema key conflicts with existing id:\",t);this._byKey.set(t,{schema:s,id:t})}}reset(){this._byId=new Map;this._byKey=new Map;this._schemaChain=false}_collect(e,t=[],s=[]){const n=e[0];const i=this._get(n);g(i,\"Schema does not contain path\",[...t,...e].join(\".\"));s=[i,...s];const o=e.slice(1);if(!o.length)return s;return i.schema._ids._collect(o,[...t,n],s)}_get(e){return this._byId.get(e)||this._byKey.get(e)}};function xC(r,e,t){const s=a((i,{key:o})=>{if(e===(i._flags.id||o))return t},\"each\");const n=uh(r,{each:s,ref:false});return n?n.$_mutateRebuild():r}a(xC,\"fork\");function uh(r,e){let t;for(const s in r._flags){if(s[0]===\"_\")continue;const n=$o(r._flags[s],{source:\"flags\",name:s},e);if(n!==void 0){t=t||r.clone();t._flags[s]=n}}for(let s=0;s<r._rules.length;++s){const n=r._rules[s];const i=$o(n.args,{source:\"rules\",name:n.name},e);if(i!==void 0){t=t||r.clone();const o=Object.assign({},n);o.args=i;t._rules[s]=o;const c=t._singleRules.get(n.name);if(c===n)t._singleRules.set(n.name,o)}}for(const s in r.$_terms){if(s[0]===\"_\")continue;const n=$o(r.$_terms[s],{source:\"terms\",name:s},e);if(n!==void 0){t=t||r.clone();t.$_terms[s]=n}}return t}a(uh,\"modifySchema\");function $o(r,e,t,s,n){const i=s||[];if(r===null||typeof r!==\"object\")return;let o;if(Array.isArray(r)){for(let l=0;l<r.length;++l){const u=e.source===\"terms\"&&e.name===\"keys\"&&r[l].key;const f=$o(r[l],e,t,[l,...i],u);if(f!==void 0){o=o||r.slice();o[l]=f}}return o}if(t.schema!==false&&oe(r)||t.ref!==false&&rt(r)){const l=t.each(r,{...e,path:i,key:n});if(l===r)return;return l}const c=r;for(const l in c){if(l[0]===\"_\")continue;const u=$o(c[l],e,t,[l,...i],n);if(u!==void 0){o=o||Object.assign({},c);o[l]=u}}return o}a($o,\"scan\");var yy=Symbol(\"value\");function by(r){if(oe(r))return{schema:r};return r}a(by,\"schemaEntry\");var fh=class{static{a(this,\"Shadow\")}constructor(){this._values=null}set(e,t,s){if(!e.length)return;if(s===\"strip\"&&typeof e[e.length-1]===\"number\")return;this._values=this._values||new Map;let n=this._values;for(let i=0;i<e.length;++i){const o=e[i];let c=n.get(o);if(!c){c=new Map;n.set(o,c)}n=c}n[yy]=t}get(e){const t=this.node(e);if(t)return t[yy]}node(e){if(!this._values)return;return et(this._values,e,{iterables:true})}override(e,t){if(!this._values)return;const s=e.slice(0,-1);const n=e[e.length-1];const i=et(this._values,s,{iterables:true});if(t){i.set(n,t);return}if(i)i.delete(n)}};var Sl=class r{static{a(this,\"State\")}constructor(e,t,s){this.path=e;this.ancestors=t;this.mainstay=s.mainstay;this.schemas=s.schemas;this.debug=null}localize(e,t=null,s=null){const n=new r(e,t,this);if(s&&n.schemas)n.schemas=[by(s),...n.schemas];return n}nest(e,t){const s=new r(this.path,this.ancestors,this);s.schemas=s.schemas&&[by(e),...s.schemas];s.debug=t;return s}shadow(e,t){this.mainstay.shadow=this.mainstay.shadow||new fh;this.mainstay.shadow.set(this.path,e,t)}snapshot(){if(this.mainstay.shadow)this._snapshot=G(this.mainstay.shadow.node(this.path));this.mainstay.snapshot()}restore(){if(this.mainstay.shadow){this.mainstay.shadow.override(this.path,this._snapshot);this._snapshot=void 0}this.mainstay.restore()}commit(){if(this.mainstay.shadow){this.mainstay.shadow.override(this.path,this._snapshot);this._snapshot=void 0}this.mainstay.commit()}};var xe=Symbol(\"fallback\");var le=Symbol(\"invalid\");var dh=Object.freeze({fastPathError:true});var _C=Symbol(\"unsupported\");var Sy=new Map([[\"any\",new Set],[\"string\",null],[\"number\",null],[\"boolean\",null],[\"date\",null],[\"object\",new Set([\"min\",\"max\",\"length\"])],[\"array\",new Set([\"items\",\"min\",\"max\",\"length\"])],[\"alternatives\",new Set]]);var CC=[\"empty\",\"cast\",\"result\",\"artifact\",\"_endedSwitch\",\"_hasPatternMatch\",\"single\",\"match\"];var vC=[\"whens\",\"externals\",\"renames\",\"dependencies\",\"_exclusions\",\"_requireds\"];var xy=new WeakSet;function Us(r){xy.add(r);return r}a(Us,\"pure\");function AC(r,e){return{original:void 0,prefs:e,schema:r,state:void 0,error:a(()=>dh,\"error\"),errorsArray:a(()=>{const t=[];t[H.errors]=true;return t},\"errorsArray\"),warn:a(()=>{throw _C},\"warn\"),message:a(()=>dh,\"message\")}}a(AC,\"fixedHelpers\");function IC(r){return!!r.errors&&(!Array.isArray(r.errors)||r.errors.length>0)}a(IC,\"hasErrors\");function OC(r){return r===dh||r instanceof vt||Array.isArray(r)&&!!r[H.errors]}a(OC,\"isRuleError\");function wy(r){return!r||r._refs.size===0}a(wy,\"withoutReferences\");function kC(r,e,t){const s=r._definition.rules[e.method];const n=s.validate;if(!n)return null;const i=e.args;return o=>{const c=n(o,t,i,e);return OC(c)?le:c}}a(kC,\"compileRule\");function PC(r,e){const t=r.$_terms;const s=t.keys;const n=t.patterns;const i=r.$_property(\"typeof\");if(!s&&!n){return m=>!m||typeof m!==i||Array.isArray(m)?le:m}const o=[];for(const m of s||[]){const y=Bs(m.schema,e);if(!y)return null;o.push({key:m.key,compiled:y})}const c=[];const l=Object.assign({},e,{abortEarly:true,_externals:false});for(const m of n||[]){if(m.matches)return null;const y=Bs(m.rule,e);if(!y)return null;if(m.regex){c.push({regex:m.regex,rule:y,fallthrough:!!m.fallthrough})}else{const w=Bs(m.schema,l);if(!w)return null;c.push({matcher:w,rule:y,fallthrough:!!m.fallthrough})}}const u=r._flags;const f=e.stripUnknown?e.stripUnknown===true?true:!!e.stripUnknown.objects:false;const d=!!(e.stripUnknown&&typeof u.unknown===\"undefined\"||e.skipFunctions);const h=!Ds(u.unknown,e.allowUnknown);const p=h&&!c.length?new Set(o.map(m=>m.key)):null;return m=>{if(!m||typeof m!==i||Array.isArray(m))return le;const y=Object.create(Object.getPrototypeOf(m));Object.assign(y,m);const w=new Set(Object.keys(y));if(p){for(const S of w){if(p.has(S))continue;if(d&&(f||typeof y[S]===\"function\"))continue;return le}}for(const{key:S,compiled:T}of o){const _=y[S];w.delete(S);const x=T(_);if(x===xe||x===le)return x;if(x===void 0&&_!==void 0){delete y[S]}else if(x!==void 0){y[S]=x}}if(w.size){for(const S of w){const T=y[S];for(const _ of c){if(_.regex){if(!_.regex.test(S))continue}else{const k=_.matcher(S);if(k===le)continue;if(k===xe)return xe}w.delete(S);const x=_.rule(T);if(x===xe||x===le)return x;y[S]=x;if(!_.fallthrough)break}}if(w.size){if(d){for(const S of w){if(f){delete y[S];w.delete(S)}else if(typeof y[S]===\"function\"){w.delete(S)}}}if(h&&w.size)return le}}return y}}a(PC,\"compileKeys\");function NC(r,e){const t=r.$_terms;const s=t.items;const n=t._inclusions;if(s.length>1||n.length!==s.length)return null;const i=n.length?Bs(n[0],e):null;if(n.length&&!i)return null;const o=[];for(const u of t.ordered){const f=Bs(u,e);if(!f)return null;o.push(f)}const c=!!r._flags.sparse;const l=!!(e.stripUnknown&&e.stripUnknown.arrays);return u=>{const f=u;let d=0;for(let h=0;h<f.length;++h){const p=f[h];if(!c&&p===void 0)return le;if(o.length){if(d<o.length){const m=o[d++](p);if(m===xe||m===le)return m;if(!c&&m===void 0)return le;f[h]=m;continue}else if(!s.length){return le}}if(i){const m=i(p);if(m===xe)return xe;if(m===le)return l?xe:le;if(!c&&m===void 0)return le;f[h]=m}}if(d<o.length)return xe;return f}}a(NC,\"compileItems\");function LC(r){if(!Sy.has(r.type))return false;if(r._cache||r._ids._schemaChain)return false;const e=r._flags;for(const n of CC){if(e[n]!==void 0)return false}if(typeof e.unknown===\"object\")return false;const t=r.$_terms;for(const n of vC){const i=t[n];if(i&&(!Array.isArray(i)||i.length))return false}if(!wy(r._valids)||!wy(r._invalids))return false;const s=Sy.get(r.type);for(const n of r._rules){if(n._resolve.length||n.warn)return false;if(n.name===\"custom\"){if(!xy.has(n.args.method))return false;continue}if(n.name===\"warning\")return false;if(s&&!s.has(n.name))return false}return true}a(LC,\"compilable\");function Bs(r,e){if(!LC(r))return null;const t=r._preferences?Ht(e,r._preferences):e;if(t.nonEnumerables||t.debug)return null;const s=r._definition;const n=r._flags;const i=AC(r,t);const o=t.convert?s.prepare:void 0;const c=t.convert?s.coerce:void 0;const l=n.presence||t.presence;const u=n.default!==void 0&&!t.noDefaults;const f=n.default===H.deepDefault;const d=r._valids;const h=r._invalids;const p=n.insensitive;const m=!!n.only;const y=!!t.convert;let w;if(r.type===\"object\"){w=PC(r,t);if(!w)return null}else if(r.type===\"alternatives\"){w=MC(r,t);if(!w)return null}else{const N=s.validate;w=N?A=>{const B=N(A,i);if(!B)return A;if(IC(B))return le;return B.value}:null}const S=[];for(const N of r._rules){const A=s.rules[N.method];if(A.convert&&y)continue;const B=r.type===\"array\"&&N.name===\"items\"?NC(r,t):kC(r,N,i);if(!B)return null;S.push(B)}const T=n.default;const _=a(()=>{if(!T)return T;if(typeof T===\"function\")return xe;if(typeof T!==\"object\")return T;if(T[H.literal])return T.literal;if(tt(T))return xe;return G(T)},\"defaulted\");const x=a(N=>N===void 0&&u?_():N,\"finalize\");const k=a(N=>{let A=N;if(o&&A!==void 0){const B=o(A,i);if(B){if(B.errors)return le;A=B.value}}if(c&&A!==void 0&&(!c.from||c.from.includes(typeof A))){const B=c.method(A,i);if(B){if(B.errors)return le;A=B.value}}if(A===void 0){if(l===\"forbidden\")return x(A);if(l===\"required\")return le;if(l===\"optional\")return f?xe:x(A)}else if(l===\"forbidden\"){return le}if(d){const B=d.get(A,null,t,p);if(B){if(y)A=B.value;return x(A)}if(m)return le}if(h&&h.get(A,null,t,p))return le;if(w){A=w(A);if(A===xe||A===le)return A}for(const B of S){A=B(A);if(A===xe||A===le)return A}return x(A)},\"node\");if(n.failover===void 0)return k;return N=>{const A=k(N);return A===le?xe:A}}a(Bs,\"compileSchema\");function MC(r,e){const t=[];for(const s of r.$_terms.matches){if(!s.schema)return null;const n=Bs(s.schema,e);if(!n)return null;t.push(n)}return s=>{for(const n of t){const i=n(s);if(i!==le)return i}return le}}a(MC,\"compileAlternatives\");var Ey=new WeakMap;function Ry(r,e){let t=Ey.get(r);if(!t){t=new WeakMap;Ey.set(r,t)}let s=t.get(e);if(s===void 0){const n=e.debug?null:Bs(r,e);s=n?DC(n):null;t.set(e,s)}return s}a(Ry,\"compiledFor\");function DC(r){return e=>{try{return r(e)}catch{return xe}}}a(DC,\"guarded\");function Ty(r){try{return Date.prototype.getTime.call(r)}catch{return void 0}}a(Ty,\"dateTime\");function hh(r,e,t,s=new Map){if(Object.is(r,e))return true;if(typeof r!==\"object\"||r===null||typeof e!==\"object\"||e===null)return false;if(r===t||e===t)return false;const n=s.get(r);if(n)return n===e;s.set(r,e);if(Object.getPrototypeOf(r)!==Object.getPrototypeOf(e))return false;if(Array.isArray(r)!==Array.isArray(e))return false;const i=Ty(r);const o=Ty(e);if(i!==void 0||o!==void 0)return i!==void 0&&o!==void 0&&Object.is(i,o);const c=Reflect.ownKeys(r);const l=Reflect.ownKeys(e);if(c.length!==l.length)return false;for(let u=0;u<l.length;++u){const f=l[u];if(c[u]!==f)return false;const d=Object.getOwnPropertyDescriptor(r,f);const h=Object.getOwnPropertyDescriptor(e,f);if(d.enumerable!==h.enumerable||d.configurable!==h.configurable||d.writable!==h.writable)return false;if(d.get!==h.get||d.set!==h.set)return false;if(\"value\"in d){const p=t!==null&&typeof t===\"object\"?t[f]:void 0;if(!hh(d.value,h.value,p,s))return false}}return true}a(hh,\"sameResult\");var ph=class{static{a(this,\"Mainstay\")}constructor(e,t,s){this.externals=[];this.warnings=[];this.tracer=e;this.debug=t;this.links=s;this.shadow=null;this.artifacts=null;this._snapshots=[]}snapshot(){this._snapshots.push({externals:this.externals.slice(),warnings:this.warnings.slice()})}restore(){const e=this._snapshots.pop();this.externals=e.externals;this.warnings=e.warnings}commit(){this._snapshots.pop()}};function mh(r,e,t){let s=is;if(t){g(t.warnings===void 0,\"Cannot override warnings preference in synchronous validation\");g(t.artifacts===void 0,\"Cannot override artifacts preference in synchronous validation\");s=Ly(t)}const n=Py(r,e,s);if(n!==xe&&n!==le&&Gn===\"on\")return{value:n};const i=Oy(r,e,s);if(Gn===\"verify\")Ny(r,n,i);g(!i.mainstay.externals.length,\"Schema with external rules must use validateAsync()\");const o={value:i.value};if(i.error)o.error=i.error;if(i.mainstay.warnings.length)o.warning=lr(i.mainstay.warnings);if(i.mainstay.debug)o.debug=i.mainstay.debug;if(i.mainstay.artifacts)o.artifacts=i.mainstay.artifacts;return o}a(mh,\"entry\");async function gh(r,e,t){let s=is;if(t)s=Ly(t);const n=Py(r,e,s);if(n!==xe&&n!==le&&Gn===\"on\"){if(!s.warnings&&!s.debug&&!s.artifacts)return n;return{value:n}}const i=Oy(r,e,s);if(Gn===\"verify\")Ny(r,n,i);const o=i.mainstay;if(i.error){if(o.debug)i.error.debug=o.debug;throw i.error}if(o.externals.length){let l=i.value;const u=[];for(const f of o.externals){const d=f.state.path;const h=f.schema.type===\"link\"?o.links.get(f.schema):null;let p=l;let m;let y;const w=d.length?[l]:[];const S=d.length?et(r,d):r;if(d.length){m=d[d.length-1];let T=l;for(const _ of d.slice(0,-1)){T=T[_];w.unshift(T)}y=w[0];p=y[m]}try{const T=a((x,k)=>(h||f.schema).$_createError(x,p,k,f.state,s),\"createError\");const _=await f.method(p,{schema:f.schema,linked:h,state:f.state,prefs:t,original:S,error:T,errorsArray:My,warn:a((x,k)=>{o.warnings.push((h||f.schema).$_createError(x,p,k,f.state,s))},\"warn\"),message:a((x,k)=>(h||f.schema).$_createError(\"external\",p,k,f.state,s,{messages:x}),\"message\")});if(_===void 0||_===p)continue;if(_ instanceof vt){o.tracer.log(f.schema,f.state,\"rule\",\"external\",\"error\");u.push(_);if(s.abortEarly)break;continue}if(Array.isArray(_)&&_[H.errors]){o.tracer.log(f.schema,f.state,\"rule\",\"external\",\"error\");u.push(..._);if(s.abortEarly)break;continue}if(y){o.tracer.value(f.state,\"rule\",p,_,\"external\");y[m]=_}else{o.tracer.value(f.state,\"rule\",l,_,\"external\");l=_}}catch(T){if(s.errors.label)ss(T,`${T.message} (${f.label})`);throw T}}i.value=l;if(u.length){i.error=Yd(u,r,s);if(o.debug)i.error.debug=o.debug;throw i.error}}if(!s.warnings&&!s.debug&&!s.artifacts)return i.value;const c={value:i.value};if(o.warnings.length)c.warning=lr(o.warnings);if(o.debug)c.debug=o.debug;if(o.artifacts)c.artifacts=o.artifacts;return c}a(gh,\"entryAsync\");function Iy(r,e){if(e.isAsync())return gh(r,e);return mh(r,e)}a(Iy,\"standard\");function Oy(r,e,t){const{tracer:s,cleanup:n}=BC(e,t);const i=t.debug?[]:null;const o=e._ids._schemaChain?new Map:null;const c=new ph(s,i,o);const l=e._ids._schemaChain?[{schema:e}]:null;const u=new Sl([],[],{mainstay:c,schemas:l});const f=wl(r,e,u,t);if(n)e.$_root.untrace();const d=Yd(f.errors,r,t);return{value:f.value,error:d,mainstay:c}}a(Oy,\"validateEntry\");function BC(r,e){if(r.$_root._tracer)return{tracer:r.$_root._tracer._register(r)};if(e.debug){g(r.$_root.trace,\"Debug mode not supported\");return{tracer:r.$_root.trace()._register(r),cleanup:true}}return{tracer:qC}}a(BC,\"tracerOf\");function wl(r,e,t,s,n={}){if(e.$_terms.whens)e=e._generate(r,t,s).schema;if(e._preferences)s=$C(e,s);if(e._cache&&s.cache){const d=e._cache.get(r);t.mainstay.tracer.debug(t,\"validate\",\"cached\",!!d);if(d)return d}const i=a((d,h,p)=>e.$_createError(d,r,h,p||t,s),\"createError\");const o={original:r,prefs:s,schema:e,state:t,error:i,errorsArray:My,warn:a((d,h,p)=>{t.mainstay.warnings.push(i(d,h,p))},\"warn\"),message:a((d,h)=>e.$_createError(\"custom\",r,h,t,s,{messages:d}),\"message\")};t.mainstay.tracer.entry(e,t);const c=e._definition;if(c.prepare&&r!==void 0&&s.convert){const d=c.prepare(r,o);if(d){t.mainstay.tracer.value(t,\"prepare\",r,d.value);if(d.errors)return at(d.value,[].concat(d.errors),o);r=d.value}}if(c.coerce&&r!==void 0&&s.convert&&(!c.coerce.from||c.coerce.from.includes(typeof r))){const d=c.coerce.method(r,o);if(d){t.mainstay.tracer.value(t,\"coerced\",r,d.value);if(d.errors)return at(d.value,[].concat(d.errors),o);r=d.value}}const l=e._flags.empty;if(l&&l.$_match(HC(r,e),t.nest(l),is)){t.mainstay.tracer.value(t,\"empty\",r,void 0);r=void 0}const u=n.presence||e._flags.presence||(e._flags._endedSwitch?null:s.presence);if(r===void 0){if(u===\"forbidden\")return at(r,null,o);if(u===\"required\")return at(r,[e.$_createError(\"any.required\",r,null,t,s)],o);if(u===\"optional\"){if(e._flags.default!==H.deepDefault)return at(r,null,o);t.mainstay.tracer.value(t,\"default\",r,{});r={}}}else if(u===\"forbidden\"){return at(r,[e.$_createError(\"any.unknown\",r,null,t,s)],o)}const f=[];if(e._valids){const d=e._valids.get(r,t,s,e._flags.insensitive);if(d){if(s.convert){t.mainstay.tracer.value(t,\"valids\",r,d.value);r=d.value}t.mainstay.tracer.filter(e,t,\"valid\",d);return at(r,null,o)}if(e._flags.only){const h=e.$_createError(\"any.only\",r,{valids:e._valids.values({display:true})},t,s);if(s.abortEarly)return at(r,[h],o);f.push(h)}}if(e._invalids){const d=e._invalids.get(r,t,s,e._flags.insensitive);if(d){t.mainstay.tracer.filter(e,t,\"invalid\",d);const h=e.$_createError(\"any.invalid\",r,{invalids:e._invalids.values({display:true})},t,s);if(s.abortEarly)return at(r,[h],o);f.push(h)}}if(c.validate){const d=c.validate(r,o);if(d){t.mainstay.tracer.value(t,\"base\",r,d.value);r=d.value;if(d.errors){if(!Array.isArray(d.errors)){f.push(d.errors);return at(r,f,o)}if(d.errors.length){f.push(...d.errors);return at(r,f,o)}}}}if(!e._rules.length)return at(r,f,o);return UC(r,f,o)}a(wl,\"validate\");function UC(r,e,t){const{schema:s,state:n,prefs:i}=t;for(const o of s._rules){const c=s._definition.rules[o.method];if(c.convert&&i.convert){n.mainstay.tracer.log(s,n,\"rule\",o.name,\"full\");continue}let l;let u=o.args;if(o._resolve.length){u=Object.assign({},u);for(const d of o._resolve){const h=c.argsByName.get(d);const p=u[d].resolve(r,n,i);const m=h.normalize?h.normalize(p):p;const y=al(m,void 0,h);if(y){l=s.$_createError(\"any.ref\",p,{arg:d,ref:u[d],reason:y},n,i);break}u[d]=m}}l=l||c.validate(r,t,u,o);const f=jC(l,o);if(f.errors){n.mainstay.tracer.log(s,n,\"rule\",o.name,\"error\");if(o.warn){n.mainstay.warnings.push(...f.errors);continue}if(i.abortEarly)return at(r,f.errors,t);e.push(...f.errors)}else{n.mainstay.tracer.log(s,n,\"rule\",o.name,\"pass\");n.mainstay.tracer.value(n,\"rule\",r,f.value,o.name);r=f.value}}return at(r,e,t)}a(UC,\"rules\");function jC(r,e){if(r instanceof vt){_y(r,e);return{errors:[r],value:null}}if(Array.isArray(r)&&r[H.errors]){r.forEach(t=>_y(t,e));return{errors:r,value:null}}return{errors:null,value:r}}a(jC,\"ruleResult\");function _y(r,e){if(e.message)r._setTemplate(e.message);return r}a(_y,\"error\");function at(r,e,t){e=e||[];const{schema:s,state:n,prefs:i}=t;if(e.length){const l=Ay(\"failover\",void 0,e,t);if(l!==void 0){n.mainstay.tracer.value(n,\"failover\",r,l);r=l;e=[]}}const o=s._flags.error;if(e.length&&o){if(typeof o===\"function\"){const l=o(e);e=Array.isArray(l)?l:[l];for(const u of e)g(u instanceof Error||u instanceof vt,\"error() must return an Error object\")}else{e=[o]}}if(r===void 0){const l=Ay(\"default\",r,e,t);n.mainstay.tracer.value(n,\"default\",r,l);r=l}if(s._flags.cast&&r!==void 0){const l=s._definition.cast[s._flags.cast];if(l.from(r)){const u=l.to(r,t);n.mainstay.tracer.value(n,\"cast\",r,u,s._flags.cast);r=u}}if(s.$_terms.externals&&i.externals&&i._externals!==false){for(const{method:l}of s.$_terms.externals)n.mainstay.externals.push({method:l,schema:s,state:n,label:Uo(s._flags,n,i,void 0)})}const c={value:r,errors:e.length?e:null};if(s._flags.result){c.value=s._flags.result===\"strip\"?void 0:t.original;n.mainstay.tracer.value(n,s._flags.result,r,c.value);n.shadow(r,s._flags.result)}if(s._cache&&i.cache!==false&&!s._refs.length)s._cache.set(t.original,c);if(r!==void 0&&!c.errors&&s._flags.artifact!==void 0){n.mainstay.artifacts=n.mainstay.artifacts||new Map;if(!n.mainstay.artifacts.has(s._flags.artifact))n.mainstay.artifacts.set(s._flags.artifact,[]);n.mainstay.artifacts.get(s._flags.artifact).push(n.path)}return c}a(at,\"finalize\");var Cy=new WeakMap;function $C(r,e){const t=r._preferences;const s=e===is;if(s&&t[H.prefs])return t[H.prefs];let n=Cy.get(t);const i=n&&n.get(e);if(i)return i;const o=Ht(e,t);if(s){t[H.prefs]=o}else{if(!n){n=new WeakMap;Cy.set(t,n)}n.set(e,o)}return o}a($C,\"prefsOf\");var vy=new WeakMap;var ky=new WeakSet([is]);var Gn=\"on\";function Py(r,e,t){if(Gn===\"off\"||e.$_root._tracer)return xe;if(Gn===\"on\"&&!ky.has(t))return xe;const s=Ry(e,t);return s?s(r):xe}a(Py,\"fastPath\");function Ny(r,e,t){if(e===xe)return;if(e===le){if(!t.error)throw new Error(\"Validation fast path mismatch: invalid for the fast path, valid for the interpreter\");return}if(t.error||!hh(e,t.value,r))throw new Error(`Validation fast path mismatch: ${t.error?t.error.message:\"different value\"}`)}a(Ny,\"verifyFastPath\");function FC(r){if(!Object.isFrozen(r)||Object.getOwnPropertySymbols(r).length)return false;for(const e of Object.keys(r)){const t=r[e];if(t!==null&&typeof t===\"object\"||typeof t===\"function\")return false}return true}a(FC,\"isImmutableOptions\");function Ly(r){const e=vy.get(r);if(e)return e;const t=Ht(is,r);if(FC(r)){vy.set(r,t);ky.add(t)}return t}a(Ly,\"entrySettings\");function Ay(r,e,t,s){const{schema:n,state:i,prefs:o}=s;const c=n._flags[r];if(o.noDefaults||c===void 0)return e;i.mainstay.tracer.log(n,i,\"rule\",r,\"full\");if(!c)return c;if(typeof c===\"function\"){const l=c.length?[G(i.ancestors[0]),s]:[];try{return c(...l)}catch(u){t.push(n.$_createError(`any.${r}`,null,{error:u},i,o));return}}if(typeof c!==\"object\")return c;if(c[H.literal])return c.literal;if(tt(c))return c.resolve(e,i,o);return G(c)}a(Ay,\"defaultValue\");function HC(r,e){if(typeof r!==\"string\")return r;const t=e.$_getRule(\"trim\");if(!t||!t.args.enabled)return r;return r.trim()}a(HC,\"trim\");var qC={active:false,debug:ts,entry:ts,filter:ts,log:ts,resolve:ts,value:ts};function My(){const r=[];r[H.errors]=true;return r}a(My,\"errorsArray\");function GC(r){const e=new Map;if(r){for(const t of r){if(typeof t===\"string\")e.set(t.toLowerCase(),t)}}return e}a(GC,\"lowercases\");var zt=class r{static{a(this,\"Values\")}constructor(e,t){this._values=new Set(e);this._refs=new Set(t);this._lowercase=GC(e);this._override=false}get length(){return this._values.size+this._refs.size}add(e,t){if(tt(e)){if(!this._refs.has(e)){this._refs.add(e);if(t)t.register(e)}return}if(!this.has(e,null,null,false)){this._values.add(e);if(typeof e===\"string\")this._lowercase.set(e.toLowerCase(),e)}}static merge(e,t,s){const n=e||new r;if(t){if(t._override)return t.clone();for(const i of[...t._values,...t._refs])n.add(i)}if(s){for(const i of[...s._values,...s._refs])n.remove(i)}return n.length?n:null}remove(e){if(tt(e)){this._refs.delete(e);return}this._values.delete(e);if(typeof e===\"string\")this._lowercase.delete(e.toLowerCase())}has(e,t,s,n){return!!this.get(e,t,s,n)}get(e,t,s,n){if(!this.length)return false;if(this._values.has(e))return{value:e};if(typeof e===\"string\"&&e&&n){const i=this._lowercase.get(e.toLowerCase());if(i)return{value:i}}if(!this._refs.size&&typeof e!==\"object\")return false;if(typeof e===\"object\"){for(const i of this._values){if(Ct(i,e))return{value:i}}}if(t){for(const i of this._refs){const o=i.resolve(e,t,s,null,{in:true});if(o===void 0)continue;const c=!i.in||typeof o!==\"object\"?[o]:ce(o)?o:Object.keys(o);for(const l of c){if(typeof l!==typeof e)continue;if(n&&e&&typeof e===\"string\"){if(l.toLowerCase()===e.toLowerCase())return{value:l,ref:i}}else{if(Ct(l,e))return{value:l,ref:i}}}}}return false}override(){this._override=true}values(e){if(e&&e.display){const t=[];for(const s of[...this._values,...this._refs]){if(s!==void 0)t.push(s)}return t}return Array.from([...this._values,...this._refs])}clone(){const e=new r(this._values,this._refs);e._override=this._override;return e}slice(){return this.clone()}concat(e){g(!e._override,\"Cannot concat override set of values\");const t=new r([...this._values,...e._values],[...this._refs,...e._refs]);t._override=this._override;return t}describe(){const e=[];if(this._override)e.push({override:true});for(const t of this._values.values())e.push(t&&typeof t===\"object\"?{value:t}:t);for(const t of this._refs.values())e.push(t.describe());return e}};Object.defineProperty(zt.prototype,H.values,{value:true,writable:true,enumerable:true,configurable:true});var Dy=new WeakMap;function KC(r){let e=Dy.get(r);if(!e){e=Object.assign({},r);e.abortEarly=true;e._externals=false;Dy.set(r,e)}return e}a(KC,\"matchPreferences\");var js=class{static{a(this,\"Base\")}constructor(e){this.type=e;this.$_root=null;this._definition={};this._reset()}_reset(){this._ids=new bl;this._preferences=null;this._refs=new ll;this._cache=null;this._valids=null;this._invalids=null;this._flags={};this._rules=[];this._singleRules=new Map;this.$_terms={};this.$_temp={ruleset:null,whens:{}}}describe(){g(typeof rh===\"function\",\"Manifest functionality disabled\");return rh(this)}allow(...e){Be(e,\"allow\");return this._values(e,\"_valids\")}alter(e){g(e&&typeof e===\"object\"&&!Array.isArray(e),\"Invalid targets argument\");g(!this._inRuleset(),\"Cannot set alterations inside a ruleset\");const t=this.clone();t.$_terms.alterations=t.$_terms.alterations||[];for(const s in e){const n=e[s];g(typeof n===\"function\",\"Alteration adjuster for\",s,\"must be a function\");t.$_terms.alterations.push({target:s,adjuster:n})}t.$_temp.ruleset=false;return t}artifact(e){g(e!==void 0,\"Artifact cannot be undefined\");g(!this._cache,\"Cannot set an artifact with a rule cache\");return this.$_setFlag(\"artifact\",e)}cast(e){g(e===false||typeof e===\"string\",\"Invalid to value\");g(e===false||this._definition.cast[e],\"Type\",this.type,\"does not support casting to\",e);return this.$_setFlag(\"cast\",e===false?void 0:e)}default(e,t){return this._default(\"default\",e,t)}description(e){g(e&&typeof e===\"string\",\"Description must be a non-empty string\");return this.$_setFlag(\"description\",e)}empty(e){const t=this.clone();if(e!==void 0)e=t.$_compile(e,{override:false});return t.$_setFlag(\"empty\",e,{clone:false})}error(e){g(e,\"Missing error\");g(e instanceof Error||typeof e===\"function\",\"Must provide a valid Error object or a function\");return this.$_setFlag(\"error\",e)}example(e,t={}){g(e!==void 0,\"Missing example\");re(t,[\"override\"]);return this._inner(\"examples\",e,{single:true,override:t.override})}external(e,t){if(typeof e===\"object\"){g(!t,\"Cannot combine options with description\");t=e.description;e=e.method}g(typeof e===\"function\",\"Method must be a function\");g(t===void 0||t&&typeof t===\"string\",\"Description must be a non-empty string\");return this._inner(\"externals\",{method:e,description:t},{single:true})}failover(e,t){return this._default(\"failover\",e,t)}forbidden(){return this.presence(\"forbidden\")}id(e){if(!e)return this.$_setFlag(\"id\",void 0);g(typeof e===\"string\",\"id must be a non-empty string\");g(/^[^\\.]+$/.test(e),\"id cannot contain period character\");return this.$_setFlag(\"id\",e)}invalid(...e){return this._values(e,\"_invalids\")}label(e){g(e&&typeof e===\"string\",\"Label name must be a non-empty string\");return this.$_setFlag(\"label\",e)}meta(e){g(e!==void 0,\"Meta cannot be undefined\");return this._inner(\"metas\",e,{single:true})}note(...e){g(e.length,\"Missing notes\");for(const t of e)g(t&&typeof t===\"string\",\"Notes must be non-empty strings\");return this._inner(\"notes\",e)}only(e=true){g(typeof e===\"boolean\",\"Invalid mode:\",e);return this.$_setFlag(\"only\",e)}optional(){return this.presence(\"optional\")}prefs(e){g(e,\"Missing preferences\");g(e.context===void 0,\"Cannot override context\");g(e.externals===void 0,\"Cannot override externals\");g(e.warnings===void 0,\"Cannot override warnings\");g(e.debug===void 0,\"Cannot override debug\");Mo(e);const t=this.clone();t._preferences=Ht(t._preferences,e);return t}presence(e){g([\"optional\",\"required\",\"forbidden\"].includes(e),\"Unknown presence mode\",e);return this.$_setFlag(\"presence\",e)}raw(e=true){return this.$_setFlag(\"result\",e?\"raw\":void 0)}result(e){g([\"raw\",\"strip\"].includes(e),\"Unknown result mode\",e);return this.$_setFlag(\"result\",e)}required(){return this.presence(\"required\")}strict(e){const t=this.clone();const s=e===void 0?false:!e;t._preferences=Ht(t._preferences,{convert:s});return t}strip(e=true){return this.$_setFlag(\"result\",e?\"strip\":void 0)}tag(...e){g(e.length,\"Missing tags\");for(const t of e)g(t&&typeof t===\"string\",\"Tags must be non-empty strings\");return this._inner(\"tags\",e)}unit(e){g(e&&typeof e===\"string\",\"Unit name must be a non-empty string\");return this.$_setFlag(\"unit\",e)}valid(...e){Be(e,\"valid\");const t=this.allow(...e);t.$_setFlag(\"only\",!!t._valids,{clone:false});return t}when(e,t){const s=this.clone();if(!s.$_terms.whens)s.$_terms.whens=[];const n=dl(s,e,t);if(![\"any\",\"link\"].includes(s.type)){const i=n.is?[n]:n.switch;for(const o of i){g(!o.then||o.then.type===\"any\"||o.then.type===s.type,\"Cannot combine\",s.type,\"with\",o.then&&o.then.type);g(!o.otherwise||o.otherwise.type===\"any\"||o.otherwise.type===s.type,\"Cannot combine\",s.type,\"with\",o.otherwise&&o.otherwise.type)}}s.$_terms.whens.push(n);return s.$_mutateRebuild()}cache(e){g(!this._inRuleset(),\"Cannot set caching inside a ruleset\");g(!this._cache,\"Cannot override schema cache\");g(this._flags.artifact===void 0,\"Cannot cache a rule with an artifact\");const t=this.clone();t._cache=e||cl.provision();t.$_temp.ruleset=false;return t}clone(){const e=Object.create(Object.getPrototypeOf(this));return this._assign(e)}concat(e){g(oe(e),\"Invalid schema object\");g(this.type===\"any\"||e.type===\"any\"||e.type===this.type,\"Cannot merge type\",this.type,\"with another type:\",e.type);g(!this._inRuleset(),\"Cannot concatenate onto a schema with open ruleset\");g(!e._inRuleset(),\"Cannot concatenate a schema with open ruleset\");let t=this.clone();if(this.type===\"any\"&&e.type!==\"any\"){const s=e.clone();for(const n of Object.keys(t)){if(n!==\"type\")s[n]=t[n]}t=s}t._ids.concat(e._ids);t._refs.register(e,ul);t._preferences=t._preferences?Ht(t._preferences,e._preferences):e._preferences;t._valids=zt.merge(t._valids,e._valids,e._invalids);t._invalids=zt.merge(t._invalids,e._invalids,e._valids);for(const s of e._singleRules.keys()){if(t._singleRules.has(s)){t._rules=t._rules.filter(n=>n.keep||n.name!==s);t._singleRules.delete(s)}}for(const s of e._rules){if(!e._definition.rules[s.method].multi)t._singleRules.set(s.name,s);t._rules.push(s)}if(t._flags.empty&&e._flags.empty){t._flags.empty=t._flags.empty.concat(e._flags.empty);const s=Object.assign({},e._flags);delete s.empty;Ft(t._flags,s)}else if(e._flags.empty){t._flags.empty=e._flags.empty;const s=Object.assign({},e._flags);delete s.empty;Ft(t._flags,s)}else{Ft(t._flags,e._flags)}for(const s in e.$_terms){const n=e.$_terms[s];if(!n){if(!t.$_terms[s])t.$_terms[s]=n;continue}if(!t.$_terms[s]){t.$_terms[s]=n.slice();continue}t.$_terms[s]=t.$_terms[s].concat(n)}if(this.$_root._tracer)this.$_root._tracer._combine(t,[this,e]);return t.$_mutateRebuild()}extend(e){g(!e.base,\"Cannot extend type with another base\");return yl(this,e)}extract(e){e=Array.isArray(e)?e:e.split(\".\");return this._ids.reach(e)}fork(e,t){g(!this._inRuleset(),\"Cannot fork inside a ruleset\");let s=this;for(let n of[].concat(e)){n=Array.isArray(n)?n:n.split(\".\");s=s._ids.fork(n,t,s)}s.$_temp.ruleset=false;return s}isAsync(){if(this.$_terms.externals?.length)return true;if(this.$_terms.whens){for(const e of this.$_terms.whens){if(e.then?.isAsync())return true;if(e.otherwise?.isAsync())return true;if(e.switch){for(const t of e.switch){if(t.then?.isAsync())return true;if(t.otherwise?.isAsync())return true}}}}return false}rule(e){const t=this._definition;re(e,Object.keys(t.modifiers));g(this.$_temp.ruleset!==false,\"Cannot apply rules to empty ruleset or the last rule added does not support rule properties\");const s=this.$_temp.ruleset===null?this._rules.length-1:this.$_temp.ruleset;g(s>=0&&s<this._rules.length,\"Cannot apply rules to empty ruleset\");const n=this.clone();for(let i=s;i<n._rules.length;++i){const o=n._rules[i];const c=G(o);for(const l in e){t.modifiers[l](c,e[l]);g(c.name===o.name,\"Cannot change rule name\")}n._rules[i]=c;if(n._singleRules.get(c.name)===o)n._singleRules.set(c.name,c)}n.$_temp.ruleset=false;return n.$_mutateRebuild()}get ruleset(){g(!this._inRuleset(),\"Cannot start a new ruleset without closing the previous one\");const e=this.clone();e.$_temp.ruleset=e._rules.length;return e}get $(){return this.ruleset}tailor(e){e=[].concat(e);g(!this._inRuleset(),\"Cannot tailor inside a ruleset\");let t=this;if(this.$_terms.alterations){for(const{target:s,adjuster:n}of this.$_terms.alterations){if(e.includes(s)){t=n(t);g(oe(t),\"Alteration adjuster for\",s,\"failed to return a schema object\")}}}t=t.$_modify({each:a(s=>s.tailor(e),\"each\"),ref:false});t.$_temp.ruleset=false;return t.$_mutateRebuild()}tracer(){return lh?lh(this):this}validate(e,t){return mh(e,this,t)}validateAsync(e,t){return gh(e,this,t)}$_addRule(e){if(typeof e===\"string\")e={name:e};g(e&&typeof e===\"object\",\"Invalid options\");g(e.name&&typeof e.name===\"string\",\"Invalid rule name\");for(const o in e)g(o[0]!==\"_\",\"Cannot set private rule properties\");const t=Object.assign({},e);t._resolve=[];t.method=t.method||t.name;const s=this._definition.rules[t.method];const n=t.args;g(s,\"Unknown rule\",t.method);const i=this.clone();if(n){g(Object.keys(n).length===1||Object.keys(n).length===this._definition.rules[t.name].args.length,\"Invalid rule definition for\",this.type,t.name);for(const o in n){let c=n[o];if(s.argsByName){const l=s.argsByName.get(o);if(l.ref&&tt(c)){t._resolve.push(o);i.$_mutateRegister(c)}else{if(l.normalize){c=l.normalize(c);n[o]=c}if(l.assert){const u=al(c,o,l);g(!u,u,\"or reference\")}}}if(c===void 0){delete n[o];continue}n[o]=c}}if(!s.multi){i._ruleRemove(t.name,{clone:false});i._singleRules.set(t.name,t)}if(i.$_temp.ruleset===false)i.$_temp.ruleset=null;if(s.priority){i._rules.unshift(t)}else{i._rules.push(t)}return i}$_compile(e,t){return Kd(this.$_root,e,t)}$_createError(e,t,s,n,i,o={}){const c=o.flags!==false?this._flags:{};const l=o.messages?ml(this._definition.messages,o.messages):this._definition.messages;return new vt(e,t,s,c,l,n,i)}$_getFlag(e){return this._flags[e]}$_getRule(e){return this._singleRules.get(e)}$_mapLabels(e){e=Array.isArray(e)?e:e.split(\".\");return this._ids.labels(e)}$_match(e,t,s,n){s=KC(s);t.snapshot();const i=!wl(e,this,t,s,n).errors;t.restore();return i}$_modify(e){re(e,[\"each\",\"once\",\"ref\",\"schema\"]);return uh(this,e)||this}$_mutateRebuild(){g(!this._inRuleset(),\"Cannot add this rule inside a ruleset\");this._refs.reset();this._ids.reset();const e=a((t,{source:s,name:n,key:i})=>{const o=this._definition[s];const c=o[n]&&o[n].register;if(c!==false)this.$_mutateRegister(t,{family:c,key:i})},\"each\");this.$_modify({each:e});if(this._definition.rebuild)this._definition.rebuild(this);this.$_temp.ruleset=false;return this}$_mutateRegister(e,{family:t,key:s}={}){this._refs.register(e,t);this._ids.register(e,{key:s||void 0})}$_property(e){return this._definition.properties[e]}$_reach(e){return this._ids.reach(e)}$_rootReferences(){return this._refs.roots()}$_setFlag(e,t,s={}){g(e[0]===\"_\"||!this._inRuleset(),\"Cannot set flag inside a ruleset\");const n=this._definition.flags[e]||{};if(Ct(t,n.default))t=void 0;if(Ct(t,this._flags[e]))return this;const i=s.clone!==false?this.clone():this;if(t!==void 0){i._flags[e]=t;i.$_mutateRegister(t)}else{delete i._flags[e]}if(e[0]!==\"_\")i.$_temp.ruleset=false;return i}$_parent(e,...t){const s=this[e];return s[H.parent].call(this,...t)}$_validate(e,t,s){return wl(e,this,t,s)}_assign(e){const t=e;t.type=this.type;t.$_root=this.$_root;t.$_temp=Object.assign({},this.$_temp);t.$_temp.whens={};t._ids=this._ids.clone();t._preferences=this._preferences;t._valids=this._valids&&this._valids.clone();t._invalids=this._invalids&&this._invalids.clone();t._rules=this._rules.slice();t._singleRules=G(this._singleRules,{shallow:true});t._refs=this._refs.clone();t._flags=Object.assign({},this._flags);t._cache=null;t.$_terms={};for(const s in this.$_terms)t.$_terms[s]=this.$_terms[s]?this.$_terms[s].slice():null;t.$_super={};for(const s in this.$_super)t.$_super[s]=this._super[s].bind(t);return e}_bare(){const e=this.clone();e._reset();const t=e._definition.terms;for(const s in t){const n=t[s];e.$_terms[s]=n.init}return e.$_mutateRebuild()}_default(e,t,s={}){re(s,\"literal\");g(t!==void 0,\"Missing\",e,\"value\");g(typeof t===\"function\"||!s.literal,\"Only function value supports literal option\");if(typeof t===\"function\"&&s.literal){t={[H.literal]:true,literal:t}}const n=this.$_setFlag(e,t);return n}_generate(e,t,s){if(!this.$_terms.whens)return{schema:this};const n=[];const i=[];const o=this.$_terms.whens;for(let u=0;u<o.length;++u){const f=o[u];if(f.concat){n.push(f.concat);i.push(`${u}.concat`);continue}const d=f.ref?f.ref.resolve(e,t,s,void 0):e;const h=f.is?[f]:f.switch;const p=i.length;for(let m=0;m<h.length;++m){const{is:y,then:w,otherwise:S}=h[m];const T=`${u}${f.switch?\".\"+m:\"\"}`;if(y.$_match(d,t.nest(y,`${T}.is`),s)){if(w){const _=t.localize([...t.path,`${T}.then`],t.ancestors,t.schemas);const{schema:x,id:k}=w._generate(e,_,s);n.push(x);i.push(`${T}.then${k?`(${k})`:\"\"}`);break}}else if(S){const _=t.localize([...t.path,`${T}.otherwise`],t.ancestors,t.schemas);const{schema:x,id:k}=S._generate(e,_,s);n.push(x);i.push(`${T}.otherwise${k?`(${k})`:\"\"}`);break}}if(f.break&&i.length>p)break}const c=i.join(\", \");t.mainstay.tracer.debug(t,\"rule\",\"when\",c);if(!c)return{schema:this};if(!t.mainstay.tracer.active&&this.$_temp.whens[c])return{schema:this.$_temp.whens[c],id:c};let l=this;if(this._definition.generate)l=this._definition.generate(this,e,t,s);for(const u of n)l=l.concat(u);if(this.$_root._tracer)this.$_root._tracer._combine(l,[this,...n]);this.$_temp.whens[c]=l;return{schema:l,id:c}}_inner(e,t,s={}){g(!this._inRuleset(),`Cannot set ${e} inside a ruleset`);const n=this.clone();if(!n.$_terms[e]||s.override)n.$_terms[e]=[];const i=n.$_terms[e];if(s.single){i.push(t)}else{i.push(...t)}n.$_temp.ruleset=false;return n}_inRuleset(){return this.$_temp.ruleset!==null&&this.$_temp.ruleset!==false}_ruleRemove(e,t={}){if(!this._singleRules.has(e))return this;const s=t.clone!==false?this.clone():this;s._singleRules.delete(e);const n=[];for(let i=0;i<s._rules.length;++i){const o=s._rules[i];if(o.name===e&&!o.keep){if(s._inRuleset()&&i<s.$_temp.ruleset)--s.$_temp.ruleset;continue}n.push(o)}s._rules=n;return s}_values(e,t){Be(e,t.slice(1,-1));const s=this.clone();const n=e[0]===H.override;if(n)e=e.slice(1);if(!s[t]&&e.length){s[t]=new zt}else if(n){s[t]=e.length?new zt:null;s.$_mutateRebuild()}if(!s[t])return s;const i=s[t];if(n)i.override();for(const o of e){g(o!==void 0,\"Cannot call allow/valid/invalid with undefined\");g(o!==H.override,\"Override must be the first value\");const c=t===\"_invalids\"?\"_valids\":\"_invalids\";const l=s[c];if(l){l.remove(o);if(!l.length){g(t===\"_valids\"||!s._flags.only,\"Setting invalid value\",o,\"leaves schema rejecting all values due to previous valid rule\");s[c]=null}}i.add(o,s._refs)}return s}get\"~standard\"(){const e=a(s=>{let n;if(qt.isError(s)){n=s.details.map(({message:i,path:o})=>({message:i,path:o}))}else{n=[{message:s.message}]}return{issues:n}},\"mapToStandardError\");const t=a(s=>({value:s}),\"mapToStandardValue\");return{version:1,vendor:\"lakutata\",validate:a(s=>{const n=Iy(s,this);if(n instanceof Promise)return n.then(t,e);if(!n.error)return t(n.value);return e(n.error)},\"validate\")}}};Object.defineProperty(js.prototype,H.any,{value:{version:ns,compile:fl,root:\"$_root\"},writable:true,enumerable:true,configurable:true});Object.defineProperty(js.prototype,\"isImmutable\",{value:true,writable:true,enumerable:true,configurable:true});for(const[r,e]of[[\"deny\",\"invalid\"],[\"disallow\",\"invalid\"],[\"equal\",\"valid\"],[\"exist\",\"required\"],[\"not\",\"invalid\"],[\"options\",\"prefs\"],[\"preferences\",\"prefs\"]]){Object.defineProperty(js.prototype,r,{value:js.prototype[e],writable:true,enumerable:true,configurable:true})}var WC=new js;var By=WC;function VC(r,e,t){return r[e].call(r,t)}a(VC,\"callBuild\");var XC=By.extend({type:\"any\",flags:{only:{default:false}},terms:{alterations:{init:null},examples:{init:null},externals:{init:null},metas:{init:[]},notes:{init:[]},shared:{init:null},tags:{init:[]},whens:{init:null}},rules:{allOf:{method(...r){if(r.length===1&&Array.isArray(r[0]))r=r[0];g(r.length>0,\"Missing schemas\");const e=r.map((s,n)=>os(()=>this.$_compile(s),n,{append:true}));const t=this.$_addRule({name:\"allOf\",args:{schemas:e}});for(const s of e)t.$_mutateRegister(s);return t},validate(r,{state:e,prefs:t,errorsArray:s},{schemas:n}){for(let i=0;i<n.length;++i){const o=n[i];const c=o.$_validate(r,e.nest(o,`allOf.${i}`),t);if(c.errors){const l=s();l.push(...c.errors);return l}}return r},args:[\"schemas\"],multi:true},custom:{method(r,e){g(typeof r===\"function\",\"Method must be a function\");g(e===void 0||e&&typeof e===\"string\",\"Description must be a non-empty string\");return this.$_addRule({name:\"custom\",args:{method:r,description:e}})},validate(r,e,{method:t}){try{return t(r,e)}catch(s){return e.error(\"any.custom\",{error:s})}},args:[\"method\",\"description\"],multi:true},messages:{method(r){return this.prefs({messages:r})}},shared:{method(r){g(oe(r)&&r._flags.id,\"Schema must be a schema with an id\");const e=this.clone();e.$_terms.shared=e.$_terms.shared||[];e.$_terms.shared.push(r);e.$_mutateRegister(r);return e}},warning:{method(r,e){g(r&&typeof r===\"string\",\"Invalid warning code\");return this.$_addRule({name:\"warning\",args:{code:r,local:e},warn:true})},validate(r,e,{code:t,local:s}){return e.error(t,s)},args:[\"code\",\"local\"],multi:true}},modifiers:{keep(r,e=true){r.keep=e},message(r,e){r.message=jo(e)},warn(r,e=true){r.warn=e}},manifest:{build(r,e){for(const t in e){const s=e[t];if([\"examples\",\"externals\",\"metas\",\"notes\",\"tags\"].includes(t)){for(const n of s)r=VC(r,t.slice(0,-1),n);continue}if(t===\"alterations\"){const n={};for(const{target:i,adjuster:o}of s)n[i]=o;r=r.alter(n);continue}if(t===\"whens\"){for(const n of s){const{ref:i,is:o,not:c,then:l,otherwise:u,concat:f}=n;if(f){r=r.concat(f)}else if(i){r=r.when(i,{is:o,not:c,then:l,otherwise:u,switch:n.switch,break:n.break})}else{r=r.when(o,{then:l,otherwise:u,break:n.break})}}continue}if(t===\"shared\"){for(const n of s)r=r.shared(n)}}return r}},messages:{\"any.custom\":\"{{#label}} failed custom validation because {{#error.message}}\",\"any.default\":\"{{#label}} threw an error when running default method\",\"any.failover\":\"{{#label}} threw an error when running failover method\",\"any.invalid\":\"{{#label}} contains an invalid value\",\"any.only\":'{{#label}} must be {if(#valids.length == 1, \"\", \"one of \")}{{#valids}}',\"any.ref\":\"{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}\",\"any.required\":\"{{#label}} is required\",\"any.unknown\":\"{{#label}} is not allowed\"}});var _e=XC;var YC=_e.extend({type:\"alternatives\",flags:{match:{default:\"any\"}},terms:{matches:{init:[],register:ul}},args(r,...e){if(e.length===1){if(Array.isArray(e[0])){return r.try(...e[0])}}return r.try(...e)},validate(r,e){const{schema:t,error:s,state:n,prefs:i}=e;if(t._flags.match===\"none\"){for(let c=0;c<t.$_terms.matches.length;++c){const l=t.$_terms.matches[c];if(l.schema.$_match(r,n.nest(l.schema,`match.${c}`),i))return{errors:s(\"alternatives.none\")}}return{value:r}}if(t._flags.match){const c=[];const l=[];for(let d=0;d<t.$_terms.matches.length;++d){const h=t.$_terms.matches[d];const p=n.nest(h.schema,`match.${d}`);p.snapshot();const m=h.schema.$_validate(r,p,i);if(!m.errors){c.push(m.value);p.commit()}else{l.push(m.errors);p.restore()}}if(c.length===0){const d={details:l.map(h=>lr(h,{override:false}))};return{errors:s(\"alternatives.any\",d)}}if(t._flags.match===\"one\"){return c.length===1?{value:c[0]}:{errors:s(\"alternatives.one\")}}if(c.length!==t.$_terms.matches.length){const d={details:l.map(h=>lr(h,{override:false}))};return{errors:s(\"alternatives.all\",d)}}const u=a(d=>{return d.$_terms.matches.some(h=>{return h.schema.type===\"object\"||h.schema.type===\"alternatives\"&&u(h.schema)})},\"isAnyObj\");const f=c.every(d=>d!==null&&typeof d===\"object\"&&!Array.isArray(d));return u(t)&&f?{value:c.reduce((d,h)=>Ft(d,h,{mergeArrays:false}),Object.create(Object.getPrototypeOf(c[0])))}:{value:c[c.length-1]}}const o=[];for(let c=0;c<t.$_terms.matches.length;++c){const l=t.$_terms.matches[c];if(l.schema){const d=n.nest(l.schema,`match.${c}`);d.snapshot();const h=l.schema.$_validate(r,d,i);if(!h.errors){d.commit();return h}d.restore();o.push({schema:l.schema,reports:h.errors});continue}const u=l.ref?l.ref.resolve(r,n,i,void 0):r;const f=l.is?[l]:l.switch;for(let d=0;d<f.length;++d){const h=f[d];const{is:p,then:m,otherwise:y}=h;const w=`match.${c}${l.switch?\".\"+d:\"\"}`;if(!p.$_match(u,n.nest(p,`${w}.is`),i)){if(y){return y.$_validate(r,n.nest(y,`${w}.otherwise`),i)}}else if(m){return m.$_validate(r,n.nest(m,`${w}.then`),i)}}}return JC(o,e)},rules:{conditional:{method(r,e){g(!this._flags._endedSwitch,\"Unreachable condition\");g(!this._flags.match,\"Cannot combine match mode\",this._flags.match,\"with conditional rule\");g(e.break===void 0,\"Cannot use break option with alternatives conditional\");const t=this.clone();const s=dl(t,r,e);const n=s.is?[s]:s.switch;for(const i of n){if(i.then&&i.otherwise){t.$_setFlag(\"_endedSwitch\",true,{clone:false});break}}t.$_terms.matches.push(s);return t.$_mutateRebuild()}},match:{method(r){g([\"any\",\"one\",\"all\",\"none\"].includes(r),\"Invalid alternatives match mode\",r);if(r!==\"any\"){for(const e of this.$_terms.matches){g(e.schema,\"Cannot combine match mode\",r,\"with conditional rules\")}}return this.$_setFlag(\"match\",r)}},try:{method(...r){g(r.length,\"Missing alternative schemas\");Be(r,\"try\");g(!this._flags._endedSwitch,\"Unreachable condition\");const e=this.clone();for(const t of r){e.$_terms.matches.push({schema:e.$_compile(t)})}return e.$_mutateRebuild()}}},overrides:{label(r){const e=this.$_parent(\"label\",r);const t=a((s,n)=>{return n.path[0]!==\"is\"&&typeof s._flags.label!==\"string\"?s.label(r):void 0},\"each\");return e.$_modify({each:t,ref:false})},isAsync(){if(this.$_terms.externals?.length){return true}for(const r of this.$_terms.matches){if(r.schema?.isAsync()){return true}if(r.then?.isAsync()){return true}if(r.otherwise?.isAsync()){return true}}return false}},rebuild(r){const e=a(t=>{if(oe(t)&&t.type===\"array\"){r.$_setFlag(\"_arrayItems\",true,{clone:false})}},\"each\");r.$_modify({each:e})},manifest:{build(r,e){if(e.matches){for(const t of e.matches){const{schema:s,ref:n,is:i,not:o,then:c,otherwise:l}=t;if(s){r=r.try(s)}else if(n){r=r.conditional(n,{is:i,then:c,not:o,otherwise:l,switch:t.switch})}else{r=r.conditional(i,{then:c,otherwise:l})}}}return r}},messages:{\"alternatives.all\":\"{{#label}} does not match all of the required types\",\"alternatives.any\":\"{{#label}} does not match any of the allowed types\",\"alternatives.match\":\"{{#label}} does not match any of the allowed types\",\"alternatives.none\":\"{{#label}} matches a type which is not allowed\",\"alternatives.one\":\"{{#label}} matches more than one allowed type\",\"alternatives.types\":\"{{#label}} must be one of {{#types}}\"}});var Uy=YC;function JC(r,{error:e,state:t}){if(!r.length){return{errors:e(\"alternatives.any\")}}if(r.length===1){return{errors:r[0].reports}}const s=new Set;const n=[];for(const{reports:i,schema:o}of r){if(i.length>1){return yh(r,e)}const c=i[0];if(c instanceof vt===false){return yh(r,e)}if(c.state.path.length!==t.path.length){n.push({type:o.type,report:c});continue}if(c.code===\"any.only\"){for(const f of c.local.valids){s.add(f)}continue}const[l,u]=c.code.split(\".\");if(u!==\"base\"){n.push({type:o.type,report:c})}else if(c.code===\"object.base\"){s.add(c.local.type)}else{s.add(l)}}if(!n.length){return{errors:e(\"alternatives.types\",{types:[...s]})}}if(n.length===1){return{errors:n[0].report}}return yh(r,e)}a(JC,\"reportErrors\");function yh(r,e){const t=[];for(const s of r){t.push(...s.reports)}return{errors:e(\"alternatives.match\",lr(t,{override:false}))}}a(yh,\"unmatched\");var ZC=_e.extend({type:\"array\",flags:{single:{default:false},sparse:{default:false}},terms:{items:{init:[],manifest:\"schema\"},ordered:{init:[],manifest:\"schema\"},_exclusions:{init:[]},_inclusions:{init:[]},_requireds:{init:[]}},coerce:{from:\"object\",method(r,{schema:e,state:t,prefs:s}){if(!Array.isArray(r))return;const n=e.$_getRule(\"sort\");if(!n)return;return jy(e,r,n.args.options,t,s)}},validate(r,{schema:e,error:t}){if(!Array.isArray(r)){if(e._flags.single){const s=[r];s[H.arraySingle]=true;return{value:s}}return{errors:t(\"array.base\")}}if(!e.$_getRule(\"items\")&&!e.$_terms.externals){return}return{value:r.slice()}},rules:{has:{method(r,e={}){r=this.$_compile(r,{appendPath:true});re(e,[\"min\",\"max\"]);g(e.min===void 0||Number.isSafeInteger(e.min)&&e.min>=0,\"min must be a non-negative integer\");g(e.max===void 0||Number.isSafeInteger(e.max)&&e.max>=0,\"max must be a non-negative integer\");g(e.max===void 0||(e.min??1)<=e.max,\"min must not be greater than max\");const t=this.$_addRule({name:\"has\",args:{schema:r,options:e}});t.$_mutateRegister(r);return t},validate(r,{state:e,prefs:t,error:s},{schema:n,options:i}){const o=r;const c=n;const l=[o,...e.ancestors];const{min:u=1,max:f}=i;if(u!==1||f!==void 0){let h=0;for(let p=0;p<o.length;++p){const m=e.localize([...e.path,p],l,c);if(c.$_match(o[p],m,t))++h}if(h<u)return s(\"array.hasMin\",{min:u,count:h});if(f!==void 0&&h>f)return s(\"array.hasMax\",{max:f,count:h});return o}for(let h=0;h<o.length;++h){const p=e.localize([...e.path,h],l,c);if(c.$_match(o[h],p,t))return o}const d=c._flags.label;if(d)return s(\"array.hasKnown\",{patternLabel:d});return s(\"array.hasUnknown\",null)},args:[\"schema\",\"options\"],multi:true},items:{method(...r){Be(r,\"items\");const e=this.$_addRule(\"items\");for(let t=0;t<r.length;++t){const s=os(()=>this.$_compile(r[t]),t,{append:true});e.$_terms.items.push(s)}return e.$_mutateRebuild()},validate(r,{schema:e,error:t,state:s,prefs:n,errorsArray:i}){const o=r;const c=e.$_terms._requireds.slice();const l=e.$_terms.ordered.slice();const u=[...e.$_terms._inclusions,...c];const f=!o[H.arraySingle];delete o[H.arraySingle];const d=i();let h=o.length;for(let p=0;p<h;++p){const m=o[p];let y=false;let w=false;const S=f?p:new Number(p);const T=[...s.path,S];if(!e._flags.sparse&&m===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));if(n.abortEarly)return d;l.shift();continue}const _=[o,...s.ancestors];for(const A of e.$_terms._exclusions){if(!A.$_match(m,s.localize(T,_,A),n,{presence:\"ignore\"})){continue}d.push(t(\"array.excludes\",{pos:p,value:m},s.localize(T)));if(n.abortEarly)return d;y=true;l.shift();break}if(y)continue;if(e.$_terms.ordered.length){if(l.length){const A=l.shift();const B=A.$_validate(m,s.localize(T,_,A),n);if(!B.errors){if(A._flags.result===\"strip\"){Fo(o,p);--p;--h}else if(!e._flags.sparse&&B.value===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));if(n.abortEarly)return d;continue}else{o[p]=B.value}}else{d.push(...B.errors);if(n.abortEarly)return d}continue}else if(!e.$_terms.items.length){d.push(t(\"array.orderedLength\",{pos:p,limit:e.$_terms.ordered.length}));if(n.abortEarly)return d;break}}const x=[];let k=c.length;for(let A=0;A<k;++A){const B=s.localize(T,_,c[A]);B.snapshot();const ee=c[A].$_validate(m,B,n);x[A]=ee;if(!ee.errors){B.commit();o[p]=ee.value;w=true;Fo(c,A);if(!e._flags.sparse&&ee.value===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));if(n.abortEarly)return d}break}B.restore()}if(w)continue;const N=n.stripUnknown&&!!n.stripUnknown.arrays||false;k=u.length;for(const A of u){let B;const ee=c.indexOf(A);if(ee!==-1){B=x[ee]}else{const fe=s.localize(T,_,A);fe.snapshot();B=A.$_validate(m,fe,n);if(!B.errors){fe.commit();if(A._flags.result===\"strip\"){Fo(o,p);--p;--h}else if(!e._flags.sparse&&B.value===void 0){d.push(t(\"array.sparse\",{key:S,path:T,pos:p,value:void 0},s.localize(T)));y=true}else{o[p]=B.value}w=true;break}fe.restore()}if(k===1){if(N){Fo(o,p);--p;--h;w=true;break}d.push(...B.errors);if(n.abortEarly)return d;y=true;break}}if(y)continue;if((e.$_terms._inclusions.length||e.$_terms._requireds.length)&&!w){if(N){Fo(o,p);--p;--h;continue}d.push(t(\"array.includes\",{pos:p,value:m},s.localize(T)));if(n.abortEarly)return d}}if(c.length)Hy(e,d,c,o,s,n);if(l.length){QC(e,d,l,o,s,n);if(!d.length)e0(l,o,s,n)}return d.length?d:o},priority:true,manifest:false},length:{method(r){return this.$_addRule({name:\"length\",args:{limit:r},operator:\"=\"})},validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(r.length,t,n))return r;return e.error(\"array.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"}]},max:{method(r){return this.$_addRule({name:\"max\",method:\"length\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"length\",args:{limit:r},operator:\">=\"})}},ordered:{method(...r){Be(r,\"ordered\");const e=this.$_addRule(\"items\");for(let t=0;t<r.length;++t){const s=os(()=>this.$_compile(r[t]),t,{append:true});bh(s,e);e.$_mutateRegister(s);e.$_terms.ordered.push(s)}return e.$_mutateRebuild()}},single:{method(r){const e=r===void 0?true:!!r;g(!e||!this._flags._arrayItems,\"Cannot specify single rule when array has array items\");return this.$_setFlag(\"single\",e)}},sort:{method(r={}){re(r,[\"by\",\"order\"]);const e={order:r.order||\"ascending\"};if(r.by){e.by=cr(r.by,{ancestor:0});g(!e.by.ancestor,\"Cannot sort by ancestor\")}return this.$_addRule({name:\"sort\",args:{options:e}})},validate(r,{error:e,state:t,prefs:s,schema:n},i){const o=r;const c=i.options;const{value:l,errors:u}=jy(n,o,c,t,s);if(u)return u;for(let f=0;f<o.length;++f){if(o[f]!==l[f]){return e(\"array.sort\",{order:c.order,by:c.by?c.by.key:\"value\"})}}return o},convert:true},sparse:{method(r){const e=r===void 0?true:!!r;if(this._flags.sparse===e)return this;const t=e?this.clone():this.$_addRule(\"items\");return t.$_setFlag(\"sparse\",e,{clone:false})}},unique:{method(r,e={}){g(!r||typeof r===\"function\"||typeof r===\"string\",\"comparator must be a function or a string\");re(e,[\"ignoreUndefined\",\"separator\"]);const t={name:\"unique\",args:{options:e,comparator:r}};if(r){if(typeof r===\"string\"){const s=Ds(e.separator,\".\");t.path=s?r.split(s):[r]}else{t.comparator=r}}return this.$_addRule(t)},validate(r,{state:e,error:t},{comparator:s,options:n},i){const o=r;const c=i.comparator;const l=i.path;const u={string:Object.create(null),number:Object.create(null),undefined:Object.create(null),boolean:Object.create(null),bigint:Object.create(null),object:new Map,function:new Map,custom:new Map};const f=c||Ct;const d=n.ignoreUndefined;for(let h=0;h<o.length;++h){const p=l?et(o[h],l):o[h];const m=c?u.custom:u[typeof p];g(m,\"Failed to find unique map container for type\",typeof p);if(m instanceof Map){const y=m.entries();let w;while(!(w=y.next()).done){if(f(w.value[0],p)){const S=e.localize([...e.path,h],[o,...e.ancestors]);const T={pos:h,value:o[h],dupePos:w.value[1],dupeValue:o[w.value[1]]};if(l)T.path=s;return t(\"array.unique\",T,S)}}m.set(p,h)}else{if((!d||p!==void 0)&&m[p]!==void 0){const y={pos:h,value:o[h],dupePos:m[p],dupeValue:o[m[p]]};if(l)y.path=s;const w=e.localize([...e.path,h],[o,...e.ancestors]);return t(\"array.unique\",y,w)}m[p]=h}}return o},args:[\"comparator\",\"options\"],multi:true}},overrides:{isAsync(){if(this.$_terms.externals?.length)return true;for(const r of this.$_terms.items){if(r.isAsync())return true}for(const r of this.$_terms.ordered){if(r.isAsync())return true}return false}},cast:{set:{from:Array.isArray,to(r){return new Set(r)}}},rebuild(r){r.$_terms._inclusions=[];r.$_terms._exclusions=[];r.$_terms._requireds=[];for(const e of r.$_terms.items){bh(e,r);if(e._flags.presence===\"required\"){r.$_terms._requireds.push(e)}else if(e._flags.presence===\"forbidden\"){r.$_terms._exclusions.push(e)}else{r.$_terms._inclusions.push(e)}}for(const e of r.$_terms.ordered)bh(e,r)},manifest:{build(r,e){if(e.items)r=r.items(...e.items);if(e.ordered)r=r.ordered(...e.ordered);return r}},messages:{\"array.base\":\"{{#label}} must be an array\",\"array.excludes\":\"{{#label}} contains an excluded value\",\"array.hasKnown\":\"{{#label}} does not contain at least one required match for type {:#patternLabel}\",\"array.hasMax\":\"{{#label}} must contain at most {{#max}} required matches\",\"array.hasMin\":\"{{#label}} must contain at least {{#min}} required matches\",\"array.hasUnknown\":\"{{#label}} does not contain at least one required match\",\"array.includes\":\"{{#label}} does not match any of the allowed types\",\"array.includesRequiredBoth\":\"{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)\",\"array.includesRequiredKnowns\":\"{{#label}} does not contain {{#knownMisses}}\",\"array.includesRequiredUnknowns\":\"{{#label}} does not contain {{#unknownMisses}} required value(s)\",\"array.length\":\"{{#label}} must contain {{#limit}} items\",\"array.max\":\"{{#label}} must contain less than or equal to {{#limit}} items\",\"array.min\":\"{{#label}} must contain at least {{#limit}} items\",\"array.orderedLength\":\"{{#label}} must contain at most {{#limit}} items\",\"array.sort\":\"{{#label}} must be sorted in {#order} order by {{#by}}\",\"array.sort.mismatching\":\"{{#label}} cannot be sorted due to mismatching types\",\"array.sort.unsupported\":\"{{#label}} cannot be sorted due to unsupported type {#type}\",\"array.sparse\":\"{{#label}} must not be a sparse array item\",\"array.unique\":\"{{#label}} contains a duplicate value\"}});var Fy=ZC;function Hy(r,e,t,s,n,i){const o=[];let c=0;for(const l of t){const u=l._flags.label;if(u){o.push(u)}else{++c}}if(o.length){if(c){e.push(r.$_createError(\"array.includesRequiredBoth\",s,{knownMisses:o,unknownMisses:c},n,i))}else{e.push(r.$_createError(\"array.includesRequiredKnowns\",s,{knownMisses:o},n,i))}}else{e.push(r.$_createError(\"array.includesRequiredUnknowns\",s,{unknownMisses:c},n,i))}}a(Hy,\"fillMissedErrors\");function QC(r,e,t,s,n,i){const o=[];for(const c of t){if(c._flags.presence===\"required\")o.push(c)}if(o.length)Hy(r,e,o,s,n,i)}a(QC,\"fillOrderedErrors\");function e0(r,e,t,s){const n=[];let i=true;for(let o=r.length-1;o>=0;--o){const c=r[o];const l=[e,...t.ancestors];const u=c.$_validate(void 0,t.localize(t.path,l,c),s).value;if(i){if(u===void 0)continue;i=false}n.unshift(u)}if(n.length)e.push(...n)}a(e0,\"fillDefault\");function Fo(r,e){let t=e;while(t<r.length)r[t++]=r[t];--r.length}a(Fo,\"fastSplice\");function bh(r,e){if(r.type===\"array\"||r._flags._arrayItems){g(!e._flags.single,\"Cannot specify array item with single rule enabled\");e.$_setFlag(\"_arrayItems\",true,{clone:false})}}a(bh,\"validateSingle\");function jy(r,e,t,s,n){const i=t.order===\"ascending\"?1:-1;const o=-1*i;const c=i;const l=a((u,f)=>{let d=$y(u,f,o,c);if(d!==null)return d;if(t.by){u=t.by.resolve(u,s,n,void 0);f=t.by.resolve(f,s,n,void 0)}d=$y(u,f,o,c);if(d!==null)return d;const h=typeof u;if(h!==typeof f)throw r.$_createError(\"array.sort.mismatching\",e,null,s,n);if(h!==\"number\"&&h!==\"string\"){throw r.$_createError(\"array.sort.unsupported\",e,{type:h},s,n)}if(h===\"number\")return(u-f)*i;return u<f?o:c},\"sort\");try{return{value:e.slice().sort(l)}}catch(u){return{errors:u}}}a(jy,\"sortArray\");function $y(r,e,t,s){if(r===e)return 0;if(r===void 0)return 1;if(e===void 0)return-1;if(r===null)return s;if(e===null)return t;return null}a($y,\"compareNulls\");function qy(r){return typeof r===\"boolean\"}a(qy,\"isBool\");var t0=_e.extend({type:\"boolean\",flags:{sensitive:{default:false}},terms:{falsy:{init:null,manifest:\"values\"},truthy:{init:null,manifest:\"values\"}},coerce(r,{schema:e}){if(typeof r===\"boolean\")return;if(typeof r===\"string\"){const t=r.trim();const s=e._flags.sensitive?t:t.toLowerCase();r=s===\"true\"?true:s===\"false\"?false:r}if(typeof r!==\"boolean\"){r=e.$_terms.truthy&&e.$_terms.truthy.has(r,null,null,!e._flags.sensitive)||(e.$_terms.falsy&&e.$_terms.falsy.has(r,null,null,!e._flags.sensitive)?false:r)}return{value:r}},validate(r,{error:e}){if(typeof r!==\"boolean\")return{value:r,errors:e(\"boolean.base\")}},rules:{truthy:{method(...r){Be(r,\"truthy\");const e=this.clone();e.$_terms.truthy=e.$_terms.truthy||new zt;for(let t=0;t<r.length;++t){const s=r[t];g(s!==void 0,\"Cannot call truthy with undefined\");e.$_terms.truthy.add(s)}return e}},falsy:{method(...r){Be(r,\"falsy\");const e=this.clone();e.$_terms.falsy=e.$_terms.falsy||new zt;for(let t=0;t<r.length;++t){const s=r[t];g(s!==void 0,\"Cannot call falsy with undefined\");e.$_terms.falsy.add(s)}return e}},sensitive:{method(r=true){return this.$_setFlag(\"sensitive\",r)}}},cast:{number:{from:qy,to(r){return r?1:0}},string:{from:qy,to(r){return r?\"true\":\"false\"}}},manifest:{build(r,e){if(e.truthy)r=r.truthy(...e.truthy);if(e.falsy)r=r.falsy(...e.falsy);return r}},messages:{\"boolean.base\":\"{{#label}} must be a boolean\"}});var zy=t0;function Gy(r){return r instanceof Date}a(Gy,\"isDate\");var r0=_e.extend({type:\"date\",coerce:{from:[\"number\",\"string\"],method(r,{schema:e}){return{value:Ky(r,e._flags.format)||r}}},validate(r,{schema:e,error:t,prefs:s}){if(r instanceof Date&&!isNaN(r.getTime())){return}const n=e._flags.format;if(!s.convert||!n||typeof r!==\"string\"){return{value:r,errors:t(\"date.base\")}}return{value:r,errors:t(\"date.format\",{format:n})}},rules:{compare:{method:false,validate(r,e,{date:t},{name:s,operator:n,args:i}){const o=t===\"now\"?Date.now():t.getTime();if(ot(r.getTime(),o,n))return r;return e.error(\"date.\"+s,{limit:i.date,value:r})},args:[{name:\"date\",ref:true,normalize:a(r=>{return r===\"now\"?r:Ky(r)},\"normalize\"),assert:a(r=>r!==null,\"assert\"),message:\"must have a valid date format\"}]},format:{method(r){g([\"iso\",\"javascript\",\"unix\"].includes(r),\"Unknown date format\",r);return this.$_setFlag(\"format\",r)}},greater:{method(r){return this.$_addRule({name:\"greater\",method:\"compare\",args:{date:r},operator:\">\"})}},iso:{method(){return this.format(\"iso\")}},less:{method(r){return this.$_addRule({name:\"less\",method:\"compare\",args:{date:r},operator:\"<\"})}},max:{method(r){return this.$_addRule({name:\"max\",method:\"compare\",args:{date:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"compare\",args:{date:r},operator:\">=\"})}},timestamp:{method(r=\"javascript\"){g([\"javascript\",\"unix\"].includes(r),'\"type\" must be one of \"javascript, unix\"');return this.format(r)}}},cast:{number:{from:Gy,to(r){return r.getTime()}},string:{from:Gy,to(r,{prefs:e}){return se.date(r,e)}}},messages:{\"date.base\":\"{{#label}} must be a valid date\",\"date.format\":'{{#label}} must be in {msg(\"date.format.\" + #format) || #format} format',\"date.greater\":\"{{#label}} must be greater than {{:#limit}}\",\"date.less\":\"{{#label}} must be less than {{:#limit}}\",\"date.max\":\"{{#label}} must be less than or equal to {{:#limit}}\",\"date.min\":\"{{#label}} must be greater than or equal to {{:#limit}}\",\"date.format.iso\":\"ISO 8601 date\",\"date.format.javascript\":\"timestamp or number of milliseconds\",\"date.format.unix\":\"timestamp or number of seconds\"}});var Wy=r0;function Ky(r,e){if(r instanceof Date)return r;if(typeof r!==\"string\"&&(isNaN(r)||!isFinite(r))){return null}if(/^\\s*$/.test(r))return null;if(e===\"iso\"){if(!ol(r))return null;return El(r.toString())}const t=r;if(typeof r===\"string\"&&/^[+-]?\\d+(\\.\\d+)?$/.test(r)){r=parseFloat(r)}if(e){if(e===\"javascript\")return El(1*r);if(e===\"unix\")return El(1e3*r);if(typeof t===\"string\")return null}return El(r)}a(Ky,\"parse\");function El(r){const e=new Date(r);if(!isNaN(e.getTime()))return e;return null}a(El,\"date\");function Tl(r){return[].concat(r)}a(Tl,\"toArray\");function s0(r,e){return r.sort===e.sort?0:r.sort<e.sort?-1:1}a(s0,\"mergeSort\");var xl=class{static{a(this,\"Sorter\")}constructor(){this.nodes=[];this._items=[]}add(e,t){const s=t??{};const n=Tl(s.before??[]);const i=Tl(s.after??[]);const o=s.group??\"?\";const c=s.sort??0;te(!n.includes(o),`Item cannot come before itself: ${o}`);te(!n.includes(\"?\"),\"Item cannot come before unassociated items\");te(!i.includes(o),`Item cannot come after itself: ${o}`);te(!i.includes(\"?\"),\"Item cannot come after unassociated items\");for(const l of Tl(e)){this._items.push({seq:this._items.length,sort:c,before:n,after:i,group:o,node:l})}if(!s.manual){const l=this._sort();te(l,\"item\",o!==\"?\"?`added into group ${o}`:\"\",\"created a dependencies error\")}return this.nodes}merge(e){for(const s of Tl(e)){if(s){for(const n of s._items)this._items.push({...n})}}this._items.sort(s0);for(let s=0;s<this._items.length;++s)this._items[s].seq=s;const t=this._sort();te(t,\"merge created a dependencies error\");return this.nodes}sort(){const e=this._sort();te(e,\"sort created a dependencies error\");return this.nodes}_sort(){const e={};const t=Object.create(null);const s=Object.create(null);for(const u of this._items){const f=u.seq;const d=u.group;s[d]=s[d]??[];s[d].push(f);e[f]=u.before;for(const h of u.after){t[h]=t[h]??[];t[h].push(f)}}const n={};for(const u in e){const f=[];for(const d of e[u]){s[d]=s[d]??[];f.push(...s[d])}n[u]=f}for(const u in t){if(s[u]){for(const f of s[u])n[f].push(...t[u])}}const i={};for(const u in n){for(const f of n[u]){i[f]=i[f]??[];i[f].push(u)}}const o={};const c=[];for(let u=0;u<this._items.length;++u){let f=u;if(i[u]){f=null;for(let d=0;d<this._items.length;++d){if(o[d]===true)continue;if(!i[d])i[d]=[];const h=i[d].length;let p=0;for(let m=0;m<h;++m){if(o[i[d][m]])++p}if(p===h){f=d;break}}}if(f!==null){o[f]=true;c.push(f)}}if(c.length!==this._items.length)return false;const l={};for(const u of this._items)l[u.seq]=u;this._items=[];this.nodes=[];for(const u of c){const f=l[u];this.nodes.push(f.node);this._items.push(f)}return true}};var i0={alias:false,multiple:false,override:false};var o0=_e.extend({type:\"_keys\",properties:{typeof:\"object\"},flags:{unknown:{default:void 0}},terms:{dependencies:{init:null},keys:{init:null,manifest:{mapped:{from:\"schema\",to:\"key\"}}},patterns:{init:null},renames:{init:null}},args(r,e){return r.keys(e)},validate(r,{schema:e,error:t,state:s,prefs:n}){if(!r||typeof r!==e.$_property(\"typeof\")||Array.isArray(r)){return{value:r,errors:t(\"object.base\",{type:e.$_property(\"typeof\")})}}if(!e.$_terms.renames&&!e.$_terms.dependencies&&!e.$_terms.keys&&!e.$_terms.patterns&&!e.$_terms.externals&&typeof e._flags.unknown!==\"object\"){return}const i=a0(r,n);const o=[];if(e.$_terms.renames&&!l0(e,i,s,n,o)){return{value:i,errors:o}}if(!e.$_terms.keys&&!e.$_terms.patterns&&!e.$_terms.dependencies&&typeof e._flags.unknown!==\"object\"){return{value:i,errors:o}}const c=new Set(Object.keys(i));if(e.$_terms.keys){const l=[i,...s.ancestors];for(const u of e.$_terms.keys){const f=u.key;const d=i[f];c.delete(f);const h=s.localize([...s.path,f],l,u);const p=u.schema.$_validate(d,h,n);if(p.errors){if(n.abortEarly)return{value:i,errors:p.errors};if(p.value!==void 0)i[f]=p.value;o.push(...p.errors)}else if(u.schema._flags.result===\"strip\"||p.value===void 0&&d!==void 0){delete i[f]}else if(p.value!==void 0){i[f]=p.value}}}if(c.size||e._flags._hasPatternMatch){const l=u0(e,i,c,o,s,n);if(l)return l}if(e.$_terms.dependencies){for(const l of e.$_terms.dependencies){if(l.key!==null&&fs(l.options)(l.key.resolve(i,s,n,null,{shadow:false}))===false){continue}const u=c0[l.rel](e,l,i,s,n);if(u){const f=e.$_createError(u.code,i,u.context,s,n);if(n.abortEarly)return{value:i,errors:f};o.push(f)}}}return{value:i,errors:o}},rules:{and:{method(...r){Be(r,\"and\");return us(this,\"and\",null,r)}},append:{method(r){if(r===null||r===void 0||Object.keys(r).length===0){return this}return this.keys(r)}},assert:{method(r,e,t){if(!se.isTemplate(r))r=cr(r);g(t===void 0||typeof t===\"string\",\"Message must be a string\");e=this.$_compile(e,{appendPath:true});const s=this.$_addRule({name:\"assert\",args:{subject:r,schema:e,message:t}});s.$_mutateRegister(r);s.$_mutateRegister(e);return s},validate(r,{error:e,prefs:t,state:s},{subject:n,schema:i,message:o}){const c=n.resolve(r,s,t);const l=rt(n)?n.absolute(s):[];if(i.$_match(c,s.localize(l,[r,...s.ancestors],i),t))return r;return e(\"object.assert\",{subject:n,message:o})},args:[\"subject\",\"schema\",\"message\"],multi:true},instance:{method(r,e){g(typeof r===\"function\",\"constructor must be a function\");e=e||r.name;return this.$_addRule({name:\"instance\",args:{constructor:r,name:e}})},validate(r,e,{constructor:t,name:s}){if(r instanceof t)return r;return e.error(\"object.instance\",{type:s,value:r})},args:[\"constructor\",\"name\"]},keyNames:{method(r){r=this.$_compile(r);const e=this.$_addRule({name:\"keyNames\",args:{schema:r}});e.$_mutateRegister(r);return e},validate(r,{state:e,prefs:t,error:s},{schema:n}){const i=n;const o=[r,...e.ancestors];for(const c of Object.keys(r)){const l=e.localize([...e.path,c],o,i);if(!i.$_match(c,l,t))return s(\"object.keyNames\",{name:c})}return r},args:[\"schema\"]},keys:{method(r){g(r===void 0||typeof r===\"object\",\"Object schema must be a valid object\");g(!oe(r),\"Object schema cannot be a schema object\");const e=this.clone();if(!r){e.$_terms.keys=null}else if(!Object.keys(r).length){e.$_terms.keys=new Ho}else{e.$_terms.keys=e.$_terms.keys?e.$_terms.keys.filter(t=>!Object.hasOwn(r,t.key)):new Ho;for(const t in r){os(()=>e.$_terms.keys.push({key:t,schema:this.$_compile(r[t])}),t)}}return e.$_mutateRebuild()}},length:{method(r){return this.$_addRule({name:\"length\",args:{limit:r},operator:\"=\"})},validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(Object.keys(r).length,t,n))return r;return e.error(\"object.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"}]},max:{method(r){return this.$_addRule({name:\"max\",method:\"length\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"length\",args:{limit:r},operator:\">=\"})}},nand:{method(...r){Be(r,\"nand\");return us(this,\"nand\",null,r)}},or:{method(...r){Be(r,\"or\");return us(this,\"or\",null,r)}},oxor:{method(...r){return us(this,\"oxor\",null,r)}},pattern:{method(r,e,t={}){const s=r instanceof RegExp;if(!s)r=this.$_compile(r,{appendPath:true});g(e!==void 0,\"Invalid rule\");re(t,[\"fallthrough\",\"matches\"]);if(s)g(!r.flags.includes(\"g\")&&!r.flags.includes(\"y\"),\"pattern should not use global or sticky mode\");e=this.$_compile(e,{appendPath:true});const n=this.clone();n.$_terms.patterns=n.$_terms.patterns||[];const i={[s?\"regex\":\"schema\"]:r,rule:e};if(t.matches){i.matches=this.$_compile(t.matches);if(i.matches.type!==\"array\")i.matches=i.matches.$_root.array().items(i.matches);n.$_mutateRegister(i.matches);n.$_setFlag(\"_hasPatternMatch\",true,{clone:false})}if(t.fallthrough)i.fallthrough=true;n.$_terms.patterns.push(i);n.$_mutateRegister(e);return n}},ref:{method(){return this.$_addRule(\"ref\")},validate(r,e){if(rt(r))return r;return e.error(\"object.refType\",{value:r})}},regex:{method(){return this.$_addRule(\"regex\")},validate(r,e){if(r instanceof RegExp)return r;return e.error(\"object.regex\",{value:r})}},rename:{method(r,e,t={}){g(typeof r===\"string\"||r instanceof RegExp,\"Rename missing the from argument\");g(typeof e===\"string\"||e instanceof se,\"Invalid rename to argument\");g(e!==r,\"Cannot rename key to same name:\",r);re(t,[\"alias\",\"ignoreUndefined\",\"override\",\"multiple\"]);const s=this.clone();s.$_terms.renames=s.$_terms.renames||[];for(const n of s.$_terms.renames)g(n.from!==r,\"Cannot rename the same key multiple times\");if(e instanceof se)s.$_mutateRegister(e);s.$_terms.renames.push({from:r,to:e,options:Pd(i0,t)});return s}},schema:{method(r=\"any\"){return this.$_addRule({name:\"schema\",args:{type:r}})},validate(r,e,{type:t}){if(oe(r)&&(t===\"any\"||r.type===t)){return r}return e.error(\"object.schema\",{type:t})}},unknown:{method(r){if(r===void 0||r===null||typeof r===\"boolean\")return this.$_setFlag(\"unknown\",r!==false);const e=this.clone();const t=e.$_compile(r);e.$_mutateRegister(t);return e.$_setFlag(\"unknown\",t,{clone:false})}},with:{method(r,e,t={}){return us(this,\"with\",r,e,t)}},without:{method(r,e,t={}){return us(this,\"without\",r,e,t)}},xor:{method(...r){Be(r,\"xor\");return us(this,\"xor\",null,r)}}},overrides:{default(r,e){if(r===void 0)r=H.deepDefault;return this.$_parent(\"default\",r,e)},isAsync(){if(this.$_terms.externals?.length)return true;if(typeof this._flags.unknown===\"object\"&&this._flags.unknown.isAsync())return true;if(this.$_terms.keys?.length){for(const r of this.$_terms.keys){if(r.schema.isAsync())return true}}if(this.$_terms.patterns?.length){for(const r of this.$_terms.patterns){if(r.rule.isAsync())return true}}return false}},rebuild(r){if(r.$_terms.keys){const e=new xl;for(const t of r.$_terms.keys){os(()=>Fn(()=>e.add(t,{after:t.schema.$_rootReferences(),group:t.key})),t.key)}r.$_terms.keys=new Ho(...e.nodes)}},manifest:{build(r,e){if(e.keys)r=r.keys(e.keys);if(e.dependencies){for(const{rel:t,key:s=null,peers:n,options:i}of e.dependencies)r=us(r,t,s,n,i)}if(e.patterns){for(const{regex:t,schema:s,rule:n,fallthrough:i,matches:o}of e.patterns)r=r.pattern(t||s,n,{fallthrough:i,matches:o})}if(e.renames){for(const{from:t,to:s,options:n}of e.renames)r=r.rename(t,s,n)}return r}},messages:{\"object.and\":\"{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}\",\"object.assert\":'{{#label}} is invalid because {if(#subject.key, `\"` + #subject.key + `\" failed to ` + (#message || \"pass the assertion test\"), #message || \"the assertion failed\")}',\"object.base\":\"{{#label}} must be of type {{#type}}\",\"object.instance\":\"{{#label}} must be an instance of {{:#type}}\",\"object.keyNames\":'{{#label}} has a key name \"{{#name}}\" which is not allowed',\"object.length\":'{{#label}} must have {{#limit}} key{if(#limit == 1, \"\", \"s\")}',\"object.max\":'{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, \"\", \"s\")}',\"object.min\":'{{#label}} must have at least {{#limit}} key{if(#limit == 1, \"\", \"s\")}',\"object.missing\":\"{{#label}} must contain at least one of {{#peersWithLabels}}\",\"object.nand\":\"{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}\",\"object.oxor\":\"{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}\",\"object.pattern.match\":\"{{#label}} keys failed to match pattern requirements\",\"object.refType\":\"{{#label}} must be a reference\",\"object.regex\":\"{{#label}} must be a RegExp object\",\"object.rename.multiple\":\"{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}\",\"object.rename.override\":\"{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists\",\"object.schema\":\"{{#label}} must be a schema of {{#type}} type\",\"object.unknown\":\"{{#label}} is not allowed\",\"object.with\":\"{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}\",\"object.without\":\"{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}\",\"object.xor\":\"{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}\"}});var Rl=o0;function a0(r,e){if(typeof r===\"object\"){if(e.nonEnumerables)return G(r,{shallow:true});const n=Object.create(Object.getPrototypeOf(r));Object.assign(n,r);return n}const t=r;const s=a(function(...n){return t.apply(this,n)},\"clone\");s.prototype=G(t.prototype);Object.defineProperty(s,\"name\",{value:t.name,writable:false});Object.defineProperty(s,\"length\",{value:t.length,writable:false});Object.assign(s,r);return s}a(a0,\"clone\");function us(r,e,t,s,n){g(t===null||typeof t===\"string\",e,\"key must be a strings\");if(!n)n=s.length>1&&typeof s[s.length-1]===\"object\"?s.pop():{};re(n,[\"separator\",\"isPresent\"]);s=[].concat(s);const i=Ds(n.separator,\".\");const o=[];for(const l of s){g(typeof l===\"string\",e,\"peers must be strings\");o.push(cr(l,{separator:i,ancestor:0,prefix:false}))}if(t!==null)t=cr(t,{separator:i,ancestor:0,prefix:false});const c=r.clone();c.$_terms.dependencies=c.$_terms.dependencies||[];c.$_terms.dependencies.push(new Sh(e,t,o,s,n));return c}a(us,\"dependency\");var c0={and(r,e,t,s,n){const i=[];const o=[];const c=e.peers.length;const l=fs(e.options);for(const u of e.peers){if(l(u.resolve(t,s,n,null,{shadow:false}))===false){i.push(u.key)}else{o.push(u.key)}}if(i.length!==c&&o.length!==c){return{code:\"object.and\",context:{present:o,presentWithLabels:yt(r,o),missing:i,missingWithLabels:yt(r,i)}}}},nand(r,e,t,s,n){const i=[];const o=fs(e.options);for(const u of e.peers){if(o(u.resolve(t,s,n,null,{shadow:false})))i.push(u.key)}if(i.length!==e.peers.length)return;const c=e.paths[0];const l=e.paths.slice(1);return{code:\"object.nand\",context:{main:c,mainWithLabel:yt(r,c),peers:l,peersWithLabels:yt(r,l)}}},or(r,e,t,s,n){const i=fs(e.options);for(const o of e.peers){if(i(o.resolve(t,s,n,null,{shadow:false})))return}return{code:\"object.missing\",context:{peers:e.paths,peersWithLabels:yt(r,e.paths)}}},oxor(r,e,t,s,n){const i=[];const o=fs(e.options);for(const l of e.peers){if(o(l.resolve(t,s,n,null,{shadow:false})))i.push(l.key)}if(!i.length||i.length===1){return}const c={peers:e.paths,peersWithLabels:yt(r,e.paths)};c.present=i;c.presentWithLabels=yt(r,i);return{code:\"object.oxor\",context:c}},with(r,e,t,s,n){const i=fs(e.options);for(const o of e.peers){if(i(o.resolve(t,s,n,null,{shadow:false}))===false){return{code:\"object.with\",context:{main:e.key.key,mainWithLabel:yt(r,e.key.key),peer:o.key,peerWithLabel:yt(r,o.key)}}}}},without(r,e,t,s,n){const i=fs(e.options);for(const o of e.peers){if(i(o.resolve(t,s,n,null,{shadow:false}))){return{code:\"object.without\",context:{main:e.key.key,mainWithLabel:yt(r,e.key.key),peer:o.key,peerWithLabel:yt(r,o.key)}}}}},xor(r,e,t,s,n){const i=[];const o=fs(e.options);for(const l of e.peers){if(o(l.resolve(t,s,n,null,{shadow:false})))i.push(l.key)}if(i.length===1)return;const c={peers:e.paths,peersWithLabels:yt(r,e.paths)};if(i.length===0)return{code:\"object.missing\",context:c};c.present=i;c.presentWithLabels=yt(r,i);return{code:\"object.xor\",context:c}}};function yt(r,e){if(Array.isArray(e))return e.map(t=>r.$_mapLabels(t));return r.$_mapLabels(e)}a(yt,\"keysToLabels\");function fs(r){return typeof r.isPresent===\"function\"?r.isPresent:e=>e!==void 0}a(fs,\"isPresent\");function l0(r,e,t,s,n){const i={};for(const o of r.$_terms.renames){const c=[];const l=typeof o.from!==\"string\";if(!l){if(Object.prototype.hasOwnProperty.call(e,o.from)&&(e[o.from]!==void 0||!o.options.ignoreUndefined)){c.push(o)}}else{for(const u in e){if(e[u]===void 0&&o.options.ignoreUndefined){continue}if(u===o.to)continue;const f=o.from.exec(u);if(!f)continue;c.push({from:u,to:o.to,match:f})}}for(const u of c){const f=u.from;let d=u.to;if(d instanceof se)d=d.render(e,t,s,u.match);if(f===d)continue;if(!o.options.multiple&&i[d]){n.push(r.$_createError(\"object.rename.multiple\",e,{from:f,to:d,pattern:l},t,s));if(s.abortEarly)return false}if(Object.prototype.hasOwnProperty.call(e,d)&&!o.options.override&&!i[d]){n.push(r.$_createError(\"object.rename.override\",e,{from:f,to:d,pattern:l},t,s));if(s.abortEarly)return false}if(e[f]===void 0){delete e[d]}else{e[d]=e[f]}i[d]=true;if(!o.options.alias)delete e[f]}}return true}a(l0,\"rename\");function u0(r,e,t,s,n,i){if(r.$_terms.patterns){let l=false;const u=r.$_terms.patterns.map(d=>{if(d.matches){l=true;return[]}});const f=[e,...n.ancestors];for(const d of t){const h=e[d];const p=[...n.path,d];for(let m=0;m<r.$_terms.patterns.length;++m){const y=r.$_terms.patterns[m];if(y.regex){const T=y.regex.test(d);n.mainstay.tracer.debug(n,\"rule\",`pattern.${m}`,T?\"pass\":\"error\");if(!T)continue}else{if(!y.schema.$_match(d,n.nest(y.schema,`pattern.${m}`),i))continue}t.delete(d);const w=n.localize(p,f,{schema:y.rule,key:d});const S=y.rule.$_validate(h,w,i);if(S.errors){if(i.abortEarly)return{value:e,errors:S.errors};s.push(...S.errors)}if(y.matches)u[m].push(d);e[d]=S.value;if(!y.fallthrough)break}}if(l){for(let d=0;d<u.length;++d){const h=u[d];if(!h)continue;const p=r.$_terms.patterns[d].matches;const m=n.localize(n.path,f,p);const y=p.$_validate(h,m,i);if(y.errors){const w=lr(y.errors,{override:false});w.matches=h;const S=r.$_createError(\"object.pattern.match\",e,w,n,i);if(i.abortEarly)return{value:e,errors:S};s.push(S)}}}}const o=r._flags.unknown;if(typeof o===\"object\"){const l=[e,...n.ancestors];for(const u of t){const f=n.localize([...n.path,u],l,{schema:o,key:u});const d=o.$_validate(e[u],f,i);if(d.errors){if(i.abortEarly)return{value:e,errors:d.errors};s.push(...d.errors)}e[u]=d.value}return}if(!t.size||!r.$_terms.keys&&!r.$_terms.patterns){return}if(i.stripUnknown&&typeof r._flags.unknown===\"undefined\"||i.skipFunctions){const l=i.stripUnknown?i.stripUnknown===true?true:!!i.stripUnknown.objects:false;for(const u of t){if(l){delete e[u];t.delete(u)}else if(typeof e[u]===\"function\"){t.delete(u)}}}const c=!Ds(r._flags.unknown,i.allowUnknown);if(c){for(const l of t){const u=n.localize([...n.path,l],[]);const f=r.$_createError(\"object.unknown\",e[l],{child:l},u,i,{flags:false});if(i.abortEarly)return{value:e,errors:f};s.push(f)}}}a(u0,\"unknown\");var Sh=class{static{a(this,\"Dependency\")}constructor(e,t,s,n,i){this.rel=e;this.key=t;this.peers=s;this.paths=n;this.options=i}describe(){const e={rel:this.rel,peers:this.paths};if(this.key!==null)e.key=this.key.key;if(this.peers[0].separator!==\".\")e.options={...e.options,separator:this.peers[0].separator};if(this.options.isPresent)e.options={...e.options,isPresent:this.options.isPresent};return e}};var Ho=class extends Array{static{a(this,\"Keys\")}concat(e){const t=this.slice();const s=new Map;for(let n=0;n<t.length;++n)s.set(t[n].key,n);for(const n of e){const i=n.key;const o=s.get(i);if(o!==void 0){t[o]={key:i,schema:t[o].schema.concat(n.schema)}}else{t.push(n)}}return t}};var f0=Rl.extend({type:\"function\",properties:{typeof:\"function\"},rules:{arity:{method(r){g(Number.isSafeInteger(r)&&r>=0,\"n must be a positive integer\");return this.$_addRule({name:\"arity\",args:{n:r}})},validate(r,e,{n:t}){if(r.length===t)return r;return e.error(\"function.arity\",{n:t})}},class:{method(){return this.$_addRule(\"class\")},validate(r,e){if(/^\\s*class\\s/.test(r.toString()))return r;return e.error(\"function.class\",{value:r})}},minArity:{method(r){g(Number.isSafeInteger(r)&&r>0,\"n must be a strict positive integer\");return this.$_addRule({name:\"minArity\",args:{n:r}})},validate(r,e,{n:t}){if(r.length>=t)return r;return e.error(\"function.minArity\",{n:t})}},maxArity:{method(r){g(Number.isSafeInteger(r)&&r>=0,\"n must be a positive integer\");return this.$_addRule({name:\"maxArity\",args:{n:r}})},validate(r,e,{n:t}){if(r.length<=t)return r;return e.error(\"function.maxArity\",{n:t})}}},messages:{\"function.arity\":\"{{#label}} must have an arity of {{#n}}\",\"function.class\":\"{{#label}} must be a class\",\"function.maxArity\":\"{{#label}} must have an arity lesser or equal to {{#n}}\",\"function.minArity\":\"{{#label}} must have an arity greater or equal to {{#n}}\"}});var Vy=f0;var d0=_e.extend({type:\"link\",properties:{schemaChain:true},terms:{link:{init:null,manifest:\"single\",register:false}},args(r,e){return r.ref(e)},validate(r,{schema:e,state:t,prefs:s}){g(e.$_terms.link,\"Uninitialized link schema\");const n=Xy(e,r,t,s);const i=e.$_terms.link[0].ref;return n.$_validate(r,t.nest(n,`link:${i.display}:${n.type}`),s)},generate(r,e,t,s){return Xy(r,e,t,s)},rules:{ref:{method(r){g(!this.$_terms.link,\"Cannot reinitialize schema\");const e=cr(r);g(e.type===\"value\"||e.type===\"local\",\"Invalid reference type:\",e.type);g(e.type===\"local\"||e.ancestor===\"root\"||e.ancestor>0,\"Link cannot reference itself\");const t=this.clone();t.$_terms.link=[{ref:e}];return t}},relative:{method(r=true){return this.$_setFlag(\"relative\",r)}}},overrides:{concat(r){g(this.$_terms.link,\"Uninitialized link schema\");g(oe(r),\"Invalid schema object\");g(r.type!==\"link\",\"Cannot merge type link with another link\");const e=this.clone();if(!e.$_terms.whens){e.$_terms.whens=[]}e.$_terms.whens.push({concat:r});return e.$_mutateRebuild()}},manifest:{build(r,e){g(e.link,\"Invalid link description missing link\");return r.ref(e.link)}}});var Yy=d0;function Xy(r,e,t,s){const n=t.mainstay.links;let i=n.get(r);if(i){return i._generate(e,t,s).schema}const o=r.$_terms.link[0].ref;const{perspective:c,path:l}=h0(o,t);wh(c,\"which is outside of schema boundaries\",o,r,t,s);try{i=l.length?c.$_reach(l):c}catch{wh(false,\"to non-existing schema\",o,r,t,s)}wh(i.type!==\"link\",\"which is another link\",o,r,t,s);if(!r._flags.relative){n.set(r,i)}return i._generate(e,t,s).schema}a(Xy,\"generate\");function h0(r,e){const t=e.schemas;if(r.type===\"local\"){for(const{schema:s,key:n}of t){const i=s;const o=i._flags.id||n;if(o===r.path[0]){return{perspective:i,path:r.path.slice(1)}}if(i.$_terms.shared){for(const c of i.$_terms.shared){if(c._flags.id===r.path[0]){return{perspective:c,path:r.path.slice(1)}}}}}return{perspective:null,path:null}}if(r.ancestor===\"root\"){return{perspective:t[t.length-1].schema,path:r.path}}return{perspective:t[r.ancestor]&&t[r.ancestor].schema,path:r.path}}a(h0,\"perspectiveOf\");function wh(r,e,t,s,n,i){if(r){return}g(false,`\"${Uo(s._flags,n,i,void 0)}\" contains link reference \"${t.display}\" ${e}`)}a(wh,\"assertLink\");var At=Object.freeze({int8:[-128,127],uint8:[0,255],int16:[-32768,32767],uint16:[0,65535],int32:[-2147483648,2147483647],uint32:[0,4294967295],int64:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],uint64:[0,Number.MAX_SAFE_INTEGER]});var Gt=34028234663852886e22;function ds(r){const[e,t]=At[r];return{method(){return this.$_addRule(r)},validate(s,n){if(!Number.isInteger(s))return n.error(\"number.integer\");if(s<e||s>t)return n.error(`number.${r}`,{min:e,max:t});return s}}}a(ds,\"integerRule\");var p0=/^\\s*[+-]?(?:(?:\\d+(?:\\.\\d*)?)|(?:\\.\\d+))(?:e([+-]?\\d+))?\\s*$/i;var m0=/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;var g0=/[eE][+-]?\\d+$/;var y0=/^[+-]?(0*)?/;var b0=/\\./;var S0=/0+$/;function Jy(r){const e=r.toString();const t=e.indexOf(\".\");const s=e.indexOf(\"e\");return(t<0?0:(s<0?e.length:s)-t-1)+(s<0?0:Math.max(0,-parseInt(e.slice(s+1))))}a(Jy,\"decimalPlaces\");var w0=_e.extend({type:\"number\",flags:{unsafe:{default:false}},coerce:{from:\"string\",method(r,{schema:e,error:t}){let s=r;const n=s.match(p0);if(!n)return;s=s.trim();const i={value:parseFloat(s)};if(i.value===0)i.value=0;if(!e._flags.unsafe){if(s.match(/e/i)){if(Zy(s)!==Zy(String(i.value))){i.errors=t(\"number.unsafe\");return i}}else{const o=i.value.toString();if(o.match(/e/i))return i;if(o!==E0(s)){i.errors=t(\"number.unsafe\");return i}}}return i}},validate(r,{schema:e,error:t,prefs:s}){if(r===Infinity||r===-Infinity){return{value:r,errors:t(\"number.infinity\")}}if(!Ud(r))return{value:r,errors:t(\"number.base\")};const n={value:r};if(s.convert){const i=e.$_getRule(\"precision\");if(i){const o=Math.pow(10,i.args.limit);n.value=Math.round(n.value*o)/o}}if(n.value===0)n.value=0;if(!e._flags.unsafe&&(r>Number.MAX_SAFE_INTEGER||r<Number.MIN_SAFE_INTEGER)){n.errors=t(\"number.unsafe\")}return n},rules:{compare:{method:false,validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(r,t,n))return r;return e.error(\"number.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Ud,message:\"must be a number\"}]},double:{method(){return this.unsafe().$_addRule(\"double\")},validate(r){return r}},float:{method(){return this.unsafe().$_addRule(\"float\")},validate(r,e){if(Math.abs(r)<=Gt)return r;return e.error(\"number.float\",{min:-Gt,max:Gt})}},greater:{method(r){return this.$_addRule({name:\"greater\",method:\"compare\",args:{limit:r},operator:\">\"})}},int8:ds(\"int8\"),int16:ds(\"int16\"),int32:ds(\"int32\"),int64:ds(\"int64\"),integer:{method(){return this.$_addRule(\"integer\")},validate(r,e){if(Math.trunc(r)-r===0)return r;return e.error(\"number.integer\")}},less:{method(r){return this.$_addRule({name:\"less\",method:\"compare\",args:{limit:r},operator:\"<\"})}},max:{method(r){return this.$_addRule({name:\"max\",method:\"compare\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"compare\",args:{limit:r},operator:\">=\"})}},multiple:{method(r){const e=typeof r===\"number\"?Jy(r):null;const t=Math.pow(10,e);return this.$_addRule({name:\"multiple\",args:{base:r,baseDecimalPlace:e,pfactor:t}})},validate(r,e,{base:t,baseDecimalPlace:s,pfactor:n},i){const o=Jy(r);if(o>s){return e.error(\"number.multiple\",{multiple:i.args.base,value:r})}return Math.round(n*r)%Math.round(n*t)===0?r:e.error(\"number.multiple\",{multiple:i.args.base,value:r})},args:[{name:\"base\",ref:true,assert:a(r=>typeof r===\"number\"&&isFinite(r)&&r>0,\"assert\"),message:\"must be a positive number\"},\"baseDecimalPlace\",\"pfactor\"],multi:true},negative:{method(){return this.sign(\"negative\")}},port:{method(){return this.$_addRule(\"port\")},validate(r,e){if(Number.isSafeInteger(r)&&r>=0&&r<=65535){return r}return e.error(\"number.port\")}},positive:{method(){return this.sign(\"positive\")}},precision:{method(r){g(Number.isSafeInteger(r),\"limit must be an integer\");return this.$_addRule({name:\"precision\",args:{limit:r}})},validate(r,e,{limit:t}){const s=r.toString().match(m0);const n=Math.max((s[1]?s[1].length:0)-(s[2]?parseInt(s[2],10):0),0);if(n<=t)return r;return e.error(\"number.precision\",{limit:t,value:r})},convert:true},sign:{method(r){g([\"negative\",\"positive\"].includes(r),\"Invalid sign\",r);return this.$_addRule({name:\"sign\",args:{sign:r}})},validate(r,e,{sign:t}){if(t===\"negative\"&&r<0||t===\"positive\"&&r>0){return r}return e.error(`number.${t}`)}},uint8:ds(\"uint8\"),uint16:ds(\"uint16\"),uint32:ds(\"uint32\"),uint64:ds(\"uint64\"),unsafe:{method(r=true){g(typeof r===\"boolean\",\"enabled must be a boolean\");return this.$_setFlag(\"unsafe\",r)}}},cast:{string:{from:a(r=>typeof r===\"number\",\"from\"),to(r){return r.toString()}}},messages:{\"number.base\":\"{{#label}} must be a number\",\"number.float\":\"{{#label}} must be a valid Float value (between {{#min}} and {{#max}})\",\"number.greater\":\"{{#label}} must be greater than {{#limit}}\",\"number.infinity\":\"{{#label}} cannot be infinity\",\"number.int8\":\"{{#label}} must be a valid Int8 value (between -128 and 127)\",\"number.int16\":\"{{#label}} must be a valid Int16 value (between -32768 and 32767)\",\"number.int32\":\"{{#label}} must be a valid Int32 value (between -2147483648 and 2147483647)\",\"number.int64\":\"{{#label}} must be a valid Int64 value (between -9007199254740991 and 9007199254740991, the safe integers of JavaScript)\",\"number.integer\":\"{{#label}} must be an integer\",\"number.less\":\"{{#label}} must be less than {{#limit}}\",\"number.max\":\"{{#label}} must be less than or equal to {{#limit}}\",\"number.min\":\"{{#label}} must be greater than or equal to {{#limit}}\",\"number.multiple\":\"{{#label}} must be a multiple of {{#multiple}}\",\"number.negative\":\"{{#label}} must be a negative number\",\"number.port\":\"{{#label}} must be a valid port\",\"number.positive\":\"{{#label}} must be a positive number\",\"number.precision\":\"{{#label}} must have no more than {{#limit}} decimal places\",\"number.uint8\":\"{{#label}} must be a valid UInt8 value (between 0 and 255)\",\"number.uint16\":\"{{#label}} must be a valid UInt16 value (between 0 and 65535)\",\"number.uint32\":\"{{#label}} must be a valid UInt32 value (between 0 and 4294967295)\",\"number.uint64\":\"{{#label}} must be a valid UInt64 value (between 0 and 9007199254740991, the safe integers of JavaScript)\",\"number.unsafe\":\"{{#label}} must be a safe number\"}});var Qy=w0;function Zy(r){return r.replace(g0,\"\").replace(b0,\"\").replace(S0,\"\").replace(y0,\"\")}a(Zy,\"extractSignificantDigits\");function E0(r){r=r.replace(/^\\+/,\"\").replace(/\\.0*$/,\"\").replace(/^(-?)\\.([^\\.]*)$/,\"$10.$2\").replace(/^(-?)0+([0-9])/,\"$1$2\");if(r.includes(\".\")&&r.endsWith(\"0\")){r=r.replace(/0+$/,\"\")}if(r===\"-0\")return\"0\";return r}a(E0,\"normalizeDecimal\");var T0=Rl.extend({type:\"object\",cast:{map:{from:a(r=>r&&typeof r===\"object\",\"from\"),to(r){return new Map(Object.entries(r))}}}});var eb=T0;var rb=Ye(require(\"node:url\"),1);var tb={EMPTY_STRING:\"Address must be a non-empty string\",FORBIDDEN_UNICODE:\"Address contains forbidden Unicode characters\",MULTIPLE_AT_CHAR:\"Address cannot contain more than one @ character\",MISSING_AT_CHAR:\"Address must contain one @ character\",EMPTY_LOCAL:\"Address local part cannot be empty\",ADDRESS_TOO_LONG:\"Address too long\",LOCAL_TOO_LONG:\"Address local part too long\",EMPTY_LOCAL_SEGMENT:\"Address local part contains empty dot-separated segment\",INVALID_LOCAL_CHARS:\"Address local part contains invalid character\",DOMAIN_NON_EMPTY_STRING:\"Domain must be a non-empty string\",DOMAIN_TOO_LONG:\"Domain too long\",DOMAIN_INVALID_UNICODE_CHARS:\"Domain contains forbidden Unicode characters\",DOMAIN_INVALID_CHARS:\"Domain contains invalid character\",DOMAIN_INVALID_TLDS_CHARS:\"Domain contains invalid tld character\",DOMAIN_SEGMENTS_COUNT:\"Domain lacks the minimum required number of segments\",DOMAIN_SEGMENTS_COUNT_MAX:\"Domain contains too many segments\",DOMAIN_FORBIDDEN_TLDS:\"Domain uses forbidden TLD\",DOMAIN_EMPTY_SEGMENT:\"Domain contains empty dot-separated segment\",DOMAIN_LONG_SEGMENT:\"Domain contains dot-separated segment that is too long\"};function we(r){return{code:r,error:tb[r]}}a(we,\"errorCode\");var x0=2;var R0=/[^\\x00-\\x7f]/;var _0=/[\\x00-\\x20@\\:\\/\\\\#!\\$&\\'\\(\\)\\*\\+,;=\\?]/;var C0=/^[a-zA-Z](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/;var v0=/^[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/;var A0=/^[a-zA-Z0-9_](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/;var I0=rb.URL||URL;function O0(r){return!!r.allow}a(O0,\"isTldsAllow\");function Eh(r,e={}){if(!r){return we(\"DOMAIN_NON_EMPTY_STRING\")}if(typeof r!==\"string\"){throw new Error(\"Invalid input: domain must be a string\")}if(r.length>256){return we(\"DOMAIN_TOO_LONG\")}const t=!R0.test(r);if(!t){if(e.allowUnicode===false){return we(\"DOMAIN_INVALID_UNICODE_CHARS\")}r=r.normalize(\"NFC\")}if(_0.test(r)){return we(\"DOMAIN_INVALID_CHARS\")}r=k0(r);if(e.allowFullyQualified&&r[r.length-1]===\".\"){r=r.slice(0,-1)}const s=e.minDomainSegments||x0;const n=r.split(\".\");if(n.length<s){return we(\"DOMAIN_SEGMENTS_COUNT\")}if(e.maxDomainSegments){if(n.length>e.maxDomainSegments){return we(\"DOMAIN_SEGMENTS_COUNT_MAX\")}}const i=e.tlds;if(i){const o=n[n.length-1].toLowerCase();if(O0(i)){if(!i.allow.has(o)){return we(\"DOMAIN_FORBIDDEN_TLDS\")}}else if(i.deny.has(o)){return we(\"DOMAIN_FORBIDDEN_TLDS\")}}for(let o=0;o<n.length;++o){const c=n[o];if(!c.length){return we(\"DOMAIN_EMPTY_SEGMENT\")}if(c.length>63){return we(\"DOMAIN_LONG_SEGMENT\")}if(o<n.length-1){if(e.allowUnderscore){if(!A0.test(c)){return we(\"DOMAIN_INVALID_CHARS\")}}else{if(!v0.test(c)){return we(\"DOMAIN_INVALID_CHARS\")}}}else{if(!C0.test(c)){return we(\"DOMAIN_INVALID_TLDS_CHARS\")}}}return null}a(Eh,\"analyzeDomain\");function qo(r,e){return!Eh(r,e)}a(qo,\"isDomainValid\");function k0(r){if(r.includes(\"%\")){r=r.replace(/%/g,\"%25\")}try{return new I0(`http://${r}`).host}catch(e){return r}}a(k0,\"punycode\");var nb=Ye(require(\"node:util\"),1);var P0=/[^\\x00-\\x7f]/;var ib=new(nb.TextEncoder||TextEncoder);function zo(r,e){return!N0(r,e)}a(zo,\"isEmailValid\");function N0(r,e={}){if(typeof r!==\"string\"){throw new Error(\"Invalid input: email must be a string\")}if(!r){return we(\"EMPTY_STRING\")}const t=!P0.test(r);if(!t){if(e.allowUnicode===false){return we(\"FORBIDDEN_UNICODE\")}r=r.normalize(\"NFC\")}const s=r.split(\"@\");if(s.length!==2){return s.length>2?we(\"MULTIPLE_AT_CHAR\"):we(\"MISSING_AT_CHAR\")}const[n,i]=s;if(!n){return we(\"EMPTY_LOCAL\")}if(!e.ignoreLength){if(r.length>254){return we(\"ADDRESS_TOO_LONG\")}if(ib.encode(n).length>64){return we(\"LOCAL_TOO_LONG\")}}return L0(n,t)||Eh(i,e)}a(N0,\"validateEmail\");function L0(r,e){const t=r.split(\".\");for(const s of t){if(!s.length){return we(\"EMPTY_LOCAL_SEGMENT\")}if(e){if(!sb.test(s)){return we(\"INVALID_LOCAL_CHARS\")}continue}for(const n of s){if(sb.test(n)){continue}const i=M0(n);if(!D0.test(i)){return we(\"INVALID_LOCAL_CHARS\")}}}return null}a(L0,\"validateLocal\");function M0(r){return Array.from(ib.encode(r),e=>String.fromCharCode(e)).join(\"\")}a(M0,\"toBinary\");var sb=/^[\\w!#\\$%&'\\*\\+\\-/=\\?\\^`\\{\\|\\}~]+$/;var D0=new RegExp([\"(?:[\\\\xc2-\\\\xdf][\\\\x80-\\\\xbf])\",\"(?:\\\\xe0[\\\\xa0-\\\\xbf][\\\\x80-\\\\xbf])|(?:[\\\\xe1-\\\\xec][\\\\x80-\\\\xbf]{2})|(?:\\\\xed[\\\\x80-\\\\x9f][\\\\x80-\\\\xbf])|(?:[\\\\xee-\\\\xef][\\\\x80-\\\\xbf]{2})\",\"(?:\\\\xf0[\\\\x90-\\\\xbf][\\\\x80-\\\\xbf]{2})|(?:[\\\\xf1-\\\\xf3][\\\\x80-\\\\xbf]{3})|(?:\\\\xf4[\\\\x80-\\\\x8f][\\\\x80-\\\\xbf]{2})\"].join(\"|\"));function B0(){const r={};const e=\"\\\\dA-Fa-f\";const t=\"[\"+e+\"]\";const s=\"\\\\w-\\\\.~\";const n=\"!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=\";const i=\"%\"+e;const o=s+i+n+\":@\";const c=\"[\"+o+\"]\";const l=\"(?:0{0,2}\\\\d|0?[1-9]\\\\d|1\\\\d\\\\d|2[0-4]\\\\d|25[0-5])\";r.ipv4address=\"(?:\"+l+\"\\\\.){3}\"+l;const u=t+\"{1,4}\";const f=\"(?:\"+u+\":\"+u+\"|\"+r.ipv4address+\")\";const d=\"(?:\"+u+\":){6}\"+f;const h=\"::(?:\"+u+\":){5}\"+f;const p=\"(?:\"+u+\")?::(?:\"+u+\":){4}\"+f;const m=\"(?:(?:\"+u+\":){0,1}\"+u+\")?::(?:\"+u+\":){3}\"+f;const y=\"(?:(?:\"+u+\":){0,2}\"+u+\")?::(?:\"+u+\":){2}\"+f;const w=\"(?:(?:\"+u+\":){0,3}\"+u+\")?::\"+u+\":\"+f;const S=\"(?:(?:\"+u+\":){0,4}\"+u+\")?::\"+f;const T=\"(?:(?:\"+u+\":){0,5}\"+u+\")?::\"+u;const _=\"(?:(?:\"+u+\":){0,6}\"+u+\")?::\";r.ipv4Cidr=\"(?:\\\\d|[1-2]\\\\d|3[0-2])\";r.ipv6Cidr=\"(?:0{0,2}\\\\d|0?[1-9]\\\\d|1[01]\\\\d|12[0-8])\";r.ipv6address=\"(?:\"+d+\"|\"+h+\"|\"+p+\"|\"+m+\"|\"+y+\"|\"+w+\"|\"+S+\"|\"+T+\"|\"+_+\")\";r.ipvFuture=\"v\"+t+\"+\\\\.[\"+s+n+\":]+\";r.scheme=\"[a-zA-Z][a-zA-Z\\\\d+-\\\\.]*\";r.schemeRegex=new RegExp(r.scheme);const x=\"[\"+s+i+n+\":]*\";const k=\"\\\\[(?:\"+r.ipv6address+\"|\"+r.ipvFuture+\")\\\\]\";const N=\"[\"+s+i+n+\"]{1,255}\";const A=\"(?:\"+k+\"|\"+r.ipv4address+\"|\"+N+\")\";const B=\"\\\\d*\";const ee=\"(?:\"+x+\"@)?\"+A+\"(?::\"+B+\")?\";const fe=\"(?:\"+x+\"@)?(\"+A+\")(?::\"+B+\")?\";const Rt=c+\"*\";const Qc=c+\"+\";const xd=\"[\"+s+i+n+\"@]+\";const Ao=\"\";const _t=\"(?:\\\\/\"+Rt+\")*\";const Ns=\"\\\\/(?:\"+Qc+_t+\")?\";const Io=Qc+_t;const Oo=xd+_t;const el=\"(?:\\\\/\\\\/\\\\/\"+Rt+_t+\")\";r.hierPart=\"(?:(?:\\\\/\\\\/\"+ee+_t+\")|\"+Ns+\"|\"+Io+\"|\"+el+\")\";r.hierPartCapture=\"(?:(?:\\\\/\\\\/\"+fe+_t+\")|\"+Ns+\"|\"+Io+\")\";r.relativeRef=\"(?:(?:\\\\/\\\\/\"+ee+_t+\")|\"+Ns+\"|\"+Oo+\"|\"+Ao+\")\";r.relativeRefCapture=\"(?:(?:\\\\/\\\\/\"+fe+_t+\")|\"+Ns+\"|\"+Oo+\"|\"+Ao+\")\";r.query=\"[\"+o+\"\\\\/\\\\?]*(?=#|$)\";r.queryWithSquareBrackets=\"[\"+o+\"\\\\[\\\\]\\\\/\\\\?]*(?=#|$)\";r.fragment=\"[\"+o+\"\\\\/\\\\?]*\";return r}a(B0,\"generate\");var Kn=B0();var Wn={v4Cidr:Kn.ipv4Cidr,v6Cidr:Kn.ipv6Cidr,ipv4:Kn.ipv4address,ipv6:Kn.ipv6address,ipvfuture:Kn.ipvFuture};function ab(r){const e=Kn;const t=r.allowQuerySquareBrackets?e.queryWithSquareBrackets:e.query;const s=\"(?:\\\\?\"+t+\")?(?:#\"+e.fragment+\")?\";const n=r.domain?e.relativeRefCapture:e.relativeRef;if(r.relativeOnly){return ob(n+s)}let i=\"\";if(r.scheme){te(r.scheme instanceof RegExp||typeof r.scheme===\"string\"||Array.isArray(r.scheme),\"scheme must be a RegExp, String, or Array\");const u=[].concat(r.scheme);te(u.length>=1,\"scheme must have at least 1 scheme specified\");const f=[];for(let d=0;d<u.length;++d){const h=u[d];te(h instanceof RegExp||typeof h===\"string\",\"scheme at position \"+d+\" must be a RegExp or String\");if(h instanceof RegExp){f.push(h.source.toString())}else{te(e.schemeRegex.test(h),\"scheme at position \"+d+\" must be a valid scheme\");f.push(mt(h))}}i=f.join(\"|\")}const o=i?\"(?:\"+i+\")\":e.scheme;const c=\"(?:\"+o+\":\"+(r.domain?e.hierPartCapture:e.hierPart)+\")\";const l=r.allowRelative?\"(?:\"+c+\"|\"+n+\")\":c;return ob(l+s,i)}a(ab,\"createRegex\");function ob(r,e=null){r=`(?=.)(?!https?:/(?:$|[^/]))(?!https?:///)(?!https?:[^/])${r}`;return{raw:r,regex:new RegExp(`^${r}$`),scheme:e}}a(ob,\"wrap\");var U0=ab({});function Vn(r={}){if(r.scheme||r.allowRelative||r.relativeOnly||r.allowQuerySquareBrackets||r.domain){return ab(r)}return U0}a(Vn,\"uriRegex\");function Xn(r={}){const e=r.cidr||\"optional\";te([\"required\",\"optional\",\"forbidden\"].includes(e),\"options.cidr must be one of required, optional, forbidden\");te(r.version===void 0||typeof r.version===\"string\"||Array.isArray(r.version),\"options.version must be a string or an array of string\");let t=r.version||[\"ipv4\",\"ipv6\",\"ipvfuture\"];if(!Array.isArray(t)){t=[t]}te(t.length>=1,\"options.version must have at least 1 version specified\");for(const o of t){te(typeof o===\"string\"&&o===o.toLowerCase(),\"Invalid options.version value\");te([\"ipv4\",\"ipv6\",\"ipvfuture\"].includes(o),\"options.version contains unknown version \"+o+\" - must be one of ipv4, ipv6, ipvfuture\")}t=Array.from(new Set(t));const s=t.map(o=>{if(e===\"forbidden\"){return Wn[o]}const c=`\\\\/${o===\"ipv4\"?Wn.v4Cidr:Wn.v6Cidr}`;if(e===\"required\"){return`${Wn[o]}${c}`}return`${Wn[o]}(?:${c})?`});const n=`(?:${s.join(\"|\")})`;const i=new RegExp(`^${n}$`);return{cidr:e,versions:t,regex:i,raw:n}}a(Xn,\"ipRegex\");var j0=/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;var $0=[0,31,28,31,30,31,30,31,31,30,31,30,31];var F0=/^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i;var H0=/^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/;var q0=/^(?=.{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;var z0=/^(?:(?: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)$/;var G0=Xn({version:[\"ipv6\"],cidr:\"forbidden\"}).regex;var K0=Vn().regex;var W0=Vn({allowRelative:true}).regex;var V0=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var X0=/^(?:\\/(?:[^~/]|~0|~1)*)*$/;var Y0=/^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;var J0=/^(?:[^\\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;var Z0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Q0(r){return r%4===0&&(r%100!==0||r%400===0)}a(Q0,\"isLeapYear\");function cb(r){const e=j0.exec(r);if(!e)return false;const t=+e[1];const s=+e[2];const n=+e[3];return s>=1&&s<=12&&n>=1&&n<=(s===2&&Q0(t)?29:$0[s])}a(cb,\"isDate\");function lb(r){const e=F0.exec(r);if(!e)return false;const t=+e[1];const s=+e[2];const n=+e[3];const i=e[4];if(!i)return false;const o=e[5]===\"-\"?-1:1;const c=+(e[6]||0);const l=+(e[7]||0);if(c>23||l>59)return false;if(t<=23&&s<=59&&n<60)return true;const u=s-l*o;const f=t-c*o-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&n<61}a(lb,\"isTime\");var Yn=Object.freeze({\"date\":cb,\"time\":lb,\"date-time\":a(r=>{const e=r.split(/t|\\s/i);return e.length===2&&cb(e[0])&&lb(e[1])},\"date-time\"),\"duration\":a(r=>H0.test(r),\"duration\"),\"email\":a(r=>zo(r,{allowUnicode:false}),\"email\"),\"idn-email\":a(r=>zo(r),\"idn-email\"),\"hostname\":a(r=>q0.test(r),\"hostname\"),\"ipv4\":a(r=>z0.test(r),\"ipv4\"),\"ipv6\":a(r=>G0.test(r),\"ipv6\"),\"uri\":a(r=>K0.test(r),\"uri\"),\"uri-reference\":a(r=>r===\"\"||W0.test(r),\"uri-reference\"),\"uri-template\":a(r=>J0.test(r),\"uri-template\"),\"uuid\":a(r=>V0.test(r),\"uuid\"),\"regex\":a(r=>{try{new RegExp(r,\"u\");return true}catch{return false}},\"regex\"),\"json-pointer\":a(r=>X0.test(r),\"json-pointer\"),\"relative-json-pointer\":a(r=>Y0.test(r),\"relative-json-pointer\"),\"byte\":a(r=>Z0.test(r),\"byte\")});var ub=[\"AAA\",\"AARP\",\"ABB\",\"ABBOTT\",\"ABBVIE\",\"ABC\",\"ABLE\",\"ABOGADO\",\"ABUDHABI\",\"AC\",\"ACADEMY\",\"ACCENTURE\",\"ACCOUNTANT\",\"ACCOUNTANTS\",\"ACO\",\"ACTOR\",\"AD\",\"ADS\",\"ADULT\",\"AE\",\"AEG\",\"AERO\",\"AETNA\",\"AF\",\"AFL\",\"AFRICA\",\"AG\",\"AGAKHAN\",\"AGENCY\",\"AI\",\"AIG\",\"AIRBUS\",\"AIRFORCE\",\"AIRTEL\",\"AKDN\",\"AL\",\"ALIBABA\",\"ALIPAY\",\"ALLFINANZ\",\"ALLSTATE\",\"ALLY\",\"ALSACE\",\"ALSTOM\",\"AM\",\"AMAZON\",\"AMERICANEXPRESS\",\"AMERICANFAMILY\",\"AMEX\",\"AMFAM\",\"AMICA\",\"AMSTERDAM\",\"ANALYTICS\",\"ANDROID\",\"ANQUAN\",\"ANZ\",\"AO\",\"AOL\",\"APARTMENTS\",\"APP\",\"APPLE\",\"AQ\",\"AQUARELLE\",\"AR\",\"ARAB\",\"ARAMCO\",\"ARCHI\",\"ARMY\",\"ARPA\",\"ART\",\"ARTE\",\"AS\",\"ASDA\",\"ASIA\",\"ASSOCIATES\",\"AT\",\"ATHLETA\",\"ATTORNEY\",\"AU\",\"AUCTION\",\"AUDI\",\"AUDIBLE\",\"AUDIO\",\"AUSPOST\",\"AUTHOR\",\"AUTO\",\"AUTOS\",\"AW\",\"AWS\",\"AX\",\"AXA\",\"AZ\",\"AZURE\",\"BA\",\"BABY\",\"BAIDU\",\"BANAMEX\",\"BAND\",\"BANK\",\"BAR\",\"BARCELONA\",\"BARCLAYCARD\",\"BARCLAYS\",\"BAREFOOT\",\"BARGAINS\",\"BASEBALL\",\"BASKETBALL\",\"BAUHAUS\",\"BAYERN\",\"BB\",\"BBC\",\"BBT\",\"BBVA\",\"BCG\",\"BCN\",\"BD\",\"BE\",\"BEATS\",\"BEAUTY\",\"BEER\",\"BERLIN\",\"BEST\",\"BESTBUY\",\"BET\",\"BF\",\"BG\",\"BH\",\"BHARTI\",\"BI\",\"BIBLE\",\"BID\",\"BIKE\",\"BING\",\"BINGO\",\"BIO\",\"BIZ\",\"BJ\",\"BLACK\",\"BLACKFRIDAY\",\"BLOCKBUSTER\",\"BLOG\",\"BLOOMBERG\",\"BLUE\",\"BM\",\"BMS\",\"BMW\",\"BN\",\"BNPPARIBAS\",\"BO\",\"BOATS\",\"BOEHRINGER\",\"BOFA\",\"BOM\",\"BOND\",\"BOO\",\"BOOK\",\"BOOKING\",\"BOSCH\",\"BOSTIK\",\"BOSTON\",\"BOT\",\"BOUTIQUE\",\"BOX\",\"BR\",\"BRADESCO\",\"BRIDGESTONE\",\"BROADWAY\",\"BROKER\",\"BROTHER\",\"BRUSSELS\",\"BS\",\"BT\",\"BUILD\",\"BUILDERS\",\"BUSINESS\",\"BUY\",\"BUZZ\",\"BV\",\"BW\",\"BY\",\"BZ\",\"BZH\",\"CA\",\"CAB\",\"CAFE\",\"CAL\",\"CALL\",\"CALVINKLEIN\",\"CAM\",\"CAMERA\",\"CAMP\",\"CANON\",\"CAPETOWN\",\"CAPITAL\",\"CAPITALONE\",\"CAR\",\"CARAVAN\",\"CARDS\",\"CARE\",\"CAREER\",\"CAREERS\",\"CARS\",\"CASA\",\"CASE\",\"CASH\",\"CASINO\",\"CAT\",\"CATERING\",\"CATHOLIC\",\"CBA\",\"CBN\",\"CBRE\",\"CC\",\"CD\",\"CENTER\",\"CEO\",\"CERN\",\"CF\",\"CFA\",\"CFD\",\"CG\",\"CH\",\"CHANEL\",\"CHANNEL\",\"CHARITY\",\"CHASE\",\"CHAT\",\"CHEAP\",\"CHINTAI\",\"CHRISTMAS\",\"CHROME\",\"CHURCH\",\"CI\",\"CIPRIANI\",\"CIRCLE\",\"CISCO\",\"CITADEL\",\"CITI\",\"CITIC\",\"CITY\",\"CK\",\"CL\",\"CLAIMS\",\"CLEANING\",\"CLICK\",\"CLINIC\",\"CLINIQUE\",\"CLOTHING\",\"CLOUD\",\"CLUB\",\"CLUBMED\",\"CM\",\"CN\",\"CO\",\"COACH\",\"CODES\",\"COFFEE\",\"COLLEGE\",\"COLOGNE\",\"COM\",\"COMMBANK\",\"COMMUNITY\",\"COMPANY\",\"COMPARE\",\"COMPUTER\",\"COMSEC\",\"CONDOS\",\"CONSTRUCTION\",\"CONSULTING\",\"CONTACT\",\"CONTRACTORS\",\"COOKING\",\"COOL\",\"COOP\",\"CORSICA\",\"COUNTRY\",\"COUPON\",\"COUPONS\",\"COURSES\",\"CPA\",\"CR\",\"CREDIT\",\"CREDITCARD\",\"CREDITUNION\",\"CRICKET\",\"CROWN\",\"CRS\",\"CRUISE\",\"CRUISES\",\"CU\",\"CUISINELLA\",\"CV\",\"CW\",\"CX\",\"CY\",\"CYMRU\",\"CYOU\",\"CZ\",\"DAD\",\"DANCE\",\"DATA\",\"DATE\",\"DATING\",\"DATSUN\",\"DAY\",\"DCLK\",\"DDS\",\"DE\",\"DEAL\",\"DEALER\",\"DEALS\",\"DEGREE\",\"DELIVERY\",\"DELL\",\"DELOITTE\",\"DELTA\",\"DEMOCRAT\",\"DENTAL\",\"DENTIST\",\"DESI\",\"DESIGN\",\"DEV\",\"DHL\",\"DIAMONDS\",\"DIET\",\"DIGITAL\",\"DIRECT\",\"DIRECTORY\",\"DISCOUNT\",\"DISCOVER\",\"DISH\",\"DIY\",\"DJ\",\"DK\",\"DM\",\"DNP\",\"DO\",\"DOCS\",\"DOCTOR\",\"DOG\",\"DOMAINS\",\"DOT\",\"DOWNLOAD\",\"DRIVE\",\"DTV\",\"DUBAI\",\"DUPONT\",\"DURBAN\",\"DVAG\",\"DVR\",\"DZ\",\"EARTH\",\"EAT\",\"EC\",\"ECO\",\"EDEKA\",\"EDU\",\"EDUCATION\",\"EE\",\"EG\",\"EMAIL\",\"EMERCK\",\"ENERGY\",\"ENGINEER\",\"ENGINEERING\",\"ENTERPRISES\",\"EPSON\",\"EQUIPMENT\",\"ER\",\"ERICSSON\",\"ERNI\",\"ES\",\"ESQ\",\"ESTATE\",\"ET\",\"EU\",\"EUROVISION\",\"EUS\",\"EVENTS\",\"EXCHANGE\",\"EXPERT\",\"EXPOSED\",\"EXPRESS\",\"EXTRASPACE\",\"FAGE\",\"FAIL\",\"FAIRWINDS\",\"FAITH\",\"FAMILY\",\"FAN\",\"FANS\",\"FARM\",\"FARMERS\",\"FASHION\",\"FAST\",\"FEDEX\",\"FEEDBACK\",\"FERRARI\",\"FERRERO\",\"FI\",\"FIDELITY\",\"FIDO\",\"FILM\",\"FINAL\",\"FINANCE\",\"FINANCIAL\",\"FIRE\",\"FIRESTONE\",\"FIRMDALE\",\"FISH\",\"FISHING\",\"FIT\",\"FITNESS\",\"FJ\",\"FK\",\"FLICKR\",\"FLIGHTS\",\"FLIR\",\"FLORIST\",\"FLOWERS\",\"FLY\",\"FM\",\"FO\",\"FOO\",\"FOOD\",\"FOOTBALL\",\"FORD\",\"FOREX\",\"FORSALE\",\"FORUM\",\"FOUNDATION\",\"FOX\",\"FR\",\"FREE\",\"FRESENIUS\",\"FRL\",\"FROGANS\",\"FRONTIER\",\"FTR\",\"FUJITSU\",\"FUN\",\"FUND\",\"FURNITURE\",\"FUTBOL\",\"FYI\",\"GA\",\"GAL\",\"GALLERY\",\"GALLO\",\"GALLUP\",\"GAME\",\"GAMES\",\"GAP\",\"GARDEN\",\"GAY\",\"GB\",\"GBIZ\",\"GD\",\"GDN\",\"GE\",\"GEA\",\"GENT\",\"GENTING\",\"GEORGE\",\"GF\",\"GG\",\"GGEE\",\"GH\",\"GI\",\"GIFT\",\"GIFTS\",\"GIVES\",\"GIVING\",\"GL\",\"GLASS\",\"GLE\",\"GLOBAL\",\"GLOBO\",\"GM\",\"GMAIL\",\"GMBH\",\"GMO\",\"GMX\",\"GN\",\"GODADDY\",\"GOLD\",\"GOLDPOINT\",\"GOLF\",\"GOO\",\"GOODYEAR\",\"GOOG\",\"GOOGLE\",\"GOP\",\"GOT\",\"GOV\",\"GP\",\"GQ\",\"GR\",\"GRAINGER\",\"GRAPHICS\",\"GRATIS\",\"GREEN\",\"GRIPE\",\"GROCERY\",\"GROUP\",\"GS\",\"GT\",\"GU\",\"GUCCI\",\"GUGE\",\"GUIDE\",\"GUITARS\",\"GURU\",\"GW\",\"GY\",\"HAIR\",\"HAMBURG\",\"HANGOUT\",\"HAUS\",\"HBO\",\"HDFC\",\"HDFCBANK\",\"HEALTH\",\"HEALTHCARE\",\"HELP\",\"HELSINKI\",\"HERE\",\"HERMES\",\"HIPHOP\",\"HISAMITSU\",\"HITACHI\",\"HIV\",\"HK\",\"HKT\",\"HM\",\"HN\",\"HOCKEY\",\"HOLDINGS\",\"HOLIDAY\",\"HOMEDEPOT\",\"HOMEGOODS\",\"HOMES\",\"HOMESENSE\",\"HONDA\",\"HORSE\",\"HOSPITAL\",\"HOST\",\"HOSTING\",\"HOT\",\"HOTELS\",\"HOTMAIL\",\"HOUSE\",\"HOW\",\"HR\",\"HSBC\",\"HT\",\"HU\",\"HUGHES\",\"HYATT\",\"HYUNDAI\",\"IBM\",\"ICBC\",\"ICE\",\"ICU\",\"ID\",\"IE\",\"IEEE\",\"IFM\",\"IKANO\",\"IL\",\"IM\",\"IMAMAT\",\"IMDB\",\"IMMO\",\"IMMOBILIEN\",\"IN\",\"INC\",\"INDUSTRIES\",\"INFINITI\",\"INFO\",\"ING\",\"INK\",\"INSTITUTE\",\"INSURANCE\",\"INSURE\",\"INT\",\"INTERNATIONAL\",\"INTUIT\",\"INVESTMENTS\",\"IO\",\"IPIRANGA\",\"IQ\",\"IR\",\"IRISH\",\"IS\",\"ISMAILI\",\"IST\",\"ISTANBUL\",\"IT\",\"ITAU\",\"ITV\",\"JAGUAR\",\"JAVA\",\"JCB\",\"JE\",\"JEEP\",\"JETZT\",\"JEWELRY\",\"JIO\",\"JLL\",\"JM\",\"JMP\",\"JNJ\",\"JO\",\"JOBS\",\"JOBURG\",\"JOT\",\"JOY\",\"JP\",\"JPMORGAN\",\"JPRS\",\"JUEGOS\",\"JUNIPER\",\"KAUFEN\",\"KDDI\",\"KE\",\"KERRYHOTELS\",\"KERRYPROPERTIES\",\"KFH\",\"KG\",\"KH\",\"KI\",\"KIA\",\"KIDS\",\"KIM\",\"KINDLE\",\"KITCHEN\",\"KIWI\",\"KM\",\"KN\",\"KOELN\",\"KOMATSU\",\"KOSHER\",\"KP\",\"KPMG\",\"KPN\",\"KR\",\"KRD\",\"KRED\",\"KUOKGROUP\",\"KW\",\"KY\",\"KYOTO\",\"KZ\",\"LA\",\"LACAIXA\",\"LAMBORGHINI\",\"LAMER\",\"LAND\",\"LANDROVER\",\"LANXESS\",\"LASALLE\",\"LAT\",\"LATINO\",\"LATROBE\",\"LAW\",\"LAWYER\",\"LB\",\"LC\",\"LDS\",\"LEASE\",\"LECLERC\",\"LEFRAK\",\"LEGAL\",\"LEGO\",\"LEXUS\",\"LGBT\",\"LI\",\"LIDL\",\"LIFE\",\"LIFEINSURANCE\",\"LIFESTYLE\",\"LIGHTING\",\"LIKE\",\"LILLY\",\"LIMITED\",\"LIMO\",\"LINCOLN\",\"LINK\",\"LIVE\",\"LIVING\",\"LK\",\"LLC\",\"LLP\",\"LOAN\",\"LOANS\",\"LOCKER\",\"LOCUS\",\"LOL\",\"LONDON\",\"LOTTE\",\"LOTTO\",\"LOVE\",\"LPL\",\"LPLFINANCIAL\",\"LR\",\"LS\",\"LT\",\"LTD\",\"LTDA\",\"LU\",\"LUNDBECK\",\"LUXE\",\"LUXURY\",\"LV\",\"LY\",\"MA\",\"MADRID\",\"MAIF\",\"MAISON\",\"MAKEUP\",\"MAN\",\"MANAGEMENT\",\"MANGO\",\"MAP\",\"MARKET\",\"MARKETING\",\"MARKETS\",\"MARRIOTT\",\"MARSHALLS\",\"MATTEL\",\"MBA\",\"MC\",\"MCKINSEY\",\"MD\",\"ME\",\"MED\",\"MEDIA\",\"MEET\",\"MELBOURNE\",\"MEME\",\"MEMORIAL\",\"MEN\",\"MENU\",\"MERCKMSD\",\"MG\",\"MH\",\"MIAMI\",\"MICROSOFT\",\"MIL\",\"MINI\",\"MINT\",\"MIT\",\"MITSUBISHI\",\"MK\",\"ML\",\"MLB\",\"MLS\",\"MM\",\"MMA\",\"MN\",\"MO\",\"MOBI\",\"MOBILE\",\"MODA\",\"MOE\",\"MOI\",\"MOM\",\"MONASH\",\"MONEY\",\"MONSTER\",\"MORMON\",\"MORTGAGE\",\"MOSCOW\",\"MOTO\",\"MOTORCYCLES\",\"MOV\",\"MOVIE\",\"MP\",\"MQ\",\"MR\",\"MS\",\"MSD\",\"MT\",\"MTN\",\"MTR\",\"MU\",\"MUSEUM\",\"MUSIC\",\"MV\",\"MW\",\"MX\",\"MY\",\"MZ\",\"NA\",\"NAB\",\"NAGOYA\",\"NAME\",\"NAVY\",\"NBA\",\"NC\",\"NE\",\"NEC\",\"NET\",\"NETBANK\",\"NETFLIX\",\"NETWORK\",\"NEUSTAR\",\"NEW\",\"NEWS\",\"NEXT\",\"NEXTDIRECT\",\"NEXUS\",\"NF\",\"NFL\",\"NG\",\"NGO\",\"NHK\",\"NI\",\"NICO\",\"NIKE\",\"NIKON\",\"NINJA\",\"NISSAN\",\"NISSAY\",\"NL\",\"NO\",\"NOKIA\",\"NORTON\",\"NOW\",\"NOWRUZ\",\"NOWTV\",\"NP\",\"NR\",\"NRA\",\"NRW\",\"NTT\",\"NU\",\"NYC\",\"NZ\",\"OBI\",\"OBSERVER\",\"OFFICE\",\"OKINAWA\",\"OLAYAN\",\"OLAYANGROUP\",\"OLLO\",\"OM\",\"OMEGA\",\"ONE\",\"ONG\",\"ONL\",\"ONLINE\",\"OOO\",\"OPEN\",\"ORACLE\",\"ORANGE\",\"ORG\",\"ORGANIC\",\"ORIGINS\",\"OSAKA\",\"OTSUKA\",\"OTT\",\"OVH\",\"PA\",\"PAGE\",\"PANASONIC\",\"PARIS\",\"PARS\",\"PARTNERS\",\"PARTS\",\"PARTY\",\"PAY\",\"PCCW\",\"PE\",\"PET\",\"PF\",\"PFIZER\",\"PG\",\"PH\",\"PHARMACY\",\"PHD\",\"PHILIPS\",\"PHONE\",\"PHOTO\",\"PHOTOGRAPHY\",\"PHOTOS\",\"PHYSIO\",\"PICS\",\"PICTET\",\"PICTURES\",\"PID\",\"PIN\",\"PING\",\"PINK\",\"PIONEER\",\"PIZZA\",\"PK\",\"PL\",\"PLACE\",\"PLAY\",\"PLAYSTATION\",\"PLUMBING\",\"PLUS\",\"PM\",\"PN\",\"PNC\",\"POHL\",\"POKER\",\"POLITIE\",\"PORN\",\"POST\",\"PR\",\"PRAXI\",\"PRESS\",\"PRIME\",\"PRO\",\"PROD\",\"PRODUCTIONS\",\"PROF\",\"PROGRESSIVE\",\"PROMO\",\"PROPERTIES\",\"PROPERTY\",\"PROTECTION\",\"PRU\",\"PRUDENTIAL\",\"PS\",\"PT\",\"PUB\",\"PW\",\"PWC\",\"PY\",\"QA\",\"QPON\",\"QUEBEC\",\"QUEST\",\"RACING\",\"RADIO\",\"RE\",\"READ\",\"REALESTATE\",\"REALTOR\",\"REALTY\",\"RECIPES\",\"RED\",\"REDUMBRELLA\",\"REHAB\",\"REISE\",\"REISEN\",\"REIT\",\"RELIANCE\",\"REN\",\"RENT\",\"RENTALS\",\"REPAIR\",\"REPORT\",\"REPUBLICAN\",\"REST\",\"RESTAURANT\",\"REVIEW\",\"REVIEWS\",\"REXROTH\",\"RICH\",\"RICHARDLI\",\"RICOH\",\"RIL\",\"RIO\",\"RIP\",\"RO\",\"ROCKS\",\"RODEO\",\"ROGERS\",\"ROOM\",\"RS\",\"RSVP\",\"RU\",\"RUGBY\",\"RUHR\",\"RUN\",\"RW\",\"RWE\",\"RYUKYU\",\"SA\",\"SAARLAND\",\"SAFE\",\"SAFETY\",\"SAKURA\",\"SALE\",\"SALON\",\"SAMSCLUB\",\"SAMSUNG\",\"SANDVIK\",\"SANDVIKCOROMANT\",\"SANOFI\",\"SAP\",\"SARL\",\"SAS\",\"SAVE\",\"SAXO\",\"SB\",\"SBI\",\"SBS\",\"SC\",\"SCB\",\"SCHAEFFLER\",\"SCHMIDT\",\"SCHOLARSHIPS\",\"SCHOOL\",\"SCHULE\",\"SCHWARZ\",\"SCIENCE\",\"SCOT\",\"SD\",\"SE\",\"SEARCH\",\"SEAT\",\"SECURE\",\"SECURITY\",\"SEEK\",\"SELECT\",\"SENER\",\"SERVICES\",\"SEVEN\",\"SEW\",\"SEX\",\"SEXY\",\"SFR\",\"SG\",\"SH\",\"SHANGRILA\",\"SHARP\",\"SHELL\",\"SHIA\",\"SHIKSHA\",\"SHOES\",\"SHOP\",\"SHOPPING\",\"SHOUJI\",\"SHOW\",\"SI\",\"SILK\",\"SINA\",\"SINGLES\",\"SITE\",\"SJ\",\"SK\",\"SKI\",\"SKIN\",\"SKY\",\"SKYPE\",\"SL\",\"SLING\",\"SM\",\"SMART\",\"SMILE\",\"SN\",\"SNCF\",\"SO\",\"SOCCER\",\"SOCIAL\",\"SOFTBANK\",\"SOFTWARE\",\"SOHU\",\"SOLAR\",\"SOLUTIONS\",\"SONG\",\"SONY\",\"SOY\",\"SPA\",\"SPACE\",\"SPORT\",\"SPOT\",\"SR\",\"SRL\",\"SS\",\"ST\",\"STADA\",\"STAPLES\",\"STAR\",\"STATEBANK\",\"STATEFARM\",\"STC\",\"STCGROUP\",\"STOCKHOLM\",\"STORAGE\",\"STORE\",\"STREAM\",\"STUDIO\",\"STUDY\",\"STYLE\",\"SU\",\"SUCKS\",\"SUPPLIES\",\"SUPPLY\",\"SUPPORT\",\"SURF\",\"SURGERY\",\"SUZUKI\",\"SV\",\"SWATCH\",\"SWISS\",\"SX\",\"SY\",\"SYDNEY\",\"SYSTEMS\",\"SZ\",\"TAB\",\"TAIPEI\",\"TALK\",\"TAOBAO\",\"TARGET\",\"TATAMOTORS\",\"TATAR\",\"TATTOO\",\"TAX\",\"TAXI\",\"TC\",\"TCI\",\"TD\",\"TDK\",\"TEAM\",\"TECH\",\"TECHNOLOGY\",\"TEL\",\"TEMASEK\",\"TENNIS\",\"TEVA\",\"TF\",\"TG\",\"TH\",\"THD\",\"THEATER\",\"THEATRE\",\"TIAA\",\"TICKETS\",\"TIENDA\",\"TIPS\",\"TIRES\",\"TIROL\",\"TJ\",\"TJMAXX\",\"TJX\",\"TK\",\"TKMAXX\",\"TL\",\"TM\",\"TMALL\",\"TN\",\"TO\",\"TODAY\",\"TOKYO\",\"TOOLS\",\"TOP\",\"TORAY\",\"TOSHIBA\",\"TOTAL\",\"TOURS\",\"TOWN\",\"TOYOTA\",\"TOYS\",\"TR\",\"TRADE\",\"TRADING\",\"TRAINING\",\"TRAVEL\",\"TRAVELERS\",\"TRAVELERSINSURANCE\",\"TRUST\",\"TRV\",\"TT\",\"TUBE\",\"TUI\",\"TUNES\",\"TUSHU\",\"TV\",\"TVS\",\"TW\",\"TZ\",\"UA\",\"UBANK\",\"UBS\",\"UG\",\"UK\",\"UNICOM\",\"UNIVERSITY\",\"UNO\",\"UOL\",\"UPS\",\"US\",\"UY\",\"UZ\",\"VA\",\"VACATIONS\",\"VANA\",\"VANGUARD\",\"VC\",\"VE\",\"VEGAS\",\"VENTURES\",\"VERISIGN\",\"VERSICHERUNG\",\"VET\",\"VG\",\"VI\",\"VIAJES\",\"VIDEO\",\"VIG\",\"VIKING\",\"VILLAS\",\"VIN\",\"VIP\",\"VIRGIN\",\"VISA\",\"VISION\",\"VIVA\",\"VIVO\",\"VLAANDEREN\",\"VN\",\"VODKA\",\"VOLVO\",\"VOTE\",\"VOTING\",\"VOTO\",\"VOYAGE\",\"VU\",\"WALES\",\"WALMART\",\"WALTER\",\"WANG\",\"WANGGOU\",\"WATCH\",\"WATCHES\",\"WEATHER\",\"WEATHERCHANNEL\",\"WEBCAM\",\"WEBER\",\"WEBSITE\",\"WED\",\"WEDDING\",\"WEIBO\",\"WEIR\",\"WF\",\"WHOSWHO\",\"WIEN\",\"WIKI\",\"WILLIAMHILL\",\"WIN\",\"WINDOWS\",\"WINE\",\"WINNERS\",\"WME\",\"WOLTERSKLUWER\",\"WOODSIDE\",\"WORK\",\"WORKS\",\"WORLD\",\"WOW\",\"WS\",\"WTC\",\"WTF\",\"XBOX\",\"XEROX\",\"XIHUAN\",\"XIN\",\"XN--11B4C3D\",\"XN--1CK2E1B\",\"XN--1QQW23A\",\"XN--2SCRJ9C\",\"XN--30RR7Y\",\"XN--3BST00M\",\"XN--3DS443G\",\"XN--3E0B707E\",\"XN--3HCRJ9C\",\"XN--3PXU8K\",\"XN--42C2D9A\",\"XN--45BR5CYL\",\"XN--45BRJ9C\",\"XN--45Q11C\",\"XN--4DBRK0CE\",\"XN--4GBRIM\",\"XN--54B7FTA0CC\",\"XN--55QW42G\",\"XN--55QX5D\",\"XN--5SU34J936BGSG\",\"XN--5TZM5G\",\"XN--6FRZ82G\",\"XN--6QQ986B3XL\",\"XN--80ADXHKS\",\"XN--80AO21A\",\"XN--80AQECDR1A\",\"XN--80ASEHDB\",\"XN--80ASWG\",\"XN--8Y0A063A\",\"XN--90A3AC\",\"XN--90AE\",\"XN--90AIS\",\"XN--9DBQ2A\",\"XN--9ET52U\",\"XN--9KRT00A\",\"XN--B4W605FERD\",\"XN--BCK1B9A5DRE4C\",\"XN--C1AVG\",\"XN--C2BR7G\",\"XN--CCK2B3B\",\"XN--CCKWCXETD\",\"XN--CG4BKI\",\"XN--CLCHC0EA0B2G2A9GCD\",\"XN--CZR694B\",\"XN--CZRS0T\",\"XN--CZRU2D\",\"XN--D1ACJ3B\",\"XN--D1ALF\",\"XN--E1A4C\",\"XN--ECKVDTC9D\",\"XN--EFVY88H\",\"XN--FCT429K\",\"XN--FHBEI\",\"XN--FIQ228C5HS\",\"XN--FIQ64B\",\"XN--FIQS8S\",\"XN--FIQZ9S\",\"XN--FJQ720A\",\"XN--FLW351E\",\"XN--FPCRJ9C3D\",\"XN--FZC2C9E2C\",\"XN--FZYS8D69UVGM\",\"XN--G2XX48C\",\"XN--GCKR3F0F\",\"XN--GECRJ9C\",\"XN--GK3AT1E\",\"XN--H2BREG3EVE\",\"XN--H2BRJ9C\",\"XN--H2BRJ9C8C\",\"XN--HXT814E\",\"XN--I1B6B1A6A2E\",\"XN--IMR513N\",\"XN--IO0A7I\",\"XN--J1AEF\",\"XN--J1AMH\",\"XN--J6W193G\",\"XN--JLQ480N2RG\",\"XN--JVR189M\",\"XN--KCRX77D1X4A\",\"XN--KPRW13D\",\"XN--KPRY57D\",\"XN--KPUT3I\",\"XN--L1ACC\",\"XN--LGBBAT1AD8J\",\"XN--MGB9AWBF\",\"XN--MGBA3A3EJT\",\"XN--MGBA3A4F16A\",\"XN--MGBA7C0BBN0A\",\"XN--MGBAAM7A8H\",\"XN--MGBAB2BD\",\"XN--MGBAH1A3HJKRD\",\"XN--MGBAI9AZGQP6J\",\"XN--MGBAYH7GPA\",\"XN--MGBBH1A\",\"XN--MGBBH1A71E\",\"XN--MGBC0A9AZCG\",\"XN--MGBCA7DZDO\",\"XN--MGBCPQ6GPA1A\",\"XN--MGBERP4A5D4AR\",\"XN--MGBGU82A\",\"XN--MGBI4ECEXP\",\"XN--MGBPL2FH\",\"XN--MGBT3DHD\",\"XN--MGBTX2B\",\"XN--MGBX4CD0AB\",\"XN--MIX891F\",\"XN--MK1BU44C\",\"XN--MXTQ1M\",\"XN--NGBC5AZD\",\"XN--NGBE9E0A\",\"XN--NGBRX\",\"XN--NODE\",\"XN--NQV7F\",\"XN--NQV7FS00EMA\",\"XN--NYQY26A\",\"XN--O3CW4H\",\"XN--OGBPF8FL\",\"XN--OTU796D\",\"XN--P1ACF\",\"XN--P1AI\",\"XN--PGBS0DH\",\"XN--PSSY2U\",\"XN--Q7CE6A\",\"XN--Q9JYB4C\",\"XN--QCKA1PMC\",\"XN--QXA6A\",\"XN--QXAM\",\"XN--RHQV96G\",\"XN--ROVU88B\",\"XN--RVC1E0AM3E\",\"XN--S9BRJ9C\",\"XN--SES554G\",\"XN--T60B56A\",\"XN--TCKWE\",\"XN--TIQ49XQYJ\",\"XN--UNUP4Y\",\"XN--VERMGENSBERATER-CTB\",\"XN--VERMGENSBERATUNG-PWB\",\"XN--VHQUV\",\"XN--VUQ861B\",\"XN--W4R85EL8FHU5DNRA\",\"XN--W4RS40L\",\"XN--WGBH1C\",\"XN--WGBL6A\",\"XN--XHQ521B\",\"XN--XKC2AL3HYE2A\",\"XN--XKC2DL3A5EE0H\",\"XN--Y9A3AQ\",\"XN--YFRO4I67O\",\"XN--YGBI2AMMX\",\"XN--ZFR164B\",\"XXX\",\"XYZ\",\"YACHTS\",\"YAHOO\",\"YAMAXUN\",\"YANDEX\",\"YE\",\"YODOBASHI\",\"YOGA\",\"YOKOHAMA\",\"YOU\",\"YOUTUBE\",\"YT\",\"YUN\",\"ZA\",\"ZAPPOS\",\"ZARA\",\"ZERO\",\"ZIP\",\"ZM\",\"ZONE\",\"ZUERICH\",\"ZW\"];var Th=new Set(ub.map(r=>r.toLowerCase()));var Go=Th instanceof Set?{tlds:{allow:Th,deny:null}}:false;var fb={true:{true:/^(?:[\\w\\-]{2}[\\w\\-]{2})*(?:[\\w\\-]{2}==|[\\w\\-]{3}=)?$/,false:/^(?:[A-Za-z0-9+\\/]{2}[A-Za-z0-9+\\/]{2})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/},false:{true:/^(?:[\\w\\-]{2}[\\w\\-]{2})*(?:[\\w\\-]{2}(==)?|[\\w\\-]{3}=?)?$/,false:/^(?:[A-Za-z0-9+\\/]{2}[A-Za-z0-9+\\/]{2})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?$/}};var tv=/^data:[\\w+.-]+\\/[\\w+.-]+;((charset=[\\w-]+|base64),)?(.*)$/;var xh={withPrefix:/^0x[0-9a-f]+$/i,withOptionalPrefix:/^(?:0x)?[0-9a-f]+$/i,withoutPrefix:/^[0-9a-f]+$/i};var rv=Xn({cidr:\"forbidden\"}).regex;var sv=/^P(?!$)(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?$/;var _l={\"{\":\"}\",\"[\":\"]\",\"(\":\")\",\"\":\"\"};var db={uuidv1:\"1\",uuidv2:\"2\",uuidv3:\"3\",uuidv4:\"4\",uuidv5:\"5\",uuidv6:\"6\",uuidv7:\"7\",uuidv8:\"8\"};var nv=new Set([void 0,true,false,\"-\",\":\"]);var hb=[\"NFC\",\"NFD\",\"NFKC\",\"NFKD\"];var iv=_e.extend({type:\"string\",flags:{insensitive:{default:false},truncate:{default:false}},terms:{replacements:{init:null}},coerce:{from:\"string\",method(r,{schema:e,state:t,prefs:s}){const n=e.$_getRule(\"normalize\");if(n){r=r.normalize(n.args.form)}const i=e.$_getRule(\"case\");if(i){r=i.args.direction===\"upper\"?r.toLocaleUpperCase():r.toLocaleLowerCase()}const o=e.$_getRule(\"trim\");if(o&&o.args.enabled){r=r.trim()}if(e.$_terms.replacements){for(const l of e.$_terms.replacements){r=r.replace(l.pattern,l.replacement)}}const c=e.$_getRule(\"hex\");if(c&&c.args.options.byteAligned&&r.length%2!==0){r=`0${r}`}if(e.$_getRule(\"isoDate\")){const l=mb(r);if(l){r=l}}if(e._flags.truncate){const l=e.$_getRule(\"max\");if(l){let u=l.args.limit;if(tt(u)){u=u.resolve(r,t,s);if(!Cr(u)){return{value:r,errors:e.$_createError(\"any.ref\",u,{ref:l.args.limit,arg:\"limit\",reason:\"must be a positive integer\"},t,s)}}}r=av(r,u)}}return{value:r}}},validate(r,{schema:e,error:t}){if(typeof r!==\"string\"){return{value:r,errors:t(\"string.base\")}}if(r===\"\"){const s=e.$_getRule(\"min\");if(s&&s.args.limit===0){return}return{value:r,errors:t(\"string.empty\")}}},rules:{alphanum:{method(){return this.$_addRule(\"alphanum\")},validate(r,e){if(/^[a-zA-Z0-9]+$/.test(r)){return r}return e.error(\"string.alphanum\")}},base64:{method(r={}){re(r,[\"paddingRequired\",\"urlSafe\"]);r={urlSafe:false,paddingRequired:true,...r};g(typeof r.paddingRequired===\"boolean\",\"paddingRequired must be boolean\");g(typeof r.urlSafe===\"boolean\",\"urlSafe must be boolean\");return this.$_addRule({name:\"base64\",args:{options:r}})},validate(r,e,{options:t}){const s=fb[t.paddingRequired][t.urlSafe];if(s.test(r)){return r}return e.error(\"string.base64\")}},case:{method(r){g([\"lower\",\"upper\"].includes(r),\"Invalid case:\",r);return this.$_addRule({name:\"case\",args:{direction:r}})},validate(r,e,{direction:t}){if(t===\"lower\"&&r===r.toLocaleLowerCase()||t===\"upper\"&&r===r.toLocaleUpperCase()){return r}return e.error(`string.${t}case`)},convert:true},creditCard:{method(){return this.$_addRule(\"creditCard\")},validate(r,e){let t=r.length;let s=0;let n=1;while(t--){const i=r.charAt(t)*n;s=s+(i-(i>9)*9);n=n^3}if(s>0&&s%10===0){return r}return e.error(\"string.creditCard\")}},dataUri:{method(r={}){re(r,[\"paddingRequired\"]);r={paddingRequired:true,...r};g(typeof r.paddingRequired===\"boolean\",\"paddingRequired must be boolean\");return this.$_addRule({name:\"dataUri\",args:{options:r}})},validate(r,e,{options:t}){const s=r.match(tv);if(s){if(!s[2]){return r}if(s[2]!==\"base64\"){return r}const n=fb[t.paddingRequired].false;if(n.test(s[3])){return r}}return e.error(\"string.dataUri\")}},domain:{method(r){if(r){re(r,[\"allowFullyQualified\",\"allowUnicode\",\"allowUnderscore\",\"maxDomainSegments\",\"minDomainSegments\",\"tlds\"])}const e=Rh(r);return this.$_addRule({name:\"domain\",args:{options:r},address:e})},validate(r,e,t,{address:s}){if(qo(r,s)){return r}return e.error(\"string.domain\")}},email:{method(r={}){re(r,[\"allowFullyQualified\",\"allowUnicode\",\"ignoreLength\",\"maxDomainSegments\",\"minDomainSegments\",\"multiple\",\"separator\",\"tlds\"]);g(r.multiple===void 0||typeof r.multiple===\"boolean\",\"multiple option must be an boolean\");const e=Rh(r);const t=new RegExp(`\\\\s*[${r.separator?mt(r.separator):\",\"}]\\\\s*`);return this.$_addRule({name:\"email\",args:{options:r},regex:t,address:e})},validate(r,e,{options:t},{regex:s,address:n}){const i=t.multiple?r.split(s):[r];const o=[];for(const c of i){if(!zo(c,n)){o.push(c)}}if(!o.length){return r}return e.error(\"string.email\",{value:r,invalids:o})}},format:{method(r){g(typeof r===\"string\"&&Object.prototype.hasOwnProperty.call(Yn,r),\"Unknown format\",r);return this.$_addRule({name:\"format\",args:{name:r}})},validate(r,e,{name:t}){if(Yn[t](r))return r;return e.error(\"string.format\",{format:t})},args:[\"name\"]},guid:{alias:\"uuid\",method(r={}){re(r,[\"version\",\"separator\",\"wrapper\"]);g(r.wrapper===void 0||typeof r.wrapper===\"boolean\"||typeof r.wrapper===\"string\"&&typeof _l[r.wrapper]===\"string\",`\"wrapper\" must be true, false, or one of \"${Object.keys(_l).filter(Boolean).join('\", \"')}\"`);let e=\"\";if(r.version){const o=[].concat(r.version);g(o.length>=1,\"version must have at least 1 valid version specified\");const c=new Set;for(let l=0;l<o.length;++l){const u=o[l];g(typeof u===\"string\",\"version at position \"+l+\" must be a string\");const f=db[u.toLowerCase()];g(f,\"version at position \"+l+\" must be one of \"+Object.keys(db).join(\", \"));g(!c.has(f),\"version at position \"+l+\" must not be a duplicate\");e+=f;c.add(f)}}g(nv.has(r.separator),'separator must be one of true, false, \"-\", or \":\"');const t=r.separator===void 0?\"[:-]?\":r.separator===true?\"[:-]\":r.separator===false?\"[]?\":`\\\\${r.separator}`;let s;let n;if(r.wrapper===void 0){s=\"[\\\\[{\\\\(]?\";n=\"[\\\\]}\\\\)]?\"}else if(r.wrapper===true){s=\"[\\\\[{\\\\(]\";n=\"[\\\\]}\\\\)]\"}else if(r.wrapper===false){s=\"\";n=\"\"}else{s=mt(r.wrapper);n=mt(_l[r.wrapper])}const i=new RegExp(`^(${s})[0-9A-F]{8}(${t})[0-9A-F]{4}\\\\2?[${e||\"0-9A-F\"}][0-9A-F]{3}\\\\2?[${e?\"89AB\":\"0-9A-F\"}][0-9A-F]{3}\\\\2?[0-9A-F]{12}(${n})$`,\"i\");return this.$_addRule({name:\"guid\",args:{options:r},regex:i})},validate(r,e,t,{regex:s}){const n=s.exec(r);if(!n){return e.error(\"string.guid\")}const i=n[1];const o=n[n.length-1];if((i||o)&&_l[i]!==o){return e.error(\"string.guid\")}return r}},hex:{method(r={}){re(r,[\"byteAligned\",\"prefix\"]);r={byteAligned:false,prefix:false,...r};g(typeof r.byteAligned===\"boolean\",\"byteAligned must be boolean\");g(typeof r.prefix===\"boolean\"||r.prefix===\"optional\",'prefix must be boolean or \"optional\"');return this.$_addRule({name:\"hex\",args:{options:r}})},validate(r,e,{options:t}){const s=t.prefix===\"optional\"?xh.withOptionalPrefix:t.prefix===true?xh.withPrefix:xh.withoutPrefix;if(!s.test(r)){return e.error(\"string.hex\")}if(t.byteAligned&&r.length%2!==0){return e.error(\"string.hexAlign\")}return r}},hostname:{method(){return this.$_addRule(\"hostname\")},validate(r,e){if(qo(r,{minDomainSegments:1})||rv.test(r)){return r}return e.error(\"string.hostname\")}},insensitive:{method(){return this.$_setFlag(\"insensitive\",true)}},ip:{method(r={}){re(r,[\"cidr\",\"version\"]);const{cidr:e,versions:t,regex:s}=Fn(()=>Xn(r));const n=r.version?t:void 0;return this.$_addRule({name:\"ip\",args:{options:{cidr:e,version:n}},regex:s})},validate(r,e,{options:t},{regex:s}){if(s.test(r)){return r}if(t.version){return e.error(\"string.ipVersion\",{value:r,cidr:t.cidr,version:t.version})}return e.error(\"string.ip\",{value:r,cidr:t.cidr})}},isoDate:{method(){return this.$_addRule(\"isoDate\")},validate(r,{error:e}){if(mb(r)){return r}return e(\"string.isoDate\")}},isoDuration:{method(){return this.$_addRule(\"isoDuration\")},validate(r,e){if(sv.test(r)){return r}return e.error(\"string.isoDuration\")}},length:{method(r,e){return _h(this,\"length\",r,\"=\",e)},validate(r,e,{limit:t,encoding:s},{name:n,operator:i,args:o}){let c;if(s){c=Buffer&&Buffer.byteLength(r,s)}else{const l=r.length;const u=ot(Math.ceil(l/2),t,i);c=u===ot(l,t,i)?l:ov(r)}if(ot(c,t,i)){return r}return e.error(\"string.\"+n,{limit:o.limit,value:r,encoding:s})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"},\"encoding\"]},lowercase:{method(){return this.case(\"lower\")}},max:{method(r,e){return _h(this,\"max\",r,\"<=\",e)},args:[\"limit\",\"encoding\"]},min:{method(r,e){return _h(this,\"min\",r,\">=\",e)},args:[\"limit\",\"encoding\"]},normalize:{method(r=\"NFC\"){g(hb.includes(r),\"normalization form must be one of \"+hb.join(\", \"));return this.$_addRule({name:\"normalize\",args:{form:r}})},validate(r,{error:e},{form:t}){if(r===r.normalize(t)){return r}return e(\"string.normalize\",{value:r,form:t})},convert:true},pattern:{alias:\"regex\",method(r,e={}){g(r instanceof RegExp,\"regex must be a RegExp\");g(!r.flags.includes(\"g\")&&!r.flags.includes(\"y\"),\"regex should not use global or sticky mode\");if(typeof e===\"string\"){e={name:e}}re(e,[\"invert\",\"name\"]);const t=[\"string.pattern\",e.invert?\".invert\":\"\",e.name?\".name\":\".base\"].join(\"\");return this.$_addRule({name:\"pattern\",args:{regex:r,options:e},errorCode:t})},validate(r,e,{regex:t,options:s},{errorCode:n}){const i=t.test(r);if(i^s.invert){return r}return e.error(n,{name:s.name,regex:t,value:r})},args:[\"regex\",\"options\"],multi:true},replace:{method(r,e){if(typeof r===\"string\"){r=new RegExp(mt(r),\"g\")}g(r instanceof RegExp,\"pattern must be a RegExp\");g(typeof e===\"string\",\"replacement must be a String\");const t=this.clone();if(!t.$_terms.replacements){t.$_terms.replacements=[]}t.$_terms.replacements.push({pattern:r,replacement:e});return t}},token:{method(){return this.$_addRule(\"token\")},validate(r,e){if(/^\\w+$/.test(r)){return r}return e.error(\"string.token\")}},trim:{method(r=true){g(typeof r===\"boolean\",\"enabled must be a boolean\");return this.$_addRule({name:\"trim\",args:{enabled:r}})},validate(r,e,{enabled:t}){if(!t||r===r.trim()){return r}return e.error(\"string.trim\")},convert:true},truncate:{method(r=true){g(typeof r===\"boolean\",\"enabled must be a boolean\");return this.$_setFlag(\"truncate\",r)}},uppercase:{method(){return this.case(\"upper\")}},uri:{method(r={}){re(r,[\"allowRelative\",\"allowQuerySquareBrackets\",\"domain\",\"relativeOnly\",\"scheme\",\"encodeUri\"]);if(r.domain){re(r.domain,[\"allowFullyQualified\",\"allowUnicode\",\"maxDomainSegments\",\"minDomainSegments\",\"tlds\"])}const{regex:e,scheme:t}=Fn(()=>Vn(r));const s=r.domain?Rh(r.domain):null;return this.$_addRule({name:\"uri\",args:{options:r},regex:e,domain:s,scheme:t})},validate(r,e,{options:t},{regex:s,domain:n,scheme:i}){if([\"http:/\",\"https:/\"].includes(r)){return e.error(\"string.uri\")}let o=s.exec(r);if(!o&&e.prefs.convert&&t.encodeUri){const c=encodeURI(r);o=s.exec(c);if(o){r=c}}if(o){const c=o[1]||o[2];if(n&&(!t.allowRelative||c)&&!qo(c,n)){return e.error(\"string.domain\",{value:c})}return r}if(t.relativeOnly){return e.error(\"string.uriRelativeOnly\")}if(t.scheme){return e.error(\"string.uriCustomScheme\",{scheme:i,value:r})}return e.error(\"string.uri\")}}},manifest:{build(r,e){if(e.replacements){for(const{pattern:t,replacement:s}of e.replacements){r=r.replace(t,s)}}return r}},messages:{\"string.alphanum\":\"{{#label}} must only contain alpha-numeric characters\",\"string.base\":\"{{#label}} must be a string\",\"string.base64\":\"{{#label}} must be a valid base64 string\",\"string.creditCard\":\"{{#label}} must be a credit card\",\"string.dataUri\":\"{{#label}} must be a valid dataUri string\",\"string.domain\":\"{{#label}} must contain a valid domain name\",\"string.email\":\"{{#label}} must be a valid email\",\"string.empty\":\"{{#label}} is not allowed to be empty\",\"string.format\":\"{{#label}} must be a valid {{#format}}\",\"string.guid\":\"{{#label}} must be a valid GUID\",\"string.hex\":\"{{#label}} must only contain hexadecimal characters\",\"string.hexAlign\":\"{{#label}} hex decoded representation must be byte aligned\",\"string.hostname\":\"{{#label}} must be a valid hostname\",\"string.ip\":\"{{#label}} must be a valid ip address with a {{#cidr}} CIDR\",\"string.ipVersion\":\"{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR\",\"string.isoDate\":\"{{#label}} must be in iso format\",\"string.isoDuration\":\"{{#label}} must be a valid ISO 8601 duration\",\"string.length\":\"{{#label}} length must be {{#limit}} characters long\",\"string.lowercase\":\"{{#label}} must only contain lowercase characters\",\"string.max\":\"{{#label}} length must be less than or equal to {{#limit}} characters long\",\"string.min\":\"{{#label}} length must be at least {{#limit}} characters long\",\"string.normalize\":\"{{#label}} must be unicode normalized in the {{#form}} form\",\"string.token\":\"{{#label}} must only contain alpha-numeric and underscore characters\",\"string.pattern.base\":\"{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}\",\"string.pattern.name\":\"{{#label}} with value {:[.]} fails to match the {{#name}} pattern\",\"string.pattern.invert.base\":\"{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}\",\"string.pattern.invert.name\":\"{{#label}} with value {:[.]} matches the inverted {{#name}} pattern\",\"string.trim\":\"{{#label}} must not have leading or trailing whitespace\",\"string.uri\":\"{{#label}} must be a valid uri\",\"string.uriCustomScheme\":\"{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern\",\"string.uriRelativeOnly\":\"{{#label}} must be a valid relative uri\",\"string.uppercase\":\"{{#label}} must only contain uppercase characters\"}});var gb=iv;function Rh(r){if(!r){return Go||r}g(r.minDomainSegments===void 0||Number.isSafeInteger(r.minDomainSegments)&&r.minDomainSegments>0,\"minDomainSegments must be a positive integer\");g(r.maxDomainSegments===void 0||Number.isSafeInteger(r.maxDomainSegments)&&r.maxDomainSegments>0,\"maxDomainSegments must be a positive integer\");if(r.tlds===false){return r}if(r.tlds===true||r.tlds===void 0){g(Go,\"Built-in TLD list disabled\");return Object.assign({},r,Go)}g(typeof r.tlds===\"object\",\"tlds must be true, false, or an object\");const e=r.tlds.deny;if(e){if(Array.isArray(e)){r=Object.assign({},r,{tlds:{deny:new Set(e)}})}g(r.tlds.deny instanceof Set,\"tlds.deny must be an array, Set, or boolean\");g(!r.tlds.allow,\"Cannot specify both tlds.allow and tlds.deny lists\");pb(r.tlds.deny,\"tlds.deny\");return r}const t=r.tlds.allow;if(!t){return{...r,tlds:false}}if(t===true){g(Go,\"Built-in TLD list disabled\");return Object.assign({},r,Go)}if(Array.isArray(t)){r=Object.assign({},r,{tlds:{allow:new Set(t)}})}g(r.tlds.allow instanceof Set,\"tlds.allow must be an array, Set, or boolean\");pb(r.tlds.allow,\"tlds.allow\");return r}a(Rh,\"addressOptions\");function pb(r,e){for(const t of r){g(qo(t,{minDomainSegments:1,maxDomainSegments:1}),`${e} must contain valid top level domain names`)}}a(pb,\"validateTlds\");function mb(r){if(!ol(r)){return null}if(/.*T.*[+-]\\d\\d$/.test(r)){r+=\"00\"}const e=new Date(r);if(isNaN(e.getTime())){return null}return e.toISOString()}a(mb,\"isoDate\");function ov(r){let e=r.length;for(let t=0;t<r.length-1;++t){const s=r.charCodeAt(t);if(s>=55296&&s<=56319){const n=r.charCodeAt(t+1);if(n>=56320&&n<=57343){--e;++t}}}return e}a(ov,\"codePointLength\");function av(r,e){if(r.length<=e)return r;let t=0;for(let s=0;s<e&&t<r.length;++s){const n=r.charCodeAt(t);const i=r.charCodeAt(t+1);t+=n>=55296&&n<=56319&&i>=56320&&i<=57343?2:1}return r.slice(0,t)}a(av,\"codePointSlice\");function _h(r,e,t,s,n){g(!n||Buffer&&Buffer.isEncoding(n),\"Invalid encoding:\",n);return r.$_addRule({name:e,method:\"length\",args:{limit:t,encoding:n},operator:s})}a(_h,\"length\");var Ch=class r extends Map{static{a(this,\"SymbolMap\")}slice(){return new r(this)}};var cv=_e.extend({type:\"symbol\",terms:{map:{init:new Ch}},coerce:{method(r,{schema:e,error:t}){const s=e.$_terms.map.get(r);if(s)r=s;if(!e._flags.only||typeof r===\"symbol\"){return{value:r}}return{value:r,errors:t(\"symbol.map\",{map:e.$_terms.map})}}},validate(r,{error:e}){if(typeof r!==\"symbol\")return{value:r,errors:e(\"symbol.base\")}},rules:{map:{method(r){if(r&&!r[Symbol.iterator]&&typeof r===\"object\"){r=Object.entries(r)}g(r&&r[Symbol.iterator],\"Iterable must be an iterable or object\");const e=this.clone();const t=[];for(const s of r){g(s&&s[Symbol.iterator],\"Entry must be an iterable\");const[n,i]=s;g(typeof n!==\"object\"&&typeof n!==\"function\"&&typeof n!==\"symbol\",\"Key must not be of type object, function, or Symbol\");g(typeof i===\"symbol\",\"Value must be a Symbol\");e.$_terms.map.set(n,i);t.push(i)}return e.valid(...t)}}},manifest:{build(r,e){if(e.map)r=r.map(e.map);return r}},messages:{\"symbol.base\":\"{{#label}} must be a symbol\",\"symbol.map\":\"{{#label}} must be one of {{#map}}\"}});var yb=cv;var lv=_e.extend({type:\"binary\",coerce:{from:[\"string\",\"object\"],method(r,{schema:e}){if(typeof r===\"string\"||r!==null&&r.type===\"Buffer\"){try{return{value:Buffer.from(r,e._flags.encoding)}}catch{}}}},validate(r,{error:e}){if(!Buffer.isBuffer(r))return{value:r,errors:e(\"binary.base\")}},rules:{encoding:{method(r){g(Buffer.isEncoding(r),\"Invalid encoding:\",r);return this.$_setFlag(\"encoding\",r)}},length:{method(r){return this.$_addRule({name:\"length\",method:\"length\",args:{limit:r},operator:\"=\"})},validate(r,e,{limit:t},{name:s,operator:n,args:i}){if(ot(r.length,t,n))return r;return e.error(\"binary.\"+s,{limit:i.limit,value:r})},args:[{name:\"limit\",ref:true,assert:Cr,message:\"must be a positive integer\"}]},max:{method(r){return this.$_addRule({name:\"max\",method:\"length\",args:{limit:r},operator:\"<=\"})}},min:{method(r){return this.$_addRule({name:\"min\",method:\"length\",args:{limit:r},operator:\">=\"})}}},cast:{string:{from:a(r=>Buffer.isBuffer(r),\"from\"),to(r){return r.toString()}}},messages:{\"binary.base\":\"{{#label}} must be a buffer or a string\",\"binary.length\":\"{{#label}} must be {{#limit}} bytes\",\"binary.max\":\"{{#label}} must be less than or equal to {{#limit}} bytes\",\"binary.min\":\"{{#label}} must be at least {{#limit}} bytes\"}});var bb=lv;var Ko={};var Sb=false;function Cl(){if(!Sb){Sb=true;uv()}return Ko}a(Cl,\"getSchemas\");function uv(){const r=b.string().min(1).max(2).allow(false);Ko.preferences=b.object({allowUnknown:b.boolean(),abortEarly:b.boolean(),artifacts:b.boolean(),cache:b.boolean(),context:b.object(),convert:b.boolean(),dateFormat:b.valid(\"date\",\"iso\",\"string\",\"time\",\"utc\"),debug:b.boolean(),errors:{escapeHtml:b.boolean(),label:b.valid(\"path\",\"key\",false),language:[b.string(),b.object().ref()],render:b.boolean(),stack:b.boolean(),wrap:{label:r,array:r,string:r}},externals:b.boolean(),messages:b.object(),noDefaults:b.boolean(),nonEnumerables:b.boolean(),presence:b.valid(\"required\",\"optional\",\"forbidden\"),skipFunctions:b.boolean(),stripUnknown:b.object({arrays:b.boolean(),objects:b.boolean()}).or(\"arrays\",\"objects\").allow(true,false),warnings:b.boolean()}).strict();const e=/^[a-zA-Z0-9]\\w*$/;const t=b.object({alias:b.array().items(b.string().pattern(e)).single(),args:b.array().items(b.string(),b.object({name:b.string().pattern(e).required(),ref:b.boolean(),assert:b.alternatives([b.function(),b.object().schema()]).conditional(\"ref\",{is:true,then:b.required()}),normalize:b.function(),message:b.string().when(\"assert\",{is:b.function(),then:b.required()})})),convert:b.boolean(),manifest:b.boolean(),method:b.function().allow(false),multi:b.boolean(),validate:b.function()});Ko.extension=b.object({type:b.alternatives([b.string(),b.object().regex()]).required(),args:b.function(),cast:b.object().pattern(e,b.object({from:b.function().maxArity(1).required(),to:b.function().minArity(1).maxArity(2).required()})),base:b.object().schema().when(\"type\",{is:b.object().regex(),then:b.forbidden()}),coerce:[b.function().maxArity(3),b.object({method:b.function().maxArity(3).required(),from:b.array().items(b.string()).single()})],flags:b.object().pattern(e,b.object({setter:b.string(),default:b.any()})),manifest:{build:b.function().arity(2)},messages:[b.object(),b.string()],modifiers:b.object().pattern(e,b.function().minArity(1).maxArity(2)),overrides:b.object().pattern(e,b.function()),prepare:b.function().maxArity(3),rebuild:b.function().arity(1),rules:b.object().pattern(e,t),terms:b.object().pattern(e,b.object({init:b.array().allow(null).required(),manifest:b.object().pattern(/.+/,[b.valid(\"schema\",\"single\"),b.object({mapped:b.object({from:b.string().required(),to:b.string().required()}).required()})])})),validate:b.function().maxArity(3)}).strict();Ko.extensions=b.array().items(b.object(),b.function().arity(1)).strict();const s={buffer:b.object({buffer:b.string()}),func:b.object({function:b.function().required(),options:{literal:true}}),override:b.object({override:true}),ref:b.object({ref:b.object({type:b.valid(\"value\",\"global\",\"local\"),path:b.array().required(),separator:b.string().length(1).allow(false),ancestor:b.number().min(0).integer().allow(\"root\"),map:b.array().items(b.array().length(2)).min(1),adjust:b.function(),iterables:b.boolean(),in:b.boolean(),render:b.boolean()}).required()}),regex:b.object({regex:b.string().min(3)}),special:b.object({special:b.valid(\"deep\").required()}),template:b.object({template:b.string().required(),options:b.object()}),value:b.object({value:b.alternatives([b.object(),b.array()]).required()})};s.entity=b.alternatives([b.array().items(b.link(\"...\")),b.boolean(),b.function(),b.number(),b.string(),s.buffer,s.func,s.ref,s.regex,s.special,s.template,s.value,b.link(\"/\")]);s.values=b.array().items(null,b.boolean(),b.function(),b.number().allow(Infinity,-Infinity),b.string().allow(\"\"),b.symbol(),s.buffer,s.func,s.override,s.ref,s.regex,s.template,s.value);s.messages=b.object().pattern(/.+/,[b.string(),s.template,b.object().pattern(/.+/,[b.string(),s.template])]);Ko.description=b.object({type:b.string().required(),flags:b.object({cast:b.string(),default:b.any(),description:b.string(),empty:b.link(\"/\"),failover:s.entity,id:b.string(),label:b.string(),only:true,presence:[\"optional\",\"required\",\"forbidden\"],result:[\"raw\",\"strip\"],strip:b.boolean(),unit:b.string()}).unknown(),preferences:{allowUnknown:b.boolean(),abortEarly:b.boolean(),artifacts:b.boolean(),cache:b.boolean(),convert:b.boolean(),dateFormat:[\"date\",\"iso\",\"string\",\"time\",\"utc\"],errors:{escapeHtml:b.boolean(),label:[\"path\",\"key\"],language:[b.string(),s.ref],wrap:{label:r,array:r}},externals:b.boolean(),messages:s.messages,noDefaults:b.boolean(),nonEnumerables:b.boolean(),presence:[\"required\",\"optional\",\"forbidden\"],skipFunctions:b.boolean(),stripUnknown:b.object({arrays:b.boolean(),objects:b.boolean()}).or(\"arrays\",\"objects\").allow(true,false),warnings:b.boolean()},allow:s.values,invalid:s.values,rules:b.array().min(1).items({name:b.string().required(),args:b.object().min(1),keep:b.boolean(),message:[b.string(),s.messages],warn:b.boolean()}),keys:b.object().pattern(/.*/,b.link(\"/\")),link:s.ref}).pattern(/^[a-z]\\w*$/,b.any())}a(uv,\"build\");gt.schemas=Cl;var vl;var vh={alternatives:Uy,any:_e,array:Fy,boolean:zy,date:Wy,function:Vy,link:Yy,number:Qy,object:eb,string:gb,symbol:yb};var Ah={alt:\"alternatives\",bool:\"boolean\",func:\"function\"};if(Buffer)vh.binary=bb;function fv(){const r={_types:new Set(Object.keys(vh))};for(const e of r._types){r[e]=function(...t){g(!t.length||[\"alternatives\",\"link\",\"object\"].includes(e),\"The\",e,\"type does not allow arguments\");return Ih(this,vh[e],t)}}for(const e of[\"allow\",\"custom\",\"disallow\",\"equal\",\"exist\",\"forbidden\",\"invalid\",\"not\",\"only\",\"optional\",\"options\",\"prefs\",\"preferences\",\"required\",\"strip\",\"valid\",\"when\"]){r[e]=function(...t){const s=this.any();return s[e].call(s,...t)}}Object.assign(r,dv);for(const e in Ah){const t=Ah[e];r[e]=r[t]}r.x=r.expression;if(ch)ch(r);return r}a(fv,\"createRoot\");var dv={ValidationError:qt,version:ns,cache:cl,assert(r,e,...t){wb(r,e,true,t)},attempt(r,e,...t){return wb(r,e,false,t)},build(r){g(typeof sh===\"function\",\"Manifest functionality disabled\");return sh(this,r)},checkPreferences(r){Mo(r)},compile(r,e){return fl(this,r,e)},defaults(r){g(typeof r===\"function\",\"modifier must be a function\");const e=Object.assign({},this);for(const t of e._types){const s=r(e[t].call(e));g(oe(s),\"modifier must return a valid schema object\");e[t]=function(...n){return Ih(this,s,n)}}return e},expression(r,e){return new se(r,e)},extend(...r){Be(r,\"extend\");vl=vl||Cl();g(r.length,\"You need to provide at least one extension\");this.assert(r,vl.extensions);const e=Object.assign({},this);e._types=new Set(e._types);for(let t of r){if(typeof t===\"function\")t=t(e);this.assert(t,vl.extension);const s=hv(t,e);for(const n of s){g(e[n.type]===void 0||e._types.has(n.type),\"Cannot override name\",n.type);const i=n.base||this.any();const o=yl(i,n);e._types.add(n.type);e[n.type]=function(...c){return Ih(this,o,c)}}}return e},isError:qt.isError,isExpression:se.isTemplate,isRef:rt,isSchema:oe,in(r,e){return ty(r,e)},override:H.override,ref(r,e){return as(r,e)},types(){const r={};for(const e of this._types)r[e]=this[e].call(this);for(const e in Ah)r[e]=this[e].call(this);return r}};function wb(r,e,t,s){const n=s[0]instanceof Error||typeof s[0]===\"string\"?s[0]:null;const i=n!==null?s[1]:s[0];const o=e.validate(r,Ht({errors:{stack:true}},i||{}));let c=o.error;if(!c)return o.value;if(n instanceof Error)throw n;const l=t&&typeof c.annotate===\"function\"?c.annotate():c.message;if(c instanceof qt===false)c=G(c);ss(c,n?`${n} ${l}`:l);throw c}a(wb,\"assertValue\");function Ih(r,e,t){g(r,\"Must be invoked on a validation root.\");e.$_root=r;if(!e._definition.args||!t.length)return e;return e._definition.args(e,...t)}a(Ih,\"generate\");function hv(r,e){if(typeof r.type===\"string\")return[r];const t=[];for(const s of e._types){if(r.type.test(s)){const n=Object.assign({},r);n.type=s;n.base=e[s].call(e);t.push(n)}}return t}a(hv,\"expandExtension\");var pv=fv();var b=pv;var Jn=a(r=>typeof r===\"bigint\",\"isBigint\");var mv=a(r=>({type:\"bigint\",messages:{\"bigint.base\":\"{{#label}} must be a bigint\",\"bigint.greater\":\"{{#label}} must be greater than {{#limit}}\",\"bigint.less\":\"{{#label}} must be less than {{#limit}}\",\"bigint.max\":\"{{#label}} must be less than or equal to {{#limit}}\",\"bigint.min\":\"{{#label}} must be greater than or equal to {{#limit}}\",\"bigint.multiple\":\"{{#label}} must be a multiple of {{#base}}\",\"bigint.negative\":\"{{#label}} must be a negative number\",\"bigint.port\":\"{{#label}} must be a valid port\",\"bigint.positive\":\"{{#label}} must be a positive number\"},coerce(e){if(typeof e===\"string\"||typeof e===\"number\"&&Number.isInteger(e)){try{return{value:BigInt(e)}}catch{}}return{value:e}},validate(e,t){if(!Jn(e))return{value:e,errors:t.error(\"bigint.base\")}},rules:{greater:{method(e){return this.$_addRule({name:\"greater\",args:{limit:e}})},validate(e,t,{limit:s}){return e>s?e:t.error(\"bigint.greater\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},less:{method(e){return this.$_addRule({name:\"less\",args:{limit:e}})},validate(e,t,{limit:s}){return e<s?e:t.error(\"bigint.less\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},max:{method(e){return this.$_addRule({name:\"max\",args:{limit:e}})},validate(e,t,{limit:s}){return e<=s?e:t.error(\"bigint.max\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},min:{method(e){return this.$_addRule({name:\"min\",args:{limit:e}})},validate(e,t,{limit:s}){return e>=s?e:t.error(\"bigint.min\",{limit:s.toString()})},args:[{name:\"limit\",ref:true,assert:Jn,message:\"must be a bigint\"}]},multiple:{method(e){return this.$_addRule({name:\"multiple\",args:{base:e}})},validate(e,t,{base:s}){return e%s===0n?e:t.error(\"bigint.multiple\",{base:s.toString()})},args:[{name:\"base\",ref:true,assert:a(e=>Jn(e)&&e>0n,\"assert\"),message:\"must be a positive bigint\"}],multi:true},negative:{method(){return this.$_addRule({name:\"negative\"})},validate(e,t){return e<0n?e:t.error(\"bigint.negative\")}},port:{method(){return this.$_addRule({name:\"port\"})},validate(e,t){return e>=0n&&e<=65535n?e:t.error(\"bigint.port\")}},positive:{method(){return this.$_addRule({name:\"positive\"})},validate(e,t){return e>0n?e:t.error(\"bigint.positive\")}},sign:{method(e){return this.$_addRule({name:\"sign\",args:{sign:e}})},validate(e,t,{sign:s}){return s===\"negative\"&&e<0n||s===\"positive\"&&e>0n?e:t.error(`bigint.${s}`)},args:[{name:\"sign\",assert:a(e=>[\"negative\",\"positive\"].includes(e),\"assert\"),message:'must be \"negative\" or \"positive\"'}]}}}),\"bigintExtension\");var Eb=a(r=>{return r.extend(mv)},\"extendBigInt\");var Tb=require(\"node:async_hooks\");var gv=new Tb.AsyncLocalStorage;function Oh(){return gv.getStore()}a(Oh,\"currentValidationLanguage\");var ur=class extends Z{static{a(this,\"InvalidValueException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_VALUE\";this.statusCode=400}};function hs(r,e){r.cause=e;return r}a(hs,\"withCause\");var Wo=Object.freeze({abortEarly:true,cache:false,allowUnknown:true,stripUnknown:true,convert:true});var xb={next:new Map};var kh=0;var yv=1e3;function Ph(r){if(Object.getOwnPropertySymbols(r).length)return{...Wo,...r};let e=xb;for(const t of Object.keys(r)){const s=r[t];if(s!==null&&typeof s===\"object\"||typeof s===\"function\"||Object.is(s,-0))return{...Wo,...r};let n=e.next.get(t);if(!n){n=new Map;e.next.set(t,n)}let i=n.get(s);if(!i){i={next:new Map};n.set(s,i)}e=i}if(!e.merged){if(kh>=yv){xb={next:new Map};kh=0}e.merged=Object.freeze({...Wo,...r});kh++}return e.merged}a(Ph,\"mergeOptions\");var Rb=new WeakMap;function _b(r,e){if(!b.isSchema(r))return b.object({[e]:r});let t=Rb.get(r);if(!t){t=new Map;Rb.set(r,t)}let s=t.get(e);if(!s){s=b.object({[e]:r});t.set(e,s)}return s}a(_b,\"targetSchema\");var Nh=class{static{a(this,\"ValidateMethods\")}isSchema(e){return b.isSchema(e)}isValid(e,t,s={}){try{this.validate(e,t,s);return true}catch(n){return false}}async isValidAsync(e,t,s={}){try{await this.validateAsync(e,t,s);return true}catch(n){return false}}validate(e,t,s={}){try{return this.validateIn(e,t,s)}catch(n){const i=Cb(s);if(!i)throw n;return this.validateIn(e,t,{...s,errors:{...v(s).errors,language:i}})}}validateIn(e,t,s){s=Ph(s);let n;let i;if(s.targetName){const o=_b(t,s.targetName).validate({[s.targetName]:e},v(s));n=o.error;i=v(o.value)[s.targetName]}else{const o=v(t).validate(e,v(s));n=o.error;i=v(o.value)}if(n)throw hs(new ur(n.message),n);return i}async validateAsync(e,t,s={}){try{return await this.validateAsyncIn(e,t,s)}catch(n){const i=Cb(s);if(!i)throw n;return await this.validateAsyncIn(e,t,{...s,errors:{...v(s).errors,language:i}})}}async validateAsyncIn(e,t,s){s=Ph(s);try{if(s.targetName){const n=v(await _b(t,s.targetName).validateAsync({[s.targetName]:e},v(Ph({...s,artifacts:false}))));return n[s.targetName]}else{return v(await v(t).validateAsync(e,v(s)))}}catch(n){throw hs(new ur(n.message),n)}}};function Cb(r){const e=Oh();return e&&!v(r).errors?.language?e:void 0}a(Cb,\"inLanguage\");var Ce=v(Eb(b));var $s=new Nh;var bv={\"{\":\"}\",\"(\":\")\",\"[\":\"]\"};function Sv(r){if(typeof r!==\"string\"||r===\"\")return false;let e;while(e=/(\\\\).|([@?!+*]\\(.*\\))/g.exec(r)){if(e[2])return true;r=r.slice(e.index+e[0].length)}return false}a(Sv,\"isExtglob\");function wv(r){if(r[0]===\"!\")return true;let e=0;let t=-2;let s=-2;let n=-2;let i=-2;let o=-2;while(e<r.length){if(r[e]===\"*\")return true;if(r[e+1]===\"?\"&&/[\\].+)]/.test(r[e]))return true;if(s!==-1&&r[e]===\"[\"&&r[e+1]!==\"]\"){if(s<e)s=r.indexOf(\"]\",e);if(s>e){if(o===-1||o>s)return true;o=r.indexOf(\"\\\\\",e);if(o===-1||o>s)return true}}if(n!==-1&&r[e]===\"{\"&&r[e+1]!==\"}\"){n=r.indexOf(\"}\",e);if(n>e){o=r.indexOf(\"\\\\\",e);if(o===-1||o>n)return true}}if(i!==-1&&r[e]===\"(\"&&r[e+1]===\"?\"&&/[:!=]/.test(r[e+2])&&r[e+3]!==\")\"){i=r.indexOf(\")\",e);if(i>e){o=r.indexOf(\"\\\\\",e);if(o===-1||o>i)return true}}if(t!==-1&&r[e]===\"(\"&&r[e+1]!==\"|\"){if(t<e)t=r.indexOf(\"|\",e);if(t!==-1&&r[t+1]!==\")\"){i=r.indexOf(\")\",t);if(i>t){o=r.indexOf(\"\\\\\",t);if(o===-1||o>i)return true}}}if(r[e]===\"\\\\\"){const c=r[e+1];e+=2;const l=bv[c];if(l){const u=r.indexOf(l,e);if(u!==-1)e=u+1}if(r[e]===\"!\")return true}else{e++}}return false}a(wv,\"strictCheck\");function vb(r){if(typeof r!==\"string\"||r===\"\")return false;if(Sv(r))return true;if(r.replace(/\\\\./g,\"\").includes(\"?\"))return true;return wv(r)}a(vb,\"isGlobString\");var Ev=[\"a\",\"abbr\",\"address\",\"area\",\"article\",\"aside\",\"audio\",\"b\",\"base\",\"bdi\",\"bdo\",\"blockquote\",\"body\",\"br\",\"button\",\"canvas\",\"caption\",\"cite\",\"code\",\"col\",\"colgroup\",\"data\",\"datalist\",\"dd\",\"del\",\"details\",\"dfn\",\"dialog\",\"div\",\"dl\",\"dt\",\"em\",\"embed\",\"fieldset\",\"figcaption\",\"figure\",\"footer\",\"form\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"head\",\"header\",\"hgroup\",\"hr\",\"html\",\"i\",\"iframe\",\"img\",\"input\",\"ins\",\"kbd\",\"label\",\"legend\",\"li\",\"link\",\"main\",\"map\",\"mark\",\"math\",\"menu\",\"meta\",\"meter\",\"nav\",\"noscript\",\"object\",\"ol\",\"optgroup\",\"option\",\"output\",\"p\",\"picture\",\"pre\",\"progress\",\"q\",\"rp\",\"rt\",\"ruby\",\"s\",\"samp\",\"script\",\"search\",\"section\",\"select\",\"selectedcontent\",\"slot\",\"small\",\"source\",\"span\",\"strong\",\"style\",\"sub\",\"summary\",\"sup\",\"svg\",\"table\",\"tbody\",\"td\",\"template\",\"textarea\",\"tfoot\",\"th\",\"thead\",\"time\",\"title\",\"tr\",\"track\",\"u\",\"ul\",\"var\",\"video\",\"wbr\"];var Tv=/\\s?<!doctype html>|(<html\\b[^>]*>|<body\\b[^>]*>|<x-[^>]+>)+/i;var xv=new RegExp(Ev.map(r=>`<${r}\\\\b[^>]*>`).join(\"|\"),\"i\");function Ab(r){if(typeof r!==\"string\")return false;const e=r.trim().slice(0,1e3);return Tv.test(e)||xv.test(e)}a(Ab,\"isHTML\");var Pb=\":A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";var Rv=Pb+\"\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";var _v=new RegExp(\"^[\"+Pb+\"][\"+Rv+\"]*$\");var Lh=/(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])([\\s\\S]*?)\\5)?/g;var Fs=-1;function Mh(r){return r===\" \"||r===\"\t\"||r===\"\\n\"||r===\"\\r\"}a(Mh,\"isWhiteSpace\");function Nb(r){return _v.test(r)}a(Nb,\"isName\");function Ib(r,e){const t=e;for(;e<r.length;e++){if(r[e]===\"?\"||r[e]===\" \"){const s=r.substring(t,e);if(e>5&&s===\"xml\")return Fs;if(r[e]===\"?\"&&r[e+1]===\">\"){e++;break}}}return e}a(Ib,\"readProcessingInstruction\");function Ob(r,e){if(r.length>e+5&&r[e+1]===\"-\"&&r[e+2]===\"-\"){for(e+=3;e<r.length;e++){if(r[e]===\"-\"&&r[e+1]===\"-\"&&r[e+2]===\">\"){e+=2;break}}}else if(r.length>e+8&&r.startsWith(\"DOCTYPE\",e+1)){let t=1;for(e+=8;e<r.length;e++){if(r[e]===\"<\"){t++}else if(r[e]===\">\"){t--;if(t===0)break}}}else if(r.length>e+9&&r.startsWith(\"[CDATA[\",e+1)){for(e+=8;e<r.length;e++){if(r[e]===\"]\"&&r[e+1]===\"]\"&&r[e+2]===\">\"){e+=2;break}}}return e}a(Ob,\"readCommentAndCDATA\");function Cv(r,e){const t=e;let s=\"\";let n=false;for(;e<r.length;e++){const i=r[e];if(i==='\"'||i===\"'\"){if(s===\"\"){s=i}else if(s===i){s=\"\"}}else if(i===\">\"&&s===\"\"){n=true;break}}if(s!==\"\")return void 0;return{value:r.substring(t,e),index:e,tagClosed:n}}a(Cv,\"readAttributes\");function kb(r){const e=new Set;Lh.lastIndex=0;for(let t=Lh.exec(r);t;t=Lh.exec(r)){if(t[1].length===0||t[3]!==void 0&&t[4]===void 0)return false;if(!Nb(t[2])||e.has(t[2]))return false;e.add(t[2])}return true}a(kb,\"validateAttributes\");function vv(r,e){let t=/\\d/;if(r[e]===\"x\"){e++;t=/[\\da-fA-F]/}for(;e<r.length;e++){if(r[e]===\";\")return e;if(!t.test(r[e]))break}return Fs}a(vv,\"readNumericReference\");function Av(r,e){e++;if(r[e]===\";\")return Fs;if(r[e]===\"#\")return vv(r,e+1);for(let t=0;e<r.length;e++,t++){if(/\\w/.test(r[e])&&t<20)continue;if(r[e]===\";\")break;return Fs}return e}a(Av,\"readReference\");function Lb(r){const e=[];let t=false;let s=false;if(r[0]===\"\\uFEFF\")r=r.substring(1);for(let n=0;n<r.length;n++){if(r[n]===\"<\"&&r[n+1]===\"?\"){n=Ib(r,n+2);if(n===Fs)return false}else if(r[n]===\"<\"){n++;if(r[n]===\"!\"){n=Ob(r,n);continue}let i=false;if(r[n]===\"/\"){i=true;n++}const o=n;while(n<r.length&&r[n]!==\">\"&&!Mh(r[n]))n++;let c=r.substring(o,n).trim();if(c[c.length-1]===\"/\"){c=c.substring(0,c.length-1);n--}if(!Nb(c))return false;const l=Cv(r,n);if(!l)return false;let u=l.value;n=l.index;if(u[u.length-1]===\"/\"){u=u.substring(0,u.length-1);if(!kb(u))return false;if(s)return false;if(e.length===0)s=true;t=true}else if(i){if(!l.tagClosed||u.trim().length>0||e.length===0)return false;if(e.pop()!==c)return false;if(e.length===0)s=true}else{if(!kb(u))return false;if(s)return false;e.push(c);t=true}for(n++;n<r.length;n++){if(r[n]===\"<\"){if(r[n+1]===\"!\"){n=Ob(r,n+1);continue}else if(r[n+1]===\"?\"){n=Ib(r,n+2);if(n===Fs)return false}else{break}}else if(r[n]===\"&\"){n=Av(r,n);if(n===Fs)return false}else if(s&&!Mh(r[n])){return false}}if(r[n]===\"<\")n--}else if(!Mh(r[n])){return false}}return t&&e.length===0}a(Lb,\"validateXML\");function Mb(r){return typeof r===\"string\"&&Lb(r)}a(Mb,\"isXML\");var Iv={alias:false,seconds:false,allowBlankDay:false,allowSevenAsSunday:false,allowNthWeekdayOfMonth:false};var Ov={jan:\"1\",feb:\"2\",mar:\"3\",apr:\"4\",may:\"5\",jun:\"6\",jul:\"7\",aug:\"8\",sep:\"9\",oct:\"10\",nov:\"11\",dec:\"12\"};var kv={sun:\"0\",mon:\"1\",tue:\"2\",wed:\"3\",thu:\"4\",fri:\"5\",sat:\"6\"};function Xo(r){return/^\\d+$/.test(r)?Number(r):NaN}a(Xo,\"safeParseInt\");function Vo(r,e,t){return r>=e&&r<=t}a(Vo,\"isInRange\");function Pv(r,e,t){const s=r.split(\"-\");switch(s.length){case 1:return r===\"*\"||Vo(Xo(r),e,t);case 2:{const[n,i]=s.map(Xo);return n<=i&&Vo(n,e,t)&&Vo(i,e,t)}default:return false}}a(Pv,\"isValidRange\");function Nv(r){return r===void 0||r.search(/[^\\d]/)===-1&&Xo(r)>0}a(Nv,\"isValidStep\");function Zn(r,e,t){if(r.search(/[^\\d-,\\/*]/)!==-1)return false;return r.split(\",\").every(s=>{const n=s.split(\"/\");if(s.trim().endsWith(\"/\")||n.length>2)return false;return Pv(n[0],e,t)&&Nv(n[1])})}a(Zn,\"validateForRange\");function Db(r,e){return r.toLowerCase().replace(/[a-z]{3}/g,t=>e[t]??t)}a(Db,\"unalias\");function Lv(r,e){return e&&r===\"?\"||Zn(r,1,31)}a(Lv,\"hasValidDays\");function Mv(r,e){if(r.search(/\\/[a-zA-Z]/)!==-1)return false;return Zn(e?Db(r,Ov):r,1,12)}a(Mv,\"hasValidMonths\");function Dv(r,e){if(r===\"?\")return e.allowBlankDay;if(r.search(/\\/[a-zA-Z]/)!==-1)return false;const t=e.alias?Db(r,kv):r;const s=e.allowSevenAsSunday?7:6;const n=t.split(\"#\");if(e.allowNthWeekdayOfMonth&&n.length>=2){const[i,o,...c]=n;if(c.length)return false;return Vo(Xo(o),1,5)&&Vo(Xo(i),0,s)}return Zn(t,0,s)}a(Dv,\"hasValidWeekdays\");function Bb(r,e){const t={...Iv,...e};const s=r.trim().split(/\\s+/);if(s.length>(t.seconds?6:5)||s.length<5)return false;const n=[];if(s.length===6){const f=s.shift();if(f)n.push(Zn(f,0,59))}const[i,o,c,l,u]=s;n.push(Zn(i,0,59));n.push(Zn(o,0,23));n.push(Lv(c,t.allowBlankDay));n.push(Mv(l,t.alias));n.push(Dv(u,t));n.push(!(t.allowBlankDay&&c===\"?\"&&u===\"?\"));return n.every(Boolean)}a(Bb,\"isValidCron\");var Hs=class{static{a(this,\"DataValidator\")}static Build(e){return Ce.build(e)}static Any(){return Ce.any().strict(true)}static String(){return Ce.string().strict(true)}static Number(){return Ce.number().strict(true)}static BigInt(){return Ce.bigint().strict(true)}static Boolean(){return Ce.boolean().strict(true)}static Date(){return Ce.date().strict(true)}static Object(e){return Ce.object(e).strict(true)}static Array(...e){return Ce.array().items(...e).strict(true)}static Binary(){return Ce.binary().strict(true)}static Function(){return Ce.func().strict(true)}static AsyncFunction(){return this.Function().custom(Us((e,t)=>{if((0,Ub.isAsyncFunction)(e))return e;return t.error(\"asyncFunc.invalid\")}),\"Async Function Validation\").error(e=>{for(const t of e){if(t.code===\"asyncFunc.invalid\"){t.message=\"Expected AsyncFunction but got Function\";return t}}return e[0]})}static Class(e){if(!e)return Ce.func().class();return this.Function().class().custom(Us((t,s)=>{if(!v(e).prototype)e=v(e)();if(t instanceof v(e)||t[\"prototype\"]instanceof v(e))return t;return s.error(\"any.invalid\")}),\"Class Validation\")}static InstanceOf(e){return this.Any().custom(Us((t,s)=>{if(t instanceof v(e)||t[\"prototype\"]instanceof v(e))return t;return s.error(\"any.invalid\")}),\"Class Instance Validation\")}static Glob(){return this.String().custom(Us((e,t)=>{if(typeof e===\"string\"&&vb(e))return e;return t.error(\"any.invalid\")}),\"Glob Validation\")}static Cron(e){const t={...e,alias:e?.alias!==void 0?e.alias:false,seconds:e?.seconds!==void 0?e.seconds:true,allowBlankDay:e?.allowBlankDay!==void 0?e.allowBlankDay:true,allowSevenAsSunday:e?.allowSevenAsSunday!==void 0?e.allowSevenAsSunday:true};return this.String().custom(Us((s,n)=>{if(typeof s===\"string\"&&Bb(s,t))return s;return n.error(\"any.invalid\")}),\"Cron Validation\")}static HttpDocument(){return this.String().custom(Us((e,t)=>{if(typeof e===\"string\"&&(Ab(e)||Mb(e)))return e;return t.error(\"any.invalid\")}),\"HttpDocument Validation\")}static Symbol(){return Ce.symbol().strict(true)}static Alternatives(...e){return Ce.alternatives(...e).strict(true)}static Ref(e,t){return Ce.ref(e,t)}static In(e,t){return Ce.in(e,t)}static Attempt(e,t,s){return Ce.attempt(e,t,s)}static Link(e){return Ce.link(e)}};var RB=Ye(Bn(),1);var Dh=Symbol(\"LAKUTATA.DTO.CONSTRUCTOR\");var Qn=Symbol(\"LAKUTATA.DTO.INDEX.SIGNATURE.SCHEMA\");var vr=Symbol(\"LAKUTATA.DTO.PROPERTY.SCHEMAS\");var Bh=Symbol(\"LAKUTATA.DTO.OBJECT.REFINEMENT\");function me(r){return v(r.constructor)}a(me,\"objectConstructor\");function Uh(r){const e=Symbol.constructor.prototype.constructor.__proto__;const t=!!r[Symbol.hasInstance]&&r.prototype?r:r.constructor;const s=t.prototype.constructor.__proto__;return s===e?null:s}a(Uh,\"objectParentConstructor\");function ps(r){const e=[];let t=Uh(r);while(t){e.push(t);t=Uh(t)}return e}a(ps,\"objectParentConstructors\");function jh(r){return r.prototype}a(jh,\"objectPrototype\");function bt(r){return typeof r===\"symbol\"}a(bt,\"isSymbol\");var $h=0;function ei(){$h++}a(ei,\"invalidateDTOSchemas\");function ti(r,e,t){const s=r.get(e);if(s&&s.revision===$h)return s.value;const n=t();r.set(e,{revision:$h,value:n});return n}a(ti,\"getCachedDTOSchema\");var Bv=new WeakMap;function jb(r){Reflect.defineMetadata(Dh,true,r);ei();return r}a(jb,\"defineObjectAsDTO\");function Fh(r){return!!Reflect.getMetadata(Dh,r)}a(Fh,\"isDTO\");function $b(r,e){Reflect.defineMetadata(Qn,e,r);ei();return r}a($b,\"setObjectIndexSignatureSchema\");function Hh(r){if(Reflect.hasOwnMetadata(Qn,me(r)))return Reflect.getOwnMetadata(Qn,me(r));for(const e of ps(me(r))){if(Reflect.hasOwnMetadata(Qn,e))return Reflect.getOwnMetadata(Qn,e)}return null}a(Hh,\"getObjectIndexSignatureSchemaByPrototype\");function Fb(r){return Hh(jh(r))}a(Fb,\"getObjectIndexSignatureSchemaByConstructor\");function Al(r,e,t){if(bt(e))return;if(!Fh(v(me(r))))return;e=v(e);let s;if(Reflect.hasOwnMetadata(vr,me(r))){s=Reflect.getOwnMetadata(vr,me(r))}else{s=new Map;const n=[];ps(me(r)).forEach(i=>{if(Reflect.hasOwnMetadata(vr,i))n.unshift(Reflect.getOwnMetadata(vr,i))});n.forEach(i=>i.forEach((o,c)=>s.set(v(c),o)))}s.set(e,t);Reflect.defineMetadata(vr,s,me(r));ei()}a(Al,\"setObjectPropertySchema\");function Uv(r){const e=new Map;const t=[];ps(me(r)).forEach(s=>{if(Reflect.hasOwnMetadata(vr,s))t.unshift(Reflect.getOwnMetadata(vr,s))});t.forEach(s=>s.forEach((n,i)=>e.set(v(i),n)));v(Reflect.getOwnMetadata(vr,me(r)))?.forEach((s,n)=>e.set(v(n),s));return e}a(Uv,\"getObjectPropertySchemas\");function qh(r){return ti(Bv,me(r),()=>{const e={};Uv(r).forEach((s,n)=>{e[n]=s});const t=Reflect.getMetadata(Bh,me(r));return t?t(Hs.Object(e)):Hs.Object(e)})}a(qh,\"getObjectSchemaByPrototype\");function Hb(r){return qh(jh(r))}a(Hb,\"getObjectSchemaByConstructor\");function qb(r,e){Reflect.defineMetadata(Bh,e,r);ei();return r}a(qb,\"setObjectSchemaRefinement\");var Ue=class extends rs{static{a(this,\"SchemaConversionException\")}constructor(){super(...arguments);this.errno=\"E_SCHEMA_CONVERSION\"}};function zb(r,e,t){e=e||1;t=t<r.length?t:r.length;const s=a((i,o,c,l)=>{if(i==0){if(c.length>0)l[l.length]=c;return}for(let u=0;u<o.length;u++)s(i-1,o.slice(u+1),c.concat([o[u]]),l)},\"fn\");const n=[];for(let i=e;i<r.length;i++)s(i,r,[],n);if(r.length==t)n.push(r);return n}a(zb,\"combinations\");var jv=new Set([\"[object Float32Array]\",\"[object Float64Array]\",\"[object Int8Array]\",\"[object Int16Array]\",\"[object Int32Array]\",\"[object Uint8Array]\",\"[object Uint8ClampedArray]\",\"[object Uint16Array]\",\"[object Uint32Array]\"]);var $v=Function.prototype.toString.call(Object);function Kh(r){return Object.prototype.toString.call(r)}a(Kh,\"tagOf\");function Yo(r){return r!==null&&(typeof r===\"object\"||typeof r===\"function\")}a(Yo,\"isObject\");function Il(r){return r!==null&&typeof r===\"object\"}a(Il,\"isObjectLike\");function Fv(r){return typeof r===\"number\"&&r>-1&&r%1===0&&r<=Number.MAX_SAFE_INTEGER}a(Fv,\"isLength\");function ri(r){return r!==null&&r!==void 0&&typeof r!==\"function\"&&Fv(r.length)}a(ri,\"isArrayLike\");function zh(r){return Il(r)&&Kh(r)===\"[object Arguments]\"}a(zh,\"isArguments\");function Wh(r){return Il(r)&&jv.has(Kh(r))}a(Wh,\"isTypedArray\");function Hv(r){if(!Il(r)||Kh(r)!==\"[object Object]\")return false;const e=Object.getPrototypeOf(r);if(e===null)return true;const t=Object.prototype.hasOwnProperty.call(e,\"constructor\")&&e.constructor;return typeof t===\"function\"&&t instanceof t&&Function.prototype.toString.call(t)===$v}a(Hv,\"isPlainObject\");function Wb(r){return/^(?:0|[1-9]\\d*)$/.test(r)&&Number(r)<Number.MAX_SAFE_INTEGER}a(Wb,\"isIndex\");function Vb(r,e){return r===e||r!==r&&e!==e}a(Vb,\"eq\");function Xb(r){if(ri(r)){const e=[];for(let t=0;t<r.length;++t)e.push(String(t));return e}return Object.keys(r)}a(Xb,\"keysOf\");function He(r,e){if(r===null||r===void 0)return void 0;if(e in Object(r))return r[e];let t=r;for(const s of e.split(\".\")){if(t===null||t===void 0)return void 0;t=t[s]}return t}a(He,\"get\");function Yb(r,e,t){if(!Yo(r))return r;const s=e in r?[e]:e.split(\".\");let n=r;for(let i=0;i<s.length&&n!==null&&n!==void 0;++i){const o=s[i];if(o===\"__proto__\"||o===\"constructor\"||o===\"prototype\")return r;if(i===s.length-1){Gb(n,o,t);break}const c=n[o];Gb(n,o,Yo(c)?c:Wb(s[i+1])?[]:{});n=n[o]}return r}a(Yb,\"set\");function Gb(r,e,t){if(!Yo(r))return;const s=r[e];if(!(Object.prototype.hasOwnProperty.call(r,e)&&Vb(s,t))||t===void 0&&!(e in r))r[e]=t}a(Gb,\"assignValue\");function fr(r){if(r===null||r===void 0)return true;if(ri(r)&&(Array.isArray(r)||typeof r===\"string\"||typeof r.splice===\"function\"||Buffer.isBuffer(r)||Wh(r)||zh(r)))return!r.length;if(r instanceof Map||r instanceof Set)return!r.size;for(const e in r){if(Object.prototype.hasOwnProperty.call(r,e))return false}return true}a(fr,\"isEmpty\");function Kt(r,e){if(r===null||r===void 0)return[];if(Array.isArray(r)){const s=new Array(r.length);for(let n=0;n<r.length;++n)s[n]=e(r[n],n);return s}const t=Object(r);return Xb(t).map(s=>e(t[s],ri(r)?Number(s):s))}a(Kt,\"map\");function It(r,e){if(r===null||r===void 0)return;const t=Object(r);const s=ri(r);for(const n of Xb(t)){if(e(t[n],s?Number(n):n)===false)return}}a(It,\"each\");function Vh(r){return r&&r.length?[...new Set(r)]:[]}a(Vh,\"uniq\");function Ol(r,e){const t=[];if(!(r&&r.length))return t;const s=[];for(let n=0;n<r.length;++n){const i=r[n];if(e(i,n,r)){t.push(i);s.push(n)}}for(let n=s.length-1;n>=0;--n)r.splice(s[n],1);return t}a(Ol,\"remove\");function Jb(r){const e=[];if(!r)return e;for(const t of r){if(t)e.push(t)}return e}a(Jb,\"compact\");function ms(r,e){if(!r)return false;for(const t of r){if(e(t))return true}return false}a(ms,\"some\");function Zb(r,e){const t={};if(r===null||r===void 0)return t;const s=r;for(const n in s){if(n!==\"__proto__\"&&e(s[n],n))t[n]=s[n]}return t}a(Zb,\"pickBy\");function St(r,...e){for(const t of e){if(t)Qb(r,t,new Map)}return r}a(St,\"merge\");function qv(r){const e=[];if(ri(r)){const t=Buffer.isBuffer(r);const s=!t&&Wh(r);for(let n=0;n<r.length;++n)e.push(String(n));for(const n in r){if(Wb(n)||n===\"length\")continue;if(t&&(n===\"offset\"||n===\"parent\"))continue;if(s&&(n===\"buffer\"||n===\"byteLength\"||n===\"byteOffset\"))continue;e.push(n)}return e}for(const t in r)e.push(t);return e}a(qv,\"keysIn\");function Kb(r,e){if(e===\"constructor\"&&typeof r[e]===\"function\")return void 0;if(e===\"__proto__\")return void 0;return r[e]}a(Kb,\"safeGet\");function Gh(r,e,t){if(t!==void 0&&!Vb(r[e],t)||t===void 0&&!(e in r)){if(e===\"__proto__\"){Object.defineProperty(r,e,{configurable:true,enumerable:true,value:t,writable:true})}else{r[e]=t}}}a(Gh,\"assignMergeValue\");function Qb(r,e,t){if(r===e)return;for(const s of qv(e)){const n=e[s];if(Yo(n)){zv(r,e,s,t)}else{Gh(r,s,n)}}}a(Qb,\"baseMerge\");function zv(r,e,t,s){const n=Kb(r,t);const i=Kb(e,t);const o=s.get(i);if(o){Gh(r,t,o);return}let c=true;let l=i;const u=Array.isArray(i);const f=!u&&Buffer.isBuffer(i);const d=!u&&!f&&Wh(i);if(u||f||d){if(Array.isArray(n)){l=n}else if(Il(n)&&ri(n)){l=Array.from(n)}else if(f){c=false;l=i.subarray()}else if(d){c=false;const h=i;const p=h.constructor;l=new p(h.buffer.slice(0),h.byteOffset,h.length)}else{l=[]}}else if(Hv(i)||zh(i)){l=n;if(zh(n)){l=Object.assign({},n)}else if(!Yo(n)||typeof n===\"function\"){l=typeof i.constructor===\"function\"?Object.create(Object.getPrototypeOf(i)):{}}}else{c=false}if(c){s.set(i,l);Qb(l,i,s);s.delete(i)}Gh(r,t,l)}a(zv,\"baseMergeDeep\");var Gv={or:a(function(r,e){r.anyOf=Kt(e.peers,t=>{return{required:[t]}})},\"or\"),and:a(function(r,e){r.oneOf=[{required:e.peers}];r.oneOf.push({allOf:Kt(e.peers,t=>{return{not:{required:[t]}}})})},\"and\"),nand:a(function(r,e){r.not={required:e.peers}},\"nand\"),xor:a(function(r,e){r.if={propertyNames:{enum:e.peers},minProperties:2};r.then=false;r.else={oneOf:Kt(e.peers,t=>{return{required:[t]}})}},\"xor\"),oxor:a(function(r,e){r.oneOf=Kt(e.peers,t=>{return{required:[t]}});r.oneOf.push({not:{oneOf:Kt(zb(e.peers,1,2),t=>{return{required:t}})}})},\"oxor\"),with:a(function(r,e){r.dependencies=r.dependencies||{};r.dependencies[e.key]=e.peers},\"with\"),without:a(function(r,e){r.if={required:[e.key]};r.then={not:{anyOf:Kt(e.peers,t=>{return{required:[t]}})}}},\"without\")};var Kv=[\"integer\",\"port\",...Object.keys(At)];var Wv={any:[\"allOf\"],alternatives:[\"allOf\"],boolean:[\"allOf\"],number:[\"allOf\",\"min\",\"max\",\"greater\",\"less\",\"multiple\",\"sign\",\"port\",\"float\",\"double\",\"integer\",...Object.keys(At)],bigint:[\"allOf\",\"min\",\"max\",\"greater\",\"less\",\"multiple\",\"negative\",\"positive\"],string:[\"allOf\",\"min\",\"max\",\"length\",\"format\",\"email\",\"hostname\",\"uri\",\"ip\",\"pattern\",\"alphanum\",\"token\",\"hex\",\"trim\",\"isoDate\",\"isoDuration\",\"guid\",\"uuid\"],object:[\"allOf\",\"min\",\"max\",\"length\",\"keyNames\"],array:[\"allOf\",\"min\",\"max\",\"length\",\"unique\",\"has\",\"items\",\"ordered\"]};var eS=[\"function\",\"symbol\"];var kl=[\"title\",\"description\",\"default\",\"examples\",\"example\",\"deprecated\",\"readOnly\",\"writeOnly\",\"$comment\"];var tS=[\"if\",\"then\",\"else\"];function Vv(r){return typeof r===\"object\"&&r!==null&&Object.keys(r).length===1&&r.override===true}a(Vv,\"isOverride\");function Ll(r){if(r===null||typeof r===\"string\"||typeof r===\"boolean\")return true;if(typeof r===\"number\")return isFinite(r);if(Array.isArray(r))return r.every(Ll);if(typeof r===\"object\"&&Object.getPrototypeOf(r)===Object.prototype)return Object.values(r).every(Ll);return false}a(Ll,\"isJsonValue\");function rS(r){const e=[];for(const t of r||[]){if(Vv(t))continue;if(t!==null&&typeof t===\"object\"){const s=Object.keys(t);if(s.length===1&&s[0]===\"value\"){e.push(t.value);continue}return null}e.push(t)}return e}a(rS,\"literals\");function Nl(r){if(typeof r===\"number\"&&isFinite(r))return r;if(typeof r===\"bigint\"&&r<=BigInt(Number.MAX_SAFE_INTEGER)&&r>=BigInt(Number.MIN_SAFE_INTEGER))return Number(r);return void 0}a(Nl,\"numberLimit\");function Xv(r,e,t,s){const n=Nl(e);if(n===void 0)return r;if(!r||(s?n>r.value:n<r.value))return{value:n,exclusive:t};if(n===r.value&&t)return{value:n,exclusive:t};return r}a(Xv,\"tighter\");function Pl(r){if(typeof r!==\"string\")return null;const e=/^\\/([\\s\\S]*)\\/([a-z]*)$/.exec(r);if(!e)return null;const[,t,s]=e;if(/[imsgyv]/.test(s))return null;try{new RegExp(t,\"u\")}catch{return null}return{source:t,flags:s}}a(Pl,\"toPattern\");function Yv(r){const e=r.map(t=>Array.from(t).map(s=>{const n=s.toLowerCase();const i=s.toUpperCase();if(n===i||Array.from(n).length!==1||Array.from(i).length!==1)return mt(s);return`[${mt(n)}${mt(i)}]`}).join(\"\"));return`^(?:${e.join(\"|\")})$`}a(Yv,\"insensitivePattern\");var Ar=class{static{a(this,\"JsonSchemaParser\")}constructor(e={}){this._exact=true;this._inexactSchemas=new WeakSet;const t=e;this.$schema=t.$schema||\"http://json-schema.org/draft-07/schema#\";this.includeSchemaDialect=t.includeSchemaDialect||false;this.childrenFieldName=this._getChildrenFieldName();this.optionsFieldName=this._getOptionsFieldName();this.ruleArgFieldName=this._getRuleArgFieldName();this.enumFieldName=this._getEnumFieldName();this.allowUnknownFlagName=this._getAllowUnknownFlagName();this.inheritedPreferences=t.preferences?[t.preferences]:[];if(t.logicalOpParser===false){this.logicalOpParser={}}else{this.logicalOpParser=St({},Gv,t.logicalOpParser)}}parse(e,t={},s=0){const n=this._exact;this._exact=true;const i=this._parse(e,t,s);if(!this._exact)this._inexactSchemas.add(i);this._exact=n&&this._exact;return i}isExact(e){return!this._inexactSchemas.has(e)}_inexact(){this._exact=false}_parse(e,t,s){let n={};const i=this._pushInheritiedPreferences(e);if(this._getPresence(e)===\"forbidden\"){if(i)this._popInheritiedPreferences();n.not={};return n}this._checkRules(e);this._setBasicProperties(n,e);this._setNumberFieldProperties(n,e);this._setBinaryFieldProperties(n,e);this._setStringFieldProperties(n,e);this._setDateFieldProperties(n,e);this._setArrayFieldProperties(n,e,t,s);this._setObjectProperties(n,e,t,s);this._setAlternativesProperties(n,e,t,s);this._setConditionProperties(n,e,t,s,\"whens\");this._setAllOf(n,e,t,s);this._setMetaProperties(n,e);this._setLinkFieldProperties(n,e);this._setAnyProperties(n);this._setNonJsonProperties(n,e);n=this._setSingle(n,e);n=this._setValues(n,e);if(!fr(e.shared)){It(e.shared,c=>{this.parse(c,t,s)})}this._copyMetasToSchema(e,n);n=this._retainKnownKeys(n);const o=He(e,\"flags.id\");if(o){t[o]=n;n={$ref:`${this._getLocalSchemaBasePath()}/${o}`}}if(s===0&&!fr(t))Yb(n,`${this._getLocalSchemaBasePath().replace(\"#/\",\"\").replace(/\\//,\".\")}`,t);if(this.includeSchemaDialect&&s===0&&this.$schema)n.$schema=this.$schema;if(i)this._popInheritiedPreferences();return n}_retainKnownKeys(e){if(!this.knownKeys)return e;const t=this.knownKeys;const s=Zb(e,(n,i)=>t.includes(i)||this._isKnownMetaKey(i));if(Object.keys(e).some(n=>!(n in s)&&!kl.includes(n)))this._inexact();return s}_checkRules(e){const t=Wv[e.type];if(!t){if(![\"any\",\"alternatives\",\"link\",\"function\",\"symbol\"].includes(e.type))this._inexact();if(e.type===\"link\"&&He(e,\"link.ref.type\")!==\"local\")this._inexact()}for(const n of e.rules||[]){if(!t||!t.includes(n.name))this._inexact()}const s=e.flags||{};if(s.empty!==void 0||s.single)this._inexact();if(e.renames||e.externals)this._inexact()}_pushInheritiedPreferences(e){if(e.preferences){this.inheritedPreferences.push(St({},this._getInheritedPreferences(),e.preferences));return true}return false}_popInheritiedPreferences(){this.inheritedPreferences.pop()}_getInheritedPreferences(){return this.inheritedPreferences[this.inheritedPreferences.length-1]||{}}_getPreferences(e){const t=e[this.optionsFieldName];return t?{...this._getInheritedPreferences(),...t}:this._getInheritedPreferences()}_isIfThenElseSupported(){return true}_getChildrenFieldName(){return\"keys\"}_getOptionsFieldName(){return\"preferences\"}_getRuleArgFieldName(){return\"args\"}_getEnumFieldName(){return\"allow\"}_getAllowUnknownFlagName(){return\"unknown\"}_getLocalSchemaBasePath(){return\"#/$defs\"}_getFieldDescription(e){return He(e,\"flags.description\")}_getFieldType(e){const t=e.type;if(t===\"number\"&&ms(e.rules,s=>Kv.includes(s.name)))return\"integer\";if(t===\"bigint\")return\"integer\";if(eS.includes(t))return void 0;return t}_addNullTypeIfNullable(e,t){}_getFieldExample(e){const t=He(e,\"examples\");if(!Array.isArray(t))return t;const s=t.filter(Ll);return s.length?s:void 0}_getPresence(e){const t=He(e,\"flags.presence\");if(t!==void 0)return t;const s=this._getPreferences(e);return He(s,\"presence\")}_isRequired(e){const t=this._getPresence(e);return t===\"required\"}_getDefaultValue(e){const t=He(e,\"flags.default\");return Ll(t)&&!(t!==null&&typeof t===\"object\"&&He(t,\"special\")===\"deep\")?t:void 0}_getUnknown(e){const t=He(e,`flags.${this.allowUnknownFlagName}`);if(t!==void 0)return t;const s=this._getPreferences(e);if(s.allowUnknown)return true;const n=s.stripUnknown;return n===true||!!(n&&n.objects)}_stripsUnknown(e){if(He(e,`flags.${this.allowUnknownFlagName}`)!==void 0)return false;if(!e[this.childrenFieldName]&&!e.patterns)return false;const t=He(this._getPreferences(e),\"stripUnknown\");return t===true||!!(t&&t.objects)}_stripsArrayItems(e){const t=He(this._getPreferences(e),\"stripUnknown\");return!!(t&&typeof t===\"object\"&&t.arrays)}_setIfNotEmpty(e,t,s){if(s!==null&&s!==void 0)e[t]=s}_bound(e,t,s,n){if(Nl(t)===void 0)this._inexact();return Xv(e,t,s,n)}_addKeyword(e,t,s){if(e[t]===void 0){e[t]=s}else{e.allOf=e.allOf||[];e.allOf.push({[t]:s})}}_mergeKeywords(e,t){const s=Object.keys(t);if(!s.length)return;const n=s.some(i=>e[i]!==void 0)||s.some(i=>tS.includes(i))&&tS.some(i=>e[i]!==void 0);if(!n){Object.assign(e,t)}else if(s.length===1&&s[0]===\"allOf\"){e.allOf=[...e.allOf||[],...t.allOf]}else{e.allOf=e.allOf||[];e.allOf.push(t)}}_setBasicProperties(e,t){this._setIfNotEmpty(e,\"type\",this._getFieldType(t));this._setIfNotEmpty(e,\"examples\",this._getFieldExample(t));this._setIfNotEmpty(e,\"description\",this._getFieldDescription(t));this._setIfNotEmpty(e,\"default\",this._getDefaultValue(t))}_getValuesSchema(e){return e.length===1?{const:e[0]}:{enum:e}}_setValues(e,t){const s=t.flags||{};const n=rS(t[this.enumFieldName]);const i=rS(t.invalid);const o={};for(const f of Object.keys(e)){if(kl.includes(f)||f.startsWith(\"x-\"))o[f]=e[f]}if(!n||!i)this._inexact();if(s.only){if(!n||!n.length)return{...o};const f=Vh(n);const d=f.filter(h=>typeof h===\"string\");if(s.insensitive&&d.length){const h=f.filter(m=>typeof m!==\"string\");const p={type:\"string\",pattern:Yv(d)};if(!h.length)return{...o,...p};return{...o,anyOf:[p,this._getValuesSchema(h)]}}return{...o,...this._getValuesSchema(f)}}if(i&&i.length)this._addKeyword(e,\"not\",{enum:i});const c=!!n&&n.includes(\"\")||ms(t.rules,f=>f.name===\"min\"&&He(f,`${this.ruleArgFieldName}.limit`)===0);if(e.type===\"string\"&&t.type===\"string\"&&!c&&s.empty===void 0&&!this._rejectsEmpty(e))e.minLength=1;if(!n)return{...o};if(!n.length){this._addNullTypeIfNullable(e,t);return e}if(Object.keys(e).every(f=>o[f]!==void 0))return e;let l=Vh(n);if(e.type===\"string\"&&l.includes(\"\")&&this._acceptsEmpty(e))l=l.filter(f=>f!==\"\");if(l.includes(null)&&this._canAddType(e)){if(Array.isArray(e.type)){if(!e.type.includes(\"null\"))e.type=[...e.type,\"null\"]}else if(e.type!==\"null\"){e.type=[e.type,\"null\"]}l=l.filter(f=>f!==null)}this._addNullTypeIfNullable(e,t);if(!l.length)return e;const u={};for(const f of Object.keys(e)){if(o[f]===void 0)u[f]=e[f]}return{...o,anyOf:[u,this._getValuesSchema(l)]}}_setSingle(e,t){if(t.type!==\"array\"||!He(t,\"flags.single\"))return e;const s={};const n={};for(const c of Object.keys(e)){if(kl.includes(c)||c.startsWith(\"x-\")){s[c]=e[c]}else{n[c]=e[c]}}const i=e.prefixItems||e.items;const o=Array.isArray(i)?i.length?{anyOf:i}:{}:i||{};return{...s,anyOf:[n,o]}}_acceptsEmpty(e){for(const t of Object.keys(e)){if(kl.includes(t)||t.startsWith(\"x-\")||t===\"type\"||t===\"maxLength\"||t===\"contentEncoding\")continue;if(t===\"minLength\"&&e.minLength<1)continue;if(t===\"pattern\"&&new RegExp(e.pattern,\"u\").test(\"\"))continue;return false}return true}_rejectsEmpty(e){if(typeof e.minLength===\"number\"&&e.minLength>=1)return true;if(typeof e.pattern===\"string\"&&!new RegExp(e.pattern,\"u\").test(\"\"))return true;return typeof e.format===\"string\"&&[\"date\",\"time\",\"date-time\",\"duration\",\"email\",\"idn-email\",\"hostname\",\"ipv4\",\"ipv6\",\"uri\",\"uuid\"].includes(e.format)}_canAddType(e){if(!e.type)return false;return![\"enum\",\"const\",\"anyOf\",\"oneOf\",\"allOf\",\"not\",\"if\",\"$ref\"].some(t=>e[t]!==void 0)}_setBinaryFieldProperties(e,t){if(e.type!==\"binary\")return;e.type=\"string\";if(t.flags&&t.flags.encoding)e.contentEncoding=t.flags.encoding;this._setIfNotEmpty(e,\"format\",this._getBinaryFormat())}_getBinaryFormat(){return void 0}_setObjectProperties(e,t,s,n){if(e.type!==\"object\")return;const i=t[this.childrenFieldName];const o=this._getUnknown(t);if(!i&&!t.patterns){if(typeof o===\"object\")e.additionalProperties=this.parse(o,s,n+1)}else{const c={};const l=[];e.properties=c;Kt(i,(f,d)=>{const h=this.parse(f,s,n+1);if(this._isRequired(f))l.push(d);c[d]=h});if(l.length)e.required=l;const u=this._setPatternProperties(e,t,Object.keys(i||{}),s,n);if(!u||t.renames){this._inexact();e.additionalProperties=true}else if(typeof o===\"object\"){e.additionalProperties=this.parse(o,s,n+1)}else{e.additionalProperties=o}}It(t.rules,c=>{const l=c[this.ruleArgFieldName]||{};const u=Nl(l.limit);switch(c.name){case\"min\":case\"length\":if(u!==void 0&&!ms(Object.values(i||{}),f=>He(f,\"flags.default\")!==void 0)){this._addKeyword(e,\"minProperties\",u);if(this._stripsUnknown(t))this._inexact()}else{this._inexact()}if(c.name===\"min\")break;case\"max\":if(u!==void 0&&!this._stripsUnknown(t)){this._addKeyword(e,\"maxProperties\",u)}else{this._inexact()}break;case\"keyNames\":{const f=this.parse(l.schema,s,n+1);this._setPropertyNames(e,this._stripsUnknown(t)?{anyOf:[f,{not:this._knownKeys(t)}]}:f);break}default:break}});this._setObjectDependencies(e,t)}_setPropertyNames(e,t){this._addKeyword(e,\"propertyNames\",t)}_setPatternProperties(e,t,s,n,i){if(!t.patterns||!t.patterns.length)return true;const o={};const c=[];for(const l of t.patterns){if(typeof l.rule!==\"object\"||l.regex===void 0)return false;if(l.matches!==void 0)return false;const u=Pl(l.regex);if(!u)return false;const f=new RegExp(u.source,\"u\");const d=s.filter(m=>f.test(m));let h=u.source;if(d.length||c.length){if([u.source,...c].some(y=>/\\\\[1-9]|\\\\k</.test(y)))return false;const m=d.length?`(?!(?:${d.map(y=>mt(y)).join(\"|\")})$)`:\"\";h=`^${m}${c.map(y=>`(?![\\\\s\\\\S]*?(?:${y}))`).join(\"\")}[\\\\s\\\\S]*?(?:${u.source})`;try{new RegExp(h,\"u\")}catch{return false}}const p=this.parse(l.rule,n,i+1);if(o[h]){o[h]={allOf:[o[h],p]}}else{o[h]=p}if(!l.fallthrough)c.push(u.source)}e.patternProperties=o;return true}_knownKeys(e){const t=Object.keys(e[this.childrenFieldName]||{});const s=t.length?[{enum:t}]:[];for(const n of e.patterns||[]){const i=Pl(n.regex);if(!i)return{};s.push({pattern:i.source})}if(!s.length)return{not:{}};return s.length===1?s[0]:{anyOf:s}}_isKnownKey(e,t){if(Object.hasOwn(e[this.childrenFieldName]||{},t))return true;return ms(e.patterns,s=>{const n=Pl(s.regex);return!n||new RegExp(n.source,\"u\").test(t)})}_setObjectDependencies(e,t){if(!Array.isArray(t.dependencies)||t.dependencies.length===0)return;const s=this._stripsUnknown(t);const n=t.dependencies.filter(i=>{const o=[i.key,...i.peers];if(o.some(c=>typeof c===\"string\"&&(c.includes(\".\")||s&&!this._isKnownKey(t,c)))){this._inexact();return false}return true});if(n.length===1){this._mergeKeywords(e,this._setDependencySubSchema({},n[0]))}else if(n.length>1){const i=[];const o={};for(const c of n){if(c.rel===\"with\"){this._setDependencySubSchema(o,c);continue}const l=this._setDependencySubSchema({},c);if(!fr(l))i.push(l)}if(i.length)this._mergeKeywords(e,{allOf:i});this._mergeKeywords(e,o)}}_setDependencySubSchema(e,t){const s=this.logicalOpParser[t.rel];if(typeof s!==\"function\"){this._inexact();return e}s(e,t);return e}_getNumberFormat(e){return void 0}_setNumberFieldProperties(e,t){if(e.type!==\"number\"&&e.type!==\"integer\")return;const s=this.ruleArgFieldName;let n;let i;const o=t.rules||[];It(o,c=>{const l=c[s]||{};const u=At[c.name];if(u){n=this._bound(n,u[0],false,true);i=this._bound(i,u[1],false,false);return}switch(c.name){case\"max\":i=this._bound(i,l.limit,false,false);break;case\"min\":n=this._bound(n,l.limit,false,true);break;case\"greater\":n=this._bound(n,l.limit,true,true);break;case\"less\":i=this._bound(i,l.limit,true,false);break;case\"port\":n=this._bound(n,0,false,true);i=this._bound(i,65535,false,false);break;case\"float\":n=this._bound(n,-Gt,false,true);i=this._bound(i,Gt,false,false);break;case\"multiple\":{const f=Nl(l.base);if(f!==void 0){this._addKeyword(e,\"multipleOf\",f)}else{this._inexact()}break}case\"sign\":case\"positive\":case\"negative\":{const f=c.name===\"sign\"?l.sign:c.name;if(f===\"positive\")n=this._bound(n,0,true,true);if(f===\"negative\")i=this._bound(i,0,true,false);break}default:break}});if(n)e[n.exclusive?\"exclusiveMinimum\":\"minimum\"]=n.value;if(i)e[i.exclusive?\"exclusiveMaximum\":\"maximum\"]=i.value;this._setIfNotEmpty(e,\"format\",this._getNumberFormat(o))}_setStringFieldProperties(e,t){if(e.type!==\"string\"||t.type!==\"string\")return;if(t.flags&&t.flags.encoding)e.contentEncoding=t.flags.encoding;const s=this.ruleArgFieldName;let n;let i;const o=a((c,l=false)=>{if(l){this._addKeyword(e,\"not\",{pattern:c})}else{this._addKeyword(e,\"pattern\",c)}},\"addPattern\");It(t.rules,c=>{const l=c[s]||{};const u=l.options||{};switch(c.name){case\"min\":case\"max\":case\"length\":if(l.encoding){this._inexact();break}if(c.name!==\"max\")n=this._bound(n,l.limit,false,true);if(c.name!==\"min\")i=this._bound(i,l.limit,false,false);break;case\"format\":this._addKeyword(e,\"format\",l.name);break;case\"email\":this._addKeyword(e,\"format\",\"email\");break;case\"hostname\":this._addKeyword(e,\"format\",\"hostname\");break;case\"uri\":this._addKeyword(e,\"format\",u.allowRelative||u.relativeOnly?\"uri-reference\":\"uri\");if(u.scheme||u.relativeOnly)this._inexact();break;case\"ip\":{const f=u.version||[];const d=f.length?f.filter(p=>p===\"ipv4\"||p===\"ipv6\"):[\"ipv4\",\"ipv6\"];const h=u.cidr===\"required\"?[]:d.map(p=>({format:p}));if(u.cidr!==\"forbidden\"||d.length!==(f.length||2)){this._inexact();h.push({pattern:\"^[0-9a-zA-Z:.]+(?:/[0-9]{1,3})?$\"})}if(h.length===1){this._mergeKeywords(e,h[0])}else{this._addKeyword(e,\"anyOf\",h)}break}case\"pattern\":{const f=Pl(l.regex);if(f){o(f.source,!!u.invert)}else{this._inexact()}break}case\"alphanum\":o(\"^[a-zA-Z0-9]+$\");break;case\"token\":o(\"^[a-zA-Z0-9_]+$\");break;case\"hex\":o(u.prefix===\"optional\"?\"^(?:0[xX])?[0-9a-fA-F]+$\":u.prefix===true?\"^0[xX][0-9a-fA-F]+$\":\"^[0-9a-fA-F]+$\");if(u.byteAligned)o(\"^(?:[\\\\s\\\\S]{2})*$\");break;case\"trim\":if(l.enabled!==false)o(\"^(?:\\\\S(?:[\\\\s\\\\S]*\\\\S)?)?$\");break;case\"isoDate\":this._addKeyword(e,\"format\",\"date-time\");break;case\"isoDuration\":this._addKeyword(e,\"format\",\"duration\");break;case\"uuid\":case\"guid\":this._addKeyword(e,\"format\",\"uuid\");break;default:break}});if(n&&n.value>0)e.minLength=n.value;if(i)e.maxLength=i.value}_setContains(e,t,s){const n=s.min===void 0?1:s.min;if(n!==1||s.max!==void 0)this._inexact();if(n<1)return;this._addKeyword(e,\"contains\",t)}_setTuple(e,t,s){e.items=t;e.additionalItems=s===void 0?false:s}_setArrayFieldProperties(e,t,s,n){if(e.type!==\"array\")return;const i=this.ruleArgFieldName;let o;let c;It(t.rules,f=>{const d=f[i]||{};switch(f.name){case\"max\":c=this._bound(c,d.limit,false,false);break;case\"min\":o=this._bound(o,d.limit,false,true);break;case\"length\":o=this._bound(o,d.limit,false,true);c=this._bound(c,d.limit,false,false);break;case\"unique\":if(typeof d.comparator!==\"function\"){e.uniqueItems=true}else{this._inexact()}break;case\"has\":this._setContains(e,this.parse(d.schema,s,n+1),d.options||{});break;default:break}});if(o)e.minItems=o.value;if(c)e.maxItems=c.value;if(this._stripsArrayItems(t)){this._inexact();e.items={};return}if(ms([...t.items||[],...t.ordered||[]],f=>this._getPresence(f)!==void 0&&this._getPresence(f)!==\"optional\"))this._inexact();let l;if(t.items&&t.items.length){if(t.items.length===1){l=this.parse(t.items[0],s,n+1)}else{l={anyOf:Kt(t.items,f=>{return this.parse(f,s,n+1)})}}}const u=t.ordered;if(u&&u.length){this._setTuple(e,u.map(f=>this.parse(f,s,n+1)),l)}else{e.items=l||{}}}_setDateFieldProperties(e,t){if(e.type!==\"date\")return;const s=t.flags&&t.flags.format;if(s===\"javascript\"||s===\"unix\"){e.type=\"number\"}else{e.type=\"string\";e.format=\"date-time\"}}_setAlternativesProperties(e,t,s,n){if(e.type!==\"alternatives\")return;delete e.type;if(t.matches.length===0)return;const i=t.matches;if(i[0].schema){const o=t.flags&&t.flags.match;const c=Kt(i,u=>{return this.parse(u.schema,s,n+1)});const l=c.every(u=>this.isExact(u));if(o===\"none\"){if(l)this._mergeKeywords(e,{not:c.length===1?c[0]:{anyOf:c}})}else if(c.length===1){this._mergeKeywords(e,c[0])}else{this._mergeKeywords(e,{[o===\"one\"?l?\"oneOf\":\"anyOf\":o===\"all\"?\"allOf\":\"anyOf\"]:c})}}else{this._setConditionProperties(e,t,s,n,\"matches\",\"anyOf\")}}_setConditionProperties(e,t,s,n,i,o=\"allOf\"){const c=t[i];if(!c||c.length===0)return;if(i===\"whens\"&&(t.type!==\"any\"||t.rules||t.allow||t.invalid))this._inexact();let l=this._isIfThenElseSupported();const u=Ol(t.metas,f=>{return typeof f[\"if-style\"]!==\"undefined\"});if(l&&u.length>0&&u[0][\"if-style\"]===false)l=false;if(c.length>1){this._mergeKeywords(e,{[o]:Jb(Kt(c,f=>{return this._setConditionSchema(l,{},f,s,n+1)}))})}else{const f=this._setConditionSchema(l,{},c[0],s,n+1);if(f)this._mergeKeywords(e,f)}}_setConditionSchema(e,t,s,n,i){if(!s.is&&!s.switch)return;if(s.switch){this._parseSwitchCondition(e,t,s,n,i)}else{if(e){this._parseIfThenElseCondition(t,s,n,i)}else{this._setConditionCompositionStyle(t,s,n,i)}}return t}_parseIfThenElseCondition(e,t,s,n){if(t.ref)return this._setConditionCompositionStyle(e,t,s,n);const i=this.parse(t.is,s,n);if(!this.isExact(i))return this._setBranches(e,t,s,n);e.if=i;if(t.then)e.then=this.parse(t.then,s,n);if(t.otherwise)e.else=this.parse(t.otherwise,s,n);return e}_setBranches(e,t,s,n){this._inexact();if(!t.then||!t.otherwise)return e;e.anyOf=[this.parse(t.then,s,n),this.parse(t.otherwise,s,n)];return e}_parseSwitchCondition(e,t,s,n,i){if(s.ref)this._inexact();const o=[];for(const c of s.switch){if(e&&!s.ref){const l=this._parseIfThenElseCondition({},c,n,i+1);o.push(l)}else{if(c.then)o.push(this.parse(c.then,n,i+1));if(c.otherwise)o.push(this.parse(c.otherwise,n,i+1))}}if(o.length>1){t.anyOf=o}else{St(t,o[0])}}_setConditionCompositionStyle(e,t,s,n){if(t.ref){this._inexact();const i=e.anyOf||[];if(t.then)i.push(this.parse(t.then,s,n+1));if(t.otherwise)i.push(this.parse(t.otherwise,s,n+1));if(i.length>1){e.anyOf=i}else{St(e,i[0])}}else{if(t.is&&!this.isExact(this.parse(t.is,s,n+1))){this._setBranches(e,t,s,n+1)}else if(t.is&&t.then&&t.otherwise){e.allOf=[{anyOf:[{not:this.parse(t.is,s,n+1)},this.parse(t.then,s,n+1)]},{anyOf:[this.parse(t.is,s,n+1),this.parse(t.otherwise,s,n+1)]}]}else if(t.is&&t.then){e.anyOf=[{not:this.parse(t.is,s,n+1)},this.parse(t.then,s,n+1)]}else if(t.is&&t.otherwise){e.anyOf=[this.parse(t.is,s,n+1),this.parse(t.otherwise,s,n+1)]}}return e}_setAnyProperties(e){if(e.type!==\"any\")return;e.type=[\"array\",\"boolean\",\"number\",\"object\",\"string\",\"null\"]}_setAllOf(e,t,s,n){for(const i of t.rules||[]){if(i.name!==\"allOf\")continue;const o=He(i,`${this.ruleArgFieldName}.schemas`);this._mergeKeywords(e,{allOf:o.map(c=>this.parse(c,s,n+1))})}}_setNonJsonProperties(e,t){if(!eS.includes(t.type))return;this._addKeyword(e,\"not\",{})}_setMetaProperties(e,t){It(t.metas,s=>{if(s.contentMediaType)e.contentMediaType=s.contentMediaType;if(s.format)e.format=s.format;if(s.title)e.title=s.title})}_setLinkFieldProperties(e,t){if(e.type!==\"link\")return;delete e.type;if(He(t,\"link.ref.type\")===\"local\"){e.$ref=`${this._getLocalSchemaBasePath()}/${t.link.ref.path.join(\"/\")}`}}_copyMetasToSchema(e,t){if(!fr(e.metas)){It(e.metas,s=>{It(s,(n,i)=>{if(this._isKnownMetaKey(i))t[i]=n})})}}_isKnownMetaKey(e){return false}};var qs=class extends Ar{static{a(this,\"JsonDraft04SchemaParser\")}constructor(e={}){super(St({$schema:\"http://json-schema.org/draft-04/schema#\",logicalOpParser:{xor:null,with:a(function(t,s){t.dependencies=t.dependencies||{};t.dependencies[s.key]=s.peers},\"with\"),without:null}},e))}_isIfThenElseSupported(){return false}_setNumberFieldProperties(e,t){super._setNumberFieldProperties(e,t);if(typeof e.exclusiveMinimum!==\"undefined\"){e.minimum=e.exclusiveMinimum;e.exclusiveMinimum=true}if(typeof e.exclusiveMaximum!==\"undefined\"){e.maximum=e.exclusiveMaximum;e.exclusiveMaximum=true}if(typeof e.minimum!==\"undefined\"&&e.minimum===e.exclusiveMinimum)e.exclusiveMinimum=true;if(typeof e.maximum!==\"undefined\"&&e.maximum===e.exclusiveMaximum)e.exclusiveMaximum=true}_getLocalSchemaBasePath(){return\"#/definitions\"}_setContains(e,t,s){this._inexact()}_setPropertyNames(e,t){this._inexact()}_getValuesSchema(e){return{enum:e}}};var zs=class extends Ar{static{a(this,\"JsonDraft201909SchemaParser\")}constructor(e={}){super(St({$schema:\"https://json-schema.org/draft/2019-09/schema\",logicalOpParser:{with:a(function(t,s){t.dependentRequired=t.dependentRequired||{};t.dependentRequired[s.key]=s.peers},\"with\")}},e))}_setContains(e,t,s){const n={contains:t};if(s.min!==void 0&&s.min!==1)n.minContains=s.min;if(s.max!==void 0)n.maxContains=s.max;this._mergeKeywords(e,n)}_isKnownMetaKey(e){return e===\"deprecated\"||e===\"readOnly\"||e===\"writeOnly\"}};var Gs=class extends zs{static{a(this,\"JsonDraft202012SchemaParser\")}constructor(e={}){super(St({$schema:\"https://json-schema.org/draft/2020-12/schema\"},e))}_setTuple(e,t,s){e.prefixItems=t;e.items=s===void 0?false:s}};function Xh(r){const e=r.map(t=>t.name);if(e.some(t=>[\"int8\",\"uint8\",\"int16\",\"uint16\",\"int32\",\"port\"].includes(t)))return\"int32\";if(e.some(t=>[\"uint32\",\"int64\",\"uint64\"].includes(t)))return\"int64\";if(e.includes(\"float\"))return\"float\";if(e.includes(\"double\"))return\"double\";return void 0}a(Xh,\"openApiNumberFormat\");var Jo=class extends qs{static{a(this,\"OpenApiSchemaParser\")}constructor(e={}){super(St({logicalOpParser:{xor:null,with:null,without:null}},e));this.$schema=void 0;this.knownKeys=[\"$ref\",\"title\",\"multipleOf\",\"maximum\",\"exclusiveMaximum\",\"minimum\",\"exclusiveMinimum\",\"maxLength\",\"minLength\",\"pattern\",\"maxItems\",\"minItems\",\"uniqueItems\",\"maxProperties\",\"minProperties\",\"required\",\"enum\",\"description\",\"format\",\"default\",\"type\",\"allOf\",\"oneOf\",\"anyOf\",\"not\",\"items\",\"properties\",\"additionalProperties\",\"example\",\"nullable\"]}parse(e,t={},s=0){const n=super.parse(e,t,s);if(s===0&&!fr(t))n.schemas=t;delete n.components;if(n.const)n.enum=[n.const];return n}_isIfThenElseSupported(){return false}_getNumberFormat(e){return Xh(e)}_setAnyProperties(e){if(e.type===\"any\")delete e.type}_getBinaryFormat(){return\"binary\"}_setTuple(e,t,s){this._inexact();e.items={anyOf:s===void 0?t:[...t,s]};if(s===void 0&&!(typeof e.maxItems===\"number\"&&e.maxItems<=t.length))e.maxItems=t.length}_setObjectProperties(e,t,s,n){super._setObjectProperties(e,t,s,n);if(!e.patternProperties)return;const i=Object.values(e.patternProperties);delete e.patternProperties;this._inexact();if(e.additionalProperties===true)return;const o=typeof e.additionalProperties===\"object\"?[...i,e.additionalProperties]:i;e.additionalProperties=o.length===1?o[0]:{anyOf:o}}_getLocalSchemaBasePath(){return\"#/components/schemas\"}_setBasicProperties(e,t){super._setBasicProperties(e,t);if(!fr(e.examples)){e.example=e.examples[0];delete e.examples}}_addNullTypeIfNullable(e,t){super._addNullTypeIfNullable(e,t);if(e.type===\"null\"){e.type=\"object\";e.nullable=true}else if(Array.isArray(e.type)&&e.type.includes(\"null\")){Ol(e.type,s=>{return s===\"null\"});e.nullable=true;if(e.type.length===1){e.type=e.type[0]}else if(!e.type){e.type=\"object\"}}if(Array.isArray(e.type)){const s=e.anyOf||[];e.anyOf=s;It(e.type,n=>{const i=ms(s,o=>{return o.type===n});if(!i){const o={type:n};if(n===\"array\")o.items={};s.push(o)}});It(s,n=>{if(e.nullable)n.nullable=true});delete e.type;delete e.nullable}}_isKnownMetaKey(e){return e.startsWith(\"x-\")||e===\"deprecated\"||e===\"readOnly\"||e===\"writeOnly\"}};var Zo=class extends Gs{static{a(this,\"OpenApi31SchemaParser\")}constructor(e={}){super(e);this.$schema=void 0}parse(e,t={},s=0){const n=super.parse(e,t,s);if(s===0&&!fr(t))n.schemas=t;delete n.components;return n}_getNumberFormat(e){return Xh(e)}_getBinaryFormat(){return\"binary\"}_getLocalSchemaBasePath(){return\"#/components/schemas\"}_isKnownMetaKey(e){return e.startsWith(\"x-\")||e===\"deprecated\"||e===\"readOnly\"||e===\"writeOnly\"}};var Jv=[\"null\",\"boolean\",\"number\",\"integer\",\"string\",\"array\",\"object\"];var Qo={string:[\"minLength\",\"maxLength\",\"pattern\",\"format\"],number:[\"minimum\",\"maximum\",\"exclusiveMinimum\",\"exclusiveMaximum\",\"multipleOf\",\"format\"],array:[\"items\",\"prefixItems\",\"additionalItems\",\"contains\",\"minContains\",\"maxContains\",\"minItems\",\"maxItems\",\"uniqueItems\"],object:[\"properties\",\"required\",\"patternProperties\",\"additionalProperties\",\"propertyNames\",\"minProperties\",\"maxProperties\",\"dependentRequired\",\"dependencies\"]};var sS=[\"title\",\"description\",\"default\",\"examples\",\"example\",\"deprecated\",\"readOnly\",\"writeOnly\",\"$comment\"];var Zv=[\"enum\",\"const\",\"default\",\"examples\",\"example\"];var ni=\"https://lakutata.invalid/schema.json\";var Qv=[[/draft-04/,\"draft-04\"],[/draft-06/,\"draft-06\"],[/draft-07/,\"draft-07\"],[/2019-09/,\"draft-2019-09\"],[/2020-12/,\"draft-2020-12\"],[/oas\\/3\\.1/,\"openapi-3.1\"]];function qe(r){return r!==null&&typeof r===\"object\"&&!Array.isArray(r)}a(qe,\"isObject\");function de(r){return typeof r===\"boolean\"||qe(r)}a(de,\"isSchema\");function ea(r){const e=r.indexOf(\"#\");return e<0?r:r.slice(0,e)}a(ea,\"withoutFragment\");function ii(r,e){try{return new URL(r,e).href}catch{return r}}a(ii,\"resolveUri\");function ta(){return b.alternatives().try(b.any()).match(\"none\")}a(ta,\"never\");function Yh(r){if(r.length===1)return r[0];if(r[0]._valids)return b.any().allOf(...r);return r[0].allOf(...r.slice(1))}a(Yh,\"all\");function ra(r){const e=r.filter(n=>!Array.isArray(n));const t=r.filter(n=>Array.isArray(n));const s=t.map(n=>{const i=b.array().length(n.length);return n.length?i.ordered(...n.map(o=>ra([o]))):i});if(e.length)s.unshift(b.any().valid(...e));if(!s.length)return ta();return s.length===1?s[0]:b.alternatives().try(...s)}a(ra,\"literals\");var Jh=class{static{a(this,\"Importer\")}constructor(e,t){this.root=e;this.registry=new Map;this.converted=new Map;this.pending=new Map;this.shared=[];this.memo=new WeakMap;this.ids=0;this.usedIds=new Set;const s=qe(e)?e.$schema:void 0;let n=t.dialect;if(!n&&typeof s===\"string\"){n=Qv.find(([o])=>o.test(s))?.[1]}this.dialect=n||\"draft-2020-12\";this.convert=!!t.convert;const i=t.document===void 0?e:t.document;if(de(i))this.register(i,ni);if(!de(i)&&i!==null&&typeof i===\"object\")this.registry.set(ni,{node:i,base:ni});for(const[o,c]of Object.entries(t.schemas||{})){if(de(c))this.register(c,ii(o,ni))}}run(){let e=this.node(this.root,ni);for(const t of this.shared)e=e.shared(t);return e.prefs({convert:this.convert})}get idKeyword(){return this.dialect===\"draft-04\"||this.dialect===\"openapi-3.0\"?\"id\":\"$id\"}register(e,t){if(Array.isArray(e)){for(const n of e)this.register(n,t);return}if(!qe(e))return;const s=e[this.idKeyword];if(typeof s===\"string\"&&!s.startsWith(\"#\")){t=ii(s,t);this.registry.set(ea(t),{node:e,base:t})}if(!this.registry.has(ea(t)))this.registry.set(ea(t),{node:e,base:t});for(const n of[e.$anchor,e.$dynamicAnchor,typeof s===\"string\"&&s.startsWith(\"#\")?s.slice(1):void 0]){if(typeof n===\"string\"&&n)this.registry.set(`${ea(t)}#${n}`,{node:e,base:t})}for(const[n,i]of Object.entries(e)){if(Zv.includes(n))continue;if(i!==null&&typeof i===\"object\")this.register(i,t)}}resolve(e,t){const s=ii(e,t);const n=s.indexOf(\"#\");const i=n<0?\"\":decodeURIComponent(s.slice(n+1));const o=this.registry.get(ea(s));if(!i.startsWith(\"/\")&&i){const l=this.registry.get(s);if(l)return l}if(!o)throw new Ue(`Cannot resolve the reference ${e}`);if(!i)return o;if(!i.startsWith(\"/\"))throw new Ue(`Cannot resolve the reference ${e}`);let c=o.node;for(const l of i.slice(1).split(\"/\")){const u=l.replace(/~1/g,\"/\").replace(/~0/g,\"~\");if(c===null||typeof c!==\"object\"||!Object.prototype.hasOwnProperty.call(c,u))throw new Ue(`Cannot resolve the reference ${e}`);c=c[u]}if(!de(c))throw new Ue(`The reference ${e} is not a schema`);return{node:c,base:o.base}}idOf(e){const t=e.slice(e.indexOf(\"#\")+1);const s=decodeURIComponent(t.split(\"/\").pop()||\"\").replace(/~1/g,\"/\").replace(/~0/g,\"~\").replace(/[^\\w-]/g,\"_\")||\"schema\";let n=s;while(this.usedIds.has(n))n=`${s}_${++this.ids}`;this.usedIds.add(n);return n}reference(e,t){const{node:s,base:n}=this.resolve(e,t);const i=this.converted.get(s);if(i)return i;const o=this.pending.get(s);if(o){o.used=true;return b.link(`#${o.id}`)}const c=this.idOf(e);this.pending.set(s,{id:c,used:false});let l=this.node(s,n);const{used:u}=this.pending.get(s);this.pending.delete(s);if(u){this.shared.push(l.id(c));l=b.link(`#${c}`)}this.converted.set(s,l);return l}node(e,t){if(e===true)return b.any();if(e===false)return ta();if(!qe(e))throw new Ue(\"A JSON Schema must be an object or a boolean\");const s=this.memo.get(e);if(s)return s;const n=this.convertNode(e,t);this.memo.set(e,n);return n}convertNode(e,t){const s=e[this.idKeyword];if(typeof s===\"string\"&&!s.startsWith(\"#\"))t=ii(s,t);const n=[];const i=this.typed(e,t);if(i)n.push(i);if(de(e.not))n.push(b.alternatives().try(this.node(e.not,t)).match(\"none\"));const o=this.list(e.anyOf);if(o.length)n.push(o.length===1?this.node(o[0],t):b.alternatives().try(...o.map(d=>this.node(d,t))));const c=this.list(e.oneOf);if(c.length)n.push(b.alternatives().try(...c.map(d=>this.node(d,t))).match(\"one\"));for(const d of this.list(e.allOf))n.push(this.node(d,t));if(de(e.if)&&(de(e.then)||de(e.else))){n.push(b.any().when(this.node(e.if,t),{then:de(e.then)?this.node(e.then,t):b.any(),otherwise:de(e.else)?this.node(e.else,t):b.any()}))}for(const[d,h]of Object.entries(this.dependentSchemas(e))){n.push(b.any().when(b.object({[d]:b.any().required()}).unknown(),{then:this.node(h,t),otherwise:b.any()}))}const l=e.$ref??e.$dynamicRef??e.$recursiveRef;if(typeof l===\"string\")n.push(this.reference(l,t));const u=this.unevaluated(e,t);if(u)n.push(u);let f=this.values(e,n);f=this.annotate(f,e);return f}list(e){return Array.isArray(e)?e.filter(de):[]}dependentSchemas(e){const t={};for(const s of[\"dependencies\",\"dependentSchemas\"]){const n=e[s];if(!qe(n))continue;for(const[i,o]of Object.entries(n)){if(de(o))t[i]=o}}return t}values(e,t){let s;if(Array.isArray(e.enum))s=e.enum;if(Object.prototype.hasOwnProperty.call(e,\"const\"))s=s?s.filter(i=>ra([e.const]).validate(i).error===void 0):[e.const];const n=t.length===0?void 0:Yh(t);if(!s)return n||b.any();if(!s.length)return ta();if(!n)return ra(s);try{return ra(s.filter(i=>n.validate(i,{convert:this.convert}).error===void 0))}catch{return Yh([ra(s),n])}}typed(e,t){let s=typeof e.type===\"string\"?[e.type]:Array.isArray(e.type)?e.type.filter(l=>typeof l===\"string\"):void 0;if(s&&this.dialect===\"openapi-3.0\"&&e.nullable===true&&!s.includes(\"null\"))s=[...s,\"null\"];if(!s){const l=Object.keys(Qo).filter(u=>Qo[u].some(f=>e[f]!==void 0));if(!l.length)return void 0;s=[\"null\",\"boolean\",\"number\",\"string\",\"array\",\"object\"]}s=s.filter(l=>Jv.includes(l));if(s.includes(\"number\"))s=s.filter(l=>l!==\"integer\");const n=[...new Set(s)];const i=n.length>1&&n.includes(\"null\");const o=n.filter(l=>!i||l!==\"null\").map(l=>this.type(l,e,t));if(!o.length)return ta();const c=o.length===1?o[0]:b.alternatives().try(...o);return i?c.allow(null):c}type(e,t,s){switch(e){case\"null\":return b.any().valid(null);case\"boolean\":return b.boolean();case\"integer\":case\"number\":return this.number(t,e===\"integer\");case\"string\":return this.string(t);case\"array\":return this.array(t,s);default:return this.object(t,s)}}number(e,t){let s=b.number().unsafe();let n=typeof e.minimum===\"number\"?e.minimum:void 0;let i=typeof e.maximum===\"number\"?e.maximum:void 0;let o=typeof e.exclusiveMinimum===\"number\"?e.exclusiveMinimum:void 0;let c=typeof e.exclusiveMaximum===\"number\"?e.exclusiveMaximum:void 0;if(e.exclusiveMinimum===true&&n!==void 0){o=n;n=void 0}if(e.exclusiveMaximum===true&&i!==void 0){c=i;i=void 0}const l=e.format;const u=typeof l===\"string\"&&[\"int32\",\"int64\",\"float\",\"double\"].includes(l)?l:t?Object.keys(At).find(f=>At[f][0]===n&&At[f][1]===i):n===-Gt&&i===Gt?\"float\":void 0;if(u){s=s[u].call(s);if(u in At||u===\"float\"){const[f,d]=u===\"float\"?[-Gt,Gt]:At[u];if(n===f)n=void 0;if(i===d)i=void 0}}if(t&&!(u&&u in At))s=s.integer();if(n!==void 0)s=s.min(n);if(i!==void 0)s=s.max(i);if(o!==void 0)s=s.greater(o);if(c!==void 0)s=s.less(c);if(typeof e.multipleOf===\"number\"&&e.multipleOf>0)s=s.multiple(e.multipleOf);return s}string(e){let t=b.string().min(typeof e.minLength===\"number\"?e.minLength:0);if(typeof e.maxLength===\"number\")t=t.max(e.maxLength);if(typeof e.pattern===\"string\"){let n;try{n=new RegExp(e.pattern,\"u\")}catch{throw new Ue(`Invalid pattern: ${e.pattern}`)}t=t.pattern(n)}const s=e.format;if(typeof s===\"string\"&&Object.prototype.hasOwnProperty.call(Yn,s))t=t.format(s);return t}array(e,t){let s=b.array();const n=Array.isArray(e.prefixItems)?this.list(e.prefixItems):Array.isArray(e.items)?this.list(e.items):void 0;const i=n?Array.isArray(e.prefixItems)?e.items:e.additionalItems:e.items;let o=typeof e.maxItems===\"number\"?e.maxItems:void 0;if(n&&n.length)s=s.ordered(...n.map(c=>this.node(c,t)));if(i===false){const c=n?n.length:0;if(!n||!n.length)o=o===void 0?c:Math.min(o,c)}else if(de(i)&&i!==true){s=s.items(this.node(i,t))}else if(n&&n.length){s=s.items(b.any())}if(typeof e.minItems===\"number\")s=s.min(e.minItems);if(o!==void 0)s=s.max(o);if(e.uniqueItems===true)s=s.unique();if(de(e.contains)){const c=typeof e.minContains===\"number\"?e.minContains:1;const l=typeof e.maxContains===\"number\"?e.maxContains:void 0;if(l!==void 0&&c>l)return ta();s=s.has(this.node(e.contains,t),c===1&&l===void 0?{}:{min:c,max:l})}return s}object(e,t){return this.refineObject(b.object(this.objectKeys(e,t)),e,t)}objectPatterns(e,t){const s=[];if(!qe(e.patternProperties))return s;for(const[n,i]of Object.entries(e.patternProperties)){if(!de(i))continue;let o;try{o=new RegExp(n,\"u\")}catch{throw new Ue(`Invalid pattern: ${n}`)}s.push({regex:o,schema:this.node(i,t)})}return s}objectKeys(e,t){const s=qe(e.properties)?e.properties:{};const n=Array.isArray(e.required)?e.required.filter(l=>typeof l===\"string\"):[];const i=this.objectPatterns(e,t);const o=e.additionalProperties;const c={};for(const l of new Set([...Object.keys(s),...n])){const u=i.filter(({regex:h})=>h.test(l)).map(({schema:h})=>h);const f=[...de(s[l])?[this.node(s[l],t)]:[],...u];if(!de(s[l])&&!u.length&&de(o)&&o!==true)f.push(this.node(o,t));const d=f.length===0?b.any():Yh(f);c[l]=n.includes(l)?d.required():d.optional()}return c}refineObject(e,t,s){for(const{regex:i,schema:o}of this.objectPatterns(t,s))e=e.pattern(i,o,{fallthrough:true});const n=t.additionalProperties;if(n===false){e=e.unknown(false)}else if(de(n)&&n!==true){e=e.unknown(this.node(n,s))}else{e=e.unknown(true)}if(de(t.propertyNames))e=e.keyNames(this.node(t.propertyNames,s));if(typeof t.minProperties===\"number\")e=e.min(t.minProperties);if(typeof t.maxProperties===\"number\")e=e.max(t.maxProperties);for(const i of[\"dependencies\",\"dependentRequired\"]){const o=t[i];if(!qe(o))continue;for(const[c,l]of Object.entries(o)){if(Array.isArray(l)&&l.length)e=e.with(c,l.filter(u=>typeof u===\"string\"))}}return e}objectParts(){let e=this.root;let t=ni;while(qe(e)&&typeof e.$ref===\"string\"&&Object.keys(e).every(N=>N===\"$ref\"||sS.includes(N))){const N=e;const A=this.resolve(e.$ref,t);e=qe(A.node)?{...N,...A.node}:A.node;delete e.$ref;if(qe(A.node)&&typeof A.node.$ref===\"string\")e.$ref=A.node.$ref;t=A.base}if(!qe(e))throw new Ue(\"The JSON Schema of a DTO must describe objects\");const s=e.type;if(s!==void 0&&!(s===\"object\"||Array.isArray(s)&&s.includes(\"object\")))throw new Ue(\"The JSON Schema of a DTO must describe objects\");const n=e[this.idKeyword];if(typeof n===\"string\"&&!n.startsWith(\"#\"))t=ii(n,t);const i=e;const o=this.objectKeys(i,t);const{type:c,properties:l,required:u,patternProperties:f,additionalProperties:d,propertyNames:h,minProperties:p,maxProperties:m,dependentRequired:y,...w}=i;const S=Object.fromEntries(Object.entries(w).filter(([N])=>!Qo.string.includes(N)&&!Qo.number.includes(N)&&!Qo.array.includes(N)));if(qe(S.dependencies))S.dependencies=Object.fromEntries(Object.entries(S.dependencies).filter(([,N])=>de(N)));const T=Object.keys(S).some(N=>!sS.includes(N)&&![\"$schema\",\"$id\",\"id\",\"$defs\",\"definitions\",\"$comment\",\"nullable\",\"discriminator\",\"xml\",\"externalDocs\"].includes(N));const _=!T?void 0:S.unevaluatedProperties!==void 0||S.unevaluatedItems!==void 0?this.node(i,t):this.node({...S,type:\"object\"},t);const x=this.shared;const k=a(N=>{for(const A of x)N=N.shared(A);return N},\"withShared\");for(const N of Object.keys(o))o[N]=k(o[N]);return{keys:o,refine:a(N=>{let A=this.refineObject(N,i,t);if(_)A=A.allOf(_);return k(A)},\"refine\"),title:typeof i.title===\"string\"?i.title:void 0,description:typeof i.description===\"string\"?i.description:void 0}}evaluated(e,t,s,n,i=new Set){const o={keys:new Set,items:new Set,all:false};if(!qe(e)||i.has(e))return o;i=new Set(i).add(e);const c=e[this.idKeyword];if(typeof c===\"string\"&&!c.startsWith(\"#\"))t=ii(c,t);const l=a(d=>{d.keys.forEach(h=>o.keys.add(h));d.items.forEach(h=>o.items.add(h));o.all=o.all||d.all},\"add\");const u=a(d=>{const h=this.node(d,t);return h.$_match(s,n.state.nest(h,\"unevaluated\"),n.prefs)},\"matches\");if(Array.isArray(s)){const d=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:void 0;if(Array.isArray(d))for(let h=0;h<Math.min(d.length,s.length);++h)o.items.add(h);if(e.items!==void 0&&!Array.isArray(e.items)||e.additionalItems!==void 0||e.unevaluatedItems!==void 0)o.all=true;if(de(e.contains)&&this.dialect!==\"draft-2019-09\"){const h=this.node(e.contains,t);s.forEach((p,m)=>{if(h.$_match(p,n.state.nest(h,\"unevaluated\"),n.prefs))o.items.add(m)})}}else if(qe(s)){const d=Object.keys(s);if(qe(e.properties)){for(const h of Object.keys(e.properties)){if(Object.prototype.hasOwnProperty.call(s,h))o.keys.add(h)}}if(qe(e.patternProperties)){const h=Object.keys(e.patternProperties).map(p=>new RegExp(p,\"u\"));for(const p of d){if(h.some(m=>m.test(p)))o.keys.add(p)}}if(e.additionalProperties!==void 0||e.unevaluatedProperties!==void 0)o.all=true;for(const[h,p]of Object.entries(this.dependentSchemas(e))){if(Object.prototype.hasOwnProperty.call(s,h)&&u(p))l(this.evaluated(p,t,s,n,i))}}for(const d of this.list(e.allOf))l(this.evaluated(d,t,s,n,i));for(const d of[...this.list(e.anyOf),...this.list(e.oneOf)]){if(u(d))l(this.evaluated(d,t,s,n,i))}if(de(e.if)){if(u(e.if)){l(this.evaluated(e.if,t,s,n,i));if(de(e.then))l(this.evaluated(e.then,t,s,n,i))}else if(de(e.else)){l(this.evaluated(e.else,t,s,n,i))}}const f=e.$ref??e.$dynamicRef??e.$recursiveRef;if(typeof f===\"string\"){const d=this.resolve(f,t);l(this.evaluated(d.node,d.base,s,n,i))}return o}unevaluated(e,t){const{unevaluatedProperties:s,unevaluatedItems:n,...i}=e;const o=de(s)&&s!==true?this.node(s,t):void 0;const c=de(n)&&n!==true?this.node(n,t):void 0;if(!o&&!c)return void 0;return b.any().custom((l,u)=>{const f=Array.isArray(l);if(f?!c:!o||!qe(l))return l;const d=this.evaluated(i,t,l,u);if(d.all)return l;const h=f?c:o;const p=f?l.map((m,y)=>[y,m]):Object.entries(l);for(const[m,y]of p){if(f?d.items.has(m):d.keys.has(m))continue;if(!h.$_match(y,u.state.nest(h,\"unevaluated\"),u.prefs)){return u.message({custom:`{{#label}} has an unevaluated ${f?\"item\":\"key\"} {{#name}} which is not allowed`},{name:m})}}return l},\"unevaluated keys and items\")}annotate(e,t){if(typeof t.description===\"string\"&&t.description)e=e.description(t.description);if(t.default!==void 0)e=e.default(t.default);const s=Array.isArray(t.examples)?t.examples:t.example!==void 0?[t.example]:[];for(const i of s)e=e.example(i);const n={};for(const[i,o]of Object.entries(t)){if([\"title\",\"deprecated\",\"readOnly\",\"writeOnly\",\"contentEncoding\",\"contentMediaType\"].includes(i)||i.startsWith(\"x-\"))n[i]=o}if(typeof t.format===\"string\"&&!Object.prototype.hasOwnProperty.call(Yn,t.format)&&![\"int32\",\"int64\",\"float\",\"double\"].includes(t.format))n.format=t.format;if(Object.keys(n).length)e=e.meta(n);return e}};function nS(r,e={}){if(!de(r))throw new Ue(\"A JSON Schema must be an object or a boolean\");return new Jh(r,e).objectParts()}a(nS,\"importObject\");var eA={\"draft-2020-12\":Gs,\"draft-2019-09\":zs,\"draft-07\":Ar,\"draft-04\":qs,\"openapi-3.0\":Jo,\"openapi-3.1\":Zo};function Zh(r,e={}){const t=typeof r===\"function\"&&typeof r.Schema===\"function\"?r.Schema():r;if(!t||typeof t.describe!==\"function\")throw new Ue(\"Not a schema object.\");const s=e.target||\"draft-2020-12\";const n=eA[s];if(!n)throw new Ue(`Unknown JSON Schema target: ${s}`);const i=new n({includeSchemaDialect:!!e.dialect,preferences:{...e.preferences||Wo}});const o=e.definitions||{};const c=i.parse(t.describe(),o);return c}a(Zh,\"toJsonSchema\");var tA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var rA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var sa;function na(r){return ti(sA,me(r),()=>{const e=Hh(r);const t=qh(r);return e?t.pattern(I.String(),e):t})}a(na,\"getObjectSchema\");var sA=new WeakMap;var nA=new WeakMap;var iA=new WeakMap;var oA=[\"presence\",\"description\",\"label\",\"unknown\"];function aA(r){const e=r.$_terms;for(const s of[\"dependencies\",\"renames\",\"externals\",\"whens\",\"alterations\"]){const n=e[s];if(n&&(!Array.isArray(n)||n.length))return false}if(r._rules.length||r._valids||r._invalids)return false;for(const[s,n]of Object.entries(r._flags)){if(!oA.includes(s)||s===\"unknown\"&&typeof n===\"object\")return false}const t=e.keys||[];return t.every(({schema:s})=>!s.$_rootReferences().length)}a(aA,\"arePropertiesIndependent\");function cA(r,e){const t=ti(iA,me(r),()=>new Map);let s=t.get(e);if(s!==void 0)return s;s=null;const n=v(na(r));if(aA(n)){const i=(n.$_terms.keys||[]).find(({key:o})=>o===e);if(i){const o=v(Ce.object({[e]:i.schema}));s=v(n._preferences?o.prefs(n._preferences):o)}}t.set(e,s);return s}a(cA,\"getPropertySchema\");var lA=new WeakMap;function uA(r){if(!r||r.type!==\"any\"||r._rules.length||r._valids||r._invalids)return false;const e=r.$_terms;return![\"whens\",\"externals\"].some(t=>Array.isArray(e[t])&&e[t].length>0)}a(uA,\"acceptsAnything\");function fA(r,e){if(typeof e!==\"string\")return false;const t=ti(lA,me(r),()=>new Map);let s=t.get(e);if(s!==void 0)return s;const n=v(na(r));const i=(n.$_terms.keys||[]).find(({key:c})=>c===e);const o=i?void 0:(n.$_terms.patterns||[]).find(c=>c.regex?c.regex.test(e):!c.schema.validate(e).error);s=uA(i?i.schema:o?.rule);t.set(e,s);return s}a(fA,\"acceptsAnyValue\");function dA(r){const e=r.constructor;if(e===Object||e===Array)return true;return e===void 0&&Object.getPrototypeOf(r)===null}a(dA,\"isPlainData\");function Qh(r,e,t){if(typeof e===\"string\"){const s=cA(r,e);if(s)return I.validate({[e]:t},s,{noDefaults:true})[e]}return I.validate({...r,[e]:t},na(r),{noDefaults:true})[e]}a(Qh,\"validatePropertyValue\");var hA=[\"push\",\"pop\",\"shift\",\"unshift\",\"splice\",\"sort\",\"reverse\",\"fill\",\"copyWithin\"];function pA(r,e){r.length=0;for(let t=0;t<e.length;++t){if(t in e)r[t]=e[t]}r.length=e.length}a(pA,\"restoreArray\");function iS(r,e,t){if(t.had){Reflect.set(r,e,t.value)}else{Reflect.deleteProperty(r,e)}if(t.length!==void 0)r.length=t.length}a(iS,\"restoreProperty\");function oS(r,e){return{had:Object.prototype.hasOwnProperty.call(r,e),value:Reflect.get(r,e),length:Array.isArray(r)?r.length:void 0}}a(oS,\"propertyState\");function cS(r,e,t,s,n,i){const o=Reflect.get(r,e,t);if(!o)return o;if(typeof o!==\"object\"){if(typeof o!==\"function\")return o;if(Array.isArray(r)&&typeof e===\"string\"&&hA.includes(e)){return(...c)=>{const l=r.slice();try{const u=o.apply(r,c);s();return u}catch(u){pA(r,l);throw u}}}return new Proxy(o,{apply:a((c,l,u)=>Reflect.apply(c,r,u),\"apply\")})}if(n?.(i)&&!dA(o))return o;return new Proxy(o,{set(c,l,u,f){const d=oS(c,l);try{const h=Reflect.set(c,l,u,f);s();return h}catch(h){iS(c,l,d);throw h}},get(c,l,u){return cS(c,l,u,s,n,i)},deleteProperty:a((c,l)=>{const u=oS(c,l);try{const f=Reflect.deleteProperty(c,l);s();return f}catch(f){iS(c,l,u);throw f}},\"deleteProperty\")})}a(cS,\"dynamicProxyProperty\");var aS=Symbol(\"DTO.DESCRIPTION\");var I=sa=class QU extends Hs{static{a(this,\"DTO\")}constructor(e={}){super();let t;const s=a(i=>{if(typeof i!==\"string\")return false;t??=Object.create(null);return t[i]??=fA(this,i)},\"acceptsAny\");const n=new Proxy(this,{set:a((i,o,c,l)=>{if(!bt(o))c=Qh(this,o,c);return Reflect.set(i,o,c,l)},\"set\"),get:a((i,o,c)=>cS(i,o,c,()=>{if(bt(o)){sa.validate({...this},na(this),{noDefaults:true})}else{Qh(this,o,Reflect.get(i,o))}},s,o),\"get\"),deleteProperty:a((i,o)=>{if(!bt(o))Qh(this,o,void 0);return Reflect.deleteProperty(i,o)},\"deleteProperty\")});try{const i=sa.validate(e,na(this));Object.keys(i).forEach(o=>Reflect.set(this,o,i[o]))}catch(i){throw hs(new ur(v(i).message),i)}return n}static prepareValidation(e,t){const s=e?$s.isSchema(e)?v(e):this.Schema():this.Schema();const n=t?t:e?$s.isSchema(e)?{}:v(e):{};return{schema:s,options:n}}static toJsonSchema(e=\"draft-2020-12\",t={}){return Zh(this,{...t,target:e})}static toOpenAPIJsonSchema(e=\"3.1\",t={}){return Zh(this,{...t,target:e===\"3.0\"?\"openapi-3.0\":\"openapi-3.1\"})}static fromJsonSchema(e,t={}){const s=nS(e,t);const n=this;const i=t.name||s.title||`${n.name}FromJsonSchema`;const o=v({[i]:class extends n{}}[i]);for(const[c,l]of Object.entries(s.keys))Al(o.prototype,c,v(l));qb(o,c=>v(s.refine(v(c))));if(s.description)o.description(s.description);return o}static fromOpenAPI(e,t={}){const s=e.openapi;const n=t.dialect||(typeof s===\"string\"&&s.startsWith(\"3.0\")?\"openapi-3.0\":\"openapi-3.1\");const i=e.components?.schemas;if(!i||typeof i!==\"object\")throw new Ue(\"The OpenAPI document has no schemas\");const o={};for(const[c,l]of Object.entries(i)){if(!l||typeof l!==\"object\")continue;const u=l.type;if(u!==void 0&&u!==\"object\")continue;const f=`#/components/schemas/${c.replace(/~/g,\"~0\").replace(/\\//g,\"~1\")}`;o[c]=this.fromJsonSchema({$ref:f},{...t,dialect:n,document:e,name:c})}return o}static description(e){Reflect.defineMetadata(aS,e,this);ei();return this}static Schema(){return ti(nA,this,()=>{const e=Hb(this);const t=Fb(this);const s=Reflect.getOwnMetadata(aS,this);const n=t?e.pattern(sa.String(),t):e;return s===void 0?n:n.description(s)})}static required(){return this.Schema().required()}static optional(){return this.Schema().optional()}static options(e){return this.Schema().options(e)}static isValid(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return $s.isValid(e,n,i)}static async isValidAsync(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return await $s.isValidAsync(e,n,i)}static validate(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return $s.validate(e,n,i)}static async validateAsync(e,t,s){const{schema:n,options:i}=this.prepareValidation(t,s);return await $s.validateAsync(e,n,i)}};I=sa=tA([(r=>jb(r)),rA(\"design:paramtypes\",[Object])],I);var zl=Ye(require(\"util\"),1);var Ks=class extends Z{static{a(this,\"DependencyInjectionException\")}constructor(){super(...arguments);this.errno=\"E_DEPENDENCY_INJECTION\"}};var o2=Ye(Bn(),1);var ep=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.LIFETIME\");var tp=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.LIFETIME.LOCK\");var rp=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.INJECTS\");var sp=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.CONFIGURABLE.PROPERTIES\");var Ml=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.SYMBOL\");var Dl=Symbol(\"LAKUTATA.DI.TARGET.CONSTRUCTOR.AUTOLOAD\");var np=Symbol(\"LAKUTATA.DI.TARGET.CONTAINER\");var Bl=Symbol(\"LAKUTATA.DI.TARGET.ID\");var lS=require(\"node:crypto\");var uS=new Map;function gs(r){if(!Reflect.hasOwnMetadata(Ml,r)){const e=Symbol((0,lS.randomUUID)());uS.set(e,r.name);Reflect.defineMetadata(Ml,e,r)}return Reflect.getOwnMetadata(Ml,r)}a(gs,\"constructorSymbol\");function ip(r){const e=uS.get(r);if(e)return e;return r}a(ip,\"resolveConstructorNameBySymbol\");var ia=class extends Ks{static{a(this,\"ExtendableError\")}constructor(e){super(e);Object.defineProperty(this,\"message\",{enumerable:false,value:e});Object.defineProperty(this,\"name\",{enumerable:false,value:this.constructor.name});if(\"captureStackTrace\"in Error){Error.captureStackTrace(this,this.constructor)}else{Object.defineProperty(this,\"stack\",{enumerable:false,value:Error(e).stack,writable:true,configurable:true})}}};var ys=class r extends ia{static{a(this,\"DependencyInjectionTypeError\")}constructor(e,t,s,n){super(`${e}: expected ${t} to be ${s}, but got ${n}.`)}static assert(e,t,s,n,i){if(!e){throw new r(t,s,n,i)}return e}};var Ws=class extends ia{static{a(this,\"DependencyInjectionResolutionError\")}constructor(e,t,s){if(bt(e))e=ip(e).toString();const n=e.split(\"_$$\").reverse()[0];t=t.map(c=>bt(c)?ip(c).toString():c.name);t.push(v(n));const i=t.join(\" -> \");let o=`Could not resolve '${n}'.`;if(s)o=`${o} ${s}`;o=`${o} Resolution path: ${i}`;super(o)}};var Ul=class extends ia{static{a(this,\"DependencyInjectionRegistrationError\")}constructor(e,t){const s=e.toString();let n=`Could not register '${s}'.`;if(t){n+=` ${t}`}super(n)}};var ke={SINGLETON:\"SINGLETON\",TRANSIENT:\"TRANSIENT\",SCOPED:\"SCOPED\"};function fS(r,e){return r===ke.SINGLETON&&e!==ke.SINGLETON||r===ke.SCOPED&&e===ke.TRANSIENT}a(fS,\"isLifetimeLonger\");var oi=require(\"node:fs\");var ct=Ye(require(\"node:path\"),1);var mA=/[*?[]/;function dS(r){const e=[];let t=0;let s=0;for(let n=0;n<r.length;n++){const i=r[n];if(i===\"\\\\\"){n++}else if(i===\"{\"){t++}else if(i===\"}\"){t--}else if(i===\",\"&&t===0){e.push(r.substring(s,n));s=n+1}}e.push(r.substring(s));return e}a(dS,\"splitAlternatives\");function gA(r){const e=/^(-?\\d+|[a-zA-Z])\\.\\.(-?\\d+|[a-zA-Z])(?:\\.\\.(-?\\d+))?$/.exec(r);if(!e)return void 0;const t=/\\d/.test(e[1]);if(t!==/\\d/.test(e[2]))return void 0;const s=t?parseInt(e[1]):e[1].charCodeAt(0);const n=t?parseInt(e[2]):e[2].charCodeAt(0);const i=Math.max(Math.abs(e[3]?parseInt(e[3]):1),1);const o=t&&(/^-?0\\d/.test(e[1])||/^-?0\\d/.test(e[2]))?Math.max(e[1].length,e[2].length):0;const c=[];for(let l=s;s<=n?l<=n:l>=n;l+=s<=n?i:-i){if(!t){c.push(String.fromCharCode(l))}else{const u=String(Math.abs(l)).padStart(o-(l<0?1:0),\"0\");c.push(l<0?`-${u}`:u)}}return c}a(gA,\"sequence\");function oa(r){let e=0;let t=-1;for(let s=0;s<r.length;s++){const n=r[s];if(n===\"\\\\\"){s++}else if(n===\"{\"){if(e++===0)t=s}else if(n===\"}\"&&e>0&&--e===0){const i=r.substring(0,t);const o=r.substring(t+1,s);const c=r.substring(s+1);const l=gA(o)??(dS(o).length>1?dS(o):void 0);if(!l)return oa(c).map(u=>`${i}{${o}}${u}`);return l.flatMap(u=>oa(`${i}${u}${c}`))}}return[r]}a(oa,\"expandBraces\");function yA(r,e){let t=e+1;let s=\"[\";if(r[t]===\"!\"||r[t]===\"^\"){s+=\"^\";t++}if(r[t]===\"]\"){s+=\"\\\\]\";t++}for(;t<r.length;t++){const n=r[t];if(n===\"]\")return{source:s+\"]\",end:t};if(n===\"\\\\\"&&t+1<r.length){s+=`\\\\${r[++t]}`}else if(n===\"[\"||n===\"^\"){s+=`\\\\${n}`}else{s+=n}}return void 0}a(yA,\"parseCharacterClass\");function bA(r){return r.replace(/\\\\(.)/g,\"$1\")}a(bA,\"unescape\");function SA(r){return mA.test(r.replace(/\\\\./g,\"\"))}a(SA,\"isMagic\");function op(r,e){if(r===\"**\")return{type:\"globstar\"};if(!SA(r))return{type:\"name\",name:bA(r)};let t=\"^\";for(let s=0;s<r.length;s++){const n=r[s];if(n===\"\\\\\"&&s+1<r.length){t+=r[++s].replace(/[.*+?^${}()|[\\]\\\\/]/g,\"\\\\$&\")}else if(n===\"*\"){while(r[s+1]===\"*\")s++;t+=\"[^/]*\"}else if(n===\"?\"){t+=\"[^/]\"}else if(n===\"[\"){const i=yA(r,s);if(i){t+=i.source;s=i.end}else{t+=\"\\\\[\"}}else{t+=n.replace(/[.*+?^${}()|[\\]\\\\/]/g,\"\\\\$&\")}}return{type:\"pattern\",regex:new RegExp(t+\"$\",e?\"i\":\"\"),dot:r[0]===\".\"}}a(op,\"compileSegment\");function hS(r,e){return r?aa(r,e):e}a(hS,\"joinRelative\");function aa(r,e){return r.endsWith(ct.default.sep)?r+e:r+ct.default.sep+e}a(aa,\"joinName\");function wA(r,e){const t=ct.default.isAbsolute(r);const s=t?ct.default.parse(r).root:\"\";const n=r.substring(s.length);const i=n.split(\"/\");const o=i.length>1&&i[i.length-1]===\"\";const c=i.filter((d,h)=>d!==\"\"||h===0&&i.length===1);const l=c.map(d=>op(d,e.nocase));let u=t?s:e.cwd;let f=t?s:\"\";while(l.length>1&&l[0].type===\"name\"){const d=l.shift().name;u=ct.default.join(u,d);f=t||f?ct.default.join(f,d):d}return{base:u,prefix:f,segments:l,directoryOnly:o}}a(wA,\"compilePattern\");function EA(r,e){const t=\"\\0\";return oa(r.replace(/^\\.\\//,\"\")).map(s=>{const n=s.split(\"/\").filter(i=>i!==\"\").map(i=>{if(i===\"**\")return t;const o=op(i,false);return o.type===\"pattern\"?o.regex.source.slice(1,-1):o.type===\"name\"?o.name.replace(/[.*+?^${}()|[\\]\\\\/]/g,\"\\\\$&\"):t}).join(\"/\").replace(new RegExp(`^${t}$`),\".*\").replace(new RegExp(`^${t}/`),\"(?:.*/)?\").replace(new RegExp(`/${t}/`,\"g\"),\"(?:/.*)?/\").replace(new RegExp(`/${t}$`),\"(?:/.*)?\");return new RegExp(`^${n}$`,e?\"i\":\"\")})}a(EA,\"compileIgnore\");function*TA(r,e,t){function*s(u){const f=yield{type:\"readdir\",path:u};if(!f)return[];const d=[];for(const h of f){const p=h.isSymbolicLink();let m=h.isDirectory();if(p){const y=yield{type:\"stat\",path:aa(u,h.name)};m=!!y&&y.isDirectory()}d.push({name:h.name,directory:m,link:p})}return d}a(s,\"entriesOf\");const n=a((u,f)=>u[0]!==\".\"||e.dot||f,\"visible\");const i=new Set;function*o(u,f,d){if(!u.link)return aa(d,u.name);return yield{type:\"realpath\",path:f}}a(o,\"realOf\");function*c(u,f,d,h,p){const m=r.segments[h];if(!m){t(f,u,true);return}const y=h===r.segments.length-1;if(m.type===\"globstar\"){const S=p??(yield*s(u));if(y){t(f,u,true)}else{yield*c(u,f,d,h+1,S)}for(const T of S){if(!n(T.name,false))continue;const _=aa(u,T.name);const x=hS(f,T.name);if(!T.directory){if(y)t(x,_,false);continue}if(T.link&&!e.follow){if(y)t(x,_,true);continue}const k=yield*o(T,_,d);if(!k||i.has(k))continue;i.add(k);yield*c(_,x,k,h);i.delete(k)}return}const w=[];if(m.type===\"name\"&&(m.name===\".\"||m.name===\"..\")){w.push({name:m.name,directory:true,link:false})}else if(m.type===\"name\"&&!e.nocase&&!p){const S=yield{type:\"stat\",path:ct.default.join(u,m.name)};if(S)w.push({name:m.name,directory:S.isDirectory(),link:false})}else{const S=m.type===\"name\"?e.nocase?m.name.toLowerCase():m.name:void 0;for(const T of p??(yield*s(u))){const _=m.type===\"name\"?(e.nocase?T.name.toLowerCase():T.name)===S:n(T.name,m.dot)&&m.regex.test(T.name);if(_)w.push(T)}}for(const S of w){const T=S.name===\".\"||S.name===\"..\";const _=T?ct.default.join(u,S.name):aa(u,S.name);const x=T?f?ct.default.join(f,S.name):S.name:hS(f,S.name);if(y){t(x,_,S.directory)}else if(S.directory){const k=yield*o(S,_,d);if(k)yield*c(_,x,k,h+1)}}}a(c,\"step\");if(!r.segments.length){const u=yield{type:\"stat\",path:r.base};if(u)t(r.prefix,r.base,u.isDirectory());return}const l=yield{type:\"realpath\",path:r.base};if(!l)return;i.add(l);yield*c(r.base,r.prefix,l,0)}a(TA,\"walkPattern\");function xA(r){const e=r.nocase??(process.platform===\"darwin\"||process.platform===\"win32\");const t=r.ignore===void 0?[]:Array.isArray(r.ignore)?r.ignore:[r.ignore];return{cwd:ct.default.resolve(r.cwd??process.cwd()),absolute:r.absolute??false,dot:r.dot??false,nodir:r.nodir??false,follow:r.follow??false,nocase:e,ignore:t.flatMap(s=>EA(s,e))}}a(xA,\"configure\");function RA(r,e){const t=xA(e);const s=new Map;const n=[];for(const i of Array.isArray(r)?r:[r]){for(const o of oa(i)){const c=wA(o,t);const l=ct.default.isAbsolute(o);n.push(TA(c,t,(u,f,d)=>{if(t.nodir&&d)return;if(c.directoryOnly&&!d)return;if(t.ignore.length){const h=ct.default.relative(t.cwd,f).split(ct.default.sep).join(\"/\")||\".\";if(t.ignore.some(p=>p.test(h)))return}s.set(f,t.absolute||l?f:u||\".\")}))}}return{walks:n,results:a(()=>[...new Set(s.values())].sort(),\"results\")}}a(RA,\"prepare\");function _A(r){try{switch(r.type){case\"readdir\":return(0,oi.readdirSync)(r.path,{withFileTypes:true});case\"stat\":return(0,oi.statSync)(r.path);case\"realpath\":return(0,oi.realpathSync)(r.path)}}catch{return null}}a(_A,\"answerSync\");function pS(r,e={}){const{walks:t,results:s}=RA(r,e);for(const n of t){let i;for(let o=n.next();!o.done;o=n.next(i))i=_A(o.value)}return s()}a(pS,\"GlobSync\");var jl=Ye(require(\"path\"),1);function mS(r){const e=[];r.forEach(t=>{t.forEach(s=>{e.push(s)})});return e}a(mS,\"flatten\");function gS(r,e){const t=r;if(typeof t===\"string\"||bt(t))return{[r]:e};return v(t)}a(gS,\"nameValueToObject\");function bs(r){if(typeof r!==\"function\")return false;const e=Object.getOwnPropertyDescriptor(r,\"prototype\");if(!e)return false;if(!e.writable)return true;return!!r.name&&r.name[0]===r.name[0].toUpperCase()}a(bs,\"isClass\");function Vs(r){return typeof r===\"function\"}a(Vs,\"isFunction\");function yS(r){return Array.from(new Set(r))}a(yS,\"uniq\");function CA(r,e){return pS(r,{cwd:e.cwd,nodir:true,follow:true,nocase:false})}a(CA,\"defaultGlob\");var vA=/(.*)\\..*/i;function bS(r,e){e={cwd:process.cwd(),glob:CA,...e};let t=null;if(Array.isArray(r)){t=r[1];r=r[0]}r=r.replace(/\\\\/g,\"/\");const s=e.glob(r,{cwd:e.cwd});const n=s.map(i=>({name:vA.exec(jl.basename(i))[1],path:jl.resolve(e.cwd,i),opts:t}));return n}a(bS,\"_listModules\");function $l(r,e){if(Array.isArray(r)){return mS(r.map(t=>bS(t,e)))}return bS(r,e)}a($l,\"listModules\");function SS(r){return import(r)}a(SS,\"importModule\");var vS=require(\"url\");var ca=Symbol(\"Dependency Injection Resolver Config\");function cp(r){return{resolve:a(()=>r,\"resolve\"),isLeakSafe:true}}a(cp,\"asValue\");function Hl(r,e){if(!Vs(r)){throw new ys(\"asFunction\",\"fn\",\"function\",r)}const t={lifetime:ke.TRANSIENT};e=wS(t,e,r[ca]);const s=TS(r);const n={resolve:s,...e};return lp(Fl(n))}a(Hl,\"asFunction\");function ai(r,e){if(!Vs(r)){throw new ys(\"asClass\",\"Type\",\"class\",r)}const t={lifetime:ke.TRANSIENT};e=wS(t,e,r[ca]);const s=a(function i(...o){return Reflect.construct(r,o)},\"newClass\");const n=TS(s);return lp(Fl({...e,resolve:n}))}a(ai,\"asClass\");function Fl(r){function e(s){return Fl({...this,lifetime:s})}a(e,\"setLifetime\");function t(s){return Fl({...this,injector:s})}a(t,\"inject\");return ES(r,{setLifetime:e,inject:t,transient:ap(e,ke.TRANSIENT),scoped:ap(e,ke.SCOPED),singleton:ap(e,ke.SINGLETON)})}a(Fl,\"createBuildResolver\");function lp(r){function e(t){return lp({...this,dispose:t})}a(e,\"disposer\");return ES(r,{disposer:e})}a(lp,\"createDisposableResolver\");function ap(r,e){return a(function t(){return r.call(this,e)},\"partiallyApplied\")}a(ap,\"partial\");function wS(r,...e){return Object.assign({},r,...e)}a(wS,\"makeOptions\");function ES(r,e){const t={...r,...e};return t}a(ES,\"updateResolver\");function AA(r,e){const t=e(r);const s=yS([...Reflect.ownKeys(r.cradle),...Reflect.ownKeys(t)]);const n=new Proxy({},{get(i,o){if(o===Symbol.iterator){return a(function*c(){for(const l in r.cradle){yield l}for(const l in t){yield l}},\"iterateRegistrationsAndLocals\")}if(o in t){return t[o]}return r.resolve(o)},ownKeys(){return s},getOwnPropertyDescriptor(i,o){if(s.indexOf(o)>-1){return{enumerable:true,configurable:true}}return void 0}});return n}a(AA,\"createInjectorProxy\");function TS(r){return a(function e(t){const s=this.injector?AA(t,this.injector):t.cradle;return r(s)},\"resolve\")}a(TS,\"generateResolve\");var IA=new RegExp(\"([\\\\p{Ll}\\\\d])(\\\\p{Lu})\",\"gu\");var OA=new RegExp(\"(\\\\p{Lu})([\\\\p{Lu}][\\\\p{Ll}])\",\"gu\");var kA=new RegExp(\"(\\\\d)(\\\\p{Ll})\",\"gu\");var PA=new RegExp(\"(\\\\p{L})(\\\\d)\",\"gu\");var NA=/[^\\p{L}\\d]+/giu;var ql=\"$1\\0$2\";function xS(r,e){let t=r.replace(IA,ql).replace(OA,ql);if(e&&e.separateNumbers){t=t.replace(kA,ql).replace(PA,ql)}t=t.replace(NA,\"\\0\");let s=0;let n=t.length;while(t.charAt(s)===\"\\0\")s++;if(s===n)return[];while(t.charAt(n-1)===\"\\0\")n--;return t.slice(s,n).split(/\\0/g)}a(xS,\"split\");function RS(r){return r===false?e=>e.toLowerCase():e=>e.toLocaleLowerCase(r)}a(RS,\"toLower\");function _S(r){return r===false?e=>e.toUpperCase():e=>e.toLocaleUpperCase(r)}a(_S,\"toUpper\");function CS(r,e){const t=RS(e?.locale);const s=_S(e?.locale);return xS(r,e).map((n,i)=>{if(i===0){return t(n)}const o=n[0];const c=o>=\"0\"&&o<=\"9\"?\"_\"+o:s(o);return c+t(n.slice(1))}).join(\"\")}a(CS,\"camelCase\");var LA={camelCase:a(r=>CS(r),\"camelCase\")};function up(r,e,t){t??={};const s=r.container;t=DA(t);const n=r.listModules(e,t);if(t.esModules){return MA(r,s,n,t)}else{const i=n.map(o=>{const c=r.require(o.path);return AS(c,o)});return IS(i,s,n,t)}}a(up,\"loadModules\");async function MA(r,e,t,s){const n=[];for(const c of t){const l=(0,vS.pathToFileURL)(c.path).toString();n.push(v(r.require(l)))}const i=await Promise.all(n);const o=[];for(let c=0;c<t.length;c++){o.push(v(AS(i[c],t[c])))}return IS(o,e,t,s)}a(MA,\"loadEsModules\");function AS(r,e){const t=[];if(!r)return t;if(Vs(r)){t.push({name:e.name,path:e.path,value:r,opts:e.opts});return t}if(r.default&&Vs(r.default)){t.push({name:e.name,path:e.path,value:r.default,opts:e.opts})}for(const s of Object.keys(r)){if(s===\"default\")continue;if(Vs(r[s])&&ca in r[s]){t.push({name:s,path:e.path,value:r[s],opts:e.opts})}}return t}a(AS,\"parseLoadedModule\");function IS(r,e,t,s){r.reduce((n,i)=>n.concat(i),[]).filter(n=>n).forEach(BA.bind(null,e,s));return{loadedModules:t}}a(IS,\"registerModules\");function DA(r){return{resolverOptions:{lifetime:ke.TRANSIENT,...r&&r.resolverOptions},...r}}a(DA,\"optsWithDefaults\");function BA(r,e,t){const s=t.value[ca];let n=s&&s.name;if(!n){n=t.name;let l=e.formatName;if(l){if(typeof l===\"string\"){l=LA[l]}if(l){n=l(n,t)}}}let i=t.opts;if(typeof i===\"string\"){i={lifetime:i}}const o={...e.resolverOptions,...i,...s};const c=o.register?o.register:bs(t.value)?ai:Hl;r.register(n,c(t.value,o))}a(BA,\"registerDescriptor\");var la=class extends Z{static{a(this,\"LifetimeLockedException\")}constructor(){super(...arguments);this.errno=\"E_LIFETIME_LOCKED\"}};function ci(r){return Reflect.getMetadata(ep,r)}a(ci,\"getObjectLifetime\");function UA(r){return!!Reflect.getMetadata(tp,r)}a(UA,\"getObjectLifetimeLocked\");function OS(r,e,t=false){if(UA(r)&&ci(r)!==e)throw new la(\"[{0}] Object lifecycle settings cannot be applied because the parent object lifecycle of the current operation object is locked\",[r.name]);if(t)Reflect.defineMetadata(tp,true,r);Reflect.defineMetadata(ep,e,r);return r}a(OS,\"setObjectLifetime\");var Ss=Symbol(\"OWR\");var fp=Symbol(\"OFR\");function dp(r){if(!Reflect.hasOwnMetadata(fp,r))Reflect.defineMetadata(fp,new FinalizationRegistry(e=>{const t=Reflect.getOwnMetadata(Ss,r)||new Set;t.delete(e);Reflect.defineMetadata(Ss,t,r)}),r);if(!Reflect.hasOwnMetadata(Ss,r))Reflect.defineMetadata(Ss,new Set,r);return Reflect.getOwnMetadata(Ss,r)}a(dp,\"getObjectWeakRefs\");function ua(r,e){const t=dp(r);const s=new WeakRef(e);v(Reflect.getOwnMetadata(fp,r)).register(e,s);t.add(s);Reflect.defineMetadata(Ss,t,r)}a(ua,\"appendObjectWeakRefs\");function kS(r){if(!Reflect.hasOwnMetadata(Ss,r))return;Reflect.deleteMetadata(Ss,r)}a(kS,\"clearObjectWeakRefs\");var PS=Symbol(\"familyTree\");var NS=Symbol(\"rollUpRegistrations\");var jA=\"DependencyInjectionContainerCradle\";function hp(r={}){return LS(r)}a(hp,\"createContainer\");function LS(r,e,t){r={strict:false,...r};const s=t??[];const n={};const i=new Proxy({[zl.inspect.custom]:p},{get:a((x,k)=>y(k),\"get\"),set:a((x,k)=>{throw new Error(`Attempted setting property \"${k}\" on container cradle - this is not allowed.`)},\"set\"),ownKeys(){return Array.from(i)},getOwnPropertyDescriptor(x,k){const N=u();if(Object.getOwnPropertyDescriptor(N,k)){return{enumerable:true,configurable:true}}return void 0}});const o={options:r,cradle:i,inspect:l,cache:new Map,loadModules:T,createScope:d,register:h,build:S,resolve:y,hasRegistration:w,dispose:_,getRegistration:m,[zl.inspect.custom]:l,[NS]:u,get registrations(){return u()}};const c=e?[o].concat(v(e)[PS]):[o];o[PS]=c;return o;function l(){return`[DependencyInjectionContainer (${e?\"scoped, \":\"\"}registrations: ${Object.keys(o.registrations).length})]`}a(l,\"inspect\");function u(){return{...e&&e[NS](),...n}}a(u,\"rollUpRegistrations\");function*f(){const x=u();for(const k in x){yield k}}a(f,\"cradleIterator\");function d(){return LS(r,o,s)}a(d,\"createScope\");function h(x,k){const N=gS(x,k);const A=[...Object.keys(N),...Object.getOwnPropertySymbols(N)];for(const B of A){const ee=N[B];if(r.strict&&ee.lifetime===ke.SINGLETON){if(e){throw new Ul(B,\"Cannot register a singleton on a scoped container.\")}}n[B]=ee}return o}a(h,\"register\");function p(){return Object.prototype.toString.call(i)}a(p,\"toStringRepresentationFn\");function m(x){const k=n[x];if(k){return k}if(e){return e.getRegistration(x)}return null}a(m,\"getRegistration\");function y(x,k){k=k||{};try{const N=m(x);if(N&&!r.strict){const fe=N.lifetime||ke.TRANSIENT;if(fe!==ke.TRANSIENT){const Rt=o.cache.get(x);if(Rt!==void 0)return Rt.value}}for(let fe=0;fe<s.length;fe++){if(s[fe].name===x){throw new Ws(x,s,\"Cyclic dependencies detected.\")}}if(x===\"toJSON\"){return p}if(x===\"constructor\"){return hp}if(!N){switch(x){case zl.inspect.custom:case\"inspect\":case\"toString\":return p;case Symbol.toStringTag:return jA;case\"then\":return void 0;case Symbol.iterator:return f}if(k.allowUnregistered){return void 0}throw new Ws(x,s)}const A=N.lifetime||ke.TRANSIENT;if(r.strict&&!N.isLeakSafe){const fe=s.findIndex(({lifetime:Rt})=>fS(Rt,A));if(fe>-1){throw new Ws(x,s,`Dependency '${x.toString()}' has a shorter lifetime than its ancestor: '${s[fe].name.toString()}'`)}}s.push({name:x,lifetime:A});let B;let ee;switch(A){case ke.TRANSIENT:ee=N.resolve(o);break;case ke.SINGLETON:B=o.cache.get(x);if(B!==void 0){ee=B.value;break}ee=N.resolve(o);o.cache.set(x,{resolver:N,value:ee});break;case ke.SCOPED:B=o.cache.get(x);if(B!==void 0){ee=B.value;break}ee=N.resolve(o);o.cache.set(x,{resolver:N,value:ee});break;default:throw new Ws(x,s,`Unknown lifetime \"${N.lifetime}\"`)}s.pop();if(ci(ee.constructor)===ke.TRANSIENT)ua(this,ee);return ee}catch(N){s.length=0;throw N}}a(y,\"resolve\");function w(x){return!!m(x)}a(w,\"hasRegistration\");function S(x,k){if(x&&x.resolve){return x.resolve(o)}const N=\"build\";const A=\"targetOrResolver\";ys.assert(x,N,A,\"a registration, function or class\",x);ys.assert(typeof x===\"function\",N,A,\"a function or class\",x);const B=bs(x)?ai(x,k):Hl(x,k);return B.resolve(o)}a(S,\"build\");function T(x,k){const N={require:r.require||function(A){return require(A)},listModules:$l,container:o};if(k?.esModules){N.require=SS;return up(N,x,k).then(()=>o)}else{up(N,x,k);return o}}a(T,\"loadModules\");async function _(){const x=Array.from(o.cache.entries());o.cache.clear();return Promise.all(x.map(async([,k])=>{const{resolver:N,value:A}=k;const B=N;if(B.dispose){await Promise.resolve();return B.dispose(A)}return Promise.resolve()})).then(()=>void 0)}a(_,\"dispose\")}a(LS,\"createContainerInternal\");function MS(r){return(typeof r===\"object\"||typeof r===\"function\")&&r!==null&&typeof r.then===\"function\"}a(MS,\"isPromiseLike\");function BS(r,e,t){async function s(){await Promise.resolve();await Reflect.apply(e,r,t!==null&&t!==void 0?t:[]);delete r[\"then\"];return r}a(s,\"applyAsyncConstructor\");if(MS(r)){DS(r,Promise.resolve(r).then(s))}else{DS(r,s())}}a(BS,\"appendAsyncConstructor\");function DS(r,e){r.then=e.then.bind(e)}a(DS,\"setThenMethod\");var Gl=class extends Object{static{a(this,\"AsyncConstructor\")}constructor(e){super();BS(this,e)}};function Kl(r,e=false){return t=>OS(t,r,e)}a(Kl,\"Lifetime\");function Xs(r=false){return Kl(\"SINGLETON\",r)}a(Xs,\"Singleton\");function fa(r=false){return Kl(\"TRANSIENT\",r)}a(fa,\"Transient\");function pp(r=false){return Kl(\"SCOPED\",r)}a(pp,\"Scoped\");var da=class extends Z{static{a(this,\"MethodNotFoundException\")}constructor(){super(...arguments);this.errno=\"E_METHOD_NOT_FOUND\"}};var lw=require(\"node:crypto\");var US=new WeakMap;function jS(r,e){US.set(r,e)}a(jS,\"setConfigurableRecords\");function $S(r){return(r&&US.get(r))??{}}a($S,\"getConfigurableRecords\");function FS(r,e){Reflect.defineMetadata(Bl,e,r)}a(FS,\"setIdToInstance\");function HS(r){const e=Reflect.getOwnMetadata(Bl,r);if(typeof e===\"string\")return e;if(gs(v(r.constructor))!==e)return e;return void 0}a(HS,\"getIdFromInstance\");function Wl(r){return Reflect.getOwnMetadata(Bl,r)}a(Wl,\"getRegistrationNameFromInstance\");function qS(r,e){Reflect.defineMetadata(r.$uuid,e,r)}a(qS,\"setConfigurableRecordsToInstance\");function mp(r){const e=Reflect.getOwnMetadata(r.$uuid,r);if(e)return e;return{}}a(mp,\"getConfigurableRecordsFromInstance\");var Vl=Symbol(\"REMOVED\");function Xl(r,e){let t=Reflect.getOwnMetadata(r,e);if(!t){t=new Map;Reflect.defineMetadata(r,t,e)}return t}a(Xl,\"ownDeclarations\");function Yl(r,e){const t=new Map;for(const s of[...ps(e).reverse(),e]){const n=Reflect.getOwnMetadata(r,s);n?.forEach((i,o)=>{if(i===Vl){t.delete(o)}else{t.set(o,i)}})}return t}a(Yl,\"mergedDeclarations\");function zS(r,e,t=I.Any(),s){Xl(sp,me(r)).set(e,{schema:t,fn:s?s:n=>n})}a(zS,\"setObjectConfigurableProperty\");function Jl(r){return Yl(sp,me(r))}a(Jl,\"getObjectConfigurableProperties\");function GS(r,e){Xl(rp,me(r)).set(e,Vl)}a(GS,\"removeObjectInjectItem\");function KS(r){return Yl(rp,me(r))}a(KS,\"getObjectInjectItemsByPrototype\");function WS(r){if(!Reflect.hasOwnMetadata(Dl,r))Reflect.defineMetadata(Dl,true,r);return r}a(WS,\"markObjectAsAutoload\");function VS(r){return!!Reflect.getOwnMetadata(Dl,r)}a(VS,\"getObjectIsAutoload\");function XS(r,e){Reflect.defineMetadata(np,()=>e,r)}a(XS,\"setObjectContainerGetter\");function ha(r){const e=Reflect.getOwnMetadata(np,r);return e()}a(ha,\"getObjectContainer\");function pa(r,e){return typeof r===\"function\"&&!!r.prototype&&r.prototype instanceof e}a(pa,\"isSubclassOf\");var ma=Symbol(\"OBJECT.TYPE\");var je;(function(r){r[\"Unknown\"]=\"Unknown\";r[\"Object\"]=\"Object\";r[\"Provider\"]=\"Provider\";r[\"Component\"]=\"Component\";r[\"Module\"]=\"Module\"})(je||(je={}));var gp;function YS(r){gp=r}a(YS,\"registerBaseObject\");function ws(r){return e=>JS(e,r)}a(ws,\"DefineObjectType\");function JS(r,e){Reflect.defineMetadata(ma,gp&&pa(r,gp)?e:je.Unknown,r);return r}a(JS,\"setObjectType\");function ga(r){if(Reflect.hasOwnMetadata(ma,r))return Reflect.getOwnMetadata(ma,r);let e=je.Unknown;for(const t of ps(r)){if(Reflect.hasOwnMetadata(ma,t)){e=Reflect.getOwnMetadata(ma,t);break}}JS(r,e);return ga(r)}a(ga,\"getObjectType\");var yp;var ZS=new WeakSet;var Zl=new WeakMap;function QS(r){yp=r}a(QS,\"declareApplicationClass\");function ew(r){ZS.add(r);Zl.get(r)?.resolve();Zl.delete(r)}a(ew,\"markApplicationLaunched\");function tw(r){let e=r;while(e&&!(yp&&e instanceof v(yp)))e=e.getParent?.();if(!e)return void 0;if(ZS.has(e))return Promise.resolve();let t=Zl.get(e);if(!t){let s=a(()=>void 0,\"resolve\");const n=new Promise(i=>{s=i});t={promise:n,resolve:s};Zl.set(e,t)}return t.promise}a(tw,\"whenApplicationLaunched\");var rw=require(\"node:async_hooks\");var bp=new rw.AsyncLocalStorage;var Sp=new WeakMap;function sw(r,e){const t={object:r,active:true};const s=bp.run([...bp.getStore()??[],t],async()=>{try{await e()}finally{t.active=false}});const n={promise:s,ended:false};s.catch($t).finally(()=>n.ended=true);Sp.set(r,n);return s}a(sw,\"runObjectStartup\");function nw(r){return!!bp.getStore()?.some(e=>e.active&&e.object===r)}a(nw,\"isInObjectStartup\");async function li(r){const e=Sp.get(r);if(!e||nw(r))return;await e.promise}a(li,\"waitForObjectStartup\");function wp(r){const e=Sp.get(r);if(!e||e.ended||nw(r))return void 0;return e.promise.catch($t)}a(wp,\"waitForObjectStartupEnd\");var iw=a((r,e)=>{_r(`${e}: ${r.stack?r.stack:r.message}`)},\"defaultLifecycleErrorReporter\");var ow=iw;function aw(r){ow=r?r:iw}a(aw,\"setLifecycleErrorReporter\");function Ep(r,e){if(r instanceof AggregateError)return r.errors.flatMap(s=>Ep(s,r.message));const t=r instanceof Error?r:new Error(String(r));return[e?new Error(`${e}: ${t.message}`,{cause:t}):t]}a(Ep,\"flatten\");function cw(r,e){for(const t of r){try{ow(t,e)}catch{}}}a(cw,\"report\");function Ql(r,e){const t=e&&!(r instanceof AggregateError)?`Failed to destroy object \"${e}\"`:void 0;cw(Ep(r,t),\"An error occurred while destroying an object\")}a(Ql,\"reportDestroyError\");function Tp(r,e){cw(Ep(r,`Failed to run the launched() hook of object \"${e}\"`),\"An error occurred in the launched() hook of an object\")}a(Tp,\"reportLaunchedError\");var Es=class extends Z{static{a(this,\"ObjectDestroyedException\")}constructor(){super(...arguments);this.errno=\"E_OBJECT_DESTROYED\"}};var $A=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var FA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var ya;var dr=Symbol(\"__init\");var st=Symbol(\"__destroy\");var ba=Symbol(\"__revive\");var HA=Symbol(\"anonymous\");var xp=Symbol(\"OBJECT.SYMBOL.PROPERTY\");var Re=ya=class U$ extends Gl{static{a(this,\"BaseObject\")}#e;#t;#r=(0,lw.randomUUID)();#s=false;#u=false;#n=\"constructing\";#a;#o;#c=0;#i(){if(this.#n===\"destroying\"||this.#n===\"destroyed\")throw new Es('Object \"{className}\" has been destroyed',{className:this.className})}async#f(){const e=mp(this);const t=[];Jl(this).forEach((s,n)=>{if(bt(n))return;const i=e[v(n)];const o=i!==void 0?i:this[n];t.push(new Promise((c,l)=>{I.validateAsync(o,s.schema,{targetName:n}).then(u=>{return Promise.resolve(s.fn.bind(this)(u)).then(f=>{this[n]=f;return c()}).catch(l)}).catch(l)}))});await Promise.all(t)}async#m(){const e=KS(this);const t=[];e.forEach((s,n)=>{const i=v(s.name);t.push(new Promise((o,c)=>{this.#e.get(i).then(l=>{Promise.resolve(s.transform(l)).then(u=>{Reflect.set(this,n,u);return o()}).catch(c)}).catch(l=>c(new Ks(\"Unable to inject value for property {0} of {1} because: {2}\",[n,this.className,l.message])))}))});await Promise.all(t)}#l(){const e=HS(this);this.#t=e?e:HA}constructor(e){super(async()=>{this.#l();const t=Object.getOwnPropertyDescriptor(this,\"then\");if(t)Object.defineProperty(this,\"then\",{enumerable:false});await this[dr]()});this.#e=new Wt(e[Rp],this);XS(this,this.#e);if(this.beforeDestroy!==ya.prototype.beforeDestroy){uw(this.#e,()=>this.#o?Promise.resolve():this.#d())}}#d(){return this.#o??=(async()=>{const e=wp(this);if(e)await e;await this.beforeDestroy()})()}static get className(){return this.name}static acceptsOption(e,t){$t(e,t);return false}get className(){return me(this).name}async[dr](...e){this.#i();this.#e.registerContainerToItsParent();if(!this.#s){await this.#m();this.#s=true}if(!this.#u){await this.#f();this.#u=true}for(const t of e)await t();await this.init();this.#i();this.#n=\"ready\";if(this.startup!==ya.prototype.startup)void sw(this,()=>this.startup());if(this.launched!==ya.prototype.launched)this.#h()}#h(){const e=++this.#c;const t=a(()=>{if(e!==this.#c||this.#n!==\"ready\")return;try{Promise.resolve(this.launched()).catch(s=>Tp(s,this.className))}catch(s){Tp(s,this.className)}},\"run\");void(tw(this)??Promise.resolve()).then(()=>li(this)).then(t,$t)}[ba](){if(this.#n!==\"destroyed\")return;this.#e.revive();this.#a=void 0;this.#o=void 0;this.#s=false;this.#n=\"constructing\"}async[st](...e){if(this.#a)return await this.#a.catch($t);this.#n=\"destroying\";this.#a=(async()=>{const t=[];const s=wp(this);if(s)await s;if(this.#o){await this.#o.catch($t)}else{try{await this.#d()}catch(n){t.push(n)}}await this.#e.destroy();for(const n of e){try{await n()}catch(i){t.push(i)}}try{await this.destroy()}catch(n){t.push(n)}this.#n=\"destroyed\";if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,`Failed to destroy object \"${this.className}\"`)})();return await this.#a}async init(){}async startup(){}async launched(){}async beforeDestroy(){}async destroy(){}async getObject(e,t={}){this.#i();return await this.#e.get(e,t)}async buildObject(e,t={}){this.#i();return this.#e.build(e,t)}getConfigurableRecords(){return{...mp(this)}}getParent(){return this.#e.parent?.owner()}getModule(){let e=this.getParent();while(e&&ga(v(me(e)))!==je.Module){e=e.getParent()}return v(e)}get $uuid(){return this.#r}get $id(){return this.#t}get $symbol(){if(Reflect.hasOwnMetadata(xp,this))return Reflect.getOwnMetadata(xp,this);Reflect.defineMetadata(xp,Symbol(this.$uuid),this);return this.$symbol}setProperty(e,t){this[e]=t}getProperty(e,t){if(this.hasProperty(e))return v(this[e]);return v(t)}hasProperty(e){return typeof e===\"string\"?this.propertyNames().includes(e):this.propertySymbols().includes(e)}propertySymbols(){return Object.getOwnPropertySymbols(this)}propertyNames(){return Object.getOwnPropertyNames(this)}hasMethod(e){const t=this.hasProperty(e);if(t)return false;return typeof this[e]===\"function\"}getMethod(e,t=false){if(this.hasMethod(e)){const s=a((...n)=>this[e](...n),\"callMethod\");return s}else if(t){throw new da('Method \"{methodName}\" not found in \"{className}\"',{methodName:e,className:this.constructor.name})}else{return(...s)=>$t(...s)}}async dispose(){try{await this[st]()}finally{const e=Wl(this);if(e!==void 0)this.#e.parent?.forget(e,this)}}async[Symbol.asyncDispose](){await this.dispose()}};Re=ya=$A([fa(),ws(je.Object),FA(\"design:paramtypes\",[Object])],Re);YS(Re);function ve(r){return(e,t)=>Al(e,t,r)}a(ve,\"Expect\");function hr(r){return e=>$b(e,r)}a(hr,\"IndexSignature\");var _p=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var fw=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var dw;var lt=Symbol(\"OBJECT_ID\");var Ir=class J$ extends I{static{a(this,\"LoadObjectOptions\")}static{dw=lt}};_p([ve(I.Alternatives(I.String(),I.Symbol()).optional()),fw(\"design:type\",Object)],Ir.prototype,dw,void 0);_p([ve(I.Class(()=>Re).required()),fw(\"design:type\",Object)],Ir.prototype,\"class\",void 0);Ir=_p([hr(I.Any())],Ir);var hw=require(\"node:util/types\");var ui=class extends Z{static{a(this,\"InvalidMethodAcceptException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_METHOD_ACCEPT\"}};function pw(r,e,t,s){const n=[];s.forEach(l=>n.push(Fh(v(l))?v(l).Schema():v(l)));t.writable=false;const i=t.value;const o=I.Array().sparse(true).ordered(...n);const c=Array.isArray(n)?n.length:1;if((0,hw.isAsyncFunction)(i)){t.value=async function(...l){const u=l.length-c;try{l=await I.validateAsync(l,o.concat(I.Array().sparse(true).ordered(...new Array(u>=0?u:0).fill(I.Any()))))}catch(f){throw hs(new ui(\"Method [{propertyKey}] accept argument {reason}\",{propertyKey:e,reason:f.message}),f)}return i.apply(this,l)}}else{t.value=function(...l){const u=l.length-c;try{l=I.validate(l,o.concat(I.Array().sparse(true).ordered(...new Array(u>=0?u:0).fill(I.Any()))))}catch(f){throw hs(new ui(\"Method [{propertyKey}] accept argument {reason}\",{propertyKey:e,reason:f.message}),f)}return i.apply(this,l)}}return t}a(pw,\"setMethodAcceptArgumentsValidator\");function Sa(...r){return(e,t,s)=>pw(e,t,s,r)}a(Sa,\"Accept\");var gw=require(\"url\");var eu=Symbol(\"LAKUTATA.MODULE.INITIALIZATION\");function tu(r){if(r===null||r===void 0)return true;if(typeof r!==\"object\"&&typeof r!==\"function\")return false;if(r instanceof Map||r instanceof Set)return r.size===0;return!Object.getOwnPropertyNames(r).length&&!Object.getOwnPropertySymbols(r).length}a(tu,\"isEmptyObject\");var zA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Cp=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Rp=Symbol(\"LAKUTATA.DI.CONTAINER.SYMBOL\");var mw=Symbol(\"LAKUTATA.DI.OWNER.SYMBOL\");var vp=new WeakMap;function uw(r,e){let t=vp.get(r);if(!t)vp.set(r,t=new Set);t.add(e);return()=>void t.delete(e)}a(uw,\"registerTeardownHook\");var Wt=class r{static{a(this,\"Container\")}#e;static#t=new FinalizationRegistry(({refs:e,ref:t})=>e.delete(t));#r;#s;#u;#n;#a;#o;constructor(e,t){this.#r=new Set;this.#s=new Set;this.#u=new WeakRef(this);this.#n=false;this.injectionNames=new Set;this.parent=e;this.#o=!e;this.#e=e?e.#e.createScope():hp({strict:false});if(this.parent)r.#t.register(this,{refs:this.parent.#s,ref:this.#u});this.#c();this.#e.register(Rp,cp(this));if(t)this.#e.register(mw,cp(new WeakRef(t)))}#c(){if(!this.parent)return;if(this.#o){this.parent.#r.add(this)}else{this.parent.#s.add(this.#u)}}#i(e){return ai(e,v(this.buildResolverOptions(e)))}#f(){if(this.#n)throw new Es(\"The container has been destroyed\")}#m(){let e=this;while(!e.#o&&e.parent)e=e.parent;return e}#l(){let e=this;while(e.parent)e=e.parent;return e}#d(){if(!this.parent)return;this.parent.#r.delete(this);this.parent.#s.delete(this.#u)}async disposer(e){try{await e.getMethod(st,false)()}catch(t){Ql(t,e.className)}}buildResolverOptions(e){const t=ci(e);return{lifetime:t,dispose:a(s=>this.disposer(s),\"dispose\")}}async processResolved(e,t,s={}){const n=pa(e?.constructor,Re);const i=n&&Wl(v(e))===void 0;if(n&&!i&&!tu(s)&&process.env.NODE_ENV!==\"production\"){_r(`The configuration passed for the already created object \"${v(e).className}\" is ignored. Use a scoped or transient object to get an instance with its own configuration.`)}if(i){const o=$S(this.#e.getRegistration(t));FS(v(e),t);qS(v(e),{...o,...s})}return Promise.resolve(e)}buildNameAndRegistrationPairFromOptions(e){const t={};const s=e[lt]?e[lt]:gs(e.class);const n={...e,class:void 0};delete n.id;delete n.class;t[s]=this.#i(e.class);jS(t[s],n);return t}async buildNameAndRegistrationPairFromGlob(e){const t=await Promise.all($l(e).map(async s=>{let n;try{n=await import((0,gw.pathToFileURL)(s.path).toString())}catch(o){throw new Error(`The file ${s.path} matched by \"${e}\" cannot be imported: ${o?.message??o}`,{cause:o})}const i={};for(const o of Object.values(n)){if(bs(o)&&pa(o,Re))i[gs(o)]=this.#i(v(o))}return i}));return Object.assign({},...t)}owner(){const e=this.#e.resolve(mw,{allowUnregistered:true});return e?e.deref():void 0}async load(e){this.#f();let t={};const s=[];e.forEach(n=>{if(typeof n===\"string\"){s.push(this.buildNameAndRegistrationPairFromGlob(n))}else if(bs(v(n))){const i={class:v(n)};t={...t,...this.buildNameAndRegistrationPairFromOptions(i)}}else{const i=v(n);t={...t,...this.buildNameAndRegistrationPairFromOptions(i)}}});if(s.length){const n=await Promise.all(s);n.forEach(i=>{t={...i,...t}})}if(!tu(t)){Object.getOwnPropertyNames(t).forEach(n=>this.injectionNames.add(n));Object.getOwnPropertySymbols(t).forEach(n=>this.injectionNames.add(n));this.#e.register(t)}}async get(e,t={}){return await this.#h(e,t,false)}async getShared(e,t={}){return await this.#h(e,t,true)}async#h(e,t,s){const n=typeof e===\"function\"?gs(e):e;this.#f();if(!this.#e.hasRegistration(n)&&typeof e===\"function\"&&VS(v(e))){const u=v(ci(v(e)));const f=u===\"SCOPED\"?this.#m():u===\"SINGLETON\"?this.#l():this;await f.load([{id:n,class:v(e)}])}const i=this.#e.getRegistration(n);const o=i?.lifetime;if(!s&&i&&o===\"SCOPED\"&&!tu(t)){const u=await this.processResolved(this.#e.build(i),n,t);ua(this.#e,u);await li(u);return u}let c=this;if(o===\"SINGLETON\"){while(!c.injectionNames.has(n)&&c.parent)c=c.parent}else if(o===\"SCOPED\"){while(!c.injectionNames.has(n)&&!c.#o&&c.parent)c=c.parent}c.#f();const l=await c.processResolved(c.#e.resolve(n),n,t);await this.#g(l);await li(l);return l}async#g(e){const t=e?.[eu];if(typeof t!==\"function\")return;for(let s=this;s;s=s.parent)if(s.owner()===e)return;await t.call(e)}has(e){if(typeof e===\"function\")return this.#e.hasRegistration(gs(e));return this.#e.hasRegistration(e)}async set(e,t={}){if(!this.has(e)){await this.load([{...t,class:e}])}return await this.get(e,{...t})}async setNamed(e,t,s={}){await this.load([{...s,class:t,[lt]:e}]);return await this.get(e)}async register(e,t={}){await this.load([{...t,class:e}])}async registerNamed(e,t,s={}){await this.load([{...s,class:t,[lt]:e}])}async build(e,t={}){this.#f();const s=await this.processResolved(this.#e.build(e,this.buildResolverOptions(e)),gs(e),t);ua(this.#e,s);await li(s);return s}createScope(){this.#f();const e=new r(this,this.owner());e.#d();e.#o=true;e.#c();return e}registerContainerToItsParent(){this.#c()}revive(){if(this.parent&&this.parent.#n)throw new Es(\"Cannot revive a container whose parent container has been destroyed\");this.#n=false;this.#a=void 0;this.#c()}forget(e,t){const s=this.#e.cache.get(e);if(s&&s.value===t)this.#e.cache.delete(e)}async clear(){const e=vp.get(this);if(e?.size){const n=await Promise.allSettled([...e].map(i=>i()));n.forEach(i=>i.status===\"rejected\"&&Ql(i.reason))}const t=[...this.#r];this.#s.forEach(n=>{const i=n.deref();if(i)t.push(i)});await Promise.all(t.map(n=>n.destroy()));try{await this.#e.dispose()}catch(n){Ql(n)}const s=[];dp(this.#e).forEach(n=>{const i=n.deref();if(i)s.push(i)});await Promise.all(s.map(n=>this.disposer(n)));kS(this.#e)}async destroy(){if(this.#a)return await this.#a;this.#n=true;this.#d();this.#a=this.clear();await this.#a}};zA([Sa(I.Array(I.Alternatives(Ir.Schema(),I.Class(()=>Re),I.Glob()))),Cp(\"design:type\",Function),Cp(\"design:paramtypes\",[Array]),Cp(\"design:returntype\",Promise)],Wt.prototype,\"load\",null);var GA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Ys=class KF extends Re{static{a(this,\"Provider\")}getEnv(e,t){const s=process.env[e];return s===void 0&&t!==void 0?t:s}};Ys=GA([pp(),ws(je.Provider)],Ys);var pr=Reflect.ownKeys;function ru(){return Object.create(null)}a(ru,\"node\");var su=class r{static{a(this,\"EventEmitter2\")}static get defaultMaxListeners(){return r.prototype._maxListeners}static set defaultMaxListeners(e){if(typeof e!==\"number\"||e<0||Number.isNaN(e))throw TypeError(\"n must be a non-negative number\");r.prototype._maxListeners=e}static{r.prototype._maxListeners=10}constructor(e){this.delimiter=\".\";this.event=\"\";this.verboseMemoryLeak=false;this._newListener=false;this._removeListener=false;this._events={};this.configure(e)}init(){this._events={};if(this._conf)this.configure(this._conf)}configure(e){if(!e)return;this._conf=e;if(e.delimiter)this.delimiter=e.delimiter;if(e.maxListeners!==void 0)this._maxListeners=e.maxListeners;if(e.wildcard)this.wildcard=e.wildcard;if(e.newListener)this._newListener=e.newListener;if(e.removeListener)this._removeListener=e.removeListener;if(e.verboseMemoryLeak)this.verboseMemoryLeak=e.verboseMemoryLeak;if(e.ignoreErrors)this.ignoreErrors=e.ignoreErrors;if(this.wildcard)this.listenerTree=ru()}logPossibleMemoryLeak(e,t){let s=`(node) warning: possible EventEmitter memory leak detected. ${e} listeners added. Use emitter.setMaxListeners() to increase limit.`;if(this.verboseMemoryLeak)s+=` Event name: ${String(t)}.`;const n=new Error(s);n.name=\"MaxListenersExceededWarning\";n.emitter=this;n.count=e;process.emitWarning(n)}split(e){if(typeof e!==\"string\")return e;const t=[];let s=0;let n;while((n=e.indexOf(this.delimiter,s))!==-1){t.push(e.slice(s,n));s=n+this.delimiter.length}t.push(e.slice(s));return t}searchListenerTree(e,t,s,n,i){if(!s)return null;if(n===0){const p=typeof t;if(p===\"string\"){const m=this.split(t);i=m.length;t=m.length>1&&m.length<5?Object.assign(new Array(5),m):m}else if(p===\"object\"){i=t.length}else{t=[t];i=1}}let o=null;let c;const l=t[n];const u=t[n+1];const f=a(p=>{if(!p)return;if(o)o.push(...p);else o=p},\"add\");if(n===i){if(s._listeners){if(typeof s._listeners===\"function\")e?.push(s._listeners);else e?.push(...s._listeners);o=[s]}}else if(l===\"*\"){const p=pr(s);let m=p.length;while(m-- >0){const y=p[m];if(y!==\"_listeners\")f(this.searchListenerTree(e,t,s[y],n+1,i))}return o}else if(l===\"**\"){const p=n+1===i||n+2===i&&u===\"*\";if(p&&s._listeners)o=this.searchListenerTree(e,t,s,i,i);const m=pr(s);let y=m.length;while(y-- >0){const w=m[y];if(w===\"_listeners\")continue;if(w===\"*\"||w===\"**\"){if(s[w]._listeners&&!p)f(this.searchListenerTree(e,t,s[w],i,i));c=this.searchListenerTree(e,t,s[w],n,i)}else if(w===u){c=this.searchListenerTree(e,t,s[w],n+2,i)}else{c=this.searchListenerTree(e,t,s[w],n,i)}f(c)}return o}else if(s[l]){o=this.searchListenerTree(e,t,s[l],n+1,i)}const d=s[\"*\"];if(d)this.searchListenerTree(e,t,d,n+1,i);const h=s[\"**\"];if(h){if(n<i){if(h._listeners)this.searchListenerTree(e,t,h,i,i);const p=pr(h);let m=p.length;while(m-- >0){const y=p[m];if(y===\"_listeners\")continue;if(y===u){this.searchListenerTree(e,t,h[y],n+2,i)}else if(y===l){this.searchListenerTree(e,t,h[y],n+1,i)}else{const w=ru();w[y]=h[y];const S=ru();S[\"**\"]=w;this.searchListenerTree(e,t,S,n+1,i)}}}else if(h._listeners){this.searchListenerTree(e,t,h,i,i)}else if(h[\"*\"]&&h[\"*\"]._listeners){this.searchListenerTree(e,t,h[\"*\"],i,i)}}return o}growListenerTree(e,t,s){const n=typeof e===\"string\"?this.split(e):e;const i=n.length;if(i>1){for(let c=0;c+1<i;c++)if(n[c]===\"**\"&&n[c+1]===\"**\")return}let o=this.listenerTree;for(let c=0;c<i;c++){const l=n[c];o=o[l]||(o[l]=ru());if(c===i-1){if(!o._listeners){o._listeners=t}else{if(typeof o._listeners===\"function\")o._listeners=[o._listeners];const u=o._listeners;if(s)u.unshift(t);else u.push(t);if(!u.warned&&this._maxListeners>0&&u.length>this._maxListeners){u.warned=true;this.logPossibleMemoryLeak(u.length,l)}}return true}}return true}collectTreeEvents(e,t,s,n){const i=pr(e);let o=i.length;const c=e._listeners;while(o-- >0){const l=i[o];const u=e[l];const f=l===\"_listeners\"?s:s?s.concat(l):[l];const d=!!n||typeof l===\"symbol\";if(c)t.push(d?f:f.join(this.delimiter));if(typeof u===\"object\")this.collectTreeEvents(u,t,f,d)}return t}recursivelyGarbageCollect(e){const t=pr(e);let s=t.length;let n;while(s-- >0){const i=t[s];const o=e[i];if(o){n=true;if(i!==\"_listeners\"&&!this.recursivelyGarbageCollect(o))delete e[i]}}return n}setupListener(e,t){let s;let n;let i;if(t===true){n=true}else if(t===false){s=true}else{if(!t||typeof t!==\"object\")throw TypeError(\"options should be an object or true\");s=t.async;n=t.promisify;i=t.nextTick}if(s||i||n){const o=e;const c=e._origin||e;if(n===void 0)n=e.constructor.name===\"AsyncFunction\";s=true;e=a(function(...l){const u=this;const f=this.event;if(n){return(i?Promise.resolve():new Promise(h=>setImmediate(h))).then(()=>{u.event=f;return o.apply(u,l)})}const d=a(()=>{u.event=f;o.apply(u,l)},\"call\");return i?process.nextTick(d):setImmediate(d)},\"listener\");e._async=s;e._origin=c}return e}setMaxListeners(e){if(e===void 0)return;this._maxListeners=e;if(!this._conf)this._conf={};this._conf.maxListeners=e}getMaxListeners(){return this._maxListeners}once(e,t,s){return this._many(e,1,t,false,s)}prependOnceListener(e,t,s){return this._many(e,1,t,true,s)}many(e,t,s,n){return this._many(e,t,s,false,n)}prependMany(e,t,s,n){return this._many(e,t,s,true,n)}_many(e,t,s,n,i){if(typeof s!==\"function\")throw new Error(\"many only accepts instances of Function\");const o=this;const c=a(function(...l){if(--t===0)o.off(e,c);return s.apply(this,l)},\"listener\");c._origin=s;return this._on(e,c,n,i)}eventOf(e){if(!this.wildcard||e===\"newListener\"||e===\"removeListener\"||typeof e!==\"object\")return e;return e.some(t=>typeof t===\"symbol\")?e:e.join(this.delimiter)}emit(e,...t){if(!this._events&&!this._all)return false;if(!this._events)this.init();if(e===\"newListener\"&&!this._newListener&&!this._events.newListener)return false;const s=e;e=this.eventOf(e);if(this._all&&this._all.length){for(const i of this._all.slice()){this.event=e;i.call(this,t.length>=3?s:e,...t)}}let n;if(this.wildcard){n=[];this.searchListenerTree(n,s,this.listenerTree,0)}else{n=this._events[e];if(typeof n===\"function\"){this.event=e;n.apply(this,t);return true}if(n)n=n.slice()}if(n&&n.length){for(const i of n){this.event=e;i.apply(this,t)}return true}if(!this.ignoreErrors&&!this._all&&e===\"error\"){if(t[0]instanceof Error)throw t[0];throw new Error(\"Uncaught, unspecified 'error' event.\")}return!!this._all}emitAsync(e,...t){if(!this._events&&!this._all)return false;if(!this._events)this.init();if(e===\"newListener\"&&!this._newListener&&!this._events.newListener)return Promise.resolve([false]);const s=e;e=this.eventOf(e);const n=[];if(this._all){for(const o of this._all){this.event=e;n.push(o.call(this,t.length>=3?s:e,...t))}}let i;if(this.wildcard){i=[];this.searchListenerTree(i,s,this.listenerTree,0)}else{i=this._events[e]}if(typeof i===\"function\"){this.event=e;n.push(i.apply(this,t))}else if(i&&i.length){for(const o of i.slice()){this.event=e;n.push(o.apply(this,t))}}else if(!this.ignoreErrors&&!this._all&&e===\"error\"){return Promise.reject(t[0]instanceof Error?t[0]:\"Uncaught, unspecified 'error' event.\")}return Promise.all(n)}on(e,t,s){return this._on(e,t,false,s)}prependListener(e,t,s){return this._on(e,t,true,s)}addListener(e,t,s){return this._on(e,t,false,s)}onAny(e){return this._onAny(e,false)}prependAny(e){return this._onAny(e,true)}_onAny(e,t){if(typeof e!==\"function\")throw new Error(\"onAny only accepts instances of Function\");if(!this._all)this._all=[];if(t)this._all.unshift(e);else this._all.push(e);return this}_on(e,t,s,n){if(typeof e===\"function\"){this._onAny(e,!!t);return this}if(typeof t!==\"function\")throw new Error(\"on only accepts instances of Function\");if(!this._events)this.init();if(n!==void 0)t=this.setupListener(t,n);if(this._newListener)this.emit(\"newListener\",e,t);if(this.wildcard){this.growListenerTree(e,t,s);return this}const i=this._events;const o=e;const c=i[o];if(!c){i[o]=t;return this}const l=typeof c===\"function\"?[c]:c;i[o]=l;if(s)l.unshift(t);else l.push(t);if(!l.warned&&this._maxListeners>0&&l.length>this._maxListeners){l.warned=true;this.logPossibleMemoryLeak(l.length,o)}return this}isListener(e,t){return e===t||!!e.listener&&e.listener===t||!!e._origin&&e._origin===t}off(e,t){if(typeof t!==\"function\")throw new Error(\"removeListener only takes instances of Function\");let s=[];if(this.wildcard){const n=typeof e===\"string\"?e.split(this.delimiter):e.slice();const i=this.searchListenerTree(null,n,this.listenerTree,0);if(!i)return this;s=i}else{if(!this._events[e])return this;s.push({_listeners:this._events[e]})}for(const n of s){const i=n._listeners;if(Array.isArray(i)){const o=i.findIndex(c=>this.isListener(c,t));if(o<0)continue;if(this.wildcard)n._listeners.splice(o,1);else this._events[e].splice(o,1);if(i.length===0){if(this.wildcard)delete n._listeners;else delete this._events[e]}if(this._removeListener)this.emit(\"removeListener\",e,t);return this}if(i&&this.isListener(i,t)){if(this.wildcard)delete n._listeners;else delete this._events[e];if(this._removeListener)this.emit(\"removeListener\",e,t)}}if(this.listenerTree)this.recursivelyGarbageCollect(this.listenerTree);return this}removeListener(e,t){return this.off(e,t)}offAny(e){if(e&&this._all&&this._all.length>0){const t=this._all.indexOf(e);if(t>=0){this._all.splice(t,1);if(this._removeListener)this.emit(\"removeListenerAny\",e)}return this}if(this._removeListener)for(const t of this._all)this.emit(\"removeListenerAny\",t);this._all=[];return this}removeAllListeners(e){if(e===void 0){if(this._events)this.init();return this}if(this.wildcard){const t=this.searchListenerTree(null,e,this.listenerTree,0);if(!t)return this;for(const s of t)s._listeners=null;if(this.listenerTree)this.recursivelyGarbageCollect(this.listenerTree)}else if(this._events){this._events[e]=null}return this}listeners(e){const t=this._events;if(e===void 0){if(this.wildcard)throw Error(\"event name required for wildcard emitter\");if(!t)return[];const n=[];const i=pr(t);let o=i.length;while(o-- >0){const c=t[i[o]];if(typeof c===\"function\")n.push(c);else n.push(...c)}return n}if(this.wildcard){if(!this.listenerTree)return[];const n=[];const i=typeof e===\"string\"?e.split(this.delimiter):e.slice();this.searchListenerTree(n,i,this.listenerTree,0);return n}if(!t)return[];const s=t[e];if(!s)return[];return typeof s===\"function\"?[s]:s}eventNames(e){if(this.wildcard)return this.collectTreeEvents(this.listenerTree,[],null,e);return this._events?pr(this._events):[]}listenerCount(e){return this.listeners(e).length}hasListeners(e){if(this.wildcard){const n=[];const i=typeof e===\"string\"?e.split(this.delimiter):e.slice();this.searchListenerTree(n,i,this.listenerTree,0);return n.length>0}const t=this._events;const s=this._all;return!!(s&&s.length||t&&(e===void 0?pr(t).length:t[e]))}listenersAny(){return this._all?this._all:[]}countAllListeners(){const e=a(s=>!s?0:typeof s===\"function\"?1:s.length,\"count\");if(!this.wildcard)return this._events?pr(this._events).reduce((s,n)=>s+e(this._events[n]),0):0;const t=a(s=>pr(s).reduce((n,i)=>i===\"_listeners\"?n+e(s._listeners):n+t(s[i]),0),\"countTree\");return this.listenerTree?t(this.listenerTree):0}};var fi={async:true,nextTick:false,promisify:true,objectify:false};var KA={wildcard:true,delimiter:\".\",newListener:false,removeListener:false,maxListeners:11,verboseMemoryLeak:true,ignoreErrors:false};function We(r){return typeof r===\"symbol\"?[r]:r}a(We,\"eventName\");var wa=class{static{a(this,\"EventEmitter\")}constructor(e={}){Reflect.defineMetadata(this.constructor.name,new su({...KA,...e}),this)}emit(e,...t){return Reflect.getMetadata(this.constructor.name,this).emit(We(e),...t)}async emitRequest(e,...t){return Reflect.getMetadata(this.constructor.name,this).emitAsync(We(e),...t)}addListener(e,t){Reflect.getMetadata(this.constructor.name,this).addListener(We(e),t);return this}on(e,t){Reflect.getMetadata(this.constructor.name,this).on(We(e),t,fi);return this}prependListener(e,t){Reflect.getMetadata(this.constructor.name,this).prependListener(We(e),t,fi);return this}once(e,t){Reflect.getMetadata(this.constructor.name,this).once(We(e),t,fi);return this}prependOnceListener(e,t){Reflect.getMetadata(this.constructor.name,this).prependOnceListener(We(e),t,fi);return this}many(e,t,s){Reflect.getMetadata(this.constructor.name,this).many(We(e),t,s,fi);return this}prependMany(e,t,s){Reflect.getMetadata(this.constructor.name,this).prependMany(We(e),t,s,fi);return this}onAny(e){Reflect.getMetadata(this.constructor.name,this).onAny(e);return this}prependAny(e){Reflect.getMetadata(this.constructor.name,this).prependAny(e);return this}offAny(e){Reflect.getMetadata(this.constructor.name,this).offAny(e);return this}removeListener(e,t){Reflect.getMetadata(this.constructor.name,this).removeListener(We(e),t);return this}off(e,t){Reflect.getMetadata(this.constructor.name,this).off(We(e),t);return this}removeAllListeners(e){Reflect.getMetadata(this.constructor.name,this).removeAllListeners(We(e));return this}setMaxListeners(e){return Reflect.getMetadata(this.constructor.name,this).setMaxListeners(e)}getMaxListeners(){return Reflect.getMetadata(this.constructor.name,this).getMaxListeners()}eventNames(e){const t=Reflect.getMetadata(this.constructor.name,this).eventNames(e);return e?t:t.map(s=>Array.isArray(s)&&s.length===1&&typeof s[0]===\"symbol\"?s[0]:s)}listenerCount(e){if(e===void 0)return Reflect.getMetadata(this.constructor.name,this).countAllListeners();return Reflect.getMetadata(this.constructor.name,this).listenerCount(We(e))}listeners(e){const t=Reflect.getMetadata(this.constructor.name,this);if(e===void 0)return t.eventNames(true).flatMap(s=>t.listeners(s));return t.listeners(We(e))}listenersAny(){return[...Reflect.getMetadata(this.constructor.name,this).listenersAny()]}hasListeners(e){const t=Reflect.getMetadata(this.constructor.name,this);if(e===void 0)return t.countAllListeners()>0;return t.hasListeners(We(e)).valueOf()}};var nu=class extends wa{static{a(this,\"SynchronousEventEmitter\")}on(e,t){Reflect.getMetadata(this.constructor.name,this).on(We(e),t);return this}once(e,t){Reflect.getMetadata(this.constructor.name,this).once(We(e),t);return this}};function Ve(r=I.Any(),e){return(t,s)=>{zS(t,s,r,e);GS(t,s)}}a(Ve,\"Configurable\");var yw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var WA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Ts=class hH extends Ys{static{a(this,\"Component\")}#e=new wa;async[dr](...e){await super[dr](...e)}async[st](...e){await super[st](async()=>{this.#e.removeAllListeners()},...e)}get container(){return ha(this)}createScope(){return ha(this).createScope()}emit(e,...t){return this.#e.emit(e,...t)}async emitRequest(e,...t){return this.#e.emitRequest(e,...t)}addListener(e,t){this.#e.addListener(e,t);return this}on(e,t){this.#e.on(e,t);return this}prependListener(e,t){this.#e.prependListener(e,t);return this}once(e,t){this.#e.once(e,t);return this}prependOnceListener(e,t){this.#e.prependOnceListener(e,t);return this}many(e,t,s){this.#e.many(e,t,s);return this}prependMany(e,t,s){this.#e.prependMany(e,t,s);return this}onAny(e){this.#e.onAny(e);return this}prependAny(e){this.#e.prependAny(e);return this}offAny(e){this.#e.offAny(e);return this}removeListener(e,t){this.#e.removeListener(e,t);return this}off(e,t){this.#e.off(e,t);return this}removeAllListeners(e){this.#e.removeAllListeners(e);return this}setMaxListeners(e){this.#e.setMaxListeners(e)}getMaxListeners(){return this.#e.getMaxListeners()}eventNames(e){return this.#e.eventNames(e)}listenerCount(e){return this.#e.listenerCount(e)}listeners(e){return this.#e.listeners(e)}listenersAny(){return this.#e.listenersAny()}hasListeners(e){return this.#e.hasListeners(e)}async reload(){await this[st]();this[ba]();await this[dr]()}};yw([Ve(I.Number().integer().min(0).optional().default(11),function(r){this.setMaxListeners(r);return r}),WA(\"design:type\",Number)],Ts.prototype,\"maxListeners\",void 0);Ts=yw([Xs(true),ws(je.Component)],Ts);var VA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var di=class SH extends I{static{a(this,\"LoadNamedObjectOptions\")}};di=VA([hr(Ir.Schema())],di);var bw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var XA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var hi=class CH extends I{static{a(this,\"LoadAnonymousObjectOptions\")}};bw([ve(I.Class(()=>Re).required()),XA(\"design:type\",Object)],hi.prototype,\"class\",void 0);hi=bw([hr(I.Any())],hi);var Sw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var ww=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var xs=class extends I{static{a(this,\"ModuleLoadObjectsOptions\")}};Sw([ve(di.optional().default({})),ww(\"design:type\",di)],xs.prototype,\"named\",void 0);Sw([ve(I.Array(I.Alternatives(hi.Schema(),I.Class(Re),I.Glob())).optional().default([])),ww(\"design:type\",Array)],xs.prototype,\"anonymous\",void 0);var Ew=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var YA=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var pi=class $H extends I{static{a(this,\"OverridableObjectOptions\")}};Ew([ve(I.Class(()=>Re).optional()),YA(\"design:type\",Object)],pi.prototype,\"class\",void 0);pi=Ew([hr(I.Any())],pi);var JA=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Rs=class KH extends I{static{a(this,\"OverridableNamedObjectOptions\")}};Rs=JA([hr(pi.Schema())],Rs);var Ea=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Ta=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var wt=class extends I{static{a(this,\"ModuleOptions\")}};Ea([ve(Rs.optional()),Ta(\"design:type\",Rs)],wt.prototype,\"components\",void 0);Ea([ve(Rs.optional()),Ta(\"design:type\",Rs)],wt.prototype,\"providers\",void 0);Ea([ve(xs.optional().default({named:{},anonymous:[]})),Ta(\"design:type\",xs)],wt.prototype,\"objects\",void 0);Ea([ve(I.Array(I.Alternatives(I.String(),I.Class(Re),I.AsyncFunction())).optional().default([])),Ta(\"design:type\",Array)],wt.prototype,\"bootstrap\",void 0);Ea([ve(I.Boolean().optional()),Ta(\"design:type\",Boolean)],wt.prototype,\"checkOptions\",void 0);var xa=class extends Z{static{a(this,\"OverridableObjectTargetConfigNotFoundException\")}constructor(){super(...arguments);this.errno=\"E_OVERRIDABLE_OBJECT_TARGET_CONFIG_NOT_FOUND\"}};var Ra=class extends Z{static{a(this,\"InvalidObjectTypeException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_OBJECT_TYPE\"}};function Tw(r){return new Set(r)}a(Tw,\"arrayToSet\");function xw(r){return Array.from(r)}a(xw,\"setToArray\");var mi=class{static{a(this,\"ModuleConfigLoader\")}constructor(e,t,s=[]){this.$presetLoadOptionsSet=new Set;this.$loadOptions=[];this.$bootstrap=[];this.$module=e;this.$presetLoadOptionsSet=Tw(s);this.$bootstrap=t.bootstrap?t.bootstrap:[];t.objects?.anonymous?.forEach(n=>this.$loadOptions.push(n));if(t.objects&&t.objects.named){const n=t.objects.named;Object.keys(n).forEach(i=>this.$loadOptions.push({...n[i],[lt]:i}))}this.processOverridableNamedObjectOptions(je.Component,t.components);this.processOverridableNamedObjectOptions(je.Provider,t.providers)}validateObjectType(e,t,s){const n=ga(t);if(n===e)return t;const i=e.toLowerCase();const o=n.toLowerCase();const c=n===je.Component||n===je.Provider?`, declare it in the ${o}s configuration`:n===je.Module?\", declare it in the objects configuration (objects.named)\":\"\";throw new Ra('{0} configuration only accepts object declarations of {1} types: \"{2}\" ({3}) is a {4}{5}',[e,i,s??t.name,t.name,o,c])}processOverridableNamedObjectOptions(e,t){if(!t)return;Object.keys(t).forEach(s=>{const n=t[s];n[lt]=s;if(n.class){n.class=this.validateObjectType(e,n.class,s);for(const i of this.$presetLoadOptionsSet){if(typeof i===\"string\"||i instanceof Re)continue;if(s===i[lt])this.$presetLoadOptionsSet.delete(i)}return this.$loadOptions.push(v(n))?void 0:void 0}for(const i of this.$presetLoadOptionsSet){if(typeof i===\"string\")continue;if(i instanceof Re)continue;if(n[lt]===i[lt]){this.$loadOptions.push(Object.assign({},i,n));return this.$presetLoadOptionsSet.delete(i)?void 0:void 0}}throw new xa(\"No applicable configuration target found\")})}get loadOptions(){return[...this.$loadOptions,...xw(this.$presetLoadOptionsSet)]}get bootstrap(){return this.$bootstrap}};var Ow=require(\"node:util/types\");var _w=require(\"node:crypto\");var Rw={alphanumeric:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",alphabetic:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",numeric:\"0123456789\",hex:\"0123456789abcdef\",binary:\"01\",octal:\"01234567\"};function Cw(r=32,e=\"alphanumeric\"){if(!Number.isInteger(r)||r<0)throw new RangeError(`Invalid length: ${r}, a non-negative integer is expected`);const t=a(o=>Object.hasOwn(Rw,o)?Rw[o]:o,\"charsetOf\");const s=[...Array.isArray(e)?e.map(t).join(\"\"):t(e)];if(!s.length)throw new RangeError(\"The character set is empty\");const n=2**32-2**32%s.length;const i=[];while(i.length<r){const o=(0,_w.getRandomValues)(new Uint32Array(Math.min(r-i.length,16384)));for(const c of o)if(c<n)i.push(s[c%s.length])}return i.join(\"\")}a(Cw,\"randomString\");function Ap(){return Cw(32,\"alphanumeric\")}a(Ap,\"nonceString\");var _a=class extends Z{static{a(this,\"InvalidObjectOptionsException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_OBJECT_OPTIONS\"}};var ZA=new Set([\"class\",\"id\"]);function vw(r){const e=[];const t=[];for(const s of r){if(typeof s!==\"object\"||!s||typeof s.class!==\"function\")continue;const n=s.class;const i=s[lt];const o=typeof i===\"string\"?`\"${i}\" (${n.name})`:n.name;const c=Jl(v(n.prototype));for(const l of Object.keys(s)){const u=s[l];if(ZA.has(l)||u===void 0)continue;const f=c.get(l);if(!f){if(!n.acceptsOption(l,u))t.push(QA(o,l,c));continue}try{I.validate(u,f.schema,{targetName:l})}catch(d){if(!(d instanceof ur))continue;e.push(`The option \"${l}\" of ${o} is invalid: ${d.message}`)}}}t.forEach(s=>_r(s));if(e.length)throw new _a(e.join(\"\\n\"))}a(vw,\"checkObjectOptions\");function QA(r,e,t){const s=[...t.keys()].filter(i=>typeof i===\"string\").sort();const n=s.length?`its configurable properties: ${s.join(\", \")}`:\"it has no configurable property\";return`The option \"${e}\" of ${r} is not a configurable property, it is ignored (${n})`}a(QA,\"unknownOptionMessage\");var Aw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Iw=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Ip=`_$.MODULE.INITIALIZED_${Ap()}`;var Op=`_$.MODULE.INITIALIZE_ERROR_${Ap()}`;var Ca=class kw extends Ts{static{a(this,\"Module\")}get container(){return ha(this)}#e;#t;#r;constructor(e){super(e);this.ConfigLoader=mi;this.options={};this.#e=[];this.#t=[];this.#r=true}async[dr](...e){const t={};t.promise=new Promise((s,n)=>{t.resolve=s;t.reject=n});t.promise.catch(()=>void 0);this.#s=t;setImmediate(()=>void(async()=>{try{await super[dr](...e,async()=>{if(this.#r)vw(this.#e);await this.container.load(this.#e)},async()=>{Reflect.defineMetadata(\"#bootstrap\",this.#t,this);for(const s of this.#t){if((0,Ow.isAsyncFunction)(s)){await v(s)(this)}else{await this.getObject(v(s))}}Reflect.deleteMetadata(\"#bootstrap\",this)});this.emit(Ip);t.resolve()}catch(s){this.emit(Op,s);t.reject(s)}})())}#s;async[eu](){await this.#s?.promise}async[st](...e){this.#s?.resolve();return await super[st](...e)}mode(){return Ad()}async reload(){await this[st]();this[ba]();await new Promise((e,t)=>{const s=a(()=>{this.off(Op,n);e()},\"onInitialized\");const n=a(i=>{this.off(Ip,s);t(i)},\"onInitializeError\");this.once(Ip,s);this.once(Op,n);this[dr]().catch(t)})}async getObject(e,t={}){return await super.getObject(e,t)}static{Aw([Ve(wt.optional().default({}).options({stripUnknown:false}),function(e){const t=this.getConfigurableRecords().options!==void 0?e:{};const{bootstrap:s,loadOptions:n}=new this.ConfigLoader(this,this.options);s.forEach(o=>this.#t.push(o));const i=new this.ConfigLoader(this,t,n);i.bootstrap.forEach(o=>this.#t.push(o));this.#e=i.loadOptions;this.#r=(t.checkOptions??this.options.checkOptions)!==false;return e}),Iw(\"design:type\",wt)],kw.prototype,\"options\",void 0)}};Ca=Aw([Xs(true),ws(je.Module),Iw(\"design:paramtypes\",[Object])],Ca);var Pw=require(\"node:os\");var va=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Aa=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var eI=Object.keys(Pw.constants.signals).filter(r=>r!==\"SIGKILL\"&&r!==\"SIGSTOP\");var Ot=class extends wt{static{a(this,\"ApplicationOptions\")}};va([ve(I.String().required()),Aa(\"design:type\",String)],Ot.prototype,\"id\",void 0);va([ve(I.String().required()),Aa(\"design:type\",String)],Ot.prototype,\"name\",void 0);va([ve(I.String().optional().default(\"auto\")),Aa(\"design:type\",String)],Ot.prototype,\"timezone\",void 0);va([ve(I.String().valid(\"development\",\"production\").optional()),Aa(\"design:type\",String)],Ot.prototype,\"mode\",void 0);va([ve(I.Alternatives(I.Boolean().valid(false),I.Array(I.String().valid(...eI))).optional().default(()=>[\"SIGTERM\",\"SIGINT\"])),Aa(\"design:type\",Object)],Ot.prototype,\"shutdownSignals\",void 0);var iu=class extends mi{static{a(this,\"ApplicationConfigLoader\")}constructor(e,t,s=[]){if(Ot.isValid(t)){const n=Kg({appId:t.id,appName:t.name,timezone:t.timezone?t.timezone:\"auto\",mode:Gg(t.mode)}).appId;if(!process.versions.nw)process.title=n}super(e,t,s)}};var ou=Ye(require(\"path\"),1);var Js=class extends Z{static{a(this,\"InvalidAliasNameException\")}constructor(){super(...arguments);this.errno=\"E_INVALID_ALIAS_NAME\"}};var Ia=class extends Z{static{a(this,\"AliasExistsException\")}constructor(){super(...arguments);this.errno=\"E_ALIAS_EXISTS\"}};var Oa=class extends Z{static{a(this,\"AliasNotFoundException\")}constructor(){super(...arguments);this.errno=\"E_ALIAS_NOT_FOUND\"}};var ka=class{static{a(this,\"Alias\")}constructor(){this.aliasNameRegExp=/^@[a-zA-Z0-9]+$/;this.aliasMap=new Map;const e=ou.default.resolve;ou.default.resolve=(...t)=>{const s=t.map(n=>this.resolve(n));return e(...s)}}static init(){const e=new this;Reflect.defineMetadata(this,e,this)}static getAliasInstance(){if(!Reflect.hasOwnMetadata(this,this))this.init();return Reflect.getMetadata(this,this)}set(e,t,s=false){if(!this.aliasNameRegExp.test(e))throw new Js(\"The alias should start with '@' and only contain characters a-z|A-Z|0-9. The current alias '{aliasName}' does not comply with this rule.\",{aliasName:e});if(this.aliasMap.has(e)&&!s)throw new Ia(\"The alias '{aliasName}' already exists.\",{aliasName:e});this.aliasMap.set(e,t)}get(e){if(!this.aliasNameRegExp.test(e))throw new Js(\"The alias should start with '@' and only contain characters a-z|A-Z|0-9. The current alias '{aliasName}' does not comply with this rule.\",{aliasName:e});if(!this.aliasMap.has(e))throw new Oa(\"The alias '{aliasName}' not found.\",{aliasName:e});const t=this.aliasMap.get(e);return this.resolve(t)}has(e){if(!this.aliasNameRegExp.test(e))throw new Js(\"The alias should start with '@' and only contain characters a-z|A-Z|0-9. The current alias '{aliasName}' does not comply with this rule.\",{aliasName:e});return this.aliasMap.has(e)}resolve(e){let t=true;const s=[];this.aliasMap.forEach((n,i)=>s.push({name:i,path:n}));s.sort((n,i)=>n.name.length<i.name.length?1:-1);while(t){let n=false;s.forEach(({name:i,path:o})=>{if(e.includes(i)){n=true;e=e.replace(i,o)}});t=n}return ou.default.normalize(e)}list(){const e={};this.aliasMap.forEach((t,s)=>Reflect.set(e,s,t));return e}};var Lw=require(\"node:util\");var Nw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var tI=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Pa={trace:10,debug:20,info:30,warn:40,error:50,silent:Infinity};var Na=class I4 extends Ts{static{a(this,\"ConsoleLogger\")}write(e,t){if(Pa[e]<Pa[this.level])return;const[s,...n]=t;const i=typeof s===\"object\"&&s!==null&&typeof n[0]===\"string\"?[...n,s]:t;const o=`[${new Date().toISOString()}] ${e.toUpperCase()} (${Qr()}): ${(0,Lw.formatWithOptions)({colors:false},...i)}\n`;Pa[e]>=Pa.warn?process.stderr.write(o):process.stdout.write(o)}error(...e){this.write(\"error\",e)}warn(...e){this.write(\"warn\",e)}info(...e){this.write(\"info\",e)}debug(...e){this.write(\"debug\",e)}trace(...e){this.write(\"trace\",e)}};Nw([Ve(I.String().valid(...Object.keys(Pa)).optional().default(\"info\")),tI(\"design:type\",String)],Na.prototype,\"level\",void 0);Na=Nw([Xs()],Na);var Uw=require(\"fs\");var Pp=Ye(require(\"node:path\"),1);var jw=require(\"node:fs\");var $w=require(\"node:os\");function Mw(r){const e=new Map;for(const i in r)if(i.toUpperCase().startsWith(\"MIGRATION_\")&&r[i]!==void 0)e.set(i.toUpperCase(),r[i]);const t=a(i=>[\"1\",\"true\",\"yes\"].includes((e.get(i)??\"\").toLowerCase()),\"flag\");const s=e.get(\"MIGRATION_TRANSACTION\")||void 0;if(s!==void 0&&s!==\"all\"&&s!==\"none\"&&s!==\"each\")throw new Error(`MIGRATION_TRANSACTION is all, none or each, not \"${s}\"`);const n={database:e.get(\"MIGRATION_DATABASE\")||void 0,transaction:s,fake:t(\"MIGRATION_FAKE\")};if(e.get(\"MIGRATION_GENERATE\"))return{action:\"generate\",path:e.get(\"MIGRATION_GENERATE\"),...n};if(t(\"MIGRATION_RUN\"))return{action:\"run\",...n};if(t(\"MIGRATION_REVERT\"))return{action:\"revert\",...n};if(t(\"MIGRATION_SHOW\"))return{action:\"show\",...n};return void 0}a(Mw,\"readMigrationCommand\");var kp=false;function La(r,e=500){if(kp)return;kp=true;process.exitCode=r;setTimeout(()=>process.exit(r),e).unref()}a(La,\"endProcess\");function Dw(){return kp}a(Dw,\"isEnding\");var Bw=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var gi=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var Je;(function(r){r[\"Launched\"]=\"LAUNCHED\";r[\"Done\"]=\"DONE\";r[\"UncaughtException\"]=\"UNCAUGHT_EXCEPTION\";r[\"FatalException\"]=\"FATAL_EXCEPTION\"})(Je||(Je={}));var yi=class r extends Ca{static{a(this,\"Application\")}constructor(){super(...arguments);this.ConfigLoader=iu;this.options=r.copyPresetOptions()}static{this.eventEmitter=new nu}static{this.environmentVariableMap=new Map}static{this.aliasDeclarations=[]}static{this.launchStarted=false}static{this.presetOptions={}}static#e;static#t=false;static#r;static preset(e){const t=this.presetOptions;if(e.components)Reflect.set(t,\"components\",{...t.components,...e.components});if(e.providers)Reflect.set(t,\"providers\",{...t.providers,...e.providers});if(e.objects)Reflect.set(t,\"objects\",{named:{...t.objects?.named,...e.objects.named},anonymous:[...t.objects?.anonymous??[],...e.objects.anonymous??[]]});if(e.bootstrap)Reflect.set(t,\"bootstrap\",[...new Set([...t.bootstrap??[],...e.bootstrap])]);return this}static async getLogger(){return this.appInstance?await this.appInstance.getLogger():await this.getConsoleLogger()}static getConsoleLogger(){if(!this.#e)this.#e=new Wt().set(Na);return this.#e}static env(e){Object.keys(e).forEach(t=>this.environmentVariableMap.set(t,e[t]));return this.launch()}static alias(e,t=false){this.aliasDeclarations.push({alias:e?e:{},createIfNotExist:t});return this.launch()}static onLaunched(e){const t=this.appInstance;if(t){void(async()=>e(t,await t.getLogger()))();return this}this.eventEmitter.once(Je.Launched,async s=>e(s,await s.getLogger()));return this.launch()}static onDone(e){this.eventEmitter.once(Je.Done,async(t,s)=>e(t,await t.getLogger(),s));return this.launch()}static onUncaughtException(e){this.eventEmitter.on(Je.UncaughtException,async t=>{const s=await this.getLogger();await e(t,s)});return this.launch()}static onFatalException(e){this.eventEmitter.once(Je.FatalException,async t=>{const s=await this.getLogger();let n=await e(t,s);if(typeof n!==\"number\")n=1;return La(n)});return this.launch()}static run(e){Reflect.set(this,\"launchOptions\",e);return this.launch()}static launch(){if(this.launchStarted)return this;if(this.launchTimeout)clearTimeout(this.launchTimeout);this.launchTimeout=setTimeout(()=>{this.launchStarted=true;process.on(\"uncaughtException\",e=>void this.processUncaughtException(e));this.launchApplication().then(e=>Reflect.set(this,\"appInstance\",e)).catch(e=>this.processFatalException(e))});return this}static async processUncaughtException(e){if(this.eventEmitter.listenerCount(Je.UncaughtException)){this.eventEmitter.emit(Je.UncaughtException,e);return}const t=new Error(\"UncaughtException\",{cause:e});try{const s=await this.getLogger();s.warn(t)}catch(s){console.error(t,s)}}static processFatalException(e){if(Dw())return;if(!this.eventEmitter.listenerCount(Je.FatalException)){return process.nextTick(async()=>{const t=new Error(\"FatalException\",{cause:e});try{const s=await this.getLogger();s.error(t)}catch(s){console.error(t,s)}return La(1)})}this.eventEmitter.emit(Je.FatalException,e)}static listenShutdownSignals(e){let t=false;for(const s of e){process.on(s,()=>{const n=128+($w.constants.signals[s]??0);if(t||!this.appInstance)return process.exit(n);t=true;this.eventEmitter.emit(\"exit\",this.appInstance,0,s)})}}static listenNaturalEnd(e){r.stopListeningNaturalEnd();const t=a(()=>{r.stopListeningNaturalEnd();if(r.#t)return;const s=Number(process.exitCode??0);r.eventEmitter.emit(\"exit\",e,Number.isInteger(s)?s:1)},\"listener\");r.#r=t;process.once(\"beforeExit\",t)}static stopListeningNaturalEnd(){if(r.#r)process.removeListener(\"beforeExit\",r.#r);r.#r=void 0}static async launchApplication(){this.eventEmitter.once(\"exit\",async(i,o,c)=>{this.#t=true;try{const l=c?{code:o?o:0,signal:c}:{code:o?o:0};await this.eventEmitter.emitRequest(Je.Done,i,l);await n.destroy();La(o?o:0)}catch(l){La(1)}});this.environmentVariableMap.forEach((i,o)=>process.env[o]=i);const e=ka.getAliasInstance();e.set(\"@runtime\",process.cwd());this.aliasDeclarations.forEach(i=>{const o=i.alias;const c=i.createIfNotExist;Object.keys(o).forEach(l=>{e.set(l,o[l]);if(c){const u=Pp.default.resolve(l);if(!(0,jw.existsSync)(u))(0,Uw.mkdirSync)(Pp.default.resolve(l),{recursive:true})}})});const t=typeof this.launchOptions===\"object\"?this.launchOptions:await this.launchOptions();let s;try{s=Mw(process.env)}catch(i){console.error(i.message);process.exit(1)}if(s){this.eventEmitter.removeAllListeners(Je.Launched);this.eventEmitter.removeAllListeners(Je.Done);this.eventEmitter.removeAllListeners(Je.UncaughtException);this.eventEmitter.removeAllListeners(Je.FatalException);const i=s.action===\"generate\"?\"migrationGenerator\":\"migrationExecutor\";const o=a(u=>{const f=[];for(const d in u){const h=u[d]?.class;if(typeof h?.[i]===\"function\"){if(!u[d].options)continue;const p=Array.isArray(u[d].entities)?u[d].entities:[];const m=u[d].options.entities;const y={...u[d].options,...p.length?{entities:[...Array.isArray(m)?m:Object.values(m??{}),...p]}:{},dataSourceName:d};f.push({dataSourceName:d,dataSourceOptions:y,loader:h[i]})}}return f},\"getMigrationTargets\");let c=[...t.components?o(t.components):[],...t.providers?o(t.providers):[]];const l=c.map(u=>u.dataSourceName).join(\", \");if(s.database){c=c.filter(u=>u.dataSourceName===s.database);if(!c.length){console.error(`The application has no database ${s.database} (${l||\"no Database component or provider\"})`);process.exit(1)}}if(!c.length){if(s.action===\"generate\"){console.log(\"The application has no Database component or provider\");process.exit(0)}console.error(\"The application has no Database component or provider\");process.exit(1)}if(s.action===\"revert\"&&c.length>1){console.error(`The application has several databases (${l}): MIGRATION_DATABASE selects the one whose last migration is reverted`);process.exit(1)}t.bootstrap=[];if(!t.providers)t.providers={};for(let u=0;u<c.length;u++){const f=c[u];const d=`Migration${u}${Date.now()}`;const h={class:await f.loader(),exitProcess:u===c.length-1,dataSourceName:f.dataSourceName,dataSource:f.dataSourceOptions};t.providers[d]=s.action===\"generate\"?{...h,path:s.path,outputJs:false}:{...h,action:s.action,transaction:s.transaction,fake:s.fake};t.bootstrap.push(d)}}const n=new Wt;return new Promise((i,o)=>{Ot.validateAsync(t).then(c=>{if(c.shutdownSignals)this.listenShutdownSignals(c.shutdownSignals);c.bootstrap?.push(async l=>{if(r.#t)return;const u=a(function(){this.options.bootstrap?.pop();v(Reflect.getOwnMetadata(\"#bootstrap\",this))?.pop()},\"launchedCallbackRemover\");u.bind(v(l))();const f=await v(l).getLogger();aw((d,h)=>f.warn(d,h));ew(l);Reflect.set(this,\"appInstance\",l);r.listenNaturalEnd(v(l));this.eventEmitter.emit(Je.Launched,v(l))});n.set(r,{options:c}).then(i).catch(o)}).catch(o)})}static copyPresetOptions(){const e=r.presetOptions;return{...e.components?{components:{...e.components}}:{},...e.providers?{providers:{...e.providers}}:{},...e.objects?{objects:{named:{...e.objects.named},anonymous:[...e.objects.anonymous??[]]}}:{},bootstrap:[...e.bootstrap??[]]}}async getLogger(){return this.container.has(\"log\")?v(await this.getObject(\"log\")):await r.getConsoleLogger()}get alias(){return ka.getAliasInstance()}static get appId(){return jn()}static get appName(){return Qr()}get appId(){return jn()}get appName(){return Qr()}get timezone(){return Id().timezone}async[st](...e){r.stopListeningNaturalEnd();return await super[st](...e)}get uptime(){return Math.floor(process.uptime())}exit(e){if(typeof e===\"boolean\"&&e){return process.exit(2)}else{r.eventEmitter.emit(\"exit\",this,e?e:0)}}};Bw([Sa(I.Object().pattern(I.String(),I.String()).required()),gi(\"design:type\",Function),gi(\"design:paramtypes\",[Object]),gi(\"design:returntype\",Object)],yi,\"env\",null);Bw([Sa(I.Object().pattern(I.String(),I.String()).required(),I.Boolean().optional().default(false)),gi(\"design:type\",Function),gi(\"design:paramtypes\",[Object,Boolean]),gi(\"design:returntype\",Object)],yi,\"alias\",null);QS(yi);var rI=Object.freeze([\"en\",\"zh-CN\",\"zh-TW\",\"ja\",\"ko\",\"fr\",\"de\",\"es\",\"pt-BR\",\"it\",\"nl\",\"pl\",\"ru\",\"uk\",\"tr\",\"vi\",\"th\",\"id\",\"hi\",\"ar\"]);var au;var sI=new Set;function Fw(r){const e=!!au!==!!r;au=r;if(e)for(const t of sI)t(!!r)}a(Fw,\"setDebugHandler\");function P(r){return(...e)=>{if(au)au(r,e)}}a(P,\"debug\");var FE=require(\"node:events\");var Xp=require(\"node:crypto\");var Np=require(\"node:crypto\");function Lp(){return(0,Np.randomBytes)(2).readUInt16BE(0)}a(Lp,\"random16\");function cu(){return(0,Np.randomBytes)(4).readUInt32BE(0)}a(cu,\"random32\");var Or=class{static{a(this,\"BitWriter\")}constructor(e){this.bitLength=e;this.value=0}set(e,t,s){s&=(1<<e)-1;this.value|=s<<this.bitLength-e-t;return this}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};var Zs=class{static{a(this,\"BitWriter2\")}constructor(e){this.bitLength=e;this._value=0n;this.offset=0n;if(e>32){throw new Error}}set(e,t=1){let s=BigInt(e);const n=BigInt(t);s&=(1n<<n)-1n;this._value|=s<<BigInt(this.bitLength)-n-this.offset;this.offset+=n;return this}get value(){return Number(this._value)}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};function V(r,e,t=1){const s=Math.min(e+t,8);return r>>8-s&(1<<s-e)-1}a(V,\"getBit\");function he(r,e){return Ma(r)(e)}a(he,\"bufferWriter\");function Ma(r,e){const t=r.reduce((n,i)=>n+i,0);const s=e?Buffer.alloc(t):void 0;return n=>{const i=s||Buffer.alloc(t);let o=0;n.forEach((c,l)=>{const u=r[l];if(u===8)i.writeBigUInt64BE(c,o);else i.writeUIntBE(c,o,u);o+=u});return i}}a(Ma,\"createBufferWriter\");function Pe(r,e){let t=0;return e.map(s=>{let n;if(s===8){n=r.readBigUInt64BE(t)}else{n=r.readUIntBE(t,s)}t+=s;return n})}a(Pe,\"bufferReader\");var mr=class{static{a(this,\"BitStream\")}constructor(e){this.uint8Array=e;this.position=0;this.bitsPending=0}writeBits(e,t){if(e==0){return this}t&=4294967295>>>32-e;let s;if(this.bitsPending>0){if(this.bitsPending>e){this.uint8Array[this.position-1]|=t<<this.bitsPending-e;s=e;this.bitsPending-=e}else if(this.bitsPending==e){this.uint8Array[this.position-1]|=t;s=e;this.bitsPending=0}else{this.uint8Array[this.position-1]|=t>>e-this.bitsPending;s=this.bitsPending;this.bitsPending=0}}else{s=Math.min(8,e);this.bitsPending=8-s;this.uint8Array[this.position++]=t>>e-s<<this.bitsPending}e-=s;if(e>0){this.writeBits(e,t)}return this}readBits(e){return this._readBits(e)}_readBits(e,t){if(typeof t==\"undefined\"){t=0}if(e==0){return t}let s;let n;if(this.bitsPending>0){const i=this.uint8Array[this.position-1]&255>>8-this.bitsPending;n=Math.min(this.bitsPending,e);this.bitsPending-=n;s=i>>this.bitsPending}else{n=Math.min(8,e);this.bitsPending=8-n;s=this.uint8Array[this.position++]>>this.bitsPending}e-=n;t=t<<n|s;return e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0;this.bitsPending=e%8;if(this.bitsPending>0){this.bitsPending=8-this.bitsPending;this.position++}}};var nI=3988292384;var iI=2197175160;function Hw(r){return typeof r!==\"string\"}a(Hw,\"isBufferLike\");function qw(r){const e=new Array(256);for(let t=0;t<256;++t){let s=t;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;e[t]=s}return new Int32Array(e)}a(qw,\"generateCRCTable\");function zw(r){const e=new Int32Array(4096);let t;let s;let n;for(n=0;n<256;++n)e[n]=r[n];for(n=0;n<256;++n){s=r[n];for(t=256+n;t<4096;t+=256){s=e[t]=s>>>8^r[s&255]}}const i=[];for(n=1;n<16;++n){i[n-1]=e.subarray(n*256,n*256+256)}return i}a(zw,\"generateSliceBy16Tables\");function Gw(r,e,t){let s=e^-1;let n=0;const i=r.length;let o;let c;while(n<i){o=r.charCodeAt(n++);if(o<128){s=s>>>8^t[(s^o)&255]}else if(o<2048){s=s>>>8^t[(s^(192|o>>6&31))&255];s=s>>>8^t[(s^(128|o&63))&255]}else if(o>=55296&&o<57344){o=(o&1023)+64;c=r.charCodeAt(n++)&1023;s=s>>>8^t[(s^(240|o>>8&7))&255];s=s>>>8^t[(s^(128|o>>2&63))&255];s=s>>>8^t[(s^(128|c>>6&15|(o&3)<<4))&255];s=s>>>8^t[(s^(128|c&63))&255]}else{s=s>>>8^t[(s^(224|o>>12&15))&255];s=s>>>8^t[(s^(128|o>>6&63))&255];s=s>>>8^t[(s^(128|o&63))&255]}}return~s>>>0}a(Gw,\"crcGenericString\");function Kw(r,e,t,s){const[n,i,o,c,l,u,f,d,h,p,m,y,w,S,T]=s;let _=e^-1;let x=0;let k=r.length-15;while(x<k){_=T[r[x++]^_&255]^S[r[x++]^_>>>8&255]^w[r[x++]^_>>>16&255]^y[r[x++]^_>>>24]^m[r[x++]]^p[r[x++]]^h[r[x++]]^d[r[x++]]^f[r[x++]]^u[r[x++]]^l[r[x++]]^c[r[x++]]^o[r[x++]]^i[r[x++]]^n[r[x++]]^t[r[x++]]}for(k+=15;x<k;){_=_>>>8^t[(_^r[x++])&255]}return~_>>>0}a(Kw,\"crcBuffer\");var Mp=qw(nI);var oI=zw(Mp);var Dp=qw(iI);var aI=zw(Dp);function Ww(r,e=0){if(Hw(r)){return Kw(r,e,Mp,oI)}return Gw(r,e,Mp)}a(Ww,\"crc32\");function Da(r,e=0){if(Hw(r)){return Kw(r,e,Dp,aI)}return Gw(r,e,Dp)}a(Da,\"crc32c\");function Vw(r,e){return r+e&255}a(Vw,\"uint8Add\");function $e(r,e){return r+e&65535}a($e,\"uint16Add\");function gr(r,e){return Number(BigInt(r)+BigInt(e)&0xffffffffn)}a(gr,\"uint32Add\");function lu(r,e){const t=32768;return r<e&&e-r>t||r>e&&r-e<t}a(lu,\"uint16Gt\");function Et(r,e){const t=2147483648;return r<e&&e-r>t||r>e&&r-e<t}a(Et,\"uint32Gt\");function bi(r,e){return r===e||Et(r,e)}a(bi,\"uint32Gte\");var _s=a(r=>Number.parseInt(r,10),\"int\");function Ne(r,e){try{const t=r();if(t instanceof Promise)t.catch(e)}catch(t){e(t)}}a(Ne,\"runDetached\");function Vt(r,e){return(...t)=>{try{const s=r(...t);if(s instanceof Promise)s.catch(e)}catch(s){e(s)}}}a(Vt,\"detached\");var Bp=require(\"node:dgram\");var uu=a((r,e)=>e?e[r]:void 0,\"interfaceAddress\");async function fu(r=\"udp4\",e){const t=(0,Bp.createSocket)(r);setImmediate(()=>t.bind({port:0,address:uu(r,e)}));await new Promise(n=>{t.once(\"error\",n);t.once(\"listening\",n)});const s=t.address()?.port;await new Promise(n=>t.close(()=>n()));return s}a(fu,\"randomPort\");async function Xw(r,e,t=\"udp4\",s){let n;for(let i=r;i<=e;i++){const o=(0,Bp.createSocket)(t);setImmediate(()=>o.bind({port:i,address:uu(t,s)}));const c=await new Promise(l=>{o.once(\"error\",u=>l(u));o.once(\"listening\",()=>l())});if(c){await new Promise(l=>o.close(()=>l()));continue}n=o.address()?.port;await new Promise(l=>o.close(()=>l()));if(r<=n&&n<=e){break}}if(!n)throw new Error(\"port not found\");return n}a(Xw,\"findPort\");function Qs(r){if(r===\"IPv4\")return 4;if(r===\"IPv6\")return 6;return r}a(Qs,\"normalizeFamilyNodeV18\");var du=class{static{a(this,\"Subscribers\")}constructor(){this.list=[];this.size=0;this.#e=0}#e;add(e){this.list.push(e);this.size++}remove(e){if(e.removed)return false;e.removed=true;this.size--;if(++this.#e>16&&this.#e>this.size){this.list=this.list.filter(t=>!t.removed);this.#e=0}return true}clear(){for(const e of this.list)e.removed=true;this.list=[];this.size=0;this.#e=0}};var O=class{static{a(this,\"Event\")}constructor(){this.subscribers=new du;this.queued=new du;this.ended=false;this.onerror=e=>{};this.execute=(...e)=>{if(this.ended){return}for(const t of this.subscribers.list){if(!t.removed)t.execute(...e)}if(this.queued.size===0)return;(async()=>{for(const t of this.queued.list){if(!t.removed)await t.execute(...e)}})().catch(t=>{this.onerror(t)})};this.complete=()=>{if(this.ended){return}for(const e of this.subscribers.list){if(e.complete&&!e.removed){e.complete()}}this.allUnsubscribe();this.ended=true;if(this.onended){this.onended();this.onended=void 0}};this.error=e=>{if(this.ended){return}for(const t of this.subscribers.list){if(t.error&&!t.removed){t.error(e)}}this.allUnsubscribe()};this.allUnsubscribe=()=>{if(this.ended){return}this.subscribers.clear();this.queued.clear();this.onsubscriberschange?.()};this.subscribe=(e,t,s)=>{const n={execute:e,complete:t,error:s};const i=this.subscribers;i.add(n);this.onsubscriberschange?.();const o=a(()=>{if(i.remove(n))this.onsubscriberschange?.()},\"unSubscribe\");const c=a(l=>{l.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.queuingSubscribe=(e,t,s)=>{if(this.ended)throw new Error(\"event completed\");const n={execute:e,complete:t,error:s};const i=this.queued;i.add(n);const o=a(()=>{i.remove(n)},\"unSubscribe\");const c=a(l=>{l.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.once=(e,t,s)=>{const n=this.subscribe((...i)=>{n.unSubscribe();e(...i)},t,s)};this.watch=(e,t)=>new Promise((s,n)=>{const i=t&&setTimeout(()=>{n(\"Event watch timeout\")},t);const{unSubscribe:o}=this.subscribe((...c)=>{const l=e(...c);if(l){if(i)clearTimeout(i);o();s(c)}})});this.asPromise=e=>new Promise((t,s)=>{const n=e&&setTimeout(()=>{s(\"Event asPromise timeout\")},e);this.once((...i)=>{if(n)clearTimeout(n);t(i)},()=>{if(n)clearTimeout(n);t([])},i=>{if(n)clearTimeout(n);s(i)})})}pipe(e){this.subscribe((...t)=>{e.execute(...t)})}get returnTrigger(){const{execute:e,error:t,complete:s}=this;return{execute:e,error:t,complete:s}}get returnListener(){const{subscribe:e,once:t,asPromise:s}=this;return{subscribe:e,once:t,asPromise:s}}get length(){return this.subscribers.size}};var hu=class{static{a(this,\"EventDisposer\")}constructor(){this._disposer=[]}push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e());this._disposer=[]}};var Jw=require(\"node:dgram\");var Up=Ye(require(\"node:net\"),1);var Zw=Ye(require(\"node:tls\"),1);var Qw=require(\"node:net\");var kr=P(\"webrtc/common/transport\");var cI=8e3;var Yw=4*1024*1024;function lI(r){try{if(r.getRecvBufferSize()<Yw)r.setRecvBufferSize(Yw)}catch(e){kr(\"the receive buffer cannot grow\",e)}}a(lI,\"growReceiveBuffer\");function uI(r,e){return r===e||r[1]===e[1]&&r[0]===e[0]}a(uI,\"sameAddress\");var en=class r{static{a(this,\"UdpTransport\")}constructor(e,t={}){this.socketType=e;this.options=t;this.type=\"udp\";this.onData=()=>{};this.closed=false;this.send=async(s,n)=>{const i=this.connected;if(i){if(!n||uI(n,i)){this.socket.send(s)}else{kr(\"not sent to an address other than the connected one\",n)}return}if(this.waiting){this.waiting.push([s,n]);return}if(n&&!Up.isIP(n[0])){return new Promise((o,c)=>{this.socket.send(s,n[1],n[0],l=>{if(l){kr(\"send error\",n,s);c(l)}else{o()}})})}else{n=n??[this.rinfo.address,this.rinfo.port];this.socket.send(s,n[1],n[0])}};this.close=()=>new Promise(s=>{this.closed=true;this.connectOnReceive=void 0;this.connecting=void 0;this.connected=void 0;this.waiting=void 0;this.socket.once(\"close\",s);try{this.socket.close()}catch(n){s()}});this.socket=(0,Jw.createSocket)(e);this.socket.on(\"message\",(s,n)=>{if(Qs(n.family)===6){[n.address]=n.address.split(\"%\")}this.rinfo=n;if(this.connectOnReceive&&s[0]>3&&n.port===this.connectOnReceive[1]&&n.address===this.connectOnReceive[0])this.connectNow(this.connectOnReceive);try{this.onData(s,[n.address,n.port])}catch(i){kr(\"onData error\",i)}})}static async init(e,t={}){const s=new r(e,t);await s.init();return s}async init(){const e=uu(this.socketType,this.options.interfaceAddresses);if(this.options.port){this.socket.bind({port:this.options.port,address:e})}else if(this.options.portRange){const t=await Xw(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else{this.socket.bind({port:await fu(this.socketType,this.options.interfaceAddresses),address:e})}await new Promise((t,s)=>{const n=a(i=>s(i),\"failed\");this.socket.once(\"error\",n);this.socket.once(\"listening\",()=>{this.socket.off(\"error\",n);t()})});this.socket.on(\"error\",t=>kr(\"socket error\",t));lI(this.socket)}connectTo(e){if(this.closed||this.connected||this.waiting||!Up.isIP(e[0]))return;this.connectOnReceive=e}disconnect(){this.connectOnReceive=void 0;this.connecting=void 0;if(!this.connected)return;this.connected=void 0;try{this.socket.disconnect()}catch(e){kr(\"disconnect\",e)}}connectNow(e){this.connectOnReceive=void 0;this.connecting=e;const t=[];this.waiting=t;const s=a(n=>{if(this.waiting===t)this.waiting=void 0;const i=this.connecting===e;if(i)this.connecting=void 0;if(this.closed)return;if(n){kr(\"connect\",e,n)}else if(i){this.connected=e}else{this.socket.disconnect()}for(const[o,c]of t)this.send(o,c).catch(l=>kr(\"send\",l))},\"done\");try{this.socket.connect(e[1],e[0],s)}catch(n){s(n)}}get address(){return this.socket.address()}get addressFamily(){return this.socketType===\"udp6\"?6:4}get host(){return this.socket.address().address}get port(){return this.socket.address().port}};var Ba=class r{static{a(this,\"TcpTransport\")}constructor(e,t={}){this.type=\"tcp\";this.send=async(s,n)=>{await this.stream.send(s,n)};this.close=async()=>{await this.stream.close()};this.stream=new pu(\"tcp\",()=>(0,Qw.connect)({port:e[1],host:e[0]}),void 0,t.connectTimeoutMs)}static async init(e,t={}){const s=new r(e,t);try{await s.init();return s}catch(n){await s.close();throw n}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var Ua=class r{static{a(this,\"TlsTransport\")}constructor(e,t={},s={}){this.type=\"tls\";this.send=async(n,i)=>{await this.stream.send(n,i)};this.close=async()=>{await this.stream.close()};this.stream=new pu(\"tls\",()=>Zw.connect({...t,host:e[0],port:e[1]}),void 0,s.connectTimeoutMs)}static async init(e,t={},s={}){const n=new r(e,t,s);try{await n.init();return n}catch(i){await n.close();throw i}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var pu=class{static{a(this,\"StreamTransport\")}constructor(e,t,s=e===\"tls\"?\"secureConnect\":\"connect\",n=cI){this.createClient=t;this.connectEvent=s;this.connectTimeoutMs=n;this.onData=()=>{};this.closed=false;this.send=async(i,o)=>{void o;await this.connecting;await new Promise((c,l)=>{this.client.write(i,u=>{if(u){l(u);return}c()})})};this.close=async()=>{this.closed=true;this.rejectConnecting?.(new Error(`${this.type} transport closed`));this.client?.destroy()};this.type=e;this.connect()}connect(){if(this.closed){return}if(this.client){this.client.destroy()}const e=this.createClient();this.client=e;this.connecting=new Promise((t,s)=>{let n=false;const i=a(u=>{if(n)return;n=true;clearTimeout(l);e.off(this.connectEvent,o);e.off(\"error\",c);this.rejectConnecting=void 0;u?s(u):t()},\"settle\");const o=a(()=>{i()},\"onConnect\");const c=a(u=>{this.closed=true;i(u);e.destroy()},\"onConnectError\");const l=setTimeout(()=>{this.closed=true;i(new Error(`${this.type} connect timed out after ${this.connectTimeoutMs}ms`));e.destroy()},this.connectTimeoutMs);this.rejectConnecting=u=>i(u);e.once(this.connectEvent,o);e.once(\"error\",c)});e.on(\"data\",t=>{this.onData(t,this.remoteAddress)});e.on(\"error\",t=>{kr(`${this.type} transport error`,t)})}async waitForConnect(){await this.connecting}get address(){return{}}get remoteAddress(){const{remoteAddress:e,remotePort:t}=this.client;if(!e||!t){return void 0}return[fI(e),t]}};function fI(r){return r.split(\"%\")[0]}a(fI,\"stripZoneId\");var q={};__(q,{BinaryReader:()=>gu,BinaryWriter:()=>$a,NotEnoughDataError:()=>mu,decode:()=>hI,encode:()=>dI,types:()=>yI});var mu=class extends Error{static{a(this,\"NotEnoughDataError\")}constructor(e,t){super(`requested ${e} bytes but only ${t} available`);this.name=\"NotEnoughDataError\"}};var gu=class{static{a(this,\"BinaryReader\")}constructor(e){this.buf=e;this.offset=0}get length(){return this.buf.length-this.offset}get bytes(){return this.offset}readBuffer(e){this.assertSize(e);const t=this.buf.subarray(this.offset,this.offset+e);this.offset+=e;return t}readUIntBE(e){this.assertSize(e);const t=this.buf.readUIntBE(this.offset,e);this.offset+=e;return t}assertSize(e){if(e>this.length){throw new mu(e,this.length)}}};var $a=class{static{a(this,\"BinaryWriter\")}constructor(){this.chunks=[];this.written=0}get bytes(){return this.written}writeBuffer(e){this.chunks.push(e);this.written+=e.length}writeUIntBE(e,t){const s=Buffer.allocUnsafe(t);switch(t){case 1:s.writeUInt8(e,0);break;case 2:s.writeUInt16BE(e,0);break;case 4:s.writeUInt32BE(e,0);break;default:s.writeUIntBE(e,0,t)}this.writeBuffer(s)}toBuffer(){return Buffer.concat(this.chunks,this.written)}};var tE=a(r=>typeof r===\"object\"&&r!==null,\"isObject\");var ut=a(r=>tE(r)&&typeof r.encode===\"function\"&&typeof r.decode===\"function\",\"isType\");var rE=a(r=>{if(!tE(r))return false;const e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},\"isPlainObject\");var sE=a(()=>({node:void 0,current:void 0}),\"createContext\");var eE=a(r=>({node:r.node,current:r.current}),\"cloneContext\");var nE=a((r,e)=>{if(!rE(r)){throw new TypeError(e)}},\"assertSchema\");var iE=a((r,e,t,s)=>{if(ut(e)){e.encode(r,t,s)}else{oE(r,e,t,s)}},\"encodeCommon\");var oE=a((r,e,t,s)=>{nE(e,\"Argument `schema` should be a plain object.\");if(s.node===void 0){s.node=r}s.current=r;for(const n of Object.keys(e)){const i=e[n];const o=r[n];if(ut(i)){i.encode(o,t,s)}else{oE(o,i,t,s);s.current=r}}},\"encodeSchema\");var jp=a((r,e,t)=>{if(ut(e)){return e.decode(r,t)}return aE(r,e,t)},\"decodeCommon\");var aE=a((r,e,t)=>{nE(e,\"Argument #2 should be a plain object.\");const s=Object.create(null);if(t.node===void 0){t.node=s}t.current=s;for(const n of Object.keys(e)){const i=e[n];if(ut(i)){s[n]=i.decode(r,t)}else{s[n]=aE(r,i,t);t.current=s}}return s},\"decodeSchema\");function dI(r,e){const t=new $a;iE(r,e,t,sE());return t.toBuffer()}a(dI,\"encode\");function hI(r,e){return jp(new gu(r),e,sE())}a(hI,\"decode\");var ja=a(r=>({encode:a((e,t)=>t.writeUIntBE(e,r),\"encode\"),decode:a(e=>e.readUIntBE(r),\"decode\")}),\"createUIntBE\");var $p=a(r=>{if(typeof r!==\"number\"&&!ut(r)&&typeof r!==\"function\"){throw new TypeError(\"Unknown type of argument #1.\")}},\"assertLengthSpec\");var Fa=a((r,e,t)=>{if(r!==e){throw new Error(`${t} required length ${r} instead of ${e}`)}},\"checkLength\");var tn=a((r,e)=>{if(typeof r!==\"number\"){throw new TypeError(e)}},\"checkLengthType\");function pI(r){$p(r);const e=\"Length of a buffer should be a number.\";return{encode(t,s,n){if(!Buffer.isBuffer(t)){throw new TypeError(\"Argument 1 should be a Buffer or a BinaryStream.\")}if(typeof r===\"number\"){Fa(r,t.length,\"Buffer\")}else if(ut(r)){r.encode(t.length,s,n)}else{const i=r(n);tn(i,e);Fa(i,t.length,\"Buffer\")}s.writeBuffer(t)},decode(t,s){let n;if(typeof r===\"number\"){n=r}else if(ut(r)){n=r.decode(t,s)}else{n=r(s)}tn(n,e);return t.readBuffer(n)}}}a(pI,\"buffer\");function mI(r,e,t=\"count\"){if(!ut(r)&&!rE(r)){throw new TypeError(\"Argument #1 should be a valid type.\")}$p(e);const s=t===\"bytes\";const n=\"Length of an array should be a number.\";return{encode(i,o,c){if(!Array.isArray(i)){throw new TypeError(\"Argument #1 should be an Array.\")}const l=eE(c);let u;if(typeof e===\"number\"){u=e}else if(ut(e)){u=i.length}else{u=e(l);tn(u,n)}const f=new $a;for(const d of i){iE(d,r,f,l)}if(s){if(ut(e)){u=f.bytes}Fa(f.bytes,u,\"Argument #1\")}else{Fa(u,i.length,\"Argument #1\")}if(ut(e)){e.encode(u,o,l)}o.writeBuffer(f.toBuffer())},decode(i,o){const c=eE(o);let l;if(typeof e===\"number\"){l=e}else if(ut(e)){l=e.decode(i,c)}else{l=e(c)}tn(l,n);const u=[];if(s){const f=i.bytes;let d=0;while(d<l){u.push(jp(i,r,c));d=i.bytes-f}if(d>l){throw new Error(\"Incorrect length of an array.\")}}else{for(let f=0;f<l;f++){u.push(jp(i,r,c))}}return u}}}a(mI,\"array\");function gI(r,e=\"ascii\"){if(!Buffer.isEncoding(e)){throw new Error(\"Argument #2 should be an encoding name.\")}$p(r);const t=\"Length of a buffer should be a number.\";return{encode(s,n,i){const o=Buffer.from(s.toString(),e);if(typeof r===\"number\"){if(o.length!==r){throw new Error(`Size of string should be ${r} in bytes.`)}}else if(ut(r)){r.encode(o.length,n,i)}else{const c=r(i);tn(c,t);Fa(c,o.length,\"Buffer\")}n.writeBuffer(o)},decode(s,n){let i;if(typeof r===\"number\"){i=r}else if(ut(r)){i=r.decode(s,n);tn(i,\"Size of a string should be a number.\")}else{i=r(n);tn(i,t)}return s.readBuffer(i).toString(e)}}}a(gI,\"string\");var yI={uint8:ja(1),uint16be:ja(2),uint24be:ja(3),uint32be:ja(4),uint48be:ja(6),buffer:pI,array:mI,string:gI};var Ha=class{static{a(this,\"Deque\")}#e=new Array(16);#t=0;#r=0;get length(){return this.#r}push(e){if(this.#r===this.#e.length)this.#s();this.#e[this.#t+this.#r&this.#e.length-1]=e;this.#r++}unshift(e){if(this.#r===this.#e.length)this.#s();this.#t=this.#t-1&this.#e.length-1;this.#e[this.#t]=e;this.#r++}shift(){if(!this.#r)return void 0;const e=this.#e[this.#t];this.#e[this.#t]=void 0;this.#t=this.#t+1&this.#e.length-1;this.#r--;return e}at(e){const t=e<0?this.#r+e:e;if(t<0||t>=this.#r)return void 0;return this.#e[this.#t+t&this.#e.length-1]}findIndex(e){for(let t=0;t<this.#r;t++){if(e(this.#e[this.#t+t&this.#e.length-1]))return t}return-1}clear(){this.#e=new Array(16);this.#t=0;this.#r=0}*[Symbol.iterator](){for(let e=0;e<this.#r;e++)yield this.#e[this.#t+e&this.#e.length-1]}#s(){const e=new Array(this.#e.length*2);for(let t=0;t<this.#r;t++)e[t]=this.#e[this.#t+t&this.#e.length-1];this.#e=e;this.#t=0}};var cE=require(\"node:events\");var a3=P(\"webrtc/peer/helper\");function Fp(r){return r.map((e,t)=>[t,e])}a(Fp,\"enumerate\");function yr(r,e){const t=r.split(e);return[t[0],t.slice(1).join(e)]}a(yr,\"divide\");var kt=class extends cE.EventEmitter{static{a(this,\"EventTarget\")}constructor(){super(...arguments);this.addEventListener=(e,t,s)=>{if(typeof s===\"object\"&&s?.once){this.once(e,t);return}this.addListener(e,t)};this.removeEventListener=(e,t)=>{this.removeListener(e,t)};this.dispatchEvent=e=>this.emit(e.type,e)}emit(e,...t){if(typeof e!==\"string\"){return super.emit(e,...t)}if(t.length===0){return super.emit(e,new Event(e))}const[s,...n]=t;if(s&&typeof s===\"object\"&&!(\"type\"in s)){try{Object.defineProperty(s,\"type\",{configurable:true,enumerable:true,value:e})}catch{return super.emit(e,{type:e,...s},...n)}}return super.emit(e,s,...n)}};var Si=1;var Cs=7;var lE=a(r=>{switch(r){case Si:case Cs:return 16}},\"keyLength\");var uE=a(r=>{switch(r){case Si:return 14;case Cs:return 12}},\"saltLength\");function fE(r){if(!Number.isInteger(r)||r<0||!Number.isSafeInteger(r)){throw new Error(\"LEB128 encode requires a non-negative safe integer\")}const e=[];let t=r;do{let s=t&127;t=Math.floor(t/128);if(t!==0){s|=128}e.push(s)}while(t!==0);return Buffer.from(e)}a(fE,\"leb128encode\");var bI=P(\"webrtc/rtp/codec/av1\");var Hp=class r{static{a(this,\"AV1RtpPayload\")}constructor(){this.obu_or_fragment=[]}static{this.deSerialize=e=>{const t=new r;let s=0;t.zBit_RtpStartsWithFragment=V(e[s],0);t.yBit_RtpEndsWithFragment=V(e[s],1);t.w_RtpNumObus=V(e[s],2,2);t.nBit_RtpStartsNewCodedVideoSequence=V(e[s],4);s++;if(t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment){throw new Error}[...Array(t.w_RtpNumObus-1).keys()].forEach(i=>{const[o,c]=SI(e.subarray(s));const l=s+c;const u=l+o;let f=false;if(t.zBit_RtpStartsWithFragment&&i===0){f=true}t.obu_or_fragment.push({data:e.subarray(l,u),isFragment:f});s+=c+o});let n=false;if(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment){n=true}t.obu_or_fragment.push({data:e.subarray(s),isFragment:n});return t}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){const t=[];const s=e.flatMap(c=>c.obu_or_fragment).reduce((c,l,u)=>{c[u]=l;return c},{});const n=Object.keys(s).length;for(const c of Object.keys(s).map(Number)){const l=s[c];if(!l)continue;const{data:u,isFragment:f}=l;if(f){let d=[];for(let h=c;h<n;h++){const p=s[h];if(p.isFragment){d.push(p.data);delete s[h]}else{break}}if(d.length<=1){bI(\"fragment lost, maybe packet lost\");d=[]}t.push(Buffer.concat(d))}else{t.push(u)}}const i=t.map(c=>qp.deSerialize(c));const o=i.pop();return Buffer.concat([...i.map(c=>{c.obu_has_size_field=1;return c.serialize()}),o.serialize()])}};var qp=class r{static{a(this,\"AV1Obu\")}static deSerialize(e){const t=new r;let s=0;t.obu_forbidden_bit=V(e[s],0);t.obu_type=dE[V(e[s],1,4)];t.obu_extension_flag=V(e[s],5);t.obu_has_size_field=V(e[s],6);t.obu_reserved_1bit=V(e[s],7);s++;t.payload=e.subarray(s);return t}serialize(){const e=new Zs(8).set(this.obu_forbidden_bit).set(wI[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer;let t=Buffer.alloc(0);if(this.obu_has_size_field){t=fE(this.payload.length)}return Buffer.concat([e,t,this.payload])}};function SI(r){let e=0;let t=0;for(let s=0;s<8;s++){if(s>=r.length){throw new Error(\"LEB128 decode incomplete\")}const n=r.readUInt8(s);e+=(n&127)*128**s;t++;if(!(n&128)){if(!Number.isSafeInteger(e)){throw new Error(\"LEB128 value exceeds safe integer\")}return[e,t]}}throw new Error(\"LEB128 decode incomplete\")}a(SI,\"leb128decode\");var dE={0:\"Reserved\",1:\"OBU_SEQUENCE_HEADER\",2:\"OBU_TEMPORAL_DELIMITER\",3:\"OBU_FRAME_HEADER\",4:\"OBU_TILE_GROUP\",5:\"OBU_METADATA\",6:\"OBU_FRAME\",7:\"OBU_REDUNDANT_FRAME_HEADER\",8:\"OBU_TILE_LIST\",15:\"OBU_PADDING\"};var wI=Object.entries(dE).reduce((r,[e,t])=>{r[t]=Number(e);return r},{});var E3=Buffer.from([0,0,0,1]);function zp(r,e){const t=Buffer.alloc(e);r.copy(t);return t}a(zp,\"growBufferSize\");function wi(r){return Number.parseInt(r.toString(),10)}a(wi,\"Int\");function hE(r){const e=r[0];return e>127&&e<192}a(hE,\"isMedia\");var qa=4;var ze=class r{static{a(this,\"RtcpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.count=0;this.type=0;this.length=0;Object.assign(this,e)}static serialize(e,t,s,n){const i=new r({type:e,count:t,version:2,length:n});const o=i.serialize();return Buffer.concat([o,s])}serialize(){const e=new Or(8);e.set(2,0,this.version);if(this.padding)e.set(1,2,1);e.set(5,3,this.count);const t=he([1,1,2],[e.value,this.type,this.length]);return t}static deSerialize(e){const[t,s,n]=Pe(e,[1,1,2]);const i=V(t,0,2);const o=V(t,2,1)>0;const c=V(t,3,5);return new r({version:i,padding:o,count:c,type:s,length:n})}};var za=class r{static{a(this,\"FullIntraRequest\")}static{this.count=4}constructor(e={}){this.count=r.count;this.fir=[];Object.assign(this,e)}get length(){return this.serialize().length/4}static deSerialize(e){const[t,s]=Pe(e,[4,4]);const n=[];for(let i=8;i<e.length;i+=8){n.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]})}return new r({senderSsrc:t,mediaSsrc:s,fir:n})}serialize(){const e=he([4,4],[this.senderSsrc,this.mediaSsrc]);const t=Buffer.alloc(this.fir.length*8);this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{t.writeUInt32BE(s,i*8);t[i*8+4]=n});return Buffer.concat([e,t])}};var Pr=class r{static{a(this,\"PictureLossIndication\")}static{this.count=1}constructor(e={}){this.count=r.count;this.length=2;Object.assign(this,e)}static deSerialize(e){const[t,s]=Pe(e,[4,4]);return new r({senderSsrc:t,mediaSsrc:s})}serialize(){return he([4,4],[this.senderSsrc,this.mediaSsrc])}};var Nr=class r{static{a(this,\"ReceiverEstimatedMaxBitrate\")}static{this.count=15}constructor(e={}){this.count=r.count;this.uniqueID=\"REMB\";this.ssrcNum=0;this.ssrcFeedbacks=[];Object.assign(this,e)}static deSerialize(e){const[t,s,n,i,o]=Pe(e,[4,4,4,1,1]);const c=V(o,0,6);const l=(V(o,6,2)<<16)+(e[14]<<8)+e[15];const u=c>46?18446744073709551615n:BigInt(l)<<BigInt(c);const f=[];for(let d=16;d<e.length;d+=4){const h=e.slice(d).readUIntBE(0,4);f.push(h)}return new r({senderSsrc:t,mediaSsrc:s,uniqueID:he([4],[n]).toString(),ssrcNum:i,brExp:c,brMantissa:l,ssrcFeedbacks:f,bitrate:u})}serialize(){const e=Buffer.concat([he([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),he([1],[this.ssrcNum])]);const t=new Or(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);const s=Buffer.concat(this.ssrcFeedbacks.map(i=>he([4],[i])));const n=Buffer.concat([e,he([3],[t.value]),s]);this.length=n.length/4;return n}};var TI=P(\"webrtc/rtp/rtcp/psfb/index\");var Xt=class r{static{a(this,\"RtcpPayloadSpecificFeedback\")}static{this.type=206}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return ze.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let s;switch(t.count){case za.count:s=za.deSerialize(e);break;case Pr.count:s=Pr.deSerialize(e);break;case Nr.count:s=Nr.deSerialize(e);break;default:TI(\"unknown psfb packet\",t.count);break}return new r({feedback:s})}};var Yt=class r{static{a(this,\"RtcpRrPacket\")}static{this.type=201}constructor(e={}){this.ssrc=0;this.reports=[];this.type=r.type;Object.assign(this,e)}serialize(){let e=he([4],[this.ssrc]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return ze.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const[s]=Pe(e,[4]);let n=4;const i=[];for(let o=0;o<t;o++){i.push(rn.deSerialize(e.slice(n,n+24)));n+=24}return new r({ssrc:s,reports:i})}};var rn=class r{static{a(this,\"RtcpReceiverInfo\")}constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return he([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){const[t,s,n,i,o,c,l]=Pe(e,[4,1,3,4,4,4,4]);return new r({ssrc:t,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:c,dlsr:l})}};var yu=205;var Lr=class r{static{a(this,\"GenericNack\")}static{this.count=1}toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){this.count=r.count;this.lost=[];Object.assign(this,e);if(!this.header){this.header=new ze({type:yu,count:this.count,version:2})}}static deSerialize(e,t){const[s,n]=Pe(e,[4,4]);const i=[];for(let o=8;o<e.length;o+=4){const[c,l]=Pe(e.subarray(o),[2,2]);i.push(c);for(let u=0;u<16;u++){if(l>>u&1){i.push(c+u+1)}}}return new r({header:t,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){const e=he([4,4],[this.senderSsrc,this.mediaSourceSsrc]);const t=[];if(this.lost.length>0){let n=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{const c=o-n-1;if(c>=0&&c<16){i|=1<<c}else{t.push(he([2,2],[n,i]));n=o;i=0}});t.push(he([2,2],[n,i]))}const s=Buffer.concat([e,Buffer.concat(t)]);this.header.length=s.length/4;return Buffer.concat([this.header.serialize(),s])}};var xI=P(\"webrtc/rtp/rtcp/rtpfb/twcc\");var Mr=class r{static{a(this,\"TransportWideCC\")}static{this.count=15}constructor(e={}){this.count=r.count;this.length=2;this.packetChunks=[];this.recvDeltas=[];Object.assign(this,e);if(!this.header){this.header=new ze({type:205,count:this.count,version:2})}}static deSerialize(e,t){const[s,n,i,o,c,l]=Pe(e,[4,4,2,2,3,1]);const u=[];const f=[];let d=16;for(let p=0;p<o;){const m=V(e.slice(d,d+1)[0],0,1);let y;switch(m){case vs.TypeTCCRunLengthChunk:{const w=Ei.deSerialize(e.slice(d,d+2));y=w;const S=Math.min(o-p,w.runLength);if(w.packetStatus===Te.TypeTCCPacketReceivedSmallDelta||w.packetStatus===Te.TypeTCCPacketReceivedLargeDelta){for(let T=0;T<S;T++){f.push(new sn({type:w.packetStatus}))}}p+=S}break;case vs.TypeTCCStatusVectorChunk:{const w=Ga.deSerialize(e.slice(d,d+2));y=w;if(w.symbolSize===0){w.symbolList.forEach(S=>{if(S===Te.TypeTCCPacketReceivedSmallDelta){f.push(new sn({type:Te.TypeTCCPacketReceivedSmallDelta}))}})}if(w.symbolSize===1){w.symbolList.forEach(S=>{if(S===Te.TypeTCCPacketReceivedSmallDelta||S===Te.TypeTCCPacketReceivedLargeDelta){f.push(new sn({type:S}))}})}p+=w.symbolList.length}break}if(!y)throw new Error;d+=2;u.push(y)}let h=d;f.forEach(p=>{if(p.type===Te.TypeTCCPacketReceivedSmallDelta){p.deSerialize(e.slice(h,h+1));h++}if(p.type===Te.TypeTCCPacketReceivedLargeDelta){p.deSerialize(e.slice(h,h+2));h+=2}});return new r({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:c,fbPktCount:l,recvDeltas:f,packetChunks:u,header:t})}serialize(){const e=he([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]);const t=Buffer.concat(this.packetChunks.map(o=>o.serialize()));const s=Buffer.concat(this.recvDeltas.map(o=>{try{return o.serialize()}catch(c){xI(c?.message);return void 0}}).filter(o=>o));const n=Buffer.concat([e,t,s]);const i=n.length%4;this.header.padding=i!==0;if(i!==0){const o=Buffer.alloc(4-i);o[o.length-1]=o.length;this.header.length=(n.length+o.length)/4;return Buffer.concat([this.header.serialize(),n,o])}this.header.length=n.length/4;return Buffer.concat([this.header.serialize(),n])}get packetResults(){const e=[];for(const i of this.packetChunks){if(i instanceof Ei){for(let o=0;o<i.runLength;o++)e.push(i.packetStatus)}else{e.push(...i.symbolList)}}if(e.length>this.packetStatusCount)e.length=this.packetStatusCount;const t=[];let s=this.referenceTime*64e3;let n=0;e.forEach((i,o)=>{const c=new Gp({sequenceNumber:this.baseSequenceNumber+o&65535});if(i===Te.TypeTCCPacketReceivedSmallDelta||i===Te.TypeTCCPacketReceivedLargeDelta){const l=this.recvDeltas[n++];if(l){s+=l.delta;c.received=true;c.delta=l.delta;c.receivedAtMs=s/1e3}}t.push(c)});return t}};var Ei=class r{static{a(this,\"RunLengthChunk\")}constructor(e={}){Object.assign(this,e);this.type=vs.TypeTCCRunLengthChunk}static deSerialize(e){const t=V(e[0],1,2);const s=(V(e[0],3,5)<<8)+e[1];return new r({type:0,packetStatus:t,runLength:s})}serialize(){const e=new Zs(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer;return e}};var Ga=class r{static{a(this,\"StatusVectorChunk\")}constructor(e={}){this.symbolList=[];Object.assign(this,e)}static deSerialize(e){const t=vs.TypeTCCStatusVectorChunk;let s=V(e[0],1,1);const n=[];function i(o,c){for(let l=0;l<o;l++){c(l)}}a(i,\"range\");switch(s){case 0:i(6,o=>n.push(V(e[0],2+o,1)));i(8,o=>n.push(V(e[1],o,1)));break;case 1:i(3,o=>n.push(V(e[0],2+o*2,2)));i(4,o=>n.push(V(e[1],o*2,2)));break;default:s=(V(e[0],2,6)<<8)+e[1]}return new r({type:t,symbolSize:s,symbolList:n})}serialize(){const e=Buffer.alloc(2);const t=new Zs(16).set(1).set(this.symbolSize);const s=this.symbolSize===0?1:2;this.symbolList.forEach(n=>{t.set(n,s)});e.writeUInt16BE(t.value);return e}};var sn=class r{static{a(this,\"RecvDelta\")}constructor(e={}){this.parsed=false;Object.assign(this,e)}static deSerialize(e){let t;let s;if(e.length===1){t=Te.TypeTCCPacketReceivedSmallDelta;s=250*e[0]}else if(e.length===2){t=Te.TypeTCCPacketReceivedLargeDelta;s=250*e.readInt16BE()}if(t===void 0||s===void 0)throw new Error;return new r({type:t,delta:s})}deSerialize(e){const t=r.deSerialize(e);this.delta=t.delta}parseDelta(){this.delta=Math.floor(this.delta/250);if(this.delta<0||this.delta>255){if(this.delta>32767)this.delta=32767;if(this.delta<-32768)this.delta=-32768;if(!this.type)this.type=Te.TypeTCCPacketReceivedLargeDelta}else{if(!this.type)this.type=Te.TypeTCCPacketReceivedSmallDelta}this.parsed=true}serialize(){if(!this.parsed)this.parseDelta();if(this.type===Te.TypeTCCPacketReceivedSmallDelta){const e=Buffer.alloc(1);e.writeUInt8(this.delta);return e}else if(this.type===Te.TypeTCCPacketReceivedLargeDelta){const e=Buffer.alloc(2);e.writeInt16BE(this.delta);return e}throw new Error(\"errDeltaExceedLimit \"+this.delta+\" \"+this.type)}};var vs;(function(r){r[r[\"TypeTCCRunLengthChunk\"]=0]=\"TypeTCCRunLengthChunk\";r[r[\"TypeTCCStatusVectorChunk\"]=1]=\"TypeTCCStatusVectorChunk\";r[r[\"packetStatusChunkLength\"]=2]=\"packetStatusChunkLength\"})(vs||(vs={}));var Te;(function(r){r[r[\"TypeTCCPacketNotReceived\"]=0]=\"TypeTCCPacketNotReceived\";r[r[\"TypeTCCPacketReceivedSmallDelta\"]=1]=\"TypeTCCPacketReceivedSmallDelta\";r[r[\"TypeTCCPacketReceivedLargeDelta\"]=2]=\"TypeTCCPacketReceivedLargeDelta\";r[r[\"TypeTCCPacketReceivedWithoutDelta\"]=3]=\"TypeTCCPacketReceivedWithoutDelta\"})(Te||(Te={}));var Gp=class{static{a(this,\"PacketResult\")}constructor(e){this.sequenceNumber=0;this.delta=0;this.received=false;this.receivedAtMs=0;Object.assign(this,e)}};var RI=P(\"webrtc/rtp/rtcp/rtpfb/index\");var nt=class r{static{a(this,\"RtcpTransportLayerFeedback\")}static{this.type=yu}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return e}static deSerialize(e,t){let s;switch(t.count){case Lr.count:s=Lr.deSerialize(e,t);break;case Mr.count:s=Mr.deSerialize(e,t);break;default:RI(\"unknown rtpfb packet\",t.count);break}return new r({feedback:s,header:t})}};var Dr=class r{static{a(this,\"RtcpSourceDescriptionPacket\")}static{this.type=202}constructor(e){this.type=r.type;this.chunks=[];Object.assign(this,e)}get length(){let e=0;this.chunks.forEach(t=>e+=t.length);return e}serialize(){let e=Buffer.concat(this.chunks.map(t=>t.serialize()));while(e.length%4)e=Buffer.concat([e,Buffer.from([0])]);return ze.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){const s=[];for(let n=0;n<e.length;){const i=Ka.deSerialize(e.slice(n));s.push(i);n+=i.length}return new r({chunks:s})}};var Ka=class r{static{a(this,\"SourceDescriptionChunk\")}constructor(e={}){this.items=[];Object.assign(this,e)}get length(){let e=4;this.items.forEach(t=>e+=t.length);e+=1;e+=pE(e);return e}serialize(){const e=Buffer.concat([he([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);const t=Buffer.concat([e,Buffer.alloc(pE(e.length))]);return t}static deSerialize(e){const t=e.readUInt32BE();const s=[];for(let n=4;n<e.length;){const i=e[n];if(i===0)break;const o=Wa.deSerialize(e.slice(n));s.push(o);n+=o.length}return new r({source:t,items:s})}};var Wa=class r{static{a(this,\"SourceDescriptionItem\")}constructor(e){Object.assign(this,e)}get length(){return 1+1+Buffer.from(this.text).length}serialize(){const e=Buffer.from(this.text);return Buffer.concat([he([1,1],[this.type,e.length]),e])}static deSerialize(e){const t=e[0];const s=e[1];const n=e.slice(2,2+s).toString();return new r({type:t,text:n})}};function pE(r){if(r%4==0){return 0}return 4-r%4}a(pE,\"getPadding\");var Pt=class r{static{a(this,\"RtcpSrPacket\")}static{this.type=200}constructor(e){this.ssrc=0;this.reports=[];this.type=r.type;Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);e.writeUInt32BE(this.ssrc);e=Buffer.concat([e,this.senderInfo.serialize()]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return ze.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const s=e.readUInt32BE();const n=Va.deSerialize(e.subarray(4,24));let i=24;const o=[];for(let l=0;l<t;l++){o.push(rn.deSerialize(e.subarray(i,i+24)));i+=24}const c=new r({ssrc:s,senderInfo:n,reports:o});return c}};var Va=class r{static{a(this,\"RtcpSenderInfo\")}constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:_I(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return he([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){const[t,s,n,i]=Pe(e,[8,4,4,4]);return new r({ntpTimestamp:t,rtpTimestamp:s,packetCount:n,octetCount:i})}};var _I=a(r=>{const[e,t]=Pe(he([8],[r]),[4,4]);return Number(`${e}.${t}`)},\"ntpTime2Sec\");var CI=P(\"webrtc/rtp/rtcp/rtcp\");var bu=class{static{a(this,\"RtcpPacketConverter\")}static deSerialize(e){let t=0;const s=[];while(t<e.length){const n=ze.deSerialize(e.subarray(t,t+qa));t+=qa;let i=e.subarray(t,t+n.length*4);t+=n.length*4;if(n.padding){i=i.subarray(0,i.length-i.subarray(-1)[0])}try{switch(n.type){case Pt.type:s.push(Pt.deSerialize(i,n.count));break;case Yt.type:s.push(Yt.deSerialize(i,n.count));break;case Dr.type:s.push(Dr.deSerialize(i,n));break;case nt.type:s.push(nt.deSerialize(i,n));break;case Xt.type:s.push(Xt.deSerialize(i,n));break;default:break}}catch(o){CI(\"deSerialize RTCP\",o)}}return s}};function mE(r){return r.length>=2&&r[1]>=192&&r[1]<=208}a(mE,\"isRtcp\");var pe={sdesMid:\"urn:ietf:params:rtp-hdrext:sdes:mid\",sdesRTPStreamID:\"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\",repairedRtpStreamId:\"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\",transportWideCC:\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\",absSendTime:\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\",dependencyDescriptor:\"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension\",audioLevelIndication:\"urn:ietf:params:rtp-hdrext:ssrc-audio-level\",videoOrientation:\"urn:3gpp:video-orientation\"};function gE(r,e){return r.map(t=>{const s=e[t.id];if(!s){return{uri:\"unknown\",value:t.payload}}switch(s){case pe.sdesMid:case pe.sdesRTPStreamID:case pe.repairedRtpStreamId:return{uri:s,value:vI(t.payload)};case pe.transportWideCC:return{uri:s,value:AI(t.payload)};case pe.absSendTime:return{uri:s,value:II(t.payload)};case pe.audioLevelIndication:{return{uri:s,value:OI(t.payload)}}case pe.videoOrientation:return{uri:s,value:kI(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>{if(s)t[s.uri]=s.value;return t},{})}a(gE,\"rtpHeaderExtensionsParser\");function yE(r){return Buffer.from(r)}a(yE,\"serializeSdesMid\");function bE(r){return Buffer.from(r)}a(bE,\"serializeSdesRTPStreamID\");function SE(r){return Buffer.from(r)}a(SE,\"serializeRepairedRtpStreamId\");function Kp(r){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(r);return e}a(Kp,\"serializeTransportWideCC\");function vI(r){return r.toString()}a(vI,\"deserializeString\");function AI(r){return r.readUInt16BE()}a(AI,\"deserializeUint16BE\");function II(r){return Pe(r,[3])[0]}a(II,\"deserializeAbsSendTime\");function OI(r){const e=new mr(r);const t={v:e.readBits(1)===1,level:e.readBits(7)};return t}a(OI,\"deserializeAudioLevelIndication\");function kI(r){const e=new mr(r);e.readBits(4);const t={c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)};return t}a(kI,\"deserializeVideoOrientation\");var PI=P(\"packages/rtp/src/rtp/red/packet.ts\");var Ti=class r{static{a(this,\"Red\")}constructor(){this.blocks=[]}static deSerialize(e){const t=e instanceof ArrayBuffer?Buffer.from(e):e;const s=new r;let n=0;[s.header,n]=Su.deSerialize(t);s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:c})=>{if(i&&o){const l=t.subarray(n,n+i);s.blocks.push({block:l,blockPT:c,timestampOffset:o});n+=i}else{const l=t.subarray(n);s.blocks.push({block:l,blockPT:c})}});return s}serialize(){this.header=new Su;for(const{timestampOffset:t,blockPT:s,block:n}of this.blocks){if(t){this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:t})}else{this.header.fields.push({fBit:0,blockPT:s})}}let e=this.header.serialize();for(const{block:t}of this.blocks){e=Buffer.concat([e,t])}return e}};var Su=class r{static{a(this,\"RedHeader\")}constructor(){this.fields=[]}static deSerialize(e){let t=0;const s=new r;for(;;){const n={};s.fields.push(n);const i=new mr(e.subarray(t));n.fBit=i.readBits(1);n.blockPT=i.readBits(7);t++;if(n.fBit===0){break}n.timestampOffset=i.readBits(14);n.blockLength=i.readBits(10);t+=3}return[s,t]}serialize(){let e=Buffer.alloc(0);for(const t of this.fields){try{if(t.timestampOffset&&t.blockLength){const s=new mr(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,s.uint8Array])}else{const s=new mr(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){PI(s?.message)}}return e}};var wu=class{static{a(this,\"RedEncoder\")}constructor(e=1){this.distance=e;this.cache=[];this.cacheSize=10}push(e){this.cache.push(e);if(this.cache.length>this.cacheSize){this.cache.shift()}}build(){const e=new Ti;const t=this.cache.slice(-(this.distance+1));const s=t.pop();if(!s){return e}t.forEach(n=>{const i=gr(s.timestamp,-n.timestamp);if(i>NI){return}e.blocks.push({block:n.block,blockPT:n.blockPT,timestampOffset:i})});e.blocks.push({block:s.block,blockPT:s.blockPT});return e}};var NI=(1<<14)-1;var Eu=class{static{a(this,\"RedHandler\")}constructor(){this.size=150;this.sequenceNumbers=[]}push(e,t){const s=[];e.blocks.forEach(({blockPT:i,timestampOffset:o,block:c},l)=>{const u=$e(t.header.sequenceNumber,-(e.blocks.length-(l+1)));if(o){s.push(new Le(new Xe({timestamp:gr(t.header.timestamp,-o),payloadType:i,ssrc:t.header.ssrc,sequenceNumber:u,marker:true}),c))}else{s.push(new Le(new Xe({timestamp:t.header.timestamp,payloadType:i,ssrc:t.header.ssrc,sequenceNumber:u,marker:true}),c))}});const n=s.filter(i=>{if(this.sequenceNumbers.includes(i.header.sequenceNumber)){return false}else{if(this.sequenceNumbers.length>this.size){this.sequenceNumbers.shift()}this.sequenceNumbers.push(i.header.sequenceNumber);return true}});return n}};var nn={OneByte:48862,TwoByte:4096};var wE=2;var EE=4;var TE=8;var xE=12;var RE=4;var Xe=class r{static{a(this,\"RtpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.paddingSize=0;this.extension=false;this.marker=false;this.payloadOffset=0;this.payloadType=0;this.sequenceNumber=0;this.timestamp=0;this.ssrc=0;this.csrcLength=0;this.csrc=[];this.extensionProfile=nn.OneByte;this.extensions=[];Object.assign(this,e)}static deSerialize(e){const t=new r;let s=0;const n=e[s++];t.version=V(n,0,2);t.padding=V(n,2)>0;t.extension=V(n,3)>0;t.csrcLength=V(n,4,4);t.csrc=[...Array(t.csrcLength)].map(()=>{const o=e.readUInt32BE(s);s+=4;return o});s+=xE-1;const i=e[1];t.marker=V(i,0)>0;t.payloadType=V(i,1,7);t.sequenceNumber=e.readUInt16BE(wE);t.timestamp=e.readUInt32BE(EE);t.ssrc=e.readUInt32BE(TE);for(let o=0;o<t.csrc.length;o++){const c=xE+o*RE;t.csrc[o]=e.subarray(c).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(s).readUInt16BE();s+=2;const o=e.subarray(s).readUInt16BE()*4;t.extensionLength=o;s+=2;switch(t.extensionProfile){case nn.OneByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const l=e[s]>>4;const u=(e[s]&(e[s]^240))+1;s++;if(l===15){break}const f={id:l,payload:e.subarray(s,s+u)};t.extensions=[...t.extensions,f];s+=u}}break;case nn.TwoByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const l=e[s];s++;const u=e[s];s++;const f={id:l,payload:e.subarray(s,s+u)};t.extensions=[...t.extensions,f];s+=u}}break;default:{const c={id:0,payload:e.subarray(s,s+o)};t.extensions=[...t.extensions,c];s+=t.extensions[0].payload.length}break}}t.payloadOffset=s;if(t.padding){t.paddingSize=e[e.length-1]}return t}get serializeSize(){const{csrc:e,extensionProfile:t,extensions:s}=this;let n=12+e.length*RE;if(s.length>0||this.extension===true){let i=4;switch(t){case nn.OneByte:for(const o of s){i+=1+o.payload.length}break;case nn.TwoByte:for(const o of s){i+=2+o.payload.length}break;default:i+=s[0].payload.length}n+=Math.floor((i+3)/4)*4}return n}serialize(e){const t=Buffer.alloc(e);let s=0;const n=new Or(8);n.set(2,0,this.version);if(this.padding)n.set(1,2,1);if(this.extensions.length>0)this.extension=true;if(this.extension)n.set(1,3,1);n.set(4,4,this.csrc.length);t.writeUInt8(n.value,s++);const i=new Or(8);if(this.marker)i.set(1,0,1);i.set(7,1,this.payloadType);t.writeUInt8(i.value,s++);t.writeUInt16BE(this.sequenceNumber,wE);s+=2;t.writeUInt32BE(this.timestamp,EE);s+=4;t.writeUInt32BE(this.ssrc,TE);s+=4;for(const o of this.csrc){t.writeUInt32BE(o,s);s+=4}if(this.extension){const o=s;t.writeUInt16BE(this.extensionProfile,s);s+=4;const c=s;switch(this.extensionProfile){case nn.OneByte:for(const f of this.extensions){t.writeUInt8(f.id<<4|f.payload.length-1,s++);f.payload.copy(t,s);s+=f.payload.length}break;case nn.TwoByte:for(const f of this.extensions){t.writeUInt8(f.id,s++);t.writeUInt8(f.payload.length,s++);f.payload.copy(t,s);s+=f.payload.length}break;default:{const f=this.extensions[0].payload.length;if(f%4!=0){throw new Error}this.extensions[0].payload.copy(t,s);s+=f}}const l=s-c;const u=Math.trunc((l+3)/4)*4;t.writeUInt16BE(Math.trunc(u/4),o+2);for(let f=0;f<u-l;f++){t.writeUInt8(0,s);s++}}this.payloadOffset=s;return t}};var Le=class r{static{a(this,\"RtpPacket\")}constructor(e,t){this.header=e;this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new r(new Xe({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length);const{payloadOffset:t}=this.header;this.payload.copy(e,t);if(this.header.padding){const s=Buffer.alloc(this.header.paddingSize);s.writeUInt8(this.header.paddingSize,this.header.paddingSize-1);e=Buffer.concat([e,s])}return e}static deSerialize(e){const t=Xe.deSerialize(e);const s=new r(t,e.subarray(t.payloadOffset,e.length-t.paddingSize));return s}clear(){this.payload=null}};function _E(r,e,t){const s=new Le(new Xe({payloadType:e,marker:r.header.marker,sequenceNumber:r.payload.readUInt16BE(0),timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2));return s}a(_E,\"unwrapRtx\");function CE(r,e,t,s){const n=Buffer.allocUnsafe(2);n.writeUInt16BE(r.header.sequenceNumber,0);const i=new Le(new Xe({payloadType:e,marker:r.header.marker,sequenceNumber:t,timestamp:r.header.timestamp,ssrc:s,csrc:r.header.csrc,extensions:r.header.extensions}),Buffer.concat([n,r.payload]));return i}a(CE,\"wrapRtx\");var Ci=require(\"node:crypto\");var Jt=require(\"node:crypto\");var xi=class{static{a(this,\"CipherAesBase\")}constructor(e,t,s,n){this.srtpSessionKey=e;this.srtpSessionSalt=t;this.srtcpSessionKey=s;this.srtcpSessionSalt=n}encryptRtp(e,t,s){return Buffer.from([])}decryptRtp(e,t,s){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}};var Nt=class extends Error{static{a(this,\"SrtpAuthenticationError\")}constructor(e){super(e);this.name=\"SrtpAuthenticationError\"}};var vE=12;var LI=8;function Ri(r,e,t=\"Failed to authenticate SRTP packet\"){const s=r.length-e;Xa(r.length>=vE+e,t);const n=AE(()=>Xe.deSerialize(r.subarray(0,s)),t);n.paddingSize=0;Xa(n.payloadOffset>=vE&&n.payloadOffset<=s,t);return n}a(Ri,\"parseSrtpRtpHeader\");function Tu(r,e,t,s=\"Failed to authenticate SRTCP packet\"){Xa(r.length>=LI+e+t,s);return AE(()=>ze.deSerialize(r.subarray(0,qa)),s)}a(Tu,\"parseSrtcpHeader\");function Xa(r,e){if(!r){throw new Nt(e)}}a(Xa,\"assertAuthenticatedPacketLength\");function AE(r,e){try{return r()}catch{throw new Nt(e)}}a(AE,\"wrapAuthenticationError\");function xu(r,e,t=\"Failed to authenticate SRTP packet\"){if(!r.padding){r.paddingSize=0;return r}Xa(e.length>r.payloadOffset,t);const s=e[e.length-1];Xa(s>0&&s<=e.length-r.payloadOffset,t);r.paddingSize=s;return r}a(xu,\"finalizeSrtpRtpHeader\");var Ru=class extends xi{static{a(this,\"CipherAesCtr\")}constructor(e,t,s,n,i,o){super(e,t,s,n);this.srtpSessionAuthTag=i;this.srtcpSessionAuthTag=o;this.authTagLength=10}encryptRtp(e,t,s){const n=e.serialize(e.serializeSize);const i=this.generateCounter(e.sequenceNumber,s,e.ssrc,this.srtpSessionSalt);const o=(0,Jt.createCipheriv)(\"aes-128-ctr\",this.srtpSessionKey,i);const c=o.update(t);const l=this.generateSrtpAuthTag(s,n,c);return Buffer.concat([n,c,l])}decryptRtp(e,t,s=Ri(e,this.authTagLength)){const n=e.length-this.authTagLength;const i=e.subarray(0,n);const o=e.subarray(n);const c=this.generateSrtpAuthTag(t,i.subarray(0,s.payloadOffset),i.subarray(s.payloadOffset));OE(o,c,\"Failed to authenticate SRTP packet\");const l=this.generateCounter(s.sequenceNumber,t,s.ssrc,this.srtpSessionSalt);const u=(0,Jt.createDecipheriv)(\"aes-128-ctr\",this.srtpSessionKey,l);const f=i.subarray(s.payloadOffset);const d=u.update(f);const h=Buffer.concat([i.subarray(0,s.payloadOffset),d]);return[h,xu(s,h,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){let s=Buffer.from(e);const n=s.readUInt32BE(4);const i=this.generateCounter(t&65535,t>>16,n,this.srtcpSessionSalt);const o=(0,Jt.createCipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,i);const c=o.update(s.slice(8));c.copy(s,8);s=Buffer.concat([s,Buffer.alloc(4)]);s.writeUInt32BE(t,s.length-4);s[s.length-4]|=128;const l=this.generateSrtcpAuthTag(s);s=Buffer.concat([s,l]);return s}decryptRTCP(e){const t=Tu(e,this.authTagLength,IE);const s=e.length-(this.authTagLength+IE);const n=e.subarray(0,e.length-this.authTagLength);const i=e.subarray(e.length-this.authTagLength);const o=this.generateSrtcpAuthTag(n);OE(i,o,\"Failed to authenticate SRTCP packet\");const c=Buffer.from(e).slice(0,s);const l=e[s]>>>7;if(l===0)return[c,t];let u=e.readUInt32BE(s);u&=~(1<<31);const f=e.readUInt32BE(4);const d=this.generateCounter(u&65535,u>>16,f,this.srtcpSessionSalt);const h=(0,Jt.createDecipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,d);const p=h.update(c.subarray(8));p.copy(c,8);return[c,t]}generateSrtcpAuthTag(e){const t=(0,Jt.createHmac)(\"sha1\",this.srtcpSessionAuthTag);return t.update(e).digest().slice(0,10)}generateCounter(e,t,s,n){const i=Buffer.alloc(16);i.writeUInt32BE(s,4);i.writeUInt32BE(t,8);i.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let o=0;o<n.length;o++){i[o]^=n[o]}return i}generateSrtpAuthTag(e,...t){const s=(0,Jt.createHmac)(\"sha1\",this.srtpSessionAuthTag);const n=Buffer.alloc(4);n.writeUInt32BE(e);for(const i of t){s.update(i)}return s.update(n).digest().subarray(0,10)}};var IE=4;function OE(r,e,t){if(r.length!==e.length||!(0,Jt.timingSafeEqual)(r,e)){throw new Nt(t)}}a(OE,\"assertAuthTag\");var _i=require(\"node:crypto\");var _u=class extends xi{static{a(this,\"CipherAesGcm\")}constructor(e,t,s,n){super(e,t,s,n);this.aeadAuthTagLen=16;this.rtpIvWriter=Ma([2,4,4,2],true);this.rtcpIvWriter=Ma([2,4,2,4],true);this.aadWriter=Ma([4],true)}encryptRtp(e,t,s){const n=e.serialize(e.serializeSize);const i=this.rtpInitializationVector(e,s);const o=(0,_i.createCipheriv)(\"aes-128-gcm\",this.srtpSessionKey,i);o.setAAD(n);const c=o.update(t);o.final();const l=o.getAuthTag();const u=Buffer.concat([n,c,l]);return u}decryptRtp(e,t,s=Ri(e,this.aeadAuthTagLen)){const n=e.subarray(0,s.payloadOffset);const i=e.length-this.aeadAuthTagLen;const o=e.subarray(i);let c=Buffer.from([]);c=zp(c,e.length-this.aeadAuthTagLen);n.copy(c);const l=this.rtpInitializationVector(s,t);const u=e.slice(s.payloadOffset,i);const f=(0,_i.createDecipheriv)(\"aes-128-gcm\",this.srtpSessionKey,l);f.setAAD(n);f.setAuthTag(o);const d=f.update(u);PE(f,\"SRTP\");d.copy(c,s.payloadOffset);return[c,xu(s,c,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){const s=e.readUInt32BE(4);const n=e.length+this.aeadAuthTagLen;let i=Buffer.from([]);i=zp(i,n+Wp);e.slice(0,8).copy(i);const o=this.rtcpInitializationVector(s,t);const c=this.rtcpAdditionalAuthenticatedData(e,t);const l=(0,_i.createCipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,o);l.setAAD(c);const u=l.update(e.slice(8));l.final();u.copy(i,8);const f=l.getAuthTag();f.copy(i,8+u.length);c.slice(8,12).copy(i,n);return i}decryptRTCP(e){const t=Tu(e,this.aeadAuthTagLen,Wp);const s=e.length-Wp;const n=s-this.aeadAuthTagLen;const i=e.readUInt32BE(4);const o=e.readUInt32BE(s);const c=o>>>31===1;const l=o&~(kE<<24);const u=this.rtcpInitializationVector(i,l);const f=c?Buffer.concat([e.subarray(0,8),e.subarray(s)]):Buffer.concat([e.subarray(0,n),e.subarray(s)]);const d=c?e.slice(8,n):Buffer.alloc(0);const h=c?Buffer.alloc(n):Buffer.from(e.subarray(0,n));if(c){e.slice(0,8).copy(h)}const p=(0,_i.createDecipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,u);p.setAAD(f);p.setAuthTag(e.subarray(n,s));const m=p.update(d);PE(p,\"SRTCP\");if(c){m.copy(h,8)}return[h,t]}rtpInitializationVector(e,t){const s=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let n=0;n<s.length;n++){s[n]^=this.srtpSessionSalt[n]}return s}rtcpInitializationVector(e,t){const s=this.rtcpIvWriter([0,e,0,t]);for(let n=0;n<s.length;n++){s[n]^=this.srtcpSessionSalt[n]}return s}rtcpAdditionalAuthenticatedData(e,t){const s=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);s[8]|=kE;return s}};var Wp=4;var kE=128;function PE(r,e){try{r.final()}catch{throw new Nt(`Failed to authenticate ${e} packet`)}}a(PE,\"finalizeAuthenticatedDecryption\");function Cu(r,e){const t=(0,Ci.createCipheriv)(\"aes-128-ecb\",r,null);t.setAutoPadding(false);return Buffer.concat([t.update(e),t.final()])}a(Cu,\"aes128EcbEncrypt\");var vi=class{static{a(this,\"Context\")}constructor(e,t,s){this.masterKey=e;this.masterSalt=t;this.profile=s;this.srtpSSRCStates={};this.srtcpSSRCStates={};{const n=14-t.length;if(n>0){this.masterSalt=Buffer.concat([t,Buffer.alloc(n)])}}this.srtpSessionKey=this.generateSessionKey(0);this.srtpSessionSalt=this.generateSessionSalt(2);this.srtpSessionAuthTag=this.generateSessionAuthTag(1);this.srtpSessionAuth=(0,Ci.createHmac)(\"sha1\",this.srtpSessionAuthTag);this.srtcpSessionKey=this.generateSessionKey(3);this.srtcpSessionSalt=this.generateSessionSalt(5);this.srtcpSessionAuthTag=this.generateSessionAuthTag(4);this.srtcpSessionAuth=(0,Ci.createHmac)(\"sha1\",this.srtcpSessionAuthTag);switch(s){case Si:this.cipher=new Ru(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case Cs:this.cipher=new _u(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}generateSessionKey(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let n=s.length-1,i=t.length-1;n>=0;n--,i--){t[i]=t[i]^s[n]}t=Buffer.concat([t,Buffer.from([0,0])]);return Cu(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let n=s.length-1,i=t.length-1;n>=0;n--,i--){t[i]=t[i]^s[n]}t=Buffer.concat([t,Buffer.from([0,0])]);t=Cu(this.masterKey,t);return t.subarray(0,14)}generateSessionAuthTag(e){const t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let o=s.length-1,c=t.length-1;o>=0;o--,c--){t[c]=t[c]^s[o]}let n=Buffer.concat([t,Buffer.from([0,0])]);let i=Buffer.concat([t,Buffer.from([0,1])]);n=Cu(this.masterKey,n);i=Cu(this.masterKey,i);return Buffer.concat([n,i.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];if(t)return t;t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0};this.srtpSSRCStates[e]=t;return t}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];if(t)return t;t={srtcpIndex:0,ssrc:e};this.srtcpSSRCStates[e]=t;return t}updateRolloverCount(e,t){if(!t.rolloverHasProcessed){t.rolloverHasProcessed=true}else if(e===0){if(t.lastSequenceNumber>Ya){t.rolloverCounter++}}else if(t.lastSequenceNumber<Ya&&e>NE-Ya){if(t.rolloverCounter>0){t.rolloverCounter--}}else if(e<Ya&&t.lastSequenceNumber>NE-Ya){t.rolloverCounter++}t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=(0,Ci.createHmac)(\"sha1\",this.srtpSessionAuthTag);const s=Buffer.alloc(4);s.writeUInt32BE(t);return this.srtpSessionAuth.update(e).update(s).digest().slice(0,10)}index(e){const t=this.srtcpSSRCStates[e];if(!t){return 0}return t.srtcpIndex}setIndex(e,t){const s=this.getSrtcpSsrcState(e);s.srtcpIndex=t%2147483647}};var Ya=100;var NE=65535;var vu=class extends vi{static{a(this,\"SrtcpContext\")}constructor(e,t,s){super(e,t,s)}encryptRTCP(e){const t=e.readUInt32BE(4);const s=this.getSrtcpSsrcState(t);s.srtcpIndex++;if(s.srtcpIndex>>MI){s.srtcpIndex=0}const n=this.cipher.encryptRTCP(e,s.srtcpIndex);return n}decryptRTCP(e){const t=this.cipher.decryptRTCP(e);return t}};var MI=2147483647;var Ai=class{static{a(this,\"Session\")}constructor(e){this.ContextCls=e}start(e,t,s,n,i){this.localContext=new this.ContextCls(e,t,i);this.remoteContext=new this.ContextCls(s,n,i)}};var Au=class extends Ai{static{a(this,\"SrtcpSession\")}constructor(e){super(vu);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRTCP(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e){const t=this.localContext.encryptRTCP(e);return t}};var Iu=class extends vi{static{a(this,\"SrtpContext\")}constructor(e,t,s){super(e,t,s)}encryptRtp(e,t){const s=this.getSrtpSsrcState(t.ssrc);this.updateRolloverCount(t.sequenceNumber,s);const n=this.cipher.encryptRtp(t,e,s.rolloverCounter);return n}decryptRtp(e){const t=Ri(e,this.rtpAuthTagLength);const s=this.srtpSSRCStates[t.ssrc];const n=s?{...s}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,n);const i=this.cipher.decryptRtp(e,n.rolloverCounter,t);if(s){Object.assign(s,n)}else{this.srtpSSRCStates[t.ssrc]=n}return i}get rtpAuthTagLength(){return this.profile===Cs?16:10}};var Ou=class extends Ai{static{a(this,\"SrtpSession\")}constructor(e){super(Iu);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRtp(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e,t){return this.localContext.encryptRtp(e,t)}};var ku=new WeakMap;var Pu=new WeakSet;function DI(r,e){Pu.add(r);if(e==void 0)ku.delete(r);else ku.set(r,e)}a(DI,\"setTrackSourceCodecs\");function br(r){return r==void 0?void 0:ku.get(r)}a(br,\"getTrackSourceCodecs\");function on(r){if(Pu.has(r))return;Pu.add(r);if(r.codec!=void 0){ku.set(r,[r.codec])}}a(on,\"captureTrackSourceCodecs\");var Vp=class{static{a(this,\"TrackBroadcastSource\")}constructor(){this.tracks=new Set;this.upstreamStops=new Set}attach(e){this.tracks.add(e)}detach(e){this.tracks.delete(e);if(this.tracks.size>0){return}for(const t of[...this.upstreamStops]){t()}this.upstreamStops.clear()}addUpstreamStop(e){const t=a(()=>{this.upstreamStops.delete(t);e()},\"once\");this.upstreamStops.add(t)}deliverRtp(e,t){const s=[...this.tracks].filter(n=>!n.stopped);for(const n of s){n.applyIncomingRtp(e.clone(),t)}}deliverRtcp(e){for(const t of this.tracks){if(!t.stopped){t.onReceiveRtcp.execute(e)}}}deliverSourceChanged(e){for(const t of this.tracks){if(!t.stopped){t.onSourceChanged.execute(e)}}}stopAllTracks(){for(const e of[...this.tracks]){e.stop()}}};var Zt=class r extends kt{static{a(this,\"MediaStreamTrack\")}constructor(e){super();this.uuid=(0,Xp.randomUUID)().toString();this.remote=false;this.enabled=true;this.onReceiveRtp=new O;this.onReceiveRtcp=new O;this.onSourceChanged=new O;this.stopped=false;this.muted=true;this.stop=()=>{if(this.stopped){return}this.stopped=true;this.muted=true;this.onReceiveRtp.complete();this.emit(\"ended\");this.broadcastSource.detach(this)};this.writeRtp=s=>{if(this.remote){throw new Error(\"this is remoteTrack\")}const n=Buffer.isBuffer(s)?Le.deSerialize(s):s.clone();n.header.payloadType=this.codec?.payloadType??n.header.payloadType;this.broadcastSource.deliverRtp(n)};this.writeRtcp=s=>{this.broadcastSource.deliverRtcp(s)};const t=e.broadcastSource;Object.assign(this,e);this.id??=this.uuid;this.broadcastSource=t??new Vp;if(!this.stopped){this.broadcastSource.attach(this)}this.onReceiveRtp.subscribe(s=>{this.muted=false;this.header=s.header});this.label=`${this.remote?\"remote\":\"local\"} ${this.kind}`}get readyState(){return this.stopped?\"ended\":\"live\"}notifySourceChanged(e){this.broadcastSource.deliverSourceChanged(e)}applyIncomingRtp(e,t){if(this.stopped){return}this.onReceiveRtp.execute(e,t)}bindUpstreamStop(e){this.broadcastSource.addUpstreamStop(e)}stopMediaSource(){this.broadcastSource.stopAllTracks()}clone(){const e=new r({kind:this.kind,remote:this.remote,enabled:this.enabled,muted:this.muted,stopped:this.stopped,codec:this.codec,ssrc:this.ssrc,rid:this.rid,header:this.header,broadcastSource:this.broadcastSource});if(Pu.has(this)){DI(e,br(this))}else{on(e)}return e}};var Br=class r{static{a(this,\"MediaStream\")}constructor(e={}){this.tracks=[];if(Array.isArray(e)){this.tracks=e}else{Object.assign(this,e)}this.id??=(0,Xp.randomUUID)().toString()}addTrack(e){e.streamId=this.id;this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e);if(e.streamId===this.id){e.streamId=void 0}}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===\"audio\")}getVideoTracks(){return this.tracks.filter(e=>e.kind===\"video\")}getTrackById(e){return this.tracks.find(t=>t.id===e)}get active(){return this.tracks.some(e=>!e.stopped)}clone(){const e=new r;for(const t of this.tracks){e.addTrack(t.clone())}return e}};var Ja=a(()=>({type:\"nack\"}),\"useNACK\");var an=a(()=>({type:\"nack\",parameter:\"pli\"}),\"usePLI\");var Za=a(()=>({type:\"goog-remb\"}),\"useREMB\");var Nu=a(()=>({type:\"transport-cc\"}),\"useTWCC\");var ft=class{static{a(this,\"RTCRtpCodecParameters\")}constructor(e){this.rtcpFeedback=[];this.direction=\"all\";Object.assign(this,e)}get name(){return this.mimeType.split(\"/\")[1]}get contentType(){return this.mimeType.split(\"/\")[0]}get str(){let e=`${this.name}/${this.clockRate}`;if(this.channels===2)e+=\"/2\";return e}};var Qt=class{static{a(this,\"RTCRtpHeaderExtensionParameters\")}constructor(e){Object.assign(this,e)}};var Lu=class{static{a(this,\"RTCRtcpFeedback\")}constructor(e={}){Object.assign(this,e)}};var Mu=class{static{a(this,\"RTCRtpRtxParameters\")}constructor(e={}){Object.assign(this,e)}};var Du=class{static{a(this,\"RTCRtpCodingParameters\")}constructor(e){Object.assign(this,e)}};var Ii=class{static{a(this,\"RTCRtpSimulcastParameters\")}constructor(e){Object.assign(this,e)}};var Yp=a((r={})=>new ft({mimeType:\"video/h264\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],parameters:\"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1\",...r}),\"useH264\");var Bu=a((r={})=>new ft({mimeType:\"video/VP8\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],...r}),\"useVP8\");var Jp=a((r={})=>new ft({mimeType:\"video/VP9\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],...r}),\"useVP9\");var BI=a((r={})=>new ft({mimeType:\"video/AV1X\",clockRate:9e4,rtcpFeedback:[Ja(),an(),Za()],...r}),\"useAV1X\");var Uu=a((r={})=>new ft({mimeType:\"audio/OPUS\",clockRate:48e3,channels:2,...r}),\"useOPUS\");var ju=a((r={})=>new ft({mimeType:\"audio/PCMU\",clockRate:8e3,channels:1,payloadType:0,...r}),\"usePCMU\");function LE(){return{audio:[Uu(),ju()],video:[Bu()]}}a(LE,\"defaultCodecs\");function ME(r){return new ft({mimeType:r.mimeType,clockRate:r.clockRate,...r.channels!=void 0?{channels:r.channels}:{},...r.payloadType!=void 0?{payloadType:r.payloadType}:{},rtcpFeedback:r.rtcpFeedback.map(e=>({...e})),...r.parameters!=void 0?{parameters:r.parameters}:{},direction:r.direction})}a(ME,\"cloneCodecParameters\");var DE=[BI(),Jp(),Bu(),Yp(),Uu(),ju()].map(r=>r.mimeType);var rW=DE.filter(r=>r.toLowerCase().startsWith(\"video/\"));var sW=DE.filter(r=>r.toLowerCase().startsWith(\"audio/\"));var UI={\"audio/opus\":a(()=>Uu(),\"audio/opus\"),\"audio/pcmu\":a(()=>ju(),\"audio/pcmu\"),\"video/vp8\":a(()=>Bu(),\"video/vp8\"),\"video/vp9\":a(()=>Jp(),\"video/vp9\"),\"video/h264\":a(()=>Yp(),\"video/h264\")};var $u=[\"audio/opus\",\"audio/PCMU\",\"video/VP8\",\"video/VP9\",\"video/H264\"];var BE=[\"audio/opus\",\"audio/PCMU\",\"video/VP8\",\"video/H264\",\"video/VP9\"];function UE(r){return $u.find(e=>e.toLowerCase()===r.toLowerCase())??r}a(UE,\"canonicalCodec\");function Zp(r){const e=UI[r.toLowerCase()];if(!e)throw new TypeError(`The codec ${r} is not supported: ${$u.join(\", \")}`);return e()}a(Zp,\"engineCodecOf\");function jE(r){const e=r.map(Zp);return{audio:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"audio/\")),video:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"video/\"))}}a(jE,\"engineCodecsOf\");var Qa=class{static{a(this,\"RtpPacket\")}constructor(e){this.payloadType=e.payloadType;this.sequenceNumber=e.sequenceNumber;this.timestamp=e.timestamp;this.ssrc=e.ssrc??0;this.marker=e.marker??false;this.payload=Buffer.isBuffer(e.payload)?e.payload:Buffer.from(e.payload.buffer,e.payload.byteOffset,e.payload.byteLength)}static parse(e){return Qp(Le.deSerialize(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)))}toBuffer(){return em(this).serialize()}};function Qp(r){const{header:e}=r;return new Qa({payloadType:e.payloadType,sequenceNumber:e.sequenceNumber,timestamp:e.timestamp,ssrc:e.ssrc,marker:e.marker,payload:r.payload})}a(Qp,\"rtpPacketOf\");function em(r){return new Le(new Xe({payloadType:r.payloadType,sequenceNumber:r.sequenceNumber,timestamp:r.timestamp,ssrc:r.ssrc,marker:r.marker}),r.payload)}a(em,\"enginePacketOf\");var HE=new WeakMap;var qE=new WeakMap;var zE=new WeakMap;var GE=new WeakMap;var KE=new WeakMap;var $E=new WeakMap;var jI=500;var tm;var rm=class{static{a(this,\"MediaTrack\")}#e;#t;#r=new FE.EventEmitter;#s;constructor(e,t={}){const s=tm??new Zt({kind:e,codec:t.codec?Zp(t.codec):void 0});if(t.codec&&!s.codec?.mimeType.toLowerCase().startsWith(`${e}/`))throw new TypeError(`The codec ${t.codec} is not one of ${e}`);this.#e=s;this.#t=t.id??s.id??s.uuid;this.#r.setMaxListeners(0);HE.set(s,this);qE.set(this,s);zE.set(this,this.#r);s.on(\"ended\",()=>void this.#r.emit(\"ended\"));this.#r.on(\"newListener\",n=>{if(n===\"rtp\"&&!this.#s)this.#s=this.#e.onReceiveRtp.subscribe((i,o)=>{if(this.#e.remote)this.#r.emit(\"rtp\",Qp(i))}).unSubscribe});this.#r.on(\"removeListener\",n=>{if(n===\"rtp\"&&!this.#r.listenerCount(\"rtp\")){this.#s?.();this.#s=void 0}})}get id(){return this.#t}get kind(){return this.#e.kind}get remote(){return this.#e.remote}get readyState(){return this.#e.readyState}get codec(){const e=this.#e.codec?.mimeType;return e?UE(e):void 0}writeRtp(e){if(e instanceof Qa){this.#e.writeRtp(em(e))}else{this.#e.writeRtp(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength))}}requestKeyFrame(){const e=KE.get(this);if(e)return e();const t=GE.get(this);const s=this.#e.ssrc;if(t&&s!==void 0)void t.sendRtcpPLI(s)}stop(){this.#e.stop()}on(e,t){this.#r.on(e,t);return this}once(e,t){this.#r.once(e,t);return this}off(e,t){this.#r.off(e,t);return this}};function cn(r,e){let t=HE.get(r);if(!t){tm=r;try{t=new rm(r.kind)}finally{tm=void 0}}if(e)GE.set(t,e);return t}a(cn,\"trackOf\");function er(r){return qE.get(r)}a(er,\"engineTrackOf\");function WE(r){zE.get(r).emit(\"keyframerequest\");if(!r.remote)return;const e=Date.now();if(e-($E.get(r)??0)<jI)return;$E.set(r,e);r.requestKeyFrame()}a(WE,\"keyFrameRequested\");function VE(r,e,t,s){const n=new Zt({kind:r,codec:e,remote:true,...t===void 0?{}:{id:t}});const i=cn(n);KE.set(i,s.requestKeyFrame);const o=n.onReceiveRtp.length;let c=false;n.onReceiveRtp.onsubscriberschange=()=>{const l=!n.stopped&&n.onReceiveRtp.length>o;if(l!==c)s.wanted(c=l)};return{track:i,receive:a((l,u)=>n.onReceiveRtp.execute(l,u),\"receive\")}}a(VE,\"relayedTrack\");var IW=Ye(Bn(),1);function sm(){return r=>WS(r)}a(sm,\"Autoload\");var xg=require(\"node:crypto\");var nm;(function(r){r[r[\"DCEP\"]=50]=\"DCEP\";r[r[\"STRING\"]=51]=\"STRING\";r[r[\"BINARY\"]=53]=\"BINARY\";r[r[\"STRING_EMPTY\"]=56]=\"STRING_EMPTY\";r[r[\"BINARY_EMPTY\"]=57]=\"BINARY_EMPTY\"})(nm||(nm={}));var Q;(function(r){r[r[\"CLOSED\"]=1]=\"CLOSED\";r[r[\"COOKIE_WAIT\"]=2]=\"COOKIE_WAIT\";r[r[\"COOKIE_ECHOED\"]=3]=\"COOKIE_ECHOED\";r[r[\"ESTABLISHED\"]=4]=\"ESTABLISHED\";r[r[\"SHUTDOWN_PENDING\"]=5]=\"SHUTDOWN_PENDING\";r[r[\"SHUTDOWN_SENT\"]=6]=\"SHUTDOWN_SENT\";r[r[\"SHUTDOWN_RECEIVED\"]=7]=\"SHUTDOWN_RECEIVED\";r[r[\"SHUTDOWN_ACK_SENT\"]=8]=\"SHUTDOWN_ACK_SENT\"})(Q||(Q={}));var cc=require(\"node:crypto\");var ec=4;var Sr=12;var Fu=4;var XE=12;var As=Fu+XE;var Lt=class r{static{a(this,\"Chunk\")}get body(){return this._body}set body(e){this._body=e}static{this.type=-1}constructor(e=0,t=Buffer.from(\"\")){this.flags=e;this._body=t}get type(){return r.type}get bytes(){if(!this.body)throw new Error;const e=Buffer.alloc(Fu);e.writeUInt8(this.type,0);e.writeUInt8(this.flags,1);e.writeUInt16BE(this.body.length+Fu,2);const t=Buffer.concat([e,this.body,...[...Array(hn(this.body.length))].map(()=>Buffer.from(\"\\0\"))]);return t}};var tc=class extends Lt{static{a(this,\"BaseInitChunk\")}constructor(e=0,t){super(e,t);this.flags=e;if(t){this.initiateTag=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);this.outboundStreams=t.readUInt16BE(8);this.inboundStreams=t.readUInt16BE(10);this.initialTsn=t.readUInt32BE(12);this.params=JE(t.slice(16))}else{this.initiateTag=0;this.advertisedRwnd=0;this.outboundStreams=0;this.inboundStreams=0;this.initialTsn=0;this.params=[]}}get body(){const e=Buffer.alloc(16);e.writeUInt32BE(this.initiateTag,0);e.writeUInt32BE(this.advertisedRwnd,4);e.writeUInt16BE(this.outboundStreams,8);e.writeUInt16BE(this.inboundStreams,10);e.writeUInt32BE(this.initialTsn,12);return Buffer.concat([e,YE(this.params)])}};var ln=class r extends tc{static{a(this,\"InitChunk\")}static{this.type=1}get type(){return r.type}};var Oi=class r extends tc{static{a(this,\"InitAckChunk\")}static{this.type=2}get type(){return r.type}};var Hu=class r extends tc{static{a(this,\"ReConfigChunk\")}static{this.type=130}get type(){return r.type}};var un=class r extends Lt{static{a(this,\"ForwardTsnChunk\")}static{this.type=192}constructor(e=0,t){super(e,t);this.flags=e;this.streams=[];if(t){this.cumulativeTsn=t.readUInt32BE(0);let s=4;while(s<t.length){this.streams.push([t.readUInt16BE(s),t.readUInt16BE(s+2)]);s+=4}}else{this.cumulativeTsn=0}}get type(){return r.type}set body(e){}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return Buffer.concat([e,...this.streams.map(([t,s])=>{const n=Buffer.alloc(4);n.writeUInt16BE(t,0);n.writeUInt16BE(s,2);return n})])}};var tr=class r extends Lt{static{a(this,\"DataChunk\")}static{this.type=0}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.tsn=0;this.streamId=0;this.streamSeqNum=0;this.protocol=0;this.userData=Buffer.from(\"\");this.abandoned=false;this.acked=false;this.misses=0;this.retransmit=false;this.sentCount=0;this.bookSize=0;if(t){this.tsn=t.readUInt32BE(0);this.streamId=t.readUInt16BE(4);this.streamSeqNum=t.readUInt16BE(6);this.protocol=t.readUInt32BE(8);this.userData=t.slice(12)}}get bytes(){const e=As+this.userData.length;const t=Buffer.alloc(As);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.tsn,4);t.writeUInt16BE(this.streamId,8);t.writeUInt16BE(this.streamSeqNum,10);t.writeUInt32BE(this.protocol,12);let s=Buffer.concat([t,this.userData]);if(e%4){s=Buffer.concat([s,...[...Array(hn(e))].map(()=>Buffer.from(\"\\0\"))])}return s}};var ki=class r extends Lt{static{a(this,\"CookieEchoChunk\")}static{this.type=10}get type(){return r.type}};var Pi=class r extends Lt{static{a(this,\"CookieAckChunk\")}static{this.type=11}get type(){return r.type}};var fn=class extends Lt{static{a(this,\"BaseParamsChunk\")}constructor(e=0,t=void 0){super(e,t);this.flags=e;this.params=[];if(t){this.params=JE(t)}}get body(){return YE(this.params)}};var Ni=class r extends fn{static{a(this,\"AbortChunk\")}static{this.type=6}get type(){return r.type}};var dn=class r extends fn{static{a(this,\"ErrorChunk\")}static{this.type=9}static{this.CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13}}get type(){return r.type}get descriptions(){return this.params.map(([e,t])=>{const s=(Object.entries(r.CODE).find(([,n])=>n===e)||[])[0];return{name:s,body:t}})}};var Li=class r extends fn{static{a(this,\"HeartbeatChunk\")}static{this.type=4}get type(){return r.type}};var rc=class r extends fn{static{a(this,\"HeartbeatAckChunk\")}static{this.type=5}get type(){return r.type}};var Mi=class r extends fn{static{a(this,\"ReconfigChunk\")}static{this.type=130}get type(){return r.type}};var Di=class r extends Lt{static{a(this,\"SackChunk\")}static{this.type=3}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.gaps=[];this.duplicates=[];this.cumulativeTsn=0;this.advertisedRwnd=0;if(t){this.cumulativeTsn=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);const s=t.readUInt16BE(8);const n=t.readUInt16BE(10);let i=12;[...Array(s)].forEach(()=>{this.gaps.push([t.readUInt16BE(i),t.readUInt16BE(i+2)]);i+=4});[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(i));i+=4})}}get bytes(){const e=16+4*(this.gaps.length+this.duplicates.length);const t=Buffer.alloc(16);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.cumulativeTsn,4);t.writeUInt32BE(this.advertisedRwnd,8);t.writeUInt16BE(this.gaps.length,12);t.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([t,...this.gaps.map(n=>{const i=Buffer.alloc(4);i.writeUInt16BE(n[0],0);i.writeUInt16BE(n[1],2);return i})]);s=Buffer.concat([s,...this.duplicates.map(n=>{const i=Buffer.alloc(4);i.writeUInt32BE(n,0);return i})]);return s}};var sc=class r extends Lt{static{a(this,\"ShutdownChunk\")}static{this.type=7}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.cumulativeTsn=0;if(t){this.cumulativeTsn=t.readUInt32BE(0)}}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return e}};var nc=class r extends Lt{static{a(this,\"ShutdownAckChunk\")}static{this.type=8}get type(){return r.type}};var ic=class r extends Lt{static{a(this,\"ShutdownCompleteChunk\")}static{this.type=14}get type(){return r.type}};var $I=[tr,ln,Oi,Di,Li,rc,Ni,sc,nc,dn,ki,Pi,ic,Mi,un];var FI=$I.reduce((r,e)=>{r[e.type]=e;return r},{});function hn(r){const e=r%ec;return e?ec-e:0}a(hn,\"padL\");function YE(r){let e=Buffer.from(\"\");let t=Buffer.from(\"\");r.forEach(([s,n])=>{const i=n.length+4;const o=Buffer.alloc(4);o.writeUInt16BE(s,0);o.writeUInt16BE(i,2);e=Buffer.concat([e,t,o,n]);t=Buffer.concat([...Array(hn(i))].map(()=>Buffer.from(\"\\0\")))});return e}a(YE,\"encodeParams\");function JE(r){const e=[];let t=0;while(t<=r.length-4){const s=r.readUInt16BE(t);const n=r.readUInt16BE(t+2);e.push([s,r.slice(t+4,t+n)]);t+=n+hn(n)}return e}a(JE,\"decodeParams\");function ZE(r){if(r.length<Sr)throw new Error(\"SCTP packet length is less than 12 bytes\");const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);const s=r.readUInt32BE(4);const n=r.readUInt32LE(8);let i=Da(r.subarray(0,8));i=Da(HI,i);i=Da(r.subarray(Sr),i);if(n!==i>>>0)throw new Error(\"SCTP packet has invalid checksum\");const o=[];let c=Sr;while(c+4<=r.length){const l=r.readUInt8(c);const u=r.readUInt8(c+1);const f=r.readUInt16BE(c+2);const d=r.slice(c+4,c+f);const h=FI[l.toString()];if(h){o.push(new h(u,d))}else{throw new Error(\"unknown\")}c+=f+hn(f)}return[e,t,s,o]}a(ZE,\"parsePacket\");var HI=Buffer.alloc(4);function QE(r,e){if(r instanceof tr){const t=As+r.userData.length;return t+hn(t)}return e.length}a(QE,\"wireLength\");function im(r,e,t,s){const n=s.map(l=>l instanceof tr?void 0:l.bytes);let i=Sr;for(let l=0;l<s.length;l++){i+=QE(s[l],n[l])}const o=Buffer.allocUnsafe(i);o.writeUInt16BE(r,0);o.writeUInt16BE(e,2);o.writeUInt32BE(t,4);o.writeUInt32LE(0,8);let c=Sr;for(let l=0;l<s.length;l++){const u=s[l];const f=n[l];if(f){f.copy(o,c);c+=f.length;continue}const d=u;const h=As+d.userData.length;o.writeUInt8(d.type,c);o.writeUInt8(d.flags,c+1);o.writeUInt16BE(h,c+2);o.writeUInt32BE(d.tsn,c+4);o.writeUInt16BE(d.streamId,c+8);o.writeUInt16BE(d.streamSeqNum,c+10);o.writeUInt32BE(d.protocol,c+12);d.userData.copy(o,c+As);const p=hn(h);if(p)o.fill(0,c+h,c+h+p);c+=h+p}o.writeUInt32LE(Da(o)>>>0,8);return o}a(im,\"serializePackets\");function eT(r){return QE(r,r instanceof tr?void 0:r.bytes)}a(eT,\"chunkWireLength\");function tT(r,e,t,s){return im(r,e,t,[s])}a(tT,\"serializePacket\");function rT(r){return r.map((e,t)=>[t,e])}a(rT,\"enumerate\");function sT(r){return r.reduce((e,t)=>{e[t]=new O;return e},{})}a(sT,\"createEventsFromList\");var Bi=class r{static{a(this,\"OutgoingSSNResetRequestParam\")}static{this.type=13}constructor(e,t,s,n){this.requestSequence=e;this.responseSequence=t;this.lastTsn=s;this.streams=n}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(12);e.writeUInt32BE(this.requestSequence,0);e.writeUInt32BE(this.responseSequence,4);e.writeUInt32BE(this.lastTsn,8);return Buffer.concat([e,...this.streams.map(t=>{const s=Buffer.allocUnsafe(2);s.writeUInt16BE(t,0);return s})])}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);const n=e.readUInt32BE(8);const i=[];for(let o=12;o<e.length;o+=2){i.push(e.readUInt16BE(o))}return new r(t,s,n,i)}};var oc=class r{static{a(this,\"StreamAddOutgoingParam\")}static{this.type=17}constructor(e,t){this.requestSequence=e;this.newStreams=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.requestSequence,0);e.writeUInt16BE(this.newStreams,4);e.writeUInt16BE(0,6);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt16BE(4);return new r(t,s)}};var ac={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5};var pn=class r{static{a(this,\"ReconfigResponseParam\")}static{this.type=16}constructor(e,t){this.responseSequence=e;this.result=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.responseSequence,0);e.writeUInt32BE(this.result,4);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);return new r(t,s)}};var om={13:Bi,16:pn,17:oc};var X=P(\"webrtc/sctp/sctp\");var qI=24;var zI=60;var nT=65535;var ji=1191;function lm(r,e=As){const t=Sr+e;if(r<=t)return 0;const s=r-t;return s-s%ec}a(lm,\"maxPayloadSizeForMtu\");function Gu(r){if(!Number.isSafeInteger(r)||r<=0){throw new Error(\"SCTP MTU must be a positive integer\")}if(lm(r)===0){throw new Error(\"SCTP MTU is too small for a DATA chunk\")}}a(Gu,\"validateSctpMtu\");var Ui=1;var qu=2;var zu=4;var iT=10;var GI=8;var KI=10;var WI=2;var oT=1/8;var aT=1/4;var cT=3;var VI=1;var XI=60;var Ur=2**32;var YI=20;var JI=4096;var ZI=30;var lT=135;var uT=7;var fT=32776;var dT=49152;var QI=[\"new\",\"closed\",\"connected\",\"connecting\"];var lc=class r{static{a(this,\"SCTP\")}get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}constructor(e,t=5e3,s={}){this.transport=e;this.port=t;this.flush=new O;this.stateChanged=sT(QI);this.onReconfigStreams=new O;this.onReceive=new O;this.onSackReceived=async()=>{};this.associationState=Q.CLOSED;this.started=false;this.state=\"new\";this.isServer=true;this.isStopping=false;this.isClosed=false;this.hmacKey=(0,cc.randomBytes)(16);this.localPartialReliability=true;this.localVerificationTag=cu();this.remoteExtensions=[];this.remotePartialReliability=true;this.remoteVerificationTag=0;this.advertisedRwnd=1024*1024;this.lastAdvertisedRwnd=this.advertisedRwnd;this.peerAdvertisedRwnd=this.advertisedRwnd;this.inboundStreams={};this._inboundStreamsCount=0;this._inboundStreamsMax=nT;this.pendingChunks=0;this.sackDuplicates=[];this.sackMisOrdered=new Set;this.sackNeeded=false;this.sackPacketCount=0;this.sackHasNewDataInPacket=false;this.sackImmediate=false;this.fastRecoveryTransmit=false;this.flightSize=0;this.outboundQueue=new Ha;this.outboundStreamSeq={};this._outboundStreamsCount=nT;this.localTsn=Number(cu());this.lastSackedTsn=mn(this.localTsn);this.advancedPeerAckTsn=mn(this.localTsn);this.partialBytesAcked=0;this.sentQueue=new Ha;this.retransmitPending=false;this.transmitting=false;this.transmitRequested=false;this.transmitScheduled=false;this.reconfigRequestSeq=this.localTsn;this.reconfigResponseSeq=0;this.reconfigQueue=[];this.rto=cT;this.timer1Failures=0;this.timer2Failures=0;this.timerReconfigFailures=0;this.heartbeatInterval=ZI;this.send=async(n,i,o,{expiry:c,maxRetransmits:l,ordered:u}={expiry:void 0,maxRetransmits:void 0,ordered:true})=>{const f=u?this.outboundStreamSeq[n]||0:0;const d=Math.ceil(o.length/this.maxPayloadSize);let h=0;const p=[];for(let m=0;m<d;m++){const y=new tr(0,void 0);y.flags=0;if(!u){y.flags=zu}if(m===0){y.flags|=qu}if(m===d-1){y.flags|=Ui}y.tsn=this.localTsn;y.streamId=n;y.streamSeqNum=f;y.protocol=i;y.userData=o.subarray(h,h+this.maxPayloadSize);y.bookSize=y.userData.length;y.expiry=c;y.maxRetransmits=l;h+=this.maxPayloadSize;this.localTsn=gn(this.localTsn);p.push(y)}for(const m of p){this.outboundQueue.push(m)}if(u){this.outboundStreamSeq[n]=$e(f,1)}this.transmitSoon()};this.timer1Expired=()=>{if(this.isStopped)return;this.timer1Failures++;this.timer1Handle=void 0;if(this.timer1Failures>GI){this.setState(Q.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer1Chunk).catch(n=>{X(\"send timer1 chunk failed\",n.message)})});if(this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};this.timer2Expired=()=>{if(this.isStopped)return;this.timer2Failures++;this.timer2Handle=void 0;if(this.timer2Failures>iT){this.setState(Q.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer2Chunk).catch(n=>{X(\"send timer2Chunk failed\",n.message)})});if(this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};this.timer3Expired=()=>{if(this.isStopped)return;this.timer3Handle=void 0;for(const n of this.sentQueue){if(!this.maybeAbandon(n)){n.retransmit=true;this.retransmitPending=true}}this.updateAdvancedPeerAckPoint();this.fastRecoveryExit=void 0;this.flightSize=0;this.partialBytesAcked=0;this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.maxPayloadSize;this.transmit().catch(n=>X(\"transmit failed\",n))};this.timerReconfigHandleExpired=async()=>{if(this.isStopped)return;this.timerReconfigFailures++;this.rto=Math.ceil(this.rto*1.5);if(this.timerReconfigFailures>iT){X(\"timerReconfigFailures\",this.timerReconfigFailures);this.setState(Q.CLOSED);this.timerReconfigHandle=void 0}else if(this.reconfigRequest){X(\"timerReconfigHandleExpired\",this.timerReconfigFailures,this.rto);await this.sendReconfigParam(this.reconfigRequest);if(this.isStopped)return;this.timerReconfigHandle=setTimeout(Vt(this.timerReconfigHandleExpired,n=>X(\"reconfig timer failed\",n)),this.rto*1e3)}};this.timerHeartbeatExpired=async()=>{this.timerHeartbeatHandle=void 0;if(this.associationState!==Q.ESTABLISHED)return;if(this.flightSize===0&&this.outboundQueue.length===0){const n=new Li;const i=Buffer.allocUnsafe(4);i.writeUInt32BE(Math.floor(Date.now()/1e3),0);n.params.push([1,i]);await this.sendChunk(n).catch(o=>{X(\"send heartbeat failed\",o.message)})}this.heartbeatStart()};this.mtu=s.mtu??ji;Gu(this.mtu);this.maxPayloadSize=lm(this.mtu);this.cwnd=KI*this.maxPayloadSize;this.localPort=this.port;this.transport.onData=n=>{this.handleData(n).catch(i=>X(\"receive failed\",i))}}get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0){return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}return void 0}static client(e,t=5e3,s={}){const n=new r(e,t,s);n.isServer=false;return n}static server(e,t=5e3,s={}){const n=new r(e,t,s);n.isServer=true;return n}async handleData(e){if(this.isStopped)return;let t;const[,,s,n]=ZE(e);const i=n.filter(o=>o.type===ln.type).length;if(i>0){if(n.length!=1){throw new Error}t=0}else{t=this.localVerificationTag}if(s!==t){return}this.sackHasNewDataInPacket=false;for(const o of n){if(o.type===tr.type)this.receiveDataChunk(o);else await this.receiveChunk(o)}if(this.sackNeeded){if(this.sackHasNewDataInPacket){this.sackPacketCount++}if(this.sackPacketCount>=2){this.sackImmediate=true}await this.scheduleSack()}}async scheduleSack(){if(this.isStopped)return;if(!this.sackNeeded)return;if(this.sackImmediate){if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}await this.sendSack();return}if(this.sackTimeout)return;this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0;this.sendSack().catch(e=>{X(\"send delayed sack failed\",e.message)})},YI)}async sendSack(){if(this.isStopped)return;if(!this.sackNeeded)return;await this.sendChunk(this.takeSack()).catch(e=>{X(\"send sack failed\",e.message)})}takeSack(){const e=[];let t;const s=[...this.sackMisOrdered].sort((i,o)=>(i-this.lastReceivedTsn+Ur)%Ur-(o-this.lastReceivedTsn+Ur)%Ur);for(const i of s){const o=(i-this.lastReceivedTsn+Ur)%Ur;if(i===t){e[e.length-1][1]=o}else{e.push([o,o])}t=gn(i)}const n=new Di(0,void 0);n.cumulativeTsn=this.lastReceivedTsn;n.advertisedRwnd=Math.max(0,this.advertisedRwnd);this.lastAdvertisedRwnd=n.advertisedRwnd;n.duplicates=[...this.sackDuplicates];n.gaps=e;this.sackDuplicates=[];this.sackNeeded=false;this.sackPacketCount=0;this.sackImmediate=false;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}return n}async receiveChunk(e){switch(e.type){case tr.type:{this.receiveDataChunk(e)}break;case ln.type:{if(!this.isServer)return;const t=e;X(\"receive init\",t);this.lastReceivedTsn=mn(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=mn(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new Oi;s.initiateTag=this.localVerificationTag;s.advertisedRwnd=this.advertisedRwnd;s.outboundStreams=this._outboundStreamsCount;s.inboundStreams=this._inboundStreamsCount;s.initialTsn=this.localTsn;this.setExtensions(s.params);const n=Math.floor(Date.now()/1e3);const i=Buffer.allocUnsafe(4);i.writeUInt32BE(n,0);let o=i;o=Buffer.concat([o,(0,cc.createHmac)(\"sha1\",this.hmacKey).update(o).digest()]);s.params.push([uT,o]);X(\"send initAck\",s);await this.sendChunk(s).catch(c=>{X(\"send initAck failed\",c.message)})}break;case Oi.type:{if(this.associationState!=Q.COOKIE_WAIT)return;const t=e;this.timer1Cancel();this.lastReceivedTsn=mn(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=mn(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new ki;for(const[n,i]of t.params){if(n===uT){s.body=i;break}}await this.sendChunk(s).catch(n=>{X(\"send echo failed\",n.message)});this.timer1Start(s);this.setState(Q.COOKIE_ECHOED)}break;case Di.type:{await this.receiveSackChunk(e)}break;case Li.type:{const t=new rc;t.params=e.params;await this.sendChunk(t).catch(s=>{X(\"send heartbeat ack failed\",s.message)})}break;case Ni.type:{this.setState(Q.CLOSED)}break;case sc.type:{this.timer2Cancel();this.setState(Q.SHUTDOWN_RECEIVED);const t=new nc;await this.sendChunk(t).catch(s=>{X(\"send shutdown ack failed\",s.message)});this.t2Start(t);this.setState(Q.SHUTDOWN_SENT)}break;case dn.type:{X(\"ErrorChunk\",e.descriptions)}break;case ki.type:{if(!this.isServer)return;const t=e;const s=t.body;const n=(0,cc.createHmac)(\"sha1\",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=qI||!s.slice(4).equals(n)){X(\"x State cookie is invalid\");return}const i=Math.floor(Date.now()/1e3);const o=s.readUInt32BE(0);if(o<i-zI||o>i){const l=new dn(0,void 0);l.params.push([dn.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(\"\\0\")))]);await this.sendChunk(l).catch(u=>{X(\"send errorChunk failed\",u.message)});return}const c=new Pi;await this.sendChunk(c).catch(l=>{X(\"send cookieAck failed\",l.message)});this.setState(Q.ESTABLISHED)}break;case Pi.type:{if(this.associationState!=Q.COOKIE_ECHOED)return;this.timer1Cancel();this.setState(Q.ESTABLISHED)}break;case ic.type:{if(this.associationState!=Q.SHUTDOWN_ACK_SENT)return;this.timer2Cancel();this.setState(Q.CLOSED)}break;case Mi.type:{if(this.associationState!=Q.ESTABLISHED)return;const t=e;for(const[s,n]of t.params){const i=om[s];if(i){await this.receiveReconfigParam(i.parse(n))}}}break;case un.type:{this.receiveForwardTsnChunk(e)}break}}getExtensions(e){for(const[t,s]of e){if(t===dT){this.remotePartialReliability=true}else if(t===fT){this.remoteExtensions=[...s]}}}async receiveReconfigParam(e){X(\"receiveReconfigParam\",om[e.type]);switch(e.type){case Bi.type:{const t=e;const s=new pn(t.requestSequence,ac.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s);await Promise.all(t.streams.map(async n=>{const i=this.inboundStreams[n];if(i){this.pendingChunks-=i.reassembly.length;this.advertisedRwnd+=i.reassembly.reduce((o,c)=>o+c.userData.length,0)}delete this.inboundStreams[n];if(this.outboundStreamSeq[n]){if(!this.reconfigQueue.includes(n)){this.reconfigQueue.push(n)}}}));await this.transmitReconfigRequest();this.onReconfigStreams.execute(t.streams)}break;case pn.type:{const t=e;if(t.result!==ac.ReconfigResultSuccessPerformed){X(\"OutgoingSSNResetRequestParam failed\",Object.keys(ac).find(s=>ac[s]===t.result))}else if(t.responseSequence===this.reconfigRequest?.requestSequence){const s=this.reconfigRequest.streams.map(n=>{delete this.outboundStreamSeq[n];return n});this.onReconfigStreams.execute(s);this.reconfigRequest=void 0;this.timerReconfigCancel();this.rto=cT;this.timerReconfigFailures=0;if(this.reconfigQueue.length>0){await this.transmitReconfigRequest()}}}break;case oc.type:{const t=e;this._inboundStreamsCount+=t.newStreams;const s=new pn(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s)}break}}receiveDataChunk(e){this.sackNeeded=true;if((this.advertisedRwnd<=0||this.pendingChunks>=JI)&&Et(e.tsn,this.highestReceivedTsn)){this.sackImmediate=true;return}if(this.markReceived(e.tsn)){this.sackImmediate=true;return}this.sackHasNewDataInPacket=true;if(this.sackMisOrdered.size>0){this.sackImmediate=true}const t=this.getInboundStream(e.streamId);if((e.flags&(qu|Ui))===(qu|Ui)){if(e.flags&zu){this.receive(e.streamId,e.protocol,e.userData);return}if(t.reassembly.length===0&&e.streamSeqNum===t.streamSequenceNumber){t.streamSequenceNumber=$e(t.streamSequenceNumber,1);this.receive(e.streamId,e.protocol,e.userData);return}}const s=t.reassembly.length;t.addChunk(e);this.advertisedRwnd-=e.userData.length;for(const n of t.popMessages()){this.advertisedRwnd+=n[2].length;this.receive(...n)}this.pendingChunks+=t.reassembly.length-s}async receiveSackChunk(e){if(Et(this.lastSackedTsn,e.cumulativeTsn))return;const t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;const s=this.flightSize>=this.cwnd;let n=0,i=0;while(this.sentQueue.length>0&&bi(this.lastSackedTsn,this.sentQueue.at(0).tsn)){const c=this.sentQueue.shift();n++;if(!c?.acked){i+=c.bookSize;this.flightSizeDecrease(c)}if(n===1&&c.sentCount===1){this.updateRto(t-c.sentTime)}}let o=false;if(e.gaps.length>0){const c=new Set;let l;e.gaps.forEach(f=>{for(let d=f[0];d<f[1]+1;d++){l=(e.cumulativeTsn+d)%Ur;c.add(l)}});let u=e.cumulativeTsn;for(const f of this.sentQueue){if(Et(f.tsn,l)){break}if(c.has(f.tsn)&&!f.acked){i+=f.bookSize;f.acked=true;this.flightSizeDecrease(f);u=f.tsn}}for(const f of this.sentQueue){if(Et(f.tsn,u)){break}if(!c.has(f.tsn)){f.misses++;if(f.misses===3){f.misses=0;if(!this.maybeAbandon(f)){f.retransmit=true;this.retransmitPending=true}f.acked=false;this.flightSizeDecrease(f);o=true}}}}if(this.fastRecoveryExit===void 0){if(n&&s){if(this.cwnd<=this.ssthresh){this.cwnd+=Math.min(i,WI*this.maxPayloadSize)}else{this.partialBytesAcked+=i;if(this.partialBytesAcked>=this.cwnd){this.partialBytesAcked-=this.cwnd;this.cwnd+=this.maxPayloadSize}}}if(o){this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.ssthresh;this.partialBytesAcked=0;this.fastRecoveryExit=this.sentQueue.at(-1).tsn;this.fastRecoveryTransmit=true}}else if(bi(e.cumulativeTsn,this.fastRecoveryExit)){this.fastRecoveryExit=void 0}if(this.sentQueue.length===0){this.timer3Cancel()}else if(n>0){this.timer3Restart()}this.peerAdvertisedRwnd=e.advertisedRwnd;this.updateAdvancedPeerAckPoint();await this.onSackReceived();await this.transmit()}receiveForwardTsnChunk(e){this.sackNeeded=true;this.sackImmediate=true;if(bi(this.lastReceivedTsn,e.cumulativeTsn)){return}const t=a(s=>Et(s,this.lastReceivedTsn),\"isObsolete\");this.lastReceivedTsn=e.cumulativeTsn;this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const s of[...this.sackMisOrdered].sort()){if(s===gn(this.lastReceivedTsn)){this.lastReceivedTsn=s}else{break}}this.sackDuplicates=this.sackDuplicates.filter(t);this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const[s,n]of e.streams){const i=this.getInboundStream(s);i.streamSequenceNumber=$e(n,1);for(const o of i.popMessages()){this.advertisedRwnd+=o[2].length;this.receive(...o)}}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)});this.pendingChunks=Object.values(this.inboundStreams).reduce((s,n)=>s+n.reassembly.length,0);if(Et(this.lastReceivedTsn,this.highestReceivedTsn))this.highestReceivedTsn=this.lastReceivedTsn}updateRto(e){if(!this.srtt){this.rttvar=e/2;this.srtt=e}else{this.rttvar=(1-aT)*this.rttvar+aT*Math.abs(this.srtt-e);this.srtt=(1-oT)*this.srtt+oT*e}this.rto=Math.max(VI,Math.min(this.srtt+4*this.rttvar,XI))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){if(!this.inboundStreams[e]){this.inboundStreams[e]=new am}return this.inboundStreams[e]}markReceived(e){if(bi(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e)){this.sackDuplicates.push(e);return true}if(Et(e,this.highestReceivedTsn))this.highestReceivedTsn=e;if(e===gn(this.lastReceivedTsn)){this.lastReceivedTsn=e;while(this.sackMisOrdered.size>0){const t=gn(this.lastReceivedTsn);if(!this.sackMisOrdered.delete(t))break;this.lastReceivedTsn=t}if(this.sackDuplicates.length>0){const t=a(s=>Et(s,this.lastReceivedTsn),\"isObsolete\");this.sackDuplicates=this.sackDuplicates.filter(t)}}else{this.sackMisOrdered.add(e)}return false}holdReceived(e){this.advertisedRwnd-=e}releaseReceived(e){this.advertisedRwnd+=e;if(this.associationState!==Q.ESTABLISHED||this.lastReceivedTsn===void 0)return;if(this.lastAdvertisedRwnd*2<this.advertisedRwnd){this.sackNeeded=true;this.sackImmediate=true;this.scheduleSack().catch(t=>X(\"send window update failed\",t.message))}}transmitSoon(){if(this.transmitScheduled)return;this.transmitScheduled=true;queueMicrotask(()=>{this.transmitScheduled=false;this.transmit().catch(e=>X(\"transmit failed\",e))})}async transmit(){if(this.isStopped)return;if(this.transmitting){this.transmitRequested=true;return}this.transmitting=true;try{do{this.transmitRequested=false;this.transmitOnce()}while(this.transmitRequested)}finally{this.transmitting=false}}transmitOnce(){if(this.isStopped)return;const e=[];let t=Sr;let s=false;const n=a(()=>{if(e.length===0)return;this.sendChunks(e.splice(0,e.length));t=Sr},\"flush\");const i=a(u=>{const f=eT(u);if(e.length>0&&t+f>this.mtu)n();e.push(u);t+=f},\"add\");const o=a(u=>{if(!s&&this.sackNeeded&&this.lastReceivedTsn!==void 0){i(this.takeSack());s=true}i(u)},\"addData\");if(this.forwardTsnChunk){i(this.forwardTsnChunk);this.forwardTsnChunk=void 0;if(!this.timer3Handle){this.timer3Start()}}const c=this.fastRecoveryExit!=void 0?2*this.maxPayloadSize:4*this.maxPayloadSize;const l=Math.min(this.flightSize+c,this.cwnd);if(this.retransmitPending){let u=true;let f=true;for(const d of this.sentQueue){if(d.retransmit){if(this.fastRecoveryTransmit){this.fastRecoveryTransmit=false}else if(this.flightSize>=l){f=false;break}this.flightSizeIncrease(d);d.misses=0;d.retransmit=false;d.sentCount++;o(d);if(u){this.timer3Restart()}}u=false}if(f)this.retransmitPending=false}while(this.outboundQueue.length>0&&this.flightSize<l&&(this.peerRwnd>0||this.flightSize===0)){const u=this.outboundQueue.shift();if(!u)break;if(u.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(u);break}this.sentQueue.push(u);this.flightSizeIncrease(u);u.sentCount++;u.sentTime=Date.now()/1e3;o(u);this.onSent?.(u.streamId,u.protocol,u.userData.length);if(!this.timer3Handle){this.timer3Start()}}n();this.flush.execute()}sendChunks(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){X(\"send chunks failed\",\"invalid remote port\");return}const t=im(this.localPort,this.remotePort,this.remoteVerificationTag,e);this.transport.send(t).catch(s=>{X(\"send packet failed\",s.message)})}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===Q.ESTABLISHED&&!this.reconfigRequest){const e=[...new Set(this.reconfigQueue)];const t=e.slice(0,lT);this.reconfigQueue=e.slice(lT);const s=new Bi(this.reconfigRequestSeq,this.reconfigResponseSeq,mn(this.localTsn),t);this.reconfigRequestSeq=gn(this.reconfigRequestSeq);this.reconfigRequest=s;await this.sendReconfigParam(s);this.timerReconfigHandleStart()}}async sendReconfigParam(e){X(\"sendReconfigParam\",e);const t=new Mi;t.params.push([e.type,e.bytes]);await this.sendChunk(t).catch(s=>{X(\"send reconfig failed\",s.message)})}async sendResetRequest(e){X(\"sendResetRequest\",e);const t=new tr(0,void 0);t.streamId=e;this.outboundQueue.push(t);if(!this.timer3Handle){await this.transmit()}}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e;this.timer1Failures=0;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Cancel(){if(this.timer1Handle){clearTimeout(this.timer1Handle);this.timer1Handle=void 0;this.timer1Chunk=void 0}}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e;this.timer2Failures=0;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Cancel(){if(this.timer2Handle){clearTimeout(this.timer2Handle);this.timer2Handle=void 0;this.timer2Chunk=void 0}}timer3Start(){if(this.isStopped)return;if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Restart(){if(this.isStopped)return;this.timer3Cancel();this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Cancel(){if(this.timer3Handle){clearTimeout(this.timer3Handle);this.timer3Handle=void 0}}timerReconfigHandleStart(){if(this.isStopped)return;if(this.timerReconfigHandle)return;X(\"timerReconfigHandleStart\",{rto:this.rto});this.timerReconfigFailures=0;this.timerReconfigHandle=setTimeout(Vt(this.timerReconfigHandleExpired,e=>X(\"reconfig timer failed\",e)),this.rto*1e3)}timerReconfigCancel(){if(this.timerReconfigHandle){X(\"timerReconfigCancel\");clearTimeout(this.timerReconfigHandle);this.timerReconfigHandle=void 0;this.timerReconfigFailures=0}}heartbeatStart(){if(this.timerHeartbeatHandle||this.associationState!==Q.ESTABLISHED){return}this.timerHeartbeatHandle=setTimeout(Vt(this.timerHeartbeatExpired,e=>X(\"heartbeat failed\",e)),(this.rto+this.heartbeatInterval)*1e3)}heartbeatRestart(){this.heartbeatCancel();this.heartbeatStart()}heartbeatCancel(){if(this.timerHeartbeatHandle){clearTimeout(this.timerHeartbeatHandle);this.timerHeartbeatHandle=void 0}}setHeartbeatInterval(e){if(e<=0){throw new Error(\"heartbeat interval must be > 0\")}this.heartbeatInterval=e;this.heartbeatRestart()}updateAdvancedPeerAckPoint(){if(Et(this.lastSackedTsn,this.advancedPeerAckTsn)){this.advancedPeerAckTsn=this.lastSackedTsn}let e=0;const t={};while(this.sentQueue.length>0&&this.sentQueue.at(0).abandoned){const s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn;e++;if(!(s.flags&zu)){t[s.streamId]=s.streamSeqNum}}if(e){this.forwardTsnChunk=new un(0,void 0);this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn;this.forwardTsnChunk.streams=Object.entries(t).map(([s,n])=>[Number(s),n])}}maybeAbandon(e){if(e.abandoned)return true;const t=!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3;if(!t)return false;const s=this.sentQueue.findIndex(n=>n===e);for(let n=s;n>=0;n--){const i=this.sentQueue.at(n);i.abandoned=true;i.retransmit=false;if(i.flags&Ui){break}}for(let n=s;n<this.sentQueue.length;n++){const i=this.sentQueue.at(n);i.abandoned=true;i.retransmit=false;if(i.flags&Ui){break}}return true}static getCapabilities(){return new cm(65536)}setRemotePort(e){this.remotePort=e}async start(e){if(!this.started){this.started=true;this.setConnectionState(\"connecting\");if(e){this.setRemotePort(e)}if(!this.isServer){await this.init()}}}async init(){const e=new ln;e.initiateTag=this.localVerificationTag;e.advertisedRwnd=this.advertisedRwnd;e.outboundStreams=this._outboundStreamsCount;e.inboundStreams=this._inboundStreamsMax;e.initialTsn=this.localTsn;this.setExtensions(e.params);X(\"send init\",e);try{await this.sendChunk(e);this.timer1Start(e);this.setState(Q.COOKIE_WAIT)}catch(t){X(\"send init failed\",t.message)}}setExtensions(e){const t=[];if(this.localPartialReliability){e.push([dT,Buffer.from(\"\")]);t.push(un.type)}t.push(Hu.type);e.push([fT,Buffer.from(t)])}async sendChunk(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){throw new Error(\"invalid remote port\")}const t=tT(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}setState(e){if(e!=this.associationState){this.associationState=e}if(e===Q.ESTABLISHED){this.isStopping=false;this.isClosed=false;this.setConnectionState(\"connected\");this.heartbeatStart()}else if(e===Q.CLOSED){this.isClosed=true;this.timer1Cancel();this.timer2Cancel();this.timer3Cancel();this.timerReconfigCancel();this.heartbeatCancel();if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}this.setConnectionState(\"closed\");this.removeAllListeners()}}setConnectionState(e){this.state=e;X(\"setConnectionState\",e);this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(Q.CLOSED);return}this.isStopping=true;this.transport.onData=void 0;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}if(this.associationState!==Q.CLOSED){await this.abort()}this.setState(Q.CLOSED);clearTimeout(this.timer1Handle);clearTimeout(this.timer2Handle);clearTimeout(this.timer3Handle);clearTimeout(this.timerReconfigHandle);clearTimeout(this.timerHeartbeatHandle);clearTimeout(this.sackTimeout)}async abort(){const e=new Ni;await this.sendChunk(e).catch(t=>{X(\"send abort failed\",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}};var am=class{static{a(this,\"InboundStream\")}constructor(){this.reassembly=[];this.streamSequenceNumber=0}addChunk(e){if(this.reassembly.length===0||Et(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(const[t,s]of rT(this.reassembly)){if(s.tsn===e.tsn)throw new Error(\"duplicate chunk in reassembly\");if(Et(s.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0;let t;let s;let n;while(e<this.reassembly.length){const i=this.reassembly[e];if(t===void 0){n=!(i.flags&zu);if(!(i.flags&qu)){if(n){break}else{e++;continue}}if(n&&lu(i.streamSeqNum,this.streamSequenceNumber)){break}s=i.tsn;t=e}else if(i.tsn!==s){if(n){break}else{t=void 0;e++;continue}}if(i.flags&Ui){const o=this.reassembly.slice(t,e+1).map(l=>l.userData);const c=o.length===1?o[0]:Buffer.concat(o);this.reassembly.splice(t,e+1-t);if(n&&i.streamSeqNum===this.streamSequenceNumber){this.streamSequenceNumber=$e(this.streamSequenceNumber,1)}e=t;yield[i.streamId,i.protocol,c]}else{e++}s=gn(s)}}pruneChunks(e){let t=-1,s=0;for(const[n,i]of this.reassembly.entries()){if(bi(e,i.tsn)){t=n;s+=i.userData.length}else{break}}this.reassembly=this.reassembly.slice(t+1);return s}};var cm=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};function mn(r){return(r-1)%Ur}a(mn,\"tsnMinusOne\");function gn(r){return(r+1)%Ur}a(gn,\"tsnPlusOne\");function ne(r,e=r){return new DOMException(e,r)}a(ne,\"createWebRtcDomException\");function rr(r){return new TypeError(r)}a(rr,\"createWebRtcTypeError\");var IR=require(\"node:crypto\");var OR=require(\"node:net\");var hm=require(\"node:crypto\");var Tt={rsa_1:1,ecdsa_3:3};var Ku={sha256_4:4};var Wu={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199};var hT=Object.values(Wu);var jr={x25519_29:29,secp256r1_23:23};var Vu=Object.values(jr);var Xu={named_curve_3:3};var um={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027};var pT=[1,64];var Yu=[{hash:Ku.sha256_4,signature:Tt.rsa_1},{hash:Ku.sha256_4,signature:Tt.ecdsa_3}];var $r=require(\"node:crypto\");function Fr(r,e){const t=e.length;if(t<128)return Buffer.concat([Buffer.from([r,t]),e]);const s=[];for(let n=t;n>0;n=Math.floor(n/256))s.unshift(n&255);return Buffer.concat([Buffer.from([r,128|s.length,...s]),e])}a(Fr,\"der\");var yn=a((...r)=>Fr(48,Buffer.concat(r)),\"sequence\");var eO=a((...r)=>Fr(49,Buffer.concat(r)),\"set\");var tO=Buffer.from([5,0]);var rO=a(r=>Fr(12,Buffer.from(r,\"utf8\")),\"utf8String\");var sO=a(r=>Fr(3,Buffer.concat([Buffer.from([0]),r])),\"bitString\");var nO=a((r,e)=>Fr(160|r,e),\"explicit\");function mT(r){let e=0;while(e<r.length-1&&r[e]===0)e++;const t=r.subarray(e);return Fr(2,t[0]&128?Buffer.concat([Buffer.from([0]),t]):t)}a(mT,\"integer\");function fm(r){const e=r.split(\".\").map(Number);const t=[e[0]*40+e[1]];for(const s of e.slice(2)){const n=[s&127];for(let i=Math.floor(s/128);i>0;i=Math.floor(i/128))n.unshift(128|i&127);t.push(...n)}return Fr(6,Buffer.from(t))}a(fm,\"oid\");function gT(r){const e=r.toISOString().replace(/[-:T]/g,\"\").slice(0,14);return r.getUTCFullYear()<2050?Fr(23,Buffer.from(`${e.slice(2)}Z`)):Fr(24,Buffer.from(`${e}Z`))}a(gT,\"time\");var iO=a(r=>yn(eO(yn(fm(\"2.5.4.3\"),rO(r)))),\"commonName\");function yT(r=\"ecdsa\",e=\"WebRTC\",t=30){const{privateKey:s,publicKey:n}=r===\"ecdsa\"?(0,$r.generateKeyPairSync)(\"ec\",{namedCurve:\"prime256v1\"}):(0,$r.generateKeyPairSync)(\"rsa\",{modulusLength:2048,publicExponent:65537});const i=r===\"ecdsa\"?yn(fm(\"1.2.840.10045.4.3.2\")):yn(fm(\"1.2.840.113549.1.1.11\"),tO);const o=new Date(Date.now()-24*60*60*1e3);const c=new Date(o.getTime()+(t+1)*24*60*60*1e3);const l=(0,$r.randomBytes)(8);l[0]&=127;const u=iO(e);const f=yn(nO(0,mT(Buffer.from([2]))),mT(l),i,u,yn(gT(o),gT(c)),u,n.export({type:\"spki\",format:\"der\"}));const d=(0,$r.sign)(\"sha256\",f,s);const h=yn(f,i,sO(d));return{certPem:oO(h,\"CERTIFICATE\"),keyPem:s.export({type:\"pkcs8\",format:\"pem\"})}}a(yT,\"createDtlsCertificate\");function oO(r,e){const t=r.toString(\"base64\").match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----\n${t.join(\"\\n\")}\n-----END ${e}-----\n`}a(oO,\"toPem\");function Ju(r){const e=r.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);if(!e)throw new Error(\"no certificate in the PEM text\");return Buffer.from(e[1].replace(/\\s+/g,\"\"),\"base64\")}a(Ju,\"certificateDer\");function bT(r){return(0,$r.createPrivateKey)(r)}a(bT,\"privateKeyFromPem\");var Zu=require(\"node:crypto\");var sr=require(\"node:crypto\");var ST=a(()=>{const r=(0,sr.createECDH)(\"prime256v1\");const e=r.generateKeys();return{privateKey:r.getPrivateKey(),publicKey:e}},\"p256Keypair\");var wT=a(({publicKey:r,privateKey:e})=>{const t=(0,sr.createECDH)(\"prime256v1\");t.setPrivateKey(e);return t.computeSecret(r)},\"p256PreMasterSecret\");var ET=Buffer.from(\"302e020100300506032b656e04220420\",\"hex\");var TT=Buffer.from(\"302a300506032b656e032100\",\"hex\");var xT=a(()=>{const{privateKey:r,publicKey:e}=(0,sr.generateKeyPairSync)(\"x25519\");return{privateKey:r.export({type:\"pkcs8\",format:\"der\"}).subarray(ET.length),publicKey:e.export({type:\"spki\",format:\"der\"}).subarray(TT.length)}},\"x25519Keypair\");var RT=a(({publicKey:r,privateKey:e})=>(0,sr.diffieHellman)({privateKey:(0,sr.createPrivateKey)({key:Buffer.concat([ET,e]),format:\"der\",type:\"pkcs8\"}),publicKey:(0,sr.createPublicKey)({key:Buffer.concat([TT,r]),format:\"der\",type:\"spki\"})}),\"x25519PreMasterSecret\");function Qu(r,e,t){switch(t){case jr.secp256r1_23:return wT({publicKey:r,privateKey:e});case jr.x25519_29:return RT({publicKey:r,privateKey:e});default:throw new Error}}a(Qu,\"prfPreMasterSecret\");function _T(r,e,t){const s=(0,Zu.createHmac)(r,e);s.update(t);return s.digest()}a(_T,\"hmac\");function uc(r,e,t,s=\"sha256\"){const n=t;const i=[];let o=e;do{o=_T(s,r,o);const c=_T(s,r,Buffer.concat([o,e]));i.push(c);t-=c.length}while(t>0);return Buffer.concat(i,n)}a(uc,\"prfPHash\");function ef(r,e,t){const s=Buffer.concat([Buffer.from(\"master secret\"),e,t]);return uc(r,s,48)}a(ef,\"prfMasterSecret\");function tf(r,e){const t=vT(\"sha256\",e);const s=\"extended master secret\";return uc(r,Buffer.concat([Buffer.from(s),t]),48)}a(tf,\"prfExtendedMasterSecret\");function CT(r,e,t,s,n,i){const o=i?s:n;const c=i?n:s;const l=Buffer.concat([Buffer.from(r),o,c]);return uc(t,l,e)}a(CT,\"exportKeyingMaterial\");function vT(r,e){return(0,Zu.createHash)(r).update(e).digest()}a(vT,\"hash\");function AT(r,e,t,s=12){const n=vT(\"sha256\",e);return uc(r,Buffer.concat([Buffer.from(t),n]),s)}a(AT,\"prfVerifyData\");function IT(r,e){return AT(r,e,\"client finished\")}a(IT,\"prfVerifyDataClient\");function OT(r,e){return AT(r,e,\"server finished\")}a(OT,\"prfVerifyDataServer\");function kT(r,e,t,s,n,i,o=\"sha256\"){const c=s*2+n*2;const l=r;const u=Buffer.concat([t,e]);const f=uc(l,Buffer.concat([Buffer.from(\"key expansion\"),u]),c,o);const d=new q.BinaryReader(f);const h=d.readBuffer(s);const p=d.readBuffer(s);const m=d.readBuffer(n);const y=d.readBuffer(n);const w=Buffer.alloc(i,0);const S=Buffer.alloc(i,0);m.copy(w,0);y.copy(S,0);return{clientWriteKey:h,serverWriteKey:p,clientNonce:w,serverNonce:S}}a(kT,\"prfEncryptionKeys\");var dt={CLIENT:1,SERVER:2};var fc=class{static{a(this,\"AbstractCipher\")}constructor(){this.id=0;this.verifyDataLength=12}init(...e){throw new Error(\"not implemented\")}encrypt(...e){throw new Error(\"not implemented\")}decrypt(...e){throw new Error(\"not implemented\")}toString(){return this.name}};var{encode:aO,types:dm}=q;var Hr=class{static{a(this,\"CipherContext\")}constructor(e,t,s,n){this.sessionType=e;this.certPem=t;this.keyPem=s;if(t&&s&&n){this.parseX509(t,s,n)}}static{this.createSelfSignedCertificateWithKey=async(e,t)=>{const{certPem:s,keyPem:n}=yT(e.signature===Tt.rsa_1?\"rsa\":\"ecdsa\");return{certPem:s,keyPem:n,signatureHash:e}}}encryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const n=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});e.fragment=n;e.recordLayerHeader.contentLen=n.length;return e}decryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const n=this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});return n}verifyData(e){if(this.sessionType===dt.CLIENT)return IT(this.masterSecret,e);else return OT(this.masterSecret,e)}signatureData(e,t){return(0,hm.sign)(t,e,this.localPrivateKey)}generateKeySignature(e){const t=this.sessionType===dt.CLIENT?this.localRandom:this.remoteRandom;const s=this.sessionType===dt.SERVER?this.localRandom:this.remoteRandom;const n=this.valueKeySignature(t.serialize(),s.serialize(),this.localKeyPair.publicKey,this.namedCurve);return(0,hm.sign)(e,n,this.localPrivateKey)}parseX509(e,t,s){this.localCert=Ju(e);this.localPrivateKey=bT(t);this.signatureHashAlgorithm=s}valueKeySignature(e,t,s,n){const i=aO({type:Xu.named_curve_3,curve:n,len:s.length},{type:dm.uint8,curve:dm.uint16be,len:dm.uint8});return Buffer.concat([e,t,i,s])}};var qr=class{static{a(this,\"SrtpContext\")}static findMatchingSRTPProfile(e,t){for(const s of t){if(e.includes(s))return s}}};var dc=a(r=>\"0x\"+r.toString(\"hex\").replace(/(.)(.)/g,\"$1$2 \").split(\" \").filter(e=>e!=void 0&&e.length>0).join(\",0x\"),\"dumpBuffer\");var rf=a(r=>Object.entries({...r}).reduce((e,[t,s])=>{if(typeof s===\"number\"||typeof s===\"string\"){e[t]=s}if(Buffer.isBuffer(s)){e[t]=dc(s)}return e},{}),\"getObjectSummary\");var{decode:cO,encode:lO,types:$i}=q;var ge=class r{static{a(this,\"FragmentedHandshake\")}static{this.spec={msg_type:$i.uint8,length:$i.uint24be,message_seq:$i.uint16be,fragment_offset:$i.uint24be,fragment_length:$i.uint24be,fragment:$i.buffer(e=>e.current.fragment_length)}}constructor(e,t,s,n,i,o){this.msg_type=e;this.length=t;this.message_seq=s;this.fragment_offset=n;this.fragment_length=i;this.fragment=o}get summary(){return rf(this)}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(cO(e,r.spec)))}serialize(){return lO(this,r.spec)}chunk(e){let t=0;const s=this.fragment.length;if(s===0)return[new r(this.msg_type,s,this.message_seq,t,0,this.fragment)];const n=[];if(!e){e=1280-(20+8)-(1+3+2+3+3)}while(t<s){const i=Math.min(e,s-t);const o=Buffer.from(this.fragment.slice(t,t+i));if(o.length<=0){throw new Error(`Zero or less bytes processed while fragmenting handshake message.`)}n.push(new r(this.msg_type,s,this.message_seq,t,o.length,o));t+=o.length}return n}static assemble(e){if(!e?.length){throw new Error(\"cannot reassemble handshake from empty array\")}e=e.sort((s,n)=>s.fragment_offset-n.fragment_offset);const t=Buffer.alloc(e[0].length);for(const s of e){s.fragment.copy(t,s.fragment_offset)}return new r(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){const s=e.find(n=>n.msg_type===t);if(!s)return[];if(!e?.length)return[];return e.filter(n=>{return n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length})}};var{types:uO}=q;var{uint16be:sf,uint24be:fO,buffer:PT,array:dO,uint8:hc,string:hO}=uO;var pO={type:sf,data:PT(sf)};var pc=dO(pO,sf,\"bytes\");var NT=PT(fO);var LT=hc;var MT=hO(sf);var DT={hash:hc,signature:hc};var Fi={major:hc,minor:hc};var $;(function(r){r[r[\"hello_request_0\"]=0]=\"hello_request_0\";r[r[\"client_hello_1\"]=1]=\"client_hello_1\";r[r[\"server_hello_2\"]=2]=\"server_hello_2\";r[r[\"hello_verify_request_3\"]=3]=\"hello_verify_request_3\";r[r[\"certificate_11\"]=11]=\"certificate_11\";r[r[\"server_key_exchange_12\"]=12]=\"server_key_exchange_12\";r[r[\"certificate_request_13\"]=13]=\"certificate_request_13\";r[r[\"server_hello_done_14\"]=14]=\"server_hello_done_14\";r[r[\"certificate_verify_15\"]=15]=\"certificate_verify_15\";r[r[\"client_key_exchange_16\"]=16]=\"client_key_exchange_16\";r[r[\"finished_20\"]=20]=\"finished_20\"})($||($={}));var UT=require(\"node:crypto\");var{decode:mO,encode:gO,types:BT}=q;var ht=class r{static{a(this,\"DtlsRandom\")}static{this.spec={gmt_unix_time:BT.uint32be,random_bytes:BT.buffer(28)}}constructor(e=Math.floor(Date.now()/1e3),t=(0,UT.randomBytes)(28)){this.gmt_unix_time=e;this.random_bytes=t}static deSerialize(e){return new r(...Object.values(mO(e,r.spec)))}static from(e){return new r(...Object.values(e))}serialize(){return gO(this,r.spec)}};var{decode:yO,encode:bO,types:Mt}=q;var Hi=class r{static{a(this,\"ClientHello\")}static{this.spec={clientVersion:{major:Mt.uint8,minor:Mt.uint8},random:ht.spec,sessionId:Mt.buffer(Mt.uint8),cookie:Mt.buffer(Mt.uint8),cipherSuites:Mt.array(Mt.uint16be,Mt.uint16be,\"bytes\"),compressionMethods:Mt.array(Mt.uint8,Mt.uint8,\"bytes\"),extensions:pc}}constructor(e,t,s,n,i,o,c){this.clientVersion=e;this.random=t;this.sessionId=s;this.cookie=n;this.cipherSuites=i;this.compressionMethods=o;this.extensions=c;this.msgType=$.client_hello_1;this.messageSeq=0}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(yO(e,r.spec)))}serialize(){return bO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var $T=require(\"node:timers/promises\");var{decode:SO,encode:wO,types:nf}=q;var of=class r{static{a(this,\"MACHeader\")}static{this.spec={epoch:nf.uint16be,sequenceNumber:nf.uint48be,contentType:nf.uint8,protocolVersion:Fi,contentLen:nf.uint16be}}constructor(e,t,s,n,i){this.epoch=e;this.sequenceNumber=t;this.contentType=s;this.protocolVersion=n;this.contentLen=i}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(SO(e,r.spec)))}serialize(){return wO(this,r.spec)}};var qi=class r{static{a(this,\"DtlsPlaintext\")}constructor(e,t){this.recordLayerHeader=e;this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:dc(this.fragment)}}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){if(e.length<13){throw new Error(\"Invalid DTLS record: buffer is too short\")}const t=e.readUInt8(0);const s=e.readUInt8(1);const n=e.readUInt8(2);const i=e.readUInt16BE(3);const o=e.slice(5,11).readUIntBE(0,6);const c=e.readUInt16BE(11);if(e.length<13+c){throw new Error(\"Invalid DTLS record: fragment length exceeds buffer\")}const l=e.slice(13,13+c);const u=new r({contentType:t,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:c},l);return u}serialize(){const e=this.fragment.length;const t=13+e;const s=Buffer.alloc(t);s.writeUInt8(this.recordLayerHeader.contentType,0);s.writeUInt8(this.recordLayerHeader.protocolVersion.major,1);s.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2);s.writeUInt16BE(this.recordLayerHeader.epoch,3);s.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6);s.writeUInt16BE(e,11);this.fragment.copy(s,13);return s}computeMACHeader(){return new of(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}};var af=a(r=>e=>{r.lastFlight=e;return e.flatMap(t=>{t.messageSeq=r.sequenceNumber++;const s=t.toFragment();const n=s.chunk();return n})},\"createFragments\");var wr=a(r=>(e,t)=>{return e.map(s=>{const n=new qi({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment);return n})},\"createPlaintext\");var Ee;(function(r){r[r[\"changeCipherSpec\"]=20]=\"changeCipherSpec\";r[r[\"alert\"]=21]=\"alert\";r[r[\"handshake\"]=22]=\"handshake\";r[r[\"applicationData\"]=23]=\"applicationData\"})(Ee||(Ee={}));var mc;(function(r){r[r[\"CloseNotify\"]=0]=\"CloseNotify\";r[r[\"UnexpectedMessage\"]=10]=\"UnexpectedMessage\";r[r[\"BadRecordMac\"]=20]=\"BadRecordMac\";r[r[\"DecryptionFailed\"]=21]=\"DecryptionFailed\";r[r[\"RecordOverflow\"]=22]=\"RecordOverflow\";r[r[\"DecompressionFailure\"]=30]=\"DecompressionFailure\";r[r[\"HandshakeFailure\"]=40]=\"HandshakeFailure\";r[r[\"NoCertificate\"]=41]=\"NoCertificate\";r[r[\"BadCertificate\"]=42]=\"BadCertificate\";r[r[\"UnsupportedCertificate\"]=43]=\"UnsupportedCertificate\";r[r[\"CertificateRevoked\"]=44]=\"CertificateRevoked\";r[r[\"CertificateExpired\"]=45]=\"CertificateExpired\";r[r[\"CertificateUnknown\"]=46]=\"CertificateUnknown\";r[r[\"IllegalParameter\"]=47]=\"IllegalParameter\";r[r[\"UnknownCa\"]=48]=\"UnknownCa\";r[r[\"AccessDenied\"]=49]=\"AccessDenied\";r[r[\"DecodeError\"]=50]=\"DecodeError\";r[r[\"DecryptError\"]=51]=\"DecryptError\";r[r[\"ExportRestriction\"]=60]=\"ExportRestriction\";r[r[\"ProtocolVersion\"]=70]=\"ProtocolVersion\";r[r[\"InsufficientSecurity\"]=71]=\"InsufficientSecurity\";r[r[\"InternalError\"]=80]=\"InternalError\";r[r[\"UserCanceled\"]=90]=\"UserCanceled\";r[r[\"NoRenegotiation\"]=100]=\"NoRenegotiation\";r[r[\"UnsupportedExtension\"]=110]=\"UnsupportedExtension\"})(mc||(mc={}));var EO=P(\"webrtc/dtls/flight/flight:warn\");var jT=P(\"webrtc/dtls/flight/flight:err\");var Dt=class r{static{a(this,\"Flight\")}static{this.RetransmitCount=10}constructor(e,t,s,n){this.transport=e;this.dtls=t;this.flight=s;this.nextFlight=n;this.state=\"PREPARING\";this.send=i=>Promise.all(i.map(o=>this.transport.send(o)))}createPacket(e){const t=af(this.dtls)(e);this.dtls.bufferHandshakeCache(t,true,this.flight);const s=wr(this.dtls)(t.map(n=>({type:Ee.handshake,fragment:n.serialize()})),++this.dtls.recordSequenceNumber);return s}async transmit(e){const t=this.transport.closing.signal;let s=0;for(;s<=r.RetransmitCount;s++){if(t.aborted)return;this.setState(\"SENDING\");this.send(e).catch(n=>{jT(\"fail to send\",n)});this.setState(\"WAITING\");if(this.nextFlight===void 0){this.setState(\"FINISHED\");break}try{await(0,$T.setTimeout)(1e3*((s+1)/2),void 0,{signal:t})}catch{return}if(this.dtls.flight>=this.nextFlight){this.setState(\"FINISHED\");break}else{EO(this.dtls.sessionId,\"retransmit\",s,this.dtls.flight)}}if(s>r.RetransmitCount){jT(this.dtls.sessionId,\"retransmit failed\",s);throw new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}}setState(e){this.state=e}};var cf=class extends Dt{static{a(this,\"Flight1\")}constructor(e,t,s){super(e,t,1,3);this.cipher=s}async exec(e){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;const t=new Hi({major:255-1,minor:255-2},new ht,Buffer.from([]),Buffer.from([]),hT,[0],e);this.dtls.version=t.clientVersion;this.cipher.localRandom=ht.from(t.random);const s=this.createPacket([t]);const n=Buffer.concat(s.map(i=>i.serialize()));await this.transmit([n])}};var TO=P(\"webrtc/dtls/flight/client/flight3:log\");var lf=class extends Dt{static{a(this,\"Flight3\")}constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3;this.dtls.handshakeCache=[];const[t]=this.dtls.lastFlight;TO(\"dtls version\",t.clientVersion);t.cookie=e.cookie;this.dtls.cookie=e.cookie;const s=this.createPacket([t]);const n=Buffer.concat(s.map(i=>i.serialize()));await this.transmit([n])}};var uf={NULL:0,ECDHE:1};var gc={NULL:0,RSA:1,ECDSA:2,PSK:3};var yc={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5};var bn=class{static{a(this,\"KeyExchange\")}constructor(){this.id=0}toString(){return this.name}};function FT(){const r=new bn;r.id=yc.RSA;r.name=\"RSA\";r.keyType=gc.RSA;return r}a(FT,\"createRSAKeyExchange\");function HT(){const r=new bn;r.id=yc.ECDHE_RSA;r.name=\"ECDHE_RSA\";r.signType=uf.ECDHE;r.keyType=gc.RSA;return r}a(HT,\"createECDHERSAKeyExchange\");function qT(){const r=new bn;r.id=yc.ECDHE_ECDSA;r.name=\"ECDHE_ECDSA\";r.signType=uf.ECDHE;r.keyType=gc.ECDSA;return r}a(qT,\"createECDHEECDSAKeyExchange\");function zT(){const r=new bn;r.id=yc.PSK;r.name=\"PSK\";r.signType=uf.NULL;r.keyType=gc.PSK;return r}a(zT,\"createPSKKeyExchange\");function GT(){const r=new bn;r.id=yc.ECDHE_PSK;r.name=\"ECDHE_PSK\";r.signType=uf.ECDHE;r.keyType=gc.PSK;return r}a(GT,\"createECDHEPSKKeyExchange\");var ff=require(\"node:crypto\");var xO=P(\"webrtc/dtls/cipher/suites/aead:err\");var bc=class extends fc{static{a(this,\"AEADCipher\")}constructor(){super();this.keyLength=0;this.nonceLength=0;this.ivLength=0;this.authTagLength=0;this.nonceImplicitLength=0;this.nonceExplicitLength=0}get summary(){return rf(this)}init(e,t,s){const n=kT(e,s,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=n.clientWriteKey;this.serverWriteKey=n.serverWriteKey;this.clientNonce=n.clientNonce;this.serverNonce=n.serverNonce}encrypt(e,t,s){const n=e===dt.CLIENT;const i=n?this.clientNonce:this.serverNonce;const o=n?this.clientWriteKey:this.serverWriteKey;if(!i||!o)throw new Error;i.writeUInt16BE(s.epoch,this.nonceImplicitLength);i.writeUIntBE(s.sequenceNumber,this.nonceImplicitLength+2,6);const c=i.slice(this.nonceImplicitLength);const l=this.encodeAdditionalBuffer(s,t.length);const u=(0,ff.createCipheriv)(this.blockAlgorithm,o,i,{authTagLength:this.authTagLength});u.setAAD(l,{plaintextLength:t.length});const f=u.update(t);const d=u.final();const h=u.getAuthTag();return Buffer.concat([c,f,d,h])}encodeAdditionalBuffer(e,t){const s=Buffer.alloc(13);s.writeUInt16BE(e.epoch,0);s.writeUintBE(e.sequenceNumber,2,6);s.writeUInt8(e.type,8);s.writeUInt16BE(e.version,9);s.writeUInt16BE(t,11);return s}decrypt(e,t,s){const n=e===dt.CLIENT;const i=n?this.serverNonce:this.clientNonce;const o=n?this.serverWriteKey:this.clientWriteKey;if(!i||!o)throw new Error;const c=t.subarray(0,this.nonceExplicitLength);c.copy(i,this.nonceImplicitLength);const l=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength);const u=t.subarray(t.length-this.authTagLength);const f=this.encodeAdditionalBuffer(s,l.length);const d=(0,ff.createDecipheriv)(this.blockAlgorithm,o,i,{authTagLength:this.authTagLength});d.setAuthTag(u);d.setAAD(f,{plaintextLength:l.length});const h=d.update(l);try{const p=d.final();return p.length>0?Buffer.concat([h,p]):h}catch(p){xO(\"decrypt failed\",p,e,dc(t),s,this.summary);throw p}}};var Me={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395};var Sc={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var wc={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var KT=FT();var WT=HT();var VT=qT();var XT=zT();var YT=GT();function df(r){switch(r){case Me.TLS_RSA_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_RSA_WITH_AES_128_GCM_SHA256,\"TLS_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",KT,Sc);case Me.TLS_RSA_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_RSA_WITH_AES_256_GCM_SHA384,\"TLS_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",KT,wc,\"sha384\");case Me.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",WT,Sc);case Me.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",WT,wc,\"sha384\");case Me.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",VT,Sc);case Me.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",VT,wc,\"sha384\");case Me.TLS_PSK_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_PSK_WITH_AES_128_GCM_SHA256,\"TLS_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",XT,Sc,\"sha256\");case Me.TLS_PSK_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_PSK_WITH_AES_256_GCM_SHA384,\"TLS_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",XT,wc,\"sha384\");case Me.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return Er(Me.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",YT,Sc,\"sha256\");case Me.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return Er(Me.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",YT,wc,\"sha384\");default:break}return null}a(df,\"createCipher\");function Er(r,e,t,s,n,i=\"sha256\"){const o=new bc;o.id=r;o.name=e;o.blockAlgorithm=t;o.kx=s;o.hashAlgorithm=i;o.keyLength=n.K_LEN;o.nonceLength=n.N_MAX;o.nonceImplicitLength=4;o.nonceExplicitLength=8;o.ivLength=o.nonceImplicitLength;o.authTagLength=16;return o}a(Er,\"createAEADCipher\");function hf(r){switch(r){case jr.secp256r1_23:{const{privateKey:e,publicKey:t}=ST();return{curve:r,privateKey:e,publicKey:t}}case jr.x25519_29:{const{privateKey:e,publicKey:t}=xT();return{curve:r,privateKey:e,publicKey:t}}default:throw new Error}}a(hf,\"generateKeyPair\");var Tr=class{static{a(this,\"ExtendedMasterSecret\")}static{this.type=23}};var{decode:RO,encode:_O,types:JT}=q;var xr=class r{static{a(this,\"RenegotiationIndication\")}static{this.type=65281}static{this.spec={type:JT.uint16be,data:JT.uint8}}constructor(e={}){this.type=r.type;this.data=0;Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(RO(e,r.spec))}serialize(){return _O(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:CO,encode:vO,types:pm}=q;var Bt=class r{static{a(this,\"UseSRTP\")}static{this.type=14}static{this.spec={type:pm.uint16be,data:pm.buffer(pm.uint16be)}}constructor(e={}){this.type=r.type;this.data=Buffer.from([]);this.profiles=[];this.mki=Buffer.from([0]);Object.assign(this,e)}static create(e,t){const s=new r({profiles:e,mki:t});return s}static deSerialize(e){const t=new r(CO(e,r.spec));const s=t.data.readUInt16BE();const n=new Array(s/2);for(let i=0;i<n.length;i++){n[i]=t.data.readUInt16BE(i*2+2)}t.profiles=n;t.mki=t.data.slice(s+2);return t}serialize(){const e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);const t=Buffer.concat([e,...this.profiles.map(s=>{const n=Buffer.alloc(2);n.writeUInt16BE(s);return n}),this.mki]);this.data=t;return vO(this,r.spec)}static fromData(e){const t=Buffer.alloc(4);t.writeUInt16BE(r.type);t.writeUInt16BE(e.length,2);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}};var{decode:AO,encode:IO,types:ZT}=q;var zr=class r{static{a(this,\"Certificate\")}static{this.spec={certificateList:ZT.array(NT,ZT.uint24be,\"bytes\")}}constructor(e){this.certificateList=e;this.msgType=$.certificate_11}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(...Object.values(AO(e,r.spec)))}serialize(){return IO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:OO,encode:kO,types:PO}=q;var zi=class r{static{a(this,\"ChangeCipherSpec\")}static{this.spec={type:PO.uint8}}constructor(e=1){this.type=e}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(OO(e,r.spec)))}serialize(){return kO(this,r.spec)}};var{decode:NO,encode:LO,types:mm}=q;var Gi=class r{static{a(this,\"CertificateVerify\")}static{this.spec={algorithm:mm.uint16be,signature:mm.buffer(mm.uint16be)}}constructor(e,t){this.algorithm=e;this.signature=t;this.msgType=$.certificate_verify_15}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){const t=NO(e,r.spec);return new r(...Object.values(t))}serialize(){return LO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:MO,encode:DO,types:QT}=q;var Ki=class r{static{a(this,\"ClientKeyExchange\")}static{this.spec={publicKey:QT.buffer(QT.uint8)}}constructor(e){this.publicKey=e;this.msgType=$.client_key_exchange_16}static createEmpty(){return new r(void 0)}static deSerialize(e){const t=MO(e,r.spec);return new r(...Object.values(t))}serialize(){return DO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Sn=class r{static{a(this,\"Finished\")}constructor(e){this.verifyData=e;this.msgType=$.finished_20}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(e)}serialize(){return this.verifyData}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:BO,encode:UO,types:Wi}=q;var Vi=class r{static{a(this,\"ServerCertificateRequest\")}static{this.spec={certificateTypes:Wi.array(LT,Wi.uint8,\"bytes\"),signatures:Wi.array(DT,Wi.uint16be,\"bytes\"),authorities:Wi.array(MT,Wi.uint16be,\"bytes\")}}constructor(e,t,s){this.certificateTypes=e;this.signatures=t;this.authorities=s;this.msgType=$.certificate_request_13}static createEmpty(){return new r(void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(BO(e,r.spec)))}serialize(){return UO(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:ex,encode:tx,types:pf}=q;var Xi=class r{static{a(this,\"ServerHello\")}static{this.spec={serverVersion:Fi,random:ht.spec,sessionId:pf.buffer(pf.uint8),cipherSuite:pf.uint16be,compressionMethod:pf.uint8}}constructor(e,t,s,n,i,o){this.serverVersion=e;this.random=t;this.sessionId=s;this.cipherSuite=n;this.compressionMethod=i;this.extensions=o;this.msgType=$.server_hello_2}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=ex(e,r.spec);const s=new r(...Object.values(t));const n=s.serialize();if(n.length<e.length){return new r(...Object.values(ex(e,{...r.spec,extensions:pc})))}return s}serialize(){return this.extensions===void 0?tx(this,r.spec):tx(this,{...r.spec,extensions:pc})}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:jO,encode:$O}=q;var Yi=class r{static{a(this,\"ServerHelloDone\")}constructor(){this.msgType=$.server_hello_done_14}static{this.spec={}}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(jO(e,r.spec)))}serialize(){return $O(this,r.spec)}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{encode:FO}=q;function rx(r,e){return FO(r,e)}a(rx,\"encodeBuffer\");var{decode:HO,types:Is}=q;var Ji=class r{static{a(this,\"ServerKeyExchange\")}static{this.spec={ellipticCurveType:Is.uint8,namedCurve:Is.uint16be,publicKeyLength:Is.uint8,publicKey:Is.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Is.uint8,signatureAlgorithm:Is.uint8,signatureLength:Is.uint16be,signature:Is.buffer(e=>e.current.signatureLength)}}constructor(e,t,s,n,i,o,c,l){this.ellipticCurveType=e;this.namedCurve=t;this.publicKeyLength=s;this.publicKey=n;this.hashAlgorithm=i;this.signatureAlgorithm=o;this.signatureLength=c;this.signature=l;this.msgType=$.server_key_exchange_12}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=HO(e,r.spec);return new r(...Object.values(t))}serialize(){const e=rx(this,r.spec);return e}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Ze=P(\"webrtc/dtls/flight/client/flight5:log\");var mf=class extends Dt{static{a(this,\"Flight5\")}constructor(e,t,s,n){super(e,t,5,7);this.cipher=s;this.srtp=n}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,4);const t=(()=>{switch(e.msg_type){case $.server_hello_2:return Xi.deSerialize(e.fragment);case $.certificate_11:return zr.deSerialize(e.fragment);case $.server_key_exchange_12:return Ji.deSerialize(e.fragment);case $.certificate_request_13:return Vi.deSerialize(e.fragment);case $.server_hello_done_14:return Yi.deSerialize(e.fragment)}})();if(t){Zi[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}}async exec(){if(this.dtls.flight===5){Ze(this.dtls.sessionId,\"flight5 twice\");this.send(this.dtls.lastMessage).catch(s=>Ze(\"send failed\",s));return}this.dtls.flight=5;const e=this.dtls.requestedCertificateTypes.length>0;Ze(this.dtls.sessionId,\"send flight5\",e);const t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(s=>s);this.dtls.lastMessage=t;await this.transmit(t)}sendCertificate(){const e=new zr([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);const s=Buffer.concat(t.map(n=>n.serialize()));return s}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;const e=new Ki(this.cipher.localKeyPair.publicKey);const t=this.createPacket([e]);const s=Buffer.concat(t.map(l=>l.serialize()));const n=this.cipher.localKeyPair;const i=this.cipher.remoteKeyPair;if(!i.publicKey)throw new Error(\"not exist\");const o=Qu(i.publicKey,n.privateKey,n.curve);Ze(this.dtls.sessionId,\"extendedMasterSecret\",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);const c=Buffer.concat(this.dtls.sortedHandshakeCache.map(l=>l.serialize()));this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?tf(o,c):ef(o,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize());this.cipher.cipher=df(this.cipher.cipherSuite);this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize());Ze(this.dtls.sessionId,\"cipher\",this.cipher.cipher.summary);return s}sendCertificateVerify(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(c=>c.serialize()));const t=this.cipher.signatureData(e,\"sha256\");const s=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case Tt.ecdsa_3:return um.ecdsa_secp256r1_sha256;case Tt.rsa_1:return um.rsa_pkcs1_sha256}})();if(!s)throw new Error;Ze(this.dtls.sessionId,\"signatureScheme\",this.cipher.signatureHashAlgorithm?.signature,s);const n=new Gi(s,t);const i=this.createPacket([n]);const o=Buffer.concat(i.map(c=>c.serialize()));return o}sendChangeCipherSpec(){const e=zi.createEmpty().serialize();const t=wr(this.dtls)([{type:Ee.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(n=>n.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Sn(t);this.dtls.epoch=1;const[n]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const i=this.cipher.encryptPacket(n).serialize();Ze(this.dtls.sessionId,\"finished\",this.cipher.cipher.summary);return i}};var Zi={};Zi[$.server_hello_2]=({cipher:r,srtp:e,dtls:t})=>s=>{Ze(t.sessionId,\"serverHello\",s.cipherSuite);r.remoteRandom=ht.from(s.random);r.cipherSuite=s.cipherSuite;Ze(t.sessionId,\"selected cipherSuite\",r.cipherSuite);if(s.extensions){s.extensions.forEach(n=>{switch(n.type){case Bt.type:{const i=Bt.fromData(n.data);const o=qr.findMatchingSRTPProfile(i.profiles,t.options.srtpProfiles||[]);Ze(t.sessionId,\"selected srtp profile\",o);if(o==void 0)return;e.srtpProfile=o}break;case Tr.type:t.remoteExtendedMasterSecret=true;break;case xr.type:Ze(t.sessionId,\"RenegotiationIndication\");break}})}};Zi[$.certificate_11]=({cipher:r,dtls:e})=>t=>{Ze(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Zi[$.server_key_exchange_12]=({cipher:r,dtls:e})=>t=>{if(!r.localRandom||!r.remoteRandom)throw new Error;Ze(e.sessionId,\"ServerKeyExchange\",t);Ze(e.sessionId,\"selected curve\",t.namedCurve);r.remoteKeyPair={curve:t.namedCurve,publicKey:t.publicKey};r.localKeyPair=hf(t.namedCurve)};Zi[$.certificate_request_13]=({dtls:r})=>e=>{Ze(r.sessionId,\"certificate_request\",e);r.requestedCertificateTypes=e.certificateTypes;r.requestedSignatureAlgorithms=e.signatures};Zi[$.server_hello_done_14]=({dtls:r})=>e=>{Ze(r.sessionId,\"server_hello_done\",e)};var{decode:qO,encode:zO,types:sx}=q;var Qi=class r{static{a(this,\"ServerHelloVerifyRequest\")}static{this.spec={serverVersion:Fi,cookie:sx.buffer(sx.uint8)}}constructor(e,t){this.serverVersion=e;this.cookie=t;this.msgType=$.hello_verify_request_3}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){return new r(...Object.values(qO(e,r.spec)))}serialize(){return zO(this,r.spec)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){const e=this.serialize();return new ge(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var ux=require(\"node:timers/promises\");var GO=P(\"webrtc/dtls/context/dtls:log\");var Ec=class{static{a(this,\"DtlsContext\")}constructor(e,t){this.options=e;this.sessionType=t;this.version={major:255-1,minor:255-2};this.lastFlight=[];this.lastMessage=[];this.recordSequenceNumber=0;this.sequenceNumber=0;this.epoch=0;this.flight=0;this.handshakeCache={};this.requestedCertificateTypes=[];this.requestedSignatureAlgorithms=[];this.remoteExtendedMasterSecret=false;this.checkHandshakesExist=s=>!s.find(n=>this.sortedHandshakeCache.find(i=>i.msg_type===n)==void 0)}get sessionId(){return this.cookie?this.cookie.toString(\"hex\").slice(0,10):\"\"}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((t,s)=>t.message_seq-s.message_seq))}bufferHandshakeCache(e,t,s){if(!this.handshakeCache[s]){this.handshakeCache[s]={data:[],isLocal:t,flight:s}}const n=e.filter(i=>{const o=this.handshakeCache[s].data.find(c=>c.msg_type===i.msg_type);if(o){GO(this.sessionId,\"exist\",o.summary,t,s);return false}return true});this.handshakeCache[s].data=[...this.handshakeCache[s].data,...n]}};var gf=class{static{a(this,\"TransportContext\")}constructor(e){this.socket=e;this.closing=new AbortController;this.send=(t,s)=>{return this.socket.send(t,s)}}close(){this.closing.abort()}};var{decode:nx,encode:KO,types:yf}=q;var wn=class r{static{a(this,\"EllipticCurves\")}static{this.type=10}static{this.spec={type:yf.uint16be,data:yf.array(yf.uint16be,yf.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){return new r}static fromData(e){return new r({type:r.type,data:nx(e,r.spec.data)})}static deSerialize(e){return new r(nx(e,r.spec))}serialize(){return KO(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:WO,encode:VO,types:Tc}=q;var En=class r{static{a(this,\"Signature\")}static{this.type=13}static{this.spec={type:Tc.uint16be,data:Tc.array({hash:Tc.uint8,signature:Tc.uint8},Tc.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(WO(e,r.spec))}serialize(){return VO(this,r.spec)}static fromData(e){const t=Buffer.alloc(2);t.writeUInt16BE(r.type);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:XO,encode:YO,types:ix}=q;var xc=class r{static{a(this,\"Alert\")}static{this.spec={level:ix.uint8,description:ix.uint8}}constructor(e,t){this.level=e;this.description=t}static deSerialize(e){return new r(...Object.values(XO(e,r.spec)))}serialize(){return YO(this,r.spec)}};var ox=P(\"webrtc/dtls/record/receive:log\");var gm=P(\"webrtc/dtls/record/receive:err\");var ax=a(r=>{let e=0;const t=[];while(r.length>e){const s=r.readUInt16BE(e+11);if(r.length<e+(12+s)){break}const n=qi.deSerialize(r.subarray(e));t.push(n);e+=13+s}return t},\"parsePacket\");var cx=a((r,e)=>t=>{const s=t.recordLayerHeader.contentType;switch(s){case Ee.changeCipherSpec:{ox(r.sessionId,\"change cipher spec\");return[{type:Ee.changeCipherSpec,data:void 0}]}case Ee.handshake:{let n=t.fragment;try{if(t.recordLayerHeader.epoch>0){ox(r.sessionId,\"decrypt handshake\");n=e.decryptPacket(t)}}catch(i){gm(r.sessionId,\"decrypt failed\",i);throw i}try{let i=0;const o=[];while(n.length>i){const c=ge.deSerialize(n.subarray(i));o.push({type:Ee.handshake,data:c});i+=c.fragment_length+12}return o}catch(i){gm(r.sessionId,\"decSerialize failed\",i,n);throw i}}case Ee.applicationData:{return[{type:Ee.applicationData,data:e.decryptPacket(t)}]}case Ee.alert:{let n=xc.deSerialize(t.fragment);if(mc[n.description]==void 0){const i=e.decryptPacket(t);n=xc.deSerialize(i)}gm(r.sessionId,\"ContentType.alert\",n,mc[n.description],\"flight\",r.flight,\"lastFlight\",r.lastFlight);if(n.level>1){throw new Error(\"alert fatal error\")}return[{type:Ee.alert,data:void 0}]}default:{return[{type:Ee.alert,data:void 0}]}}},\"parsePlainText\");var{decode:JO,types:bf}=q;var ym=P(\"webrtc/dtls/socket:log\");var lx=P(\"webrtc/dtls/socket:err\");var Tn=class{static{a(this,\"DtlsSocket\")}constructor(e,t){this.options=e;this.sessionType=t;this.onConnect=new O;this.onData=new O;this.onError=new O;this.onClose=new O;this.srtp=new qr;this.connected=false;this.extensions=[];this.bufferFragmentedHandshakes=[];this.udpOnMessage=s=>{const n=ax(s);for(const i of n){try{const o=cx(this.dtls,this.cipher)(i);for(const c of o){switch(c.type){case Ee.handshake:{const l=c.data;const u=this.handleFragmentHandshake([l]);const f=Object.values(u.reduce((d,h)=>{if(!d[h.msg_type])d[h.msg_type]=[];d[h.msg_type].push(h);return d},{})).map(d=>ge.assemble(d)).sort((d,h)=>d.msg_type-h.msg_type);this.onHandleHandshakes(f).catch(d=>{lx(this.dtls.sessionId,\"onHandleHandshakes error\",d);this.onError.execute(d)})}break;case Ee.applicationData:{this.onData.execute(c.data)}break;case Ee.alert:this.onClose.execute();break}}}catch(o){lx(this.dtls.sessionId,\"catch udpOnMessage error\",o)}}};this.waitForReady=async s=>{for(let n=0;n<10;n++){if(s())return;await(0,ux.setTimeout)(100*n)}throw new Error(\"waitForReady timeout\")};this.send=async(s,n)=>{const i=wr(this.dtls)([{type:Ee.applicationData,fragment:s}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(i).serialize(),n)};this.dtls=new Ec(this.options,this.sessionType);this.cipher=new Hr(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.transport=new gf(this.options.transport);this.setupExtensions();this.transport.socket.onData=this.udpOnMessage}renegotiation(){ym(\"renegotiation\",this.sessionType);this.connected=false;this.cipher=new Hr(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.dtls=new Ec(this.options,this.sessionType);this.srtp=new qr;this.extensions=[];this.bufferFragmentedHandshakes=[]}setupExtensions(){ym(this.dtls.sessionId,\"support srtpProfiles\",this.options.srtpProfiles);if(this.options.srtpProfiles&&this.options.srtpProfiles.length>0){const e=Bt.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{const e=wn.createEmpty();e.data=Vu;this.extensions.push(e.extension)}{const e=En.createEmpty();e.data=Yu;this.extensions.push(e.extension)}if(this.options.extendedMasterSecret){this.extensions.push({type:Tr.type,data:Buffer.alloc(0)})}{const e=xr.createEmpty();this.extensions.push(e.extension)}}handleFragmentHandshake(e){let t=e.filter(s=>{if(s.fragment_length!==s.length){this.bufferFragmentedHandshakes.push(s);return false}return true});if(this.bufferFragmentedHandshakes.length>1){const[s]=this.bufferFragmentedHandshakes.slice(-1);if(s.fragment_offset+s.fragment_length===s.length){t=[...this.bufferFragmentedHandshakes,...t];this.bufferFragmentedHandshakes=[]}}return t}close(){this.transport.close();Ne(()=>this.transport.socket.close(),e=>ym(\"close failed\",e))}extractSessionKeys(e,t){const s=this.exportKeyingMaterial(\"EXTRACTOR-dtls_srtp\",e*2+t*2);const{clientKey:n,serverKey:i,clientSalt:o,serverSalt:c}=JO(s,{clientKey:bf.buffer(e),serverKey:bf.buffer(e),clientSalt:bf.buffer(t),serverSalt:bf.buffer(t)});if(this.sessionType===dt.CLIENT){return{localKey:n,localSalt:o,remoteKey:i,remoteSalt:c}}else{return{localKey:i,localSalt:c,remoteKey:n,remoteSalt:o}}}exportKeyingMaterial(e,t){return CT(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===dt.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}};var bm=P(\"webrtc/dtls/client:log\");var eo=class extends Tn{static{a(this,\"DtlsClient\")}constructor(e){super(e,dt.CLIENT);this.handleHandshakes=async t=>{bm(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case $.hello_verify_request_3:{const n=Qi.deSerialize(s.fragment);await new lf(this.transport,this.dtls).exec(n)}break;case $.server_hello_2:{if(this.connected)return;this.flight5=new mf(this.transport,this.dtls,this.cipher,this.srtp);this.flight5.handleHandshake(s)}break;case $.certificate_11:case $.server_key_exchange_12:case $.certificate_request_13:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s)}break;case $.server_hello_done_14:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s);const n=[11,12,this.options.certificateRequest&&13].filter(i=>typeof i===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(n));await this.flight5?.exec()}break;case $.finished_20:{this.dtls.flight=7;this.connected=true;this.onConnect.execute();bm(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;bm(this.dtls.sessionId,\"start client\")}async connect(){await new cf(this.transport,this.dtls,this.cipher).exec(this.extensions)}};var fx=require(\"node:crypto\");var nr=P(\"webrtc/dtls/flight/server/flight2:log\");var dx=a((r,e,t,s)=>n=>{nr(\"dtls version\",n.clientVersion);e.flight=2;e.recordSequenceNumber=0;e.sequenceNumber=0;n.extensions.forEach(d=>{switch(d.type){case wn.type:{const h=wn.fromData(d.data).data;nr(e.sessionId,\"curves\",h);const p=h.filter(m=>Vu.includes(m))[0];t.namedCurve=p;nr(e.sessionId,\"curve selected\",t.namedCurve)}break;case En.type:{if(!t.signatureHashAlgorithm)throw new Error(\"need to set certificate\");const h=En.fromData(d.data).data;nr(e.sessionId,\"hash,signature\",h);const p=h.find(y=>y.signature===t.signatureHashAlgorithm?.signature)?.signature;const m=h.find(y=>y.hash===t.signatureHashAlgorithm?.hash)?.hash;if(p==void 0||m==void 0){throw new Error(\"invalid signatureHash\")}}break;case Bt.type:{if(!e.options?.srtpProfiles)return;if(e.options.srtpProfiles.length===0)return;const h=Bt.fromData(d.data);nr(e.sessionId,\"srtp profiles\",h.profiles);const p=qr.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!p){throw new Error}s.srtpProfile=p;nr(e.sessionId,\"srtp profile selected\",s.srtpProfile)}break;case Tr.type:{e.remoteExtendedMasterSecret=true}break;case xr.type:{nr(e.sessionId,\"RenegotiationIndication\",d.data)}break;case 43:{const h=d.data.subarray(1);const p=[...h].map(m=>m.toString(10));nr(\"dtls supported version\",p)}break}});t.localRandom=new ht;t.remoteRandom=ht.from(n.random);const i=n.cipherSuites;nr(e.sessionId,\"cipher suites\",i);const o=(()=>{switch(t.signatureHashAlgorithm?.signature){case Tt.ecdsa_3:return Wu.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case Tt.rsa_1:return Wu.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o)){throw new Error(\"dtls cipher suite negotiation failed\")}t.cipherSuite=o;nr(e.sessionId,\"selected cipherSuite\",t.cipherSuite);t.localKeyPair=hf(t.namedCurve);e.cookie||=(0,fx.randomBytes)(20);const c=new Qi({major:255-1,minor:255-2},e.cookie);const l=af(e)([c]);const u=wr(e)(l.map(d=>({type:Ee.handshake,fragment:d.serialize()})),++e.recordSequenceNumber);const f=u.map(d=>d.serialize());for(const d of f){r.send(d).catch(h=>nr(\"send failed\",h))}},\"flight2\");var Sm=P(\"webrtc/dtls/flight/server/flight4:log\");var Sf=class extends Dt{static{a(this,\"Flight4\")}constructor(e,t,s,n){super(e,t,4,6);this.cipher=s;this.srtp=n}async exec(e,t=false){if(this.dtls.flight===4){Sm(this.dtls.sessionId,\"flight4 twice\");this.send(this.dtls.lastMessage).catch(n=>Sm(\"send failed\",n));return}this.dtls.flight=4;this.dtls.sequenceNumber=1;this.dtls.bufferHandshakeCache([e],false,4);const s=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(n=>n);this.dtls.lastMessage=s;await this.transmit(s)}sendServerHello(){const e=[];if(this.srtp.srtpProfile){e.push(Bt.create([this.srtp.srtpProfile],Buffer.from([0])).extension)}if(this.dtls.options.extendedMasterSecret){e.push({type:Tr.type,data:Buffer.alloc(0)})}const t=xr.createEmpty();e.push(t.extension);const s=new Xi(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e);const n=this.createPacket([s]);return Buffer.concat(n.map(i=>i.serialize()))}sendCertificate(){const e=new zr([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerKeyExchange(){const e=this.cipher.generateKeySignature(\"sha256\");if(!this.cipher.signatureHashAlgorithm)throw new Error(\"not exist\");const t=new Ji(Xu.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e);const s=this.createPacket([t]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificateRequest(){const e=new Vi(pT,Yu,[]);Sm(this.dtls.sessionId,\"sendCertificateRequest\",e);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerHelloDone(){const e=new Yi;const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}};var xn=P(\"webrtc/dtls/flight/server/flight6\");var wf=class extends Dt{static{a(this,\"Flight6\")}constructor(e,t,s){super(e,t,6);this.cipher=s}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,5);const t=(()=>{switch(e.msg_type){case $.certificate_11:return zr.deSerialize(e.fragment);case $.certificate_verify_15:return Gi.deSerialize(e.fragment);case $.client_key_exchange_16:return Ki.deSerialize(e.fragment);case $.finished_20:return Sn.deSerialize(e.fragment)}})();if(t){const s=Rc[t.msgType];if(!s){return}s({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){xn(this.dtls.sessionId,\"flight6 twice\");this.send(this.dtls.lastMessage).catch(t=>xn(\"send failed\",t));return}this.dtls.flight=6;const e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e;await this.transmit(e)}sendChangeCipherSpec(){const e=zi.createEmpty().serialize();const t=wr(this.dtls)([{type:Ee.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(n=>n.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Sn(t);this.dtls.epoch=1;const[n]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const i=this.cipher.encryptPacket(n).serialize();return i}};var Rc={};Rc[$.client_key_exchange_16]=({cipher:r,dtls:e})=>t=>{r.remoteKeyPair={curve:r.namedCurve,publicKey:t.publicKey};if(!r.remoteKeyPair.publicKey||!r.localKeyPair||!r.remoteRandom||!r.localRandom)throw new Error(\"not exist\");const s=Qu(r.remoteKeyPair.publicKey,r.localKeyPair.privateKey,r.localKeyPair.curve);xn(e.sessionId,\"extendedMasterSecret\",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);const n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));r.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?tf(s,n):ef(s,r.remoteRandom.serialize(),r.localRandom.serialize());r.cipher=df(r.cipherSuite);r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize());xn(e.sessionId,\"setup cipher\",r.cipher.summary)};Rc[$.certificate_11]=({cipher:r,dtls:e})=>t=>{xn(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Rc[$.certificate_verify_15]=({cipher:r,dtls:e})=>t=>{if(!r.remoteCertificate){throw new Error(\"client certificate missing before certificate verify\")}xn(e.sessionId,\"certificate_verify\",t.algorithm)};Rc[$.finished_20]=({dtls:r})=>e=>{xn(r.sessionId,\"finished\",e)};var to=P(\"webrtc/dtls/server:log\");var _c=class extends Tn{static{a(this,\"DtlsServer\")}constructor(e){super(e,dt.SERVER);this.handleHandshakes=async t=>{to(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case $.client_hello_1:{if(this.connected){this.renegotiation()}const n=Hi.deSerialize(s.fragment);if(n.cookie.length===0){to(this.dtls.sessionId,\"send flight2\");dx(this.transport,this.dtls,this.cipher,this.srtp)(n)}else if(this.dtls.cookie&&n.cookie.equals(this.dtls.cookie)){to(this.dtls.sessionId,\"send flight4\");await new Sf(this.transport,this.dtls,this.cipher,this.srtp).exec(s,this.options.certificateRequest)}else{to(\"wrong state\",{dtlsCookie:this.dtls.cookie?.toString(\"hex\").slice(10),helloCookie:n.cookie.toString(\"hex\").slice(10)})}}break;case $.certificate_11:case $.certificate_verify_15:case $.client_key_exchange_16:{if(this.connected)return;this.flight6=new wf(this.transport,this.dtls,this.cipher);this.flight6.handleHandshake(s)}break;case $.finished_20:{await this.waitForReady(()=>!!this.flight6);this.flight6?.handleHandshake(s);const n=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(i=>typeof i===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(n));await this.flight6?.exec();this.connected=true;this.onConnect.execute();to(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;to(this.dtls.sessionId,\"start server\")}};var wm=2;var Em=3;var hx=0;var ro=50;var Tm=51;var xm=53;var Tf=56;var xf=57;var Rm=\"0.0.0.0\";var _m=9;var Ef={auto:\"actpass\",client:\"active\",server:\"passive\"};var Cm=Object.keys(Ef).reduce((r,e)=>{const t=Ef[e];r[t]=e;return r},{});var px=[\"apt\",\"max-fr\",\"max-fs\",\"maxplaybackrate\",\"minptime\",\"packetization-mode\",\"level-asymmetry-allowed\",\"stereo\",\"useinbandfec\"];var vm=[\"cname\",\"msid\",\"mslabel\",\"label\"];var Am={SRTP_AES128_CM_HMAC_SHA1_80:Si,SRTP_AEAD_AES_128_GCM:Cs};var Rn=[\"sendonly\",\"sendrecv\"];var mx=[\"sendrecv\",\"recvonly\"];var so=554869826;var gx=8;var yx=1398035790;var Gr=20;var Im=24;var Om=1;var km=2;var bx=6;var Sx=50;var ie;(function(r){r[r[\"REQUEST\"]=0]=\"REQUEST\";r[r[\"INDICATION\"]=16]=\"INDICATION\";r[r[\"RESPONSE\"]=256]=\"RESPONSE\";r[r[\"ERROR\"]=272]=\"ERROR\"})(ie||(ie={}));var Ge;(function(r){r[r[\"BINDING\"]=1]=\"BINDING\";r[r[\"SHARED_SECRET\"]=2]=\"SHARED_SECRET\";r[r[\"ALLOCATE\"]=3]=\"ALLOCATE\";r[r[\"REFRESH\"]=4]=\"REFRESH\";r[r[\"SEND\"]=6]=\"SEND\";r[r[\"DATA\"]=7]=\"DATA\";r[r[\"CREATE_PERMISSION\"]=8]=\"CREATE_PERMISSION\";r[r[\"CHANNEL_BIND\"]=9]=\"CHANNEL_BIND\"})(Ge||(Ge={}));function wx(r){if(r.length<Gr){return false}if((r[0]&192)!==0){return false}if(r.readUInt32BE(4)!==so){return false}const e=r.readUInt16BE(2);if(e%4!==0){return false}return r.length===Gr+e}a(wx,\"isStunMessage\");var Ex=3e3;function Tx(r){const e=Buffer.alloc(2);e.writeUInt16BE(r.length,0);return Buffer.concat([e,r])}a(Tx,\"encodeTcpFrame\");function xx(r){const e=[];let t=0;while(r.length-t>=2){const s=r.readUInt16BE(t);if(r.length-t<s+2){break}e.push(r.subarray(t+2,t+2+s));t+=2+s}return{frames:e,rest:r.subarray(t)}}a(xx,\"splitTcpFrames\");var Pf=require(\"node:net\");var Ic=require(\"node:crypto\");var no=require(\"node:net\");function Pm(r){if((0,no.isIPv4)(r)){const n=Buffer.allocUnsafe(4);const i=r.split(\".\");for(let o=0;o<4;o++){n[o]=Number(i[o])&255}return n}if(!(0,no.isIPv6)(r)){throw new Error(`Invalid ip address: ${r}`)}const e=r.split(\":\",8);for(let n=0;n<e.length;n++){let i;if((0,no.isIPv4)(e[n])){i=Pm(e[n]);e[n]=i.subarray(0,2).toString(\"hex\")}if(i&&++n<8){e.splice(n,0,i.subarray(2,4).toString(\"hex\"))}}if(e[0]===\"\"){while(e.length<8)e.unshift(\"0\")}else if(e[e.length-1]===\"\"){while(e.length<8)e.push(\"0\")}else if(e.length<8){let n=0;for(;n<e.length&&e[n]!==\"\";n++);const i=[];for(let o=9-e.length;o>0;o--){i.push(\"0\")}e.splice(n,1,...i)}const t=Buffer.allocUnsafe(16);let s=0;for(const n of e){const i=Number.parseInt(n,16)||0;t[s++]=i>>8&255;t[s++]=i&255}return t}a(Pm,\"ipAddressToBuffer\");function Nm(r){if(r.length===4){return`${r[0]}.${r[1]}.${r[2]}.${r[3]}`}if(r.length!==16){throw new Error(`Invalid ip address buffer length: ${r.length}`)}const e=[];for(let s=0;s<16;s+=2){e.push(r.readUInt16BE(s).toString(16))}let t=e.join(\":\");t=t.replace(/(^|:)0(:0)*:0(:|$)/,\"$1::$3\");t=t.replace(/:{3,4}/,\"::\");return t}a(Nm,\"bufferToIpAddress\");function Rx(r){return(0,no.isIPv4)(r)}a(Rx,\"isIpV4Address\");function _n(r){const[e]=r;const t=Rx(e)?Om:km;const s=Buffer.alloc(4);s.writeUInt8(0,0);s.writeUInt8(t,1);s.writeUInt16BE(r[1],2);return Buffer.concat([s,Pm(e)])}a(_n,\"packAddress\");function ZO(r){if(r.length<4){throw new Error(\"STUN error code is less than 4 bytes\")}const e=r.readUInt8(2);const t=r.readUInt8(3);const s=r.slice(4).toString(\"utf8\");return[e*100+t,s]}a(ZO,\"unpackErrorCode\");function Cn(r){if(r.length<4){throw new Error(\"STUN address length is less than 4 bytes\")}const e=r.readUInt8(1);const t=r.readUInt16BE(2);const s=r.slice(4);switch(e){case Om:if(s.length!==4){throw new Error(\"STUN address has invalid length for IPv4\")}return[Nm(s),t];case km:if(s.length!==16){throw new Error(\"STUN address has invalid length for IPv6\")}return[Nm(s),t];default:throw new Error(\"STUN address has unknown protocol\")}}a(Cn,\"unpackAddress\");var Lm=Buffer.alloc(6);Lm.writeUInt16BE(so>>16,0);Lm.writeUInt32BE(so,2);function vx(r,e){const t=[...Lm,...e];let s=r.slice(0,2);for(let n=2;n<r.length;n++){const i=r[n]^t[n-2];const o=Buffer.alloc(1);o.writeUIntBE(i,0,1);s=Buffer.concat([s,o])}return s}a(vx,\"xorAddress\");function Cc(r,e){return Cn(vx(r,e))}a(Cc,\"unpackXorAddress\");function QO(r){const e=Buffer.alloc(4);e.writeUInt16BE(0,0);e.writeUInt8(Math.floor(r[0]/100),2);e.writeUInt8(r[0]%100,3);const t=Buffer.from(r[1],\"utf8\");return Buffer.concat([e,t])}a(QO,\"packErrorCode\");function ek(r){const e=Buffer.alloc(r.length*2);r.forEach((t,s)=>{e.writeUInt16BE(t,s*2)});return e}a(ek,\"packUnknownAttributes\");function tk(r){if(r.length%2!==0){throw new Error(\"UNKNOWN-ATTRIBUTES must have an even length\")}const e=[];for(let t=0;t<r.length;t+=2){e.push(r.readUInt16BE(t))}return e}a(tk,\"unpackUnknownAttributes\");function vc(r,e){return vx(_n(r),e)}a(vc,\"packXorAddress\");var io=a(r=>{const e=Buffer.alloc(4);e.writeUInt32BE(r,0);return e},\"packUnsigned\");var oo=a(r=>r.readUInt32BE(0),\"unpackUnsigned\");var rk=a(r=>{const e=Buffer.alloc(4);e.writeUInt16BE(r,0);return e},\"packUnsignedShort\");var sk=a(r=>r.readUInt16BE(0),\"unpackUnsignedShort\");var _x=a(r=>{const e=Buffer.allocUnsafe(8);e.writeBigUInt64BE(r,0);return e},\"packUnsigned64\");var Cx=a(r=>r.readBigUInt64BE(0),\"unpackUnsigned64\");var _f=a(r=>Buffer.from(r,\"utf8\"),\"packString\");var Rf=a(r=>r.toString(\"utf8\"),\"unpackString\");var nk=a(r=>{if([...r].length>=128){throw new Error(\"SOFTWARE must be shorter than 128 characters\")}return _f(r)},\"packSoftware\");var Kr=a(r=>r,\"packBytes\");var Wr=a(r=>r,\"unpackBytes\");var ik=a(()=>Buffer.alloc(0),\"packNone\");var ok=a(()=>null,\"unpackNone\");var Ax=[[1,\"MAPPED-ADDRESS\",_n,Cn],[3,\"CHANGE-REQUEST\",io,oo],[4,\"SOURCE-ADDRESS\",_n,Cn],[5,\"CHANGED-ADDRESS\",_n,Cn],[6,\"USERNAME\",_f,Rf],[8,\"MESSAGE-INTEGRITY\",Kr,Wr],[9,\"ERROR-CODE\",QO,ZO],[10,\"UNKNOWN-ATTRIBUTES\",ek,tk],[12,\"CHANNEL-NUMBER\",rk,sk],[13,\"LIFETIME\",io,oo],[18,\"XOR-PEER-ADDRESS\",vc,Cc],[19,\"DATA\",Kr,Wr],[20,\"REALM\",_f,Rf],[21,\"NONCE\",Kr,Wr],[22,\"XOR-RELAYED-ADDRESS\",vc,Cc],[23,\"REQUESTED-ADDRESS-FAMILY\",io,oo],[24,\"EVEN-PORT\",Kr,Wr],[25,\"REQUESTED-TRANSPORT\",io,oo],[28,\"MESSAGE-INTEGRITY-SHA256\",Kr,Wr],[29,\"PASSWORD-ALGORITHM\",Kr,Wr],[30,\"USERHASH\",Kr,Wr],[32,\"XOR-MAPPED-ADDRESS\",vc,Cc],[34,\"RESERVATION-TOKEN\",Kr,Wr],[36,\"PRIORITY\",io,oo],[37,\"USE-CANDIDATE\",ik,ok],[32770,\"PASSWORD-ALGORITHMS\",Kr,Wr],[32771,\"ALTERNATE-DOMAIN\",_f,Rf],[32802,\"SOFTWARE\",nk,Rf],[32803,\"ALTERNATE-SERVER\",_n,Cn],[32808,\"FINGERPRINT\",io,oo],[32809,\"ICE-CONTROLLED\",_x,Cx],[32810,\"ICE-CONTROLLING\",_x,Cx],[32811,\"RESPONSE-ORIGIN\",_n,Cn],[32812,\"OTHER-ADDRESS\",_n,Cn]];var Ac=class{static{a(this,\"AttributeRepository\")}constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){const s=this.attributes.find(n=>n[0]===e);if(s){s[1]=t}else{this.attributes.push([e,t])}return this}getAttributeValue(e){const t=this.attributes.find(s=>s[0]===e);return t?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}removeAttribute(e){this.attributes=this.attributes.filter(t=>t[0]!==e);return this}clear(){this.attributes=[]}};var Ix=Ax.reduce((r,e)=>{r[e[0]]=e;return r},{});var Ox=Ax.reduce((r,e)=>{r[e[1]]=e;return r},{});function ir(r,e){if(!wx(r)){return void 0}const t=r.readUInt16BE(0);const s=Buffer.from(r.slice(Gr-12,Gr));const n=new Ac;const i=[];let o=false;for(let c=Gr;c<r.length;){if(c+4>r.length){return void 0}const l=r.readUInt16BE(c);const u=r.readUInt16BE(c+2);const f=c+4;const d=f+u;if(d>r.length){return void 0}const h=r.slice(f,d);const p=ao(u);if(d+p>r.length){return void 0}const m=Ix[l];if(m){const[,y,,w]=m;let S;try{S=w.name===Cc.name?w(h,s):w(h)}catch{return void 0}n.setAttribute(y,S);if(y===\"FINGERPRINT\"){const T=kx(r.slice(0,c));if(n.getAttributeValue(\"FINGERPRINT\")!==T){return void 0}}else if(y===\"MESSAGE-INTEGRITY\"&&e){const T=ck(r.slice(0,c),e);const _=n.getAttributeValue(\"MESSAGE-INTEGRITY\");if(!T.equals(_)){return void 0}o=true}}else{i.push({type:l,length:u,value:Buffer.from(h)})}c=d+p}if(e&&!o){return void 0}return new Ke(t&16111,t&272,s,n.getAttributes(),i)}a(ir,\"parseMessage\");var Ke=class extends Ac{static{a(this,\"Message\")}constructor(e,t,s=(0,Ic.randomBytes)(12),n=[],i=[]){super(n);this.messageMethod=e;this.messageClass=t;this.transactionId=s;this.rawAttributes=i}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(\"hex\")}appendRawAttribute(e,t){this.rawAttributes.push({type:e,value:Buffer.from(t)});return this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){const e=Buffer.concat(this.serializedAttributes.map(s=>ak(s.type,s.value)));const t=Buffer.alloc(8);t.writeUInt16BE(this.messageMethod|this.messageClass,0);t.writeUInt16BE(e.length,2);t.writeUInt32BE(so,4);return Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){this.removeAttribute(\"FINGERPRINT\").removeAttribute(\"MESSAGE-INTEGRITY\");this.setAttribute(\"MESSAGE-INTEGRITY\",this.messageIntegrity(e));return this}messageIntegrity(e){const t=Mm(this.bytes,this.bytes.length-Gr+Im);return Buffer.from((0,Ic.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}addFingerprint(){this.removeAttribute(\"FINGERPRINT\");this.setAttribute(\"FINGERPRINT\",kx(this.bytes));return this}get serializedAttributes(){const e=[];for(const t of this.attributesKeys){const s=this.getAttributeValue(t);const[n,,i]=Ox[t];const o=i.name===vc.name?i(s,this.transactionId):i(s);e.push({type:n,value:o})}e.push(...this.rawAttributes.map(t=>({type:t.type,value:Buffer.from(t.value)})));return e}};function ak(r,e){const t=e.length;const s=ao(t);const n=Buffer.alloc(4);n.writeUInt16BE(r,0);n.writeUInt16BE(t,2);return Buffer.concat([n,e,Buffer.alloc(s)])}a(ak,\"serializeAttribute\");var Mm=a((r,e)=>{const t=Buffer.alloc(r.length);r.copy(t,0,0,2);t.writeUInt16BE(e,2);r.copy(t,4,4);return t},\"setBodyLength\");function kx(r){const e=Mm(r,r.length-Gr+gx);return(Ww(e)^yx)>>>0}a(kx,\"messageFingerprint\");function ck(r,e){const t=Mm(r,r.length-Gr+Im);return Buffer.from((0,Ic.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}a(ck,\"messageIntegrity\");function ao(r){const e=r%4;return e===0?0:4-e}a(ao,\"paddingLength\");var Nx=require(\"node:dns\");var Dm=require(\"node:net\");var Cf=class extends Error{static{a(this,\"TransactionError\")}};var co=class extends Cf{static{a(this,\"TransactionFailed\")}constructor(e,t){super();this.response=e;this.addr=t}get str(){let e=\"STUN transaction failed\";const t=this.response.getAttributeValue(\"ERROR-CODE\");if(t){const[s,n]=t;e+=` (${s} - ${n})`}return e}};var Oc=class extends Cf{static{a(this,\"TransactionTimeout\")}get str(){return\"STUN transaction timed out\"}};var vf=class extends Error{static{a(this,\"AddressFamilyMismatch\")}constructor(e,t){super(`cannot reach ${e[0]}:${e[1]} from an IPv${t} socket`);this.addr=e;this.socketFamily=t}};var kc=P(\"webrtc/ice/stun/transaction\");async function Xr(r,e=0){const t=(0,Dm.isIP)(r[0]);if(t){if(e!==0&&t!==e){throw new vf(r,e)}return r}const s=await Nx.promises.lookup(r[0],{family:e});return[s.address,r[1]]}a(Xr,\"resolveRequestAddress\");function Lx(r,e){if(r!==null&&typeof r===\"object\"){return r}const t=typeof r===\"number\"?r:void 0;return{retransmissions:t,onRequestSent:e}}a(Lx,\"normalizeTransactionOptions\");function Bm(r,e){return r[1]===e[1]&&Px(r[0])===Px(e[0])}a(Bm,\"addressEquals\");function Px(r){if((0,Dm.isIP)(r)!==6)return r;return new URL(`http://[${r.split(\"%\")[0]}]/`).hostname.slice(1,-1)}a(Px,\"canonicalHost\");var Vr=class{static{a(this,\"Transaction\")}constructor(e,t,s,n,i){this.request=e;this.addr=t;this.protocol=s;this.ended=false;this.tries=0;this.onResponse=new O;this.responseReceived=(c,l)=>{if(this.ended||this.onResponse.length===0){return}if(!Bm(this.expectedAddr,l)){kc(\"ignore STUN response from unexpected address\",l,\"expected\",this.expectedAddr);return}if(this.integrityKey){const u=c.attributesKeys.includes(\"MESSAGE-INTEGRITY\")||c.attributesKeys.includes(\"MESSAGE-INTEGRITY-SHA256\");if(!u&&!Um(c)){kc(\"ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)\");return}}if(c.messageClass===ie.RESPONSE){this.onResponse.execute(c,l);this.onResponse.complete()}else{this.onResponse.error(new co(c,l))}};this.run=async()=>{try{if(this.signal?.aborted){throw new Oc}this.attachAbortListener();this.retry().catch(l=>{kc(\"retry failed\",l)});const c=await this.onResponse.asPromise();return c}finally{this.cancel()}};this.retry=async()=>{while(this.tries<this.triesMax&&!this.ended){this.onRequestSent?.(this.tries);this.protocol.sendStun(this.request,this.addr).catch(c=>{kc(\"send stun failed\",c);if(this.failOnSendError){this.fail(c)}});await this.wait(this.timeoutDelay);if(this.ended){break}this.timeoutDelay*=2;this.tries++}if(this.tries>=this.triesMax&&!this.ended){kc(`retry failed times:${this.tries} maxLimit:${this.triesMax}`);this.failWithTimeout()}};const o=Lx(n,i);this.triesMax=1+(o.retransmissions??bx);this.timeoutDelay=o.responseTimeout??Sx;this.onRequestSent=o.onRequestSent;this.signal=o.signal;this.failOnSendError=o.failOnSendError??false;this.expectedAddr=t;this.integrityKey=o.integrityKey}attachAbortListener(){if(!this.signal){return}this.onAbort=()=>{this.failWithTimeout()};this.signal.addEventListener(\"abort\",this.onAbort,{once:true})}failWithTimeout(){this.fail(new Oc)}fail(e){if(this.ended){return}this.ended=true;this.clearWait();if(this.onResponse.length>0){this.onResponse.error(e)}}clearWait(){if(this.waitTimer!==void 0){clearTimeout(this.waitTimer);this.waitTimer=void 0}const e=this.waitResolve;this.waitResolve=void 0;e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t;this.waitTimer=setTimeout(()=>{this.waitTimer=void 0;this.waitResolve=void 0;t()},e)})}cancel(){this.ended=true;this.clearWait();if(this.signal&&this.onAbort){this.signal.removeEventListener(\"abort\",this.onAbort);this.onAbort=void 0}}};function Um(r){if(r.messageClass!==ie.ERROR||!r.getAttributeValue(\"NONCE\")){return false}const[e]=r.getAttributeValue(\"ERROR-CODE\")??[];return e===401||e===438}a(Um,\"isChallenge\");function vn(r,e,t){const s=Lx(e,t);if(r&&!s.integrityKey){s.integrityKey=r}return s}a(vn,\"buildTransactionOptions\");var Af=P(\"webrtc/ice/stun/tcpProtocol\");function Pc(r){return`${r[0]}:${r[1]}`}a(Pc,\"socketKey\");function lk(r){return r.destroyed||r.writableEnded}a(lk,\"isSocketClosed\");function Dx(r){if(!r.remoteAddress||!r.remotePort){return}return[r.remoteAddress,r.remotePort]}a(Dx,\"addressFromSocket\");async function Mx(r,e,t){return await new Promise((s,n)=>{const i=a(c=>{r.off(\"listening\",o);n(c)},\"onError\");const o=a(()=>{r.off(\"error\",i);s()},\"onListening\");r.once(\"error\",i);r.once(\"listening\",o);r.listen({host:e,port:t??0,exclusive:true})})}a(Mx,\"waitForListening\");var If=class r{static{a(this,\"BaseTcpProtocol\")}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new O;this.onDataReceived=new O;this.onConnectionClosed=new O;this.sockets=new Map}static{this.type=\"tcp\"}rememberSocket(e){const t=e.remoteAddr;if(!t){return}this.sockets.set(Pc(t),e)}forgetSocket(e){const t=e.remoteAddr;if(!t){return false}const s=Pc(t);if(this.sockets.get(s)!==e){return false}this.sockets.delete(s);return true}getOpenSocket(e){const t=this.sockets.get(Pc(e));if(!t){return}if(lk(t.socket)){this.dropSocket(t);return}return t}dropSocket(e){e.socket.destroy();if(this.forgetSocket(e)&&e.remoteAddr){this.onConnectionClosed.execute(e.remoteAddr)}}registerSocket(e,t){const s={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};if(t){this.rememberSocket(s)}e.on(\"data\",n=>{s.buffer=Buffer.concat([s.buffer,n]);const{frames:i,rest:o}=xx(s.buffer);s.buffer=o;const c=s.remoteAddr??Dx(e);if(!s.remoteAddr&&c){s.remoteAddr=c;this.rememberSocket(s)}if(!c){return}for(const l of i){if(l.length===0){continue}this.handleFrame(l,c)}});e.on(\"close\",()=>{if(this.forgetSocket(s)&&s.remoteAddr){this.onConnectionClosed.execute(s.remoteAddr)}});e.on(\"error\",n=>{Af(\"tcp socket error\",n)});return s}handleFrame(e,t){try{const s=ir(e);if(!s){this.onDataReceived.execute(e);return}if((s.messageClass===ie.RESPONSE||s.messageClass===ie.ERROR)&&this.transactions[s.transactionIdHex]){const n=this.transactions[s.transactionIdHex];const i=n.integrityKey?ir(e,n.integrityKey):s;if(!i){Af(\"STUN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(i,t)}else if(s.messageClass===ie.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){Af(\"tcp frame parse error\",s)}}async sendFrame(e,t){const s=await this.getSocket(t);try{await new Promise((n,i)=>{s.socket.write(Tx(e),o=>{if(o){i(o);return}n()})})}catch(n){Af(\"tcp write failed\",t,n);this.dropSocket(s);throw n}}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,s,n,i){if(this.transactions[e.transactionIdHex]){throw new Error(\"already requested\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await Xr(t);const c={failOnSendError:true,...vn(s,n,i)};const l=new Vr(e,o,this,c);this.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(const[t,s]of this.sockets.entries()){if(e&&t===Pc(e)){continue}s.socket.destroy();this.sockets.delete(t)}}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.pruneForSelection();this.onRequestReceived.complete();this.onDataReceived.complete();this.onConnectionClosed.complete()}};var Of=class extends If{static{a(this,\"TcpActiveProtocol\")}constructor(){super(...arguments);this.pendingSockets=new Map}async connectionMade(e){this.localIp=e}async getSocket(e){const t=Pc(e);const s=this.getOpenSocket(e);if(s){return s}const n=this.pendingSockets.get(t);if(n){return await n}const i=new Promise((o,c)=>{const l=(0,Pf.connect)({host:e[0],port:e[1],localAddress:this.localIp});const u=this.registerSocket(l,e);const f=a(h=>{l.off(\"connect\",d);c(h)},\"onError\");const d=a(()=>{l.off(\"error\",f);o(u)},\"onConnect\");l.once(\"error\",f);l.once(\"connect\",d)});this.pendingSockets.set(t,i);try{return await i}finally{this.pendingSockets.delete(t)}}};var kf=class extends If{static{a(this,\"TcpPassiveProtocol\")}constructor(){super(...arguments);this.server=(0,Pf.createServer)(e=>{this.registerSocket(e,Dx(e))})}async connectionMade(e,t){this.localIp=e;if(t){let s;for(let n=t[0];n<=t[1];n++){try{await Mx(this.server,e,n);return}catch(i){s=i}}throw s??new Error(\"tcp port not found\")}await Mx(this.server,e)}async getSocket(e){const t=this.getOpenSocket(e);if(!t){throw new Error(\"tcp passive connection not established\")}return t}get listeningPort(){const e=this.server.address();if(!e||typeof e===\"string\"){throw new Error(\"tcp passive protocol is not listening\")}return e.port}async close(){await super.close();await new Promise(e=>{this.server.close(()=>e())})}};var jm=P(\"webrtc/ice/stun/protocol\");var An=class r{static{a(this,\"StunProtocol\")}static{this.type=\"stun\"}get transactionsKeys(){return Object.keys(this.transactions)}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new O;this.onDataReceived=new O;this.connectionMade=async(e,t,s)=>{if(e){this.transport=await en.init(\"udp4\",{portRange:t,interfaceAddresses:s})}else{this.transport=await en.init(\"udp6\",{portRange:t,interfaceAddresses:s})}this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}}}datagramReceived(e,t){try{const s=ir(e);if(!s){if(this.localCandidate){this.onDataReceived.execute(e)}return}if((s.messageClass===ie.RESPONSE||s.messageClass===ie.ERROR)&&this.transactionsKeys.includes(s.transactionIdHex)){const n=this.transactions[s.transactionIdHex];const i=n.integrityKey?ir(e,n.integrityKey):s;if(!i){jm(\"STUN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(i,t)}else if(s.messageClass===ie.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){jm(\"datagramReceived error\",s)}}getExtraInfo(){const{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed){return}const s=e.bytes;await this.transport.send(s,t).catch(()=>{jm(\"sendStun failed\",t,e)})}async sendData(e,t){if(this.transport.closed){return}await this.transport.send(e,t)}connectTo(e){this.transport?.connectTo(e)}disconnect(){this.transport?.disconnect()}async request(e,t,s,n,i){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error(\"already request ed\");if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await Xr(t,this.transport.addressFamily);const c=vn(s,n,i);const l=new Vr(e,o,this,c);this.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.transport.close();this.onRequestReceived.complete();this.onDataReceived.complete()}};var Gx=require(\"node:net\");var Kx=require(\"node:timers/promises\");var Bx=require(\"node:crypto\");function Ux(r,e,t){return(0,Bx.createHash)(\"md5\").update(Buffer.from([r,e,t].join(\":\"))).digest()}a(Ux,\"makeTurnIntegrityKey\");var $m=require(\"node:crypto\");function lo(r){return(0,$m.randomBytes)(r).toString(\"hex\").substring(0,r)}a(lo,\"randomString\");function jx(){return(0,$m.randomBytes)(12)}a(jx,\"randomTransactionId\");var Nc=class{static{a(this,\"PQueue\")}constructor(){this.queue=[];this.wait=new O}put(e){this.queue.push(e);if(this.queue.length===1){this.wait.execute(e)}}get(){const e=this.queue.shift();if(!e){return new Promise(t=>{this.wait.subscribe(s=>{void this.queue.shift();t(s)})})}return e}};var Lc=a(r=>{let e;let t;const s=new Promise((i,o)=>{e=i;t=o});s.then(()=>{n.execute(void 0);n.complete()}).catch(i=>{n.execute(i??new Error);n.complete()});const n=new O;r(e,t,n).catch(()=>{});return{awaitable:s,resolve:e,reject:t}},\"cancelable\");function Nf(r){return r.length>=4&&(r[0]&192)===64}a(Nf,\"isChannelData\");function $x(r,e){const t=Buffer.alloc(4);t.writeUInt16BE(r,0);t.writeUInt16BE(e.length,2);return Buffer.concat([t,e])}a($x,\"encodeChannelData\");function Fx(r){if(!Nf(r)||r.length<4){return void 0}const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);if(r.length<4+t){return void 0}return{channelNumber:e,data:r.subarray(4,4+t)}}a(Fx,\"decodeChannelData\");function Hx(r){const e=ao(r.length);return e>0?Buffer.concat([r,Buffer.alloc(e)]):r}a(Hx,\"padTurnFrame\");function qx(r){const e=[];let t=0;let s=false;while(r.length-t>=4){let n;if(Nf(r.subarray(t))){const i=r.readUInt16BE(t+2);n=4+i+ao(i)}else if((r[t]&192)===0){if(r.length-t<20){break}const i=r.readUInt16BE(t+2);n=20+i+ao(i)}else{s=true;break}if(r.length-t<n){break}e.push(r.subarray(t,t+n));t+=n}return{frames:e,malformed:s,rest:r.subarray(t)}}a(qx,\"splitTurnTcpFrames\");var Fe=P(\"webrtc/ice/turn/protocol\");var uk=500;var fk=1e3;var dk=600;var hk=285212672;function Lf(r){return r.type===\"tcp\"||r.type===\"tls\"}a(Lf,\"isStreamTransport\");function pk(r){return r[0]}a(pk,\"permissionKey\");function zx(r){return JSON.stringify(r)}a(zx,\"channelKey\");var Fm=class r{static{a(this,\"StunOverTurnProtocol\")}static{this.type=\"turn\"}constructor(e){this.turn=e;this.type=r.type;this.disposer=new hu;this.onRequestReceived=new O;this.onDataReceived=new O;this.handleStunMessage=(t,s)=>{try{const n=ir(t);if(!n){this.onDataReceived.execute(t);return}if(n.messageClass===ie.RESPONSE||n.messageClass===ie.ERROR){const i=this.turn.transactions[n.transactionIdHex];if(i){const o=i.integrityKey?ir(t,i.integrityKey):n;if(!o){Fe(\"STUN over TURN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(o,s)}}else if(n.messageClass===ie.REQUEST){this.onRequestReceived.execute(n,s,t)}}catch(n){Fe(\"datagramReceived error\",n)}};e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}async request(e,t,s,n,i){if(this.turn.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await Xr(t);const c=vn(s,n,i);const l=new Vr(e,o,this,c);this.turn.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){this.disposer.dispose();return this.turn.close()}};var Hm=class r{static{a(this,\"TurnProtocol\")}static{this.type=\"turn\"}constructor(e,t,s,n,i,o={}){this.server=e;this.username=t;this.password=s;this.lifetime=n;this.transport=i;this.options=o;this.type=r.type;this.onData=new O;this.onRequestReceived=new O;this.onDataReceived=new O;this.transactions={};this.expiresAt=0;this.channelNumber=16384;this.channelByAddr={};this.addrByChannel={};this.channelBindQueue=Promise.resolve();this.channelBindingByAddr=new Map;this.tcpBuffer=Buffer.alloc(0);this.permissionByAddr={};this.permissionQueue=Promise.resolve();this.creatingPermissionByAddr=new Map;this.refresh=c=>{this.refreshHandle=Lc(async(l,u,f)=>{const d=new AbortController;f.once(()=>{d.abort()});while(!d.signal.aborted){const h=5/6*c*1e3;Fe(\"refresh delay\",h,{exp:c});try{await(0,Kx.setTimeout)(h,void 0,{signal:d.signal})}catch(m){if(d.signal.aborted){return}throw m}if(d.signal.aborted){return}const p=new Ke(Ge.REFRESH,ie.REQUEST);p.setAttribute(\"LIFETIME\",c);try{const[m]=await this.requestWithRetry(p,this.server,d.signal);c=m.getAttributeValue(\"LIFETIME\");Fe(\"refresh\",{exp:c});this.expiresAt=Date.now()+c*1e3}catch(m){if(d.signal.aborted){return}Fe(\"refresh error\",m)}}})};this.channelRefreshTime=this.options.channelRefreshTime??uk}async connectionMade(){this.transport.onData=(n,i)=>{this.dataReceived(n,i)};const e=new Ke(Ge.ALLOCATE,ie.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime).setAttribute(\"REQUESTED-TRANSPORT\",hk);const[t]=await this.requestWithRetry(e,this.server).catch(n=>{Fe(\"connect error\",n);throw n});this.relayedAddress=t.getAttributeValue(\"XOR-RELAYED-ADDRESS\");this.mappedAddress=t.getAttributeValue(\"XOR-MAPPED-ADDRESS\");const s=t.getAttributeValue(\"LIFETIME\");Fe(\"connect\",this.relayedAddress,this.mappedAddress,{exp:s});this.expiresAt=Date.now()+s*1e3;this.refresh(s)}handleChannelData(e){const t=Fx(e);const s=t&&this.addrByChannel[t.channelNumber];if(s&&t){this.onData.execute(t.data,s)}}handleSTUNMessage(e,t){try{const s=ir(e);if(!s){throw new Error(\"not stun message\")}if(s.messageClass===ie.RESPONSE||s.messageClass===ie.ERROR){const n=this.transactions[s.transactionIdHex];if(n){const i=n.integrityKey&&!Um(s)?ir(e,n.integrityKey):s;if(!i){Fe(\"TURN STUN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(i,t)}}else if(s.messageClass===ie.REQUEST){this.onData.execute(e,t)}if(s.getAttributeValue(\"DATA\")){const n=s.getAttributeValue(\"DATA\");const i=s.getAttributeValue(\"XOR-PEER-ADDRESS\")??t;this.onData.execute(n,i)}}catch(s){Fe(\"parse error\",e.toString())}}dataReceived(e,t){const s=a((n,i)=>{if(n.length>=4&&Nf(n)){this.handleChannelData(n)}else{this.handleSTUNMessage(n,i)}},\"datagramReceived\");if(Lf(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);const{frames:n,rest:i}=qx(this.tcpBuffer);this.tcpBuffer=i;for(const o of n){s(o,t)}}else{s(e,t)}}async send(e,t){if(this.transport.closed){return}await this.transport.send(Lf(this.transport)?Hx(e):e,t)}async createPermission(e){const t=new Ke(Ge.CREATE_PERMISSION,ie.REQUEST);t.setAttribute(\"XOR-PEER-ADDRESS\",e).setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce);await this.requestWithRetry(t,this.server)}async request(e,t,s,n,i){if(this.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(this.integrityKey){e.setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint()}const o=await this.resolveRequestTarget(t);const c=vn(this.integrityKey,n,i);const l=new Vr(e,o,this,c);this.transactions[e.transactionIdHex]=l;try{return await l.run()}finally{delete this.transactions[e.transactionIdHex]}}get serverEndpoint(){return this.pinnedServerEndpoint}async resolveRequestTarget(e){if(Lf(this.transport)||Bm(e,this.server)){return this.selectServerEndpoint()}return Xr(e,this.transport.addressFamily??0)}async serverDestination(){return this.pinnedServerEndpoint??this.selectServerEndpoint()}selectServerEndpoint(){this.serverEndpointSelection??=this.resolveServerEndpoint().then(e=>{this.pinnedServerEndpoint=e;return e},e=>{this.serverEndpointSelection=void 0;throw e});return this.serverEndpointSelection}async resolveServerEndpoint(){const e=this.transport;if(!Lf(e)){return Xr(this.server,e.addressFamily??0)}if(e.remoteAddress){return e.remoteAddress}if(e instanceof Ba||e instanceof Ua){throw new Error(`${e.type} transport has no remote address`)}return Xr(this.server)}async requestWithRetry(e,t,s){let n,i;try{[n,i]=await this.request(e,t,void 0,{signal:s})}catch(o){if(o instanceof co==false){Fe(\"requestWithRetry error\",o);throw o}const[c]=o.response.getAttributeValue(\"ERROR-CODE\");const l=o.response.getAttributeValue(\"NONCE\");const u=o.response.getAttributeValue(\"REALM\");if((c===401&&u||c===438&&this.realm)&&l){Fe(\"retry with nonce\",c);this.nonce=l;if(c===401){this.realm=u}this.integrityKey=yk(this.username,this.realm,this.password);e.transactionId=jx();[n,i]=await this.request(e,this.server,void 0,{signal:s})}else{throw o}}return[n,i]}async sendData(e,t){let s;try{s=await this.getChannel(t)}catch(n){Fe(\"channelBind error; falling back to Send Indication\",n)}if(!s){await this.getPermission(t);const n=new Ke(Ge.SEND,ie.INDICATION).setAttribute(\"DATA\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);await this.sendStun(n,await this.serverDestination());return}await this.send($x(s.number,e),await this.serverDestination())}async getPermission(e){const t=pk(e);if(this.permissionByAddr[t]){return}const s=this.creatingPermissionByAddr.get(t);if(s){return s}const n=this.permissionQueue.then(async()=>{if(this.permissionByAddr[t]){return}await this.createPermission(e);this.permissionByAddr[t]=true});this.permissionQueue=n.then(()=>void 0,()=>void 0);this.creatingPermissionByAddr.set(t,n);try{await n}catch(i){Fe(\"createPermission error\",i);throw i}finally{if(this.creatingPermissionByAddr.get(t)===n){this.creatingPermissionByAddr.delete(t)}}}async getChannel(e){const t=zx(e);const s=this.channelBindingByAddr.get(t);if(s){return s}const n=this.channelByAddr[t];const i=_s(Date.now()/1e3);if(n&&n.refreshAt>i){return n}const o=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=o.then(()=>void 0,()=>void 0);this.channelBindingByAddr.set(t,o);try{return await o}catch(c){Fe(\"channelBind error\",c);throw c}finally{if(this.channelBindingByAddr.get(t)===o){this.channelBindingByAddr.delete(t)}}}async ensureChannel(e){const t=zx(e);const s=_s(Date.now()/1e3);let n=this.channelByAddr[t];if(n&&n.refreshAt>s){return n}const i=!n;if(!n){n={number:this.channelNumber++,address:e,refreshAt:0};this.channelByAddr[t]=n;this.addrByChannel[n.number]=e}try{await this.channelBind(n.number,e);n.refreshAt=_s(Date.now()/1e3)+this.channelRefreshTime;Fe(i?\"channelBind\":\"channelBind refresh\",n);return n}catch(o){if(i){delete this.channelByAddr[t];delete this.addrByChannel[n.number]}throw o}}async channelBind(e,t){const s=new Ke(Ge.CHANNEL_BIND,ie.REQUEST);s.setAttribute(\"CHANNEL-NUMBER\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);const[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==Ge.CHANNEL_BIND){throw new Error(\"should be CHANNEL_BIND\")}}async sendStun(e,t){await this.send(e.bytes,t)}async refreshAllocation(){if(!this.expiresAt||this.transport.closed){return false}const e=new Ke(Ge.REFRESH,ie.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime);try{const[t]=await this.requestWithRetry(e,this.server);this.expiresAt=Date.now()+t.getAttributeValue(\"LIFETIME\")*1e3;return true}catch(t){Fe(\"refresh failed\",t);this.expiresAt=0;return false}}async close(){this.refreshHandle?.resolve?.();if(this.expiresAt>Date.now()&&!this.transport.closed){this.expiresAt=0;const e=new Ke(Ge.REFRESH,ie.REQUEST);e.setAttribute(\"LIFETIME\",0);await this.requestWithRetry(e,this.server,AbortSignal.timeout(fk)).catch(t=>{Fe(\"delete allocation\",t)})}await this.transport.close()}};function mk(r,e){const t=(0,Gx.isIP)(r[0]);if(t===4||t===6){if(e&&e!==t){Fe(\"udpFamily ignored for IP literal TURN server\",{address:r,udpFamily:e,literalFamily:t})}return t===6?\"udp6\":\"udp4\"}return(e??4)===6?\"udp6\":\"udp4\"}a(mk,\"selectTurnUdpSocketType\");async function gk({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,ssl:o,tlsOptions:c,transport:l,connectTimeoutMs:u,udpFamily:f}={}){s??=dk;l??=o?\"tls\":\"udp\";const d=l===\"udp\"?await en.init(mk(r,f),{portRange:n,interfaceAddresses:i}):l===\"tcp\"?await Ba.init(r,{connectTimeoutMs:u}):await Ua.init(r,c,{connectTimeoutMs:u});const h=new Hm(r,e,t,s,d);try{await h.connectionMade()}catch(p){try{await h.close()}catch(m){Fe(\"failed to close TURN client after allocation failure\",m)}throw p}return h}a(gk,\"createTurnClient\");async function Wx(r,e={}){const t=await gk(r,e);const s=new Fm(t);return s}a(Wx,\"createStunOverTurnClient\");function yk(r,e,t){return Ux(r,e,t)}a(yk,\"makeIntegrityKey\");var Mc=require(\"node:crypto\");var qm=require(\"node:net\");var it=class r{static{a(this,\"Candidate\")}constructor(e,t,s,n,i,o,c,l,u,f,d,h){this.foundation=e;this.component=t;this.transport=s;this.priority=n;this.host=i;this.port=o;this.type=c;this.relatedAddress=l;this.relatedPort=u;this.tcptype=f;this.generation=d;this.ufrag=h;this.id=(0,Mc.randomUUID)().toString()}refreshId(){this.id=(0,Mc.randomUUID)().toString()}static fromSdp(e){const t=e.split(\" \");if(t.length<8){throw new Error(\"SDP does not have enough properties\")}const s={foundation:t[0],component:Number(t[1]),transport:t[2],priority:Number(t[3]),host:t[4],port:Number(t[5]),type:t[7]};for(let d=8,h=t.length-1;d<h;d+=2){if(t[d]===\"raddr\"){s[\"related_address\"]=t[d+1]}else if(t[d]===\"rport\"){s[\"related_port\"]=Number(t[d+1])}else if(t[d]===\"tcptype\"){s[\"tcptype\"]=t[d+1]}else if(t[d]===\"generation\"){s[\"generation\"]=Number(t[d+1])}else if(t[d]===\"ufrag\"){s[\"ufrag\"]=t[d+1]}}const{foundation:n,component:i,transport:o,priority:c,host:l,port:u,type:f}=s;return new r(n,i,o,c,l,u,f,s[\"related_address\"],s[\"related_port\"],s[\"tcptype\"],s[\"generation\"],s[\"ufrag\"])}canPairWith(e){const t=(0,qm.isIPv4)(this.host);const s=(0,qm.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&Tk(this,e)&&t===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;if(this.relatedAddress)e+=` raddr ${this.relatedAddress}`;if(this.relatedPort!=void 0)e+=` rport ${this.relatedPort}`;if(this.tcptype)e+=` tcptype ${this.tcptype}`;if(this.generation!=void 0)e+=` generation ${this.generation}`;if(this.ufrag!=void 0)e+=` ufrag ${this.ufrag}`;return e}};var bk={host:126,prflx:110,srflx:100,relay:0};var Sk={host:105,prflx:90,srflx:80,relay:0};var wk={active:6,passive:4,so:2};var Ek={active:4,passive:2,so:6};function Mf(r){return r?.toLowerCase()??\"udp\"}a(Mf,\"normalizeTransport\");function zm(r){switch(r){case\"active\":case\"passive\":case\"so\":return r;default:return void 0}}a(zm,\"normalizeTcpType\");function Tk(r,e){if(Mf(r.transport)!==\"tcp\"){return true}const t=zm(r.tcptype);const s=zm(e.tcptype);if(!t||!s){return false}return t===\"active\"&&s===\"passive\"||t===\"passive\"&&s===\"active\"||t===\"so\"&&s===\"so\"}a(Tk,\"canPairTcpCandidates\");function xk({candidateType:r,transport:e=\"udp\",tcptype:t,otherPreference:s=8191}){if(Mf(e)!==\"tcp\"){return s}const n=zm(t)??\"active\";const i=r===\"srflx\"||r===\"prflx\"?Ek[n]:wk[n];return(1<<13)*i+s}a(xk,\"candidateLocalPreference\");function Rk(r,e=\"udp\"){const t=Mf(e)===\"tcp\"?Sk:bk;return t[r]??0}a(Rk,\"candidateTypePreference\");function In(r,e,t,s){const n=s===void 0?`${r}|${e}|${t}`:`${r}|${e}|${t}|${s}`;return(0,Mc.createHash)(\"md5\").update(n,\"ascii\").digest(\"hex\").slice(7)}a(In,\"candidateFoundation\");function Os(r,e=65535){const t=1;const s=typeof e===\"number\"?\"udp\":Mf(e.transport);const n=typeof e===\"number\"?e:e.localPreference??xk({candidateType:r,transport:s,tcptype:e.tcptype,otherPreference:e.otherPreference});const i=Rk(r,s);return(1<<24)*i+(1<<8)*n+(256-t)}a(Os,\"candidatePriority\");function Vx(r){switch(r){case\"passive\":return\"active\";case\"active\":return\"passive\";default:return\"so\"}}a(Vx,\"remoteTcpTypeForIncoming\");var dR=require(\"node:crypto\");var Wm=require(\"node:net\");var hR=Ye(require(\"node:timers/promises\"),1);var Zx=require(\"node:dgram\");var Qx=require(\"node:events\");var Xx=\"224.0.0.251\";var Yx=5353;var Dc={A:1,AAAA:28};function _k(r){const e=r.replace(/\\.$/,\"\").split(\".\").map(t=>{const s=Buffer.from(t,\"utf8\");return Buffer.concat([Buffer.from([s.length]),s])});return Buffer.concat([...e,Buffer.from([0])])}a(_k,\"encodeName\");function Jx(r,e){const t=[];let s=e;let n=-1;for(let i=0;i<64;i++){const o=r[s];if(o===void 0)throw new Error(\"truncated name\");if(o===0){s++;break}if((o&192)===192){if(n<0)n=s+2;s=(o&63)<<8|r[s+1];continue}t.push(r.toString(\"utf8\",s+1,s+1+o));s+=1+o}return[t.join(\".\"),n<0?s:n]}a(Jx,\"decodeName\");function Ck(r,e){if(r===Dc.A&&e.length===4)return Array.from(e).join(\".\");if(r===Dc.AAAA&&e.length===16){const t=[];for(let s=0;s<16;s+=2)t.push(e.readUInt16BE(s).toString(16));return t.join(\":\")}return e}a(Ck,\"formatAddress\");function vk(r){try{if(r.length<12||!(r[2]&128))return void 0;const e=r.readUInt16BE(4);const t=r.readUInt16BE(6)+r.readUInt16BE(8)+r.readUInt16BE(10);let s=12;for(let i=0;i<e;i++)s=Jx(r,s)[1]+4;const n=[];for(let i=0;i<t;i++){const[o,c]=Jx(r,s);const l=r.readUInt16BE(c);const u=r.readUInt32BE(c+4);const f=r.readUInt16BE(c+8);const d=r.subarray(c+10,c+10+f);s=c+10+f;const h=l===Dc.A?\"A\":l===Dc.AAAA?\"AAAA\":void 0;n.push({name:o,type:h??l,ttl:u,data:Ck(l,d)})}return n}catch{return void 0}}a(vk,\"parseMdnsResponse\");function Ak(r,e){const t=Buffer.alloc(12);t.writeUInt16BE(1,4);const s=Buffer.alloc(4);s.writeUInt16BE(Dc[e],0);s.writeUInt16BE(1,2);return Buffer.concat([t,_k(r),s])}a(Ak,\"encodeMdnsQuery\");var Df=class extends Qx.EventEmitter{static{a(this,\"MulticastDns\")}#e;#t;constructor(){super();this.#e=(0,Zx.createSocket)({type:\"udp4\",reuseAddr:true});this.#e.on(\"error\",e=>void this.emit(\"error\",e));this.#e.on(\"message\",(e,t)=>{const s=vk(e);if(s?.length)this.emit(\"response\",s,t)});this.#t=new Promise(e=>{this.#e.bind(Yx,()=>{try{this.#e.addMembership(Xx);this.#e.setMulticastTTL(255);this.#e.setMulticastLoopback(true)}catch(t){this.emit(\"error\",t)}e()})})}async query(e,t=\"A\"){await this.#t;await new Promise((s,n)=>{this.#e.send(Ak(e,t),Yx,Xx,i=>i?n(i):s())})}destroy(){try{this.#e.close()}catch{}}};var Bf=class{static{a(this,\"MdnsLookup\")}constructor(){this.cache=new Map;this.mdnsInstance=new Df;this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,s)=>{const n=a(()=>{this.mdnsInstance.removeListener(\"response\",o);clearTimeout(i)},\"cleanup\");const i=setTimeout(()=>{n();s(new Error(\"No mDNS response\"))},1e4);const o=a(c=>{const l=c.find(u=>u.type===\"A\"&&u.name.toLowerCase()===e.toLowerCase());if(!l){return}n();t(l.data)},\"l\");this.mdnsInstance.on(\"response\",o);this.mdnsInstance.query(e,\"A\").catch(c=>{n();s(c)})})}close(){this.mdnsInstance.destroy()}};var eR=require(\"node:crypto\");var Ik=P(\"webrtc/ice/iceBase:log\");var Bc=class{static{a(this,\"CandidatePair\")}get state(){return this._state}toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}constructor(e,t,s){this.protocol=e;this.remoteCandidate=t;this.iceControlling=s;this.id=(0,eR.randomUUID)().toString();this.nominated=false;this.remoteNominated=false;this._state=ae.FROZEN;this.packetsSent=0;this.packetsReceived=0;this.bytesSent=0;this.bytesReceived=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.requestsReceived=0;this.requestsSent=0;this.responsesReceived=0;this.responsesSent=0;this.retransmissionsReceived=0;this.retransmissionsSent=0;this.consentRequestsSent=0;this.requestTransactionIds=new Set}updateState(e){this._state=e}get localCandidate(){if(!this.protocol.localCandidate){throw new Error(\"localCandidate not exist\")}return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return Gm(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){const t=this.requestTransactionIds.has(e);if(!t){this.requestTransactionIds.add(e);return false}this.retransmissionsReceived++;return true}};var Uc=1;var uo=2;var tR=5;var rR=30;var Ok=1e3;var kk=500;function sR(r){if(r===void 0||!Number.isFinite(r)||r<=0){return Ok}return Math.max(kk,Math.round(r*1e3*2+200))}a(sR,\"consentResponseTimeoutMs\");var ae;(function(r){r[r[\"FROZEN\"]=0]=\"FROZEN\";r[r[\"WAITING\"]=1]=\"WAITING\";r[r[\"IN_PROGRESS\"]=2]=\"IN_PROGRESS\";r[r[\"SUCCEEDED\"]=3]=\"SUCCEEDED\";r[r[\"FAILED\"]=4]=\"FAILED\"})(ae||(ae={}));var nR={iceLite:false,useTcp:false,useIpv4:true,useIpv6:true};function Km(r){if(![\"host\",\"relay\",\"srflx\"].includes(r.type))throw new Error(`Unexpected candidate type \"${r.type}\"`);return r}a(Km,\"validateRemoteCandidate\");function iR(r,e){return r.sort((t,s)=>Gm(t.localCandidate,t.remoteCandidate,e)-Gm(s.localCandidate,s.remoteCandidate,e)).reverse()}a(iR,\"sortCandidatePairs\");function Gm(r,e,t){const s=t&&r.priority||e.priority;const n=t&&e.priority||r.priority;return(1<<32)*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}a(Gm,\"candidatePairPriority\");async function oR(r,e){const t=new Ke(Ge.BINDING,ie.REQUEST);try{const[s]=await r.request(t,e);const n=r.localCandidate;if(!n){throw new Error(\"not exist\")}const i=new it(In(\"srflx\",n.transport,n.host,e[0]),n.component,n.transport,Os(\"srflx\",{transport:n.transport,tcptype:n.tcptype}),s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[0],s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[1],\"srflx\",n.host,n.port,n.tcptype);return i}catch(s){Ik(\"error serverReflexiveCandidate\",s)}}a(oR,\"serverReflexiveCandidate\");function Uf(r){if(r&&Number.isNaN(r[1])){return[r[0],443]}return r}a(Uf,\"validateAddress\");var lR=Ye(require(\"node:os\"),1);function aR(r,e,t={},s){const n=[\"ipsec\",\"tun\",\"utun\",\"tap\"];const i=[\"vmnet\",\"veth\"];const{useLinkLocalAddress:o}=t;const c=Object.keys(r).map(l=>{for(const f of[...n,...i]){if(l.startsWith(f)){return{nic:l,addresses:[]}}}const u=(r[l]??[]).filter(f=>Qs(f.family)===e&&!f.internal&&(o?true:!s(f)));return{nic:l,addresses:u.map(f=>f.address)}}).filter(l=>!!l);c.sort((l,u)=>l.nic.localeCompare(u.nic));return Object.values(c).flatMap(l=>l.addresses)}a(aR,\"selectAddressesFromInterfaces\");var Pk=P(\"webrtc/ice/utils\");function Nk(r){return Qs(r.family)===4&&r.address?.startsWith(\"169.254.\")||Qs(r.family)===6&&r.address?.startsWith(\"fe80::\")}a(Nk,\"isLinkLocalAddress\");function cR(r,{useLinkLocalAddress:e}={}){const t=lR.networkInterfaces();Pk(t);return aR(t,r,{useLinkLocalAddress:e},Nk)}a(cR,\"nodeIpAddress\");function uR(r,e,t={}){const s=[];if(r){s.push(...cR(4,t))}if(e){s.push(...cR(6,t))}return s}a(uR,\"getHostAddresses\");var Y=P(\"webrtc/ice/ice:log\");var Lk=1e3;var Mk=3e4;var Dk={udp:65535,tcp:49151,tls:32767};function Bk(r){const e=[];if(r.turnServer&&r.turnUsername&&r.turnPassword){e.push({address:r.turnServer,username:r.turnUsername,password:r.turnPassword,transport:r.turnTransport})}e.push(...r.turnServers??[]);const t=new Map;for(const s of e){const n=Uf(s.address);if(!n||!s.username||!s.password)continue;const i=n[0].toLowerCase();let o=t.get(i);if(!o){o={key:i,attempts:[]};t.set(i,o)}const c=s.transport===void 0||s.transport===\"udp\"?[\"udp\",\"tcp\"]:[s.transport];for(const l of c){const u=o.attempts.some(f=>f.transport===l&&f.address[1]===n[1]&&f.username===s.username&&f.password===s.password);if(!u)o.attempts.push({address:n,transport:l,username:s.username,password:s.password})}}return[...t.values()]}a(Bk,\"relayServersOf\");function Uk(r){const e=[];for(const t of[r.stunServer,...r.stunServers??[]]){const s=Uf(t);if(s&&!e.some(([n,i])=>n===s[0]&&i===s[1]))e.push(s)}return e}a(Uk,\"stunServersOf\");var jf=class{static{a(this,\"Connection\")}constructor(e,t){this._iceControlling=e;this.localUsername=lo(4);this.localPassword=lo(22);this.remoteIsLite=false;this.remotePassword=\"\";this.remoteUsername=\"\";this.checkList=[];this.localCandidates=[];this.stunServers=[];this.relayServers=[];this.relays=new Map;this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.generation=-1;this.userHistory={};this.tieBreaker=(0,dR.randomBytes)(8).readBigUInt64BE(0);this.state=\"new\";this._remoteCandidates=[];this.nominating=false;this.checkListDone=false;this.checkListState=new Nc;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;this.protocols=[];this.consentFresh=false;this.consentSessionId=0;this.resolvingRemoteCandidates=0;this.noPairDeadline=0;this.onData=new O;this.stateChanged=new O;this.onIceCandidate=new O;this.queryConsent=()=>{if(this.iceLite){return}this.stopConsentLifecycle();const s=this.consentSessionId;this.consentFresh=true;const n=Lc(async(i,o,c)=>{let l=false;const u=new AbortController;const f=a(()=>{if(this.consentExpiryTimer===void 0){return}clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0},\"clearConsentExpiry\");const d=a(()=>{if(l||s!==this.consentSessionId){return}f();this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0;if(l||s!==this.consentSessionId){return}if(this.state===\"closed\"||this.state===\"failed\"){return}Y(\"Consent to send expired\");this.consentFresh=false;this.consentSessionId++;this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;if(this.queryConsentHandle===n){this.queryConsentHandle=void 0}l=true;u.abort();this.setState(\"failed\")},rR*1e3)},\"refreshConsentExpiry\");c.once(()=>{l=true;if(s===this.consentSessionId){f();this.consentRequestAbort?.abort();this.consentRequestAbort=void 0}u.abort();if(this.queryConsentHandle===n){this.queryConsentHandle=void 0}});d();const h=a(()=>tR*(.8+.4*Math.random())*1e3,\"randomizedConsentInterval\");let p=Date.now()+h();const m=a(()=>this.state===\"closed\"||this.state===\"failed\",\"isTerminalState\");try{while(!m()&&!l&&s===this.consentSessionId){await this.abortableDelay(Math.max(0,p-Date.now()),u.signal);if(l||m()||s!==this.consentSessionId){break}p=Date.now()+h();const y=this.nominated;if(!y){break}const w=y.id;const S=this.generation;const T=this.remotePassword;const{localUsername:_,remoteUsername:x,iceControlling:k}=this;const N=this.buildRequest({nominate:this.shouldNominateConsentRequest(y),localUsername:_,remoteUsername:x,iceControlling:k,localCandidate:y.localCandidate});this.consentRequestAbort?.abort();const A=new AbortController;this.consentRequestAbort=A;y.consentRequestsSent++;y.requestsSent++;const B=sR(y.rtt);const ee=performance.now();y.protocol.request(N,y.remoteAddr,Buffer.from(T,\"utf8\"),{retransmissions:0,responseTimeout:B,signal:A.signal,onRequestSent:a(fe=>{if(fe>0){y.retransmissionsSent++}},\"onRequestSent\")}).then(()=>{if(s!==this.consentSessionId||l){return}const fe=this.state;if(fe===\"closed\"||fe===\"failed\"){return}if(this.nominated?.id!==w){return}if(this.generation!==S){return}if(this.remotePassword!==T){return}const Rt=(performance.now()-ee)/1e3;y.rtt=Rt;y.totalRoundTripTime+=Rt;y.roundTripTimeMeasurements++;y.responsesReceived++;this.consentFresh=true;d();if(fe===\"disconnected\"){this.setState(\"connected\")}}).catch(fe=>{if(s===this.consentSessionId&&this.nominated?.id===w){Y(\"no stun response\",fe)}})}}catch(y){}finally{if(s===this.consentSessionId){f()}}});this.queryConsentHandle=n};this.send=async s=>{if(!this.canSendApplicationData()){return}const n=this.nominated;await n.protocol.sendData(s,n.remoteAddr);n.packetsSent++;n.bytesSent+=s.length};this.checkStart=s=>Lc(async n=>{Y(\"check start\",s.toJSON());s.updateState(ae.IN_PROGRESS);const i={};const{remotePassword:o,remoteUsername:c,generation:l}=this;const u=s.localCandidate.ufrag??this.localUsername;const f=false;const d=this.buildRequest({nominate:f,localUsername:u,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});const h=performance.now();try{s.requestsSent++;const[p,m]=await s.protocol.request(d,s.remoteAddr,Buffer.from(o,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++;const y=performance.now();const w=(y-h)/1e3;s.rtt=w;s.totalRoundTripTime+=w;s.roundTripTimeMeasurements++;Y(\"response received\",d.toJSON(),p.toJSON(),m,{localUsername:u,remoteUsername:c,remotePassword:o,generation:l,rtt:w});i.response=p;i.addr=m}catch(p){const m=p;Y(\"failure case\",d.toJSON(),m.response?JSON.stringify(m.response.toJSON(),null,2):p,{localUsername:u,remoteUsername:c,remotePassword:o,generation:l},s.remoteAddr);if(m.response?.getAttributeValue(\"ERROR-CODE\")[0]===487){if(d.attributesKeys.includes(\"ICE-CONTROLLED\")){this.switchRole(true)}else if(d.attributesKeys.includes(\"ICE-CONTROLLING\")){this.switchRole(false)}await this.checkStart(s).awaitable;n();return}if(m.response?.getAttributeValue(\"ERROR-CODE\")[0]===401){Y(\"retry 401\",s.toJSON());await this.checkStart(s).awaitable;n();return}else{Y(\"checkStart CandidatePairState.FAILED\",s.toJSON());s.updateState(ae.FAILED);this.checkComplete(s);n();return}}if(i.addr[0]!==s.remoteAddr[0]||i.addr[1]!==s.remoteAddr[1]){s.updateState(ae.FAILED);this.checkComplete(s);n();return}if(f||s.remoteNominated){s.nominated=true}else if(this.usesTcpRegularNomination(s)){}else if(this.iceControlling&&!this.nominating&&!this.nominated){this.nominating=true;const p=this.buildRequest({nominate:true,localUsername:u,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});try{s.requestsSent++;await s.protocol.request(p,s.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++}catch(m){this.nominating=false;s.updateState(ae.FAILED);this.checkComplete(s);return}s.nominated=true}s.updateState(ae.SUCCEEDED);this.checkComplete(s);n()});this.pairRemoteCandidate=s=>{for(const n of this.protocols){this.tryPair(n,s)}};this.options={...nR,...t};if(this.iceLite){this._iceControlling=false}this.applyStunTurnServersFromOptions();this.restart().catch(s=>Y(\"restart failed\",s));Y(\"new Connection\",this.options)}setIceServers(e){this.options={...this.options,stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:e.turnTransport,stunServers:e.stunServers,turnServers:e.turnServers};if(e.forceTurn!==void 0){this.options.forceTurn=e.forceTurn}if(e.useTcp!==void 0){this.options.useTcp=e.useTcp}if(e.turnTlsOptions!==void 0){this.options.turnTlsOptions=e.turnTlsOptions}if(e.turnUdpFamily!==void 0){this.options.turnUdpFamily=e.turnUdpFamily}this.applyStunTurnServersFromOptions();Y(\"Connection ice servers updated\",this.options)}applyStunTurnServersFromOptions(){this.stunServers=Uk(this.options);this.relayServers=Bk(this.options);this.stunServer=this.stunServers[0];this.turnServer=Uf(this.options.turnServer)??this.relayServers[0]?.attempts[0]?.address}get iceControlling(){return this._iceControlling}set iceControlling(e){if(this.iceLite){e=false}if(this.nominated){return}this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++;this.localUsername=lo(4);this.localPassword=lo(22);if(this.options.localPasswordPrefix){this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)}this.userHistory[this.localUsername]=this.localPassword;this.remoteUsername=\"\";this.remotePassword=\"\";this.localCandidates=[];this._remoteCandidates=[];this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.state=\"new\";this.lookup?.close?.();this.lookup=void 0;this.nominated=void 0;this.nominating=false;this.checkList=[];this.checkListDone=false;this.checkListState=new Nc;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;for(const e of this.protocols){e.disconnect?.();if(e.localCandidate){e.localCandidate.refreshId();e.localCandidate.generation=this.generation;e.localCandidate.ufrag=this.localUsername}}this.stopConsentLifecycle()}resetNominatedPair(){Y(\"resetNominatedPair\");for(const e of this.protocols)e.disconnect?.();this.nominated=void 0;this.nominating=false;this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:s}){Y(\"setRemoteParams\",{iceLite:e,usernameFragment:t,password:s});this.remoteIsLite=e;this.remoteUsername=t;this.remotePassword=s}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=true;const e=[...this.relays.values()];for(const i of this.protocols){if(i.localCandidate&&!e.includes(i)){i.localCandidate.generation=this.generation;i.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(i.localCandidate)}}let t=uR(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress});const{interfaceAddresses:s}=this.options;if(s){const i=t.filter(o=>Object.values(s).includes(o));if(i.length){t=i}}if(this.options.additionalHostAddresses){t=Array.from(new Set([...this.options.additionalHostAddresses,...t]))}const n=this.getCandidatePromises(t,this.options.stunGatherTimeout);await Promise.allSettled(n);this.localCandidatesEnd=true}this.setState(\"completed\")}appendLocalCandidate(e){this.localCandidates.push(e);this.onIceCandidate.execute(e)}isRedundant(e){const t=a(s=>s.type===\"host\"?`${s.host}|${s.port}`:`${s.relatedAddress}|${s.relatedPort}`,\"baseOf\");return this.localCandidates.some(s=>s.transport===e.transport&&s.host===e.host&&s.port===e.port&&s.type!==\"relay\"&&t(s)===t(e))}gatherRelayCandidates(e){for(const[t,s]of this.relays){if(!e.some(n=>n.key===t))this.dropRelay(t,s)}return e.map(async t=>{const s=this.relays.get(t.key);if(s){if(await s.turn.refreshAllocation()){if(this.relays.get(t.key)!==s)return;s.localCandidate.generation=this.generation;s.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(s.localCandidate);return s.localCandidate}this.dropRelay(t.key,s)}const{protocol:n,attempt:i}=await this.allocateRelay(t);if(this.state===\"closed\"||this.relays.has(t.key)){await n.close();return}this.ensureProtocol(n);this.protocols.push(n);this.relays.set(t.key,n);const o=n.turn.relayedAddress;const c=n.turn.mappedAddress;Y(\"turn candidateAddress\",o);n.localCandidate=new it(In(\"relay\",\"udp\",o[0],`${t.key}|${i.transport}`),1,\"udp\",Os(\"relay\",Dk[i.transport]),o[0],o[1],\"relay\",c[0],c[1],void 0,this.generation,this.localUsername);this.appendLocalCandidate(n.localCandidate);return n.localCandidate}).map(t=>t.catch(s=>{Y(\"query TURN server\",s)}))}allocateRelay(e){return new Promise((t,s)=>{let n=0;let i=0;let o=false;let c;const l=a(()=>{clearTimeout(c);if(o||n>=e.attempts.length)return;const u=e.attempts[n++];i++;c=setTimeout(l,Lk);Wx({address:u.address,username:u.username,password:u.password},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:u.transport,tlsOptions:this.options.turnTlsOptions,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1e3,udpFamily:this.options.turnUdpFamily}).then(f=>{i--;if(o){f.close().catch(d=>Y(\"close TURN relay\",d));return}o=true;clearTimeout(c);t({protocol:f,attempt:u})},f=>{i--;Y(\"TURN allocation failed\",u.transport,u.address,f);if(o)return;if(n<e.attempts.length){l()}else if(!i){o=true;s(f)}})},\"start\");l()})}dropRelay(e,t){this.relays.delete(e);this.protocols=this.protocols.filter(s=>s!==t);t.close().catch(s=>Y(\"close TURN relay\",s))}ensureProtocol(e){e.onRequestReceived.subscribe((t,s)=>{if(t.messageMethod!==Ge.BINDING){this.respondError(t,s,e,[400,\"Bad Request\"]);return}const n=t.getAttributeValue(\"USERNAME\");const{remoteUsername:i}=fR(n);const o=this.userHistory[i]??this.localPassword;const{iceControlling:c}=this;if(c&&t.attributesKeys.includes(\"ICE-CONTROLLING\")){if(this.tieBreaker>=t.getAttributeValue(\"ICE-CONTROLLING\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(false)}}else if(!c&&t.attributesKeys.includes(\"ICE-CONTROLLED\")){if(this.iceLite||this.tieBreaker<t.getAttributeValue(\"ICE-CONTROLLED\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(true);return}}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,s,e)){return}const l=new Ke(Ge.BINDING,ie.RESPONSE,t.transactionId);l.setAttribute(\"XOR-MAPPED-ADDRESS\",s).addMessageIntegrity(Buffer.from(o,\"utf8\")).addFingerprint();e.sendStun(l,s).catch(u=>{Y(\"sendStun error\",u)});if(this.checkList.length===0&&!this.earlyChecksDone){this.earlyChecks.push([t,s,e])}else{this.checkIncoming(t,s,e)}});e.onDataReceived.subscribe(t=>{try{const s=this.nominated;if(s&&s.protocol===e){s.packetsReceived++;s.bytesReceived+=t.length}this.onData.execute(t)}catch(s){Y(\"dataReceived\",s)}});e.onConnectionClosed?.subscribe(t=>{this.handleConnectionClosed(e,t)})}handleConnectionClosed(e,t){const s=this.nominated;if(!s||s.protocol!==e||s.remoteAddr[0]!==t[0]||s.remoteAddr[1]!==t[1]){return}if(this.state===\"closed\"||this.state===\"failed\"){return}Y(\"selected tcp connection closed\",s.toJSON());this.stopConsentLifecycle();this.setState(\"failed\")}getCandidatePromises(e,t=5){const s=[];const{stunServers:n,relayServers:i}=this;const o=this.iceLite;const c=!o&&this.options.forceTurn&&i.length>0;const l=this.protocols.filter(f=>f instanceof An&&!!f.localCandidate);e=e.filter(f=>{if(this.protocols.find(d=>d.localIp===f)){return false}return true});const u=c?[]:e.map(async f=>{const d=new An;this.ensureProtocol(d);try{await d.connectionMade((0,Wm.isIPv4)(f),this.options.portRange,this.options.interfaceAddresses);d.localIp=f;this.protocols.push(d);Y(\"protocol\",d.localIp);const h=[f,d.getExtraInfo()[1]];d.localCandidate=new it(In(\"host\",\"udp\",h[0]),1,\"udp\",Os(\"host\",{transport:\"udp\"}),h[0],h[1],\"host\",void 0,void 0,void 0,this.generation,this.localUsername);this.pairLocalProtocol(d);this.appendLocalCandidate(d.localCandidate);return d}catch(h){Y(\"error protocol STUN\",h)}});if(!c){s.push(...u.map(f=>f.then(d=>d?.localCandidate)))}if(!c&&this.options.useTcp){const f=e.map(async d=>{if(this.options.tcpPassive!==false){const h=new kf;this.ensureProtocol(h);await h.connectionMade(d,this.options.portRange);h.localIp=d;h.localCandidate=new it(In(\"host\",\"tcp\",d),1,\"tcp\",Os(\"host\",{transport:\"tcp\",tcptype:\"passive\"}),d,h.listeningPort,\"host\",void 0,void 0,\"passive\",this.generation,this.localUsername);this.protocols.push(h);this.appendLocalCandidate(h.localCandidate)}if(!o){const h=new Of;this.ensureProtocol(h);await h.connectionMade(d);h.localIp=d;h.localCandidate=new it(In(\"host\",\"tcp\",d),1,\"tcp\",Os(\"host\",{transport:\"tcp\",tcptype:\"active\"}),d,9,\"host\",void 0,void 0,\"active\",this.generation,this.localUsername);this.protocols.push(h);this.pairLocalProtocol(h);this.appendLocalCandidate(h.localCandidate)}});s.push(...f)}if(!o&&!c&&n.length){const f=[...l.map(h=>Promise.resolve(h)),...u];const d=f.flatMap(h=>n.map(async p=>{const m=await h;if(!m)return;const y=this.generation;const w=(async()=>{const _=m.localCandidate?.host;if(!_||!(0,Wm.isIPv4)(_))return;const x=await oR(m,p).catch(k=>{Y(\"error\",k)});if(!x||y!==this.generation||this.isRedundant(x))return;x.generation=this.generation;x.ufrag=this.localUsername;this.appendLocalCandidate(x);return x})();let S;const T=new Promise((_,x)=>{S=setTimeout(()=>x(new Error(\"STUN query timeout\")),t*1e3)});return Promise.race([w,T]).finally(()=>clearTimeout(S)).catch(_=>{Y(\"query STUN server\",_)})}));s.push(...d)}if(!o){s.push(...this.gatherRelayCandidates(i))}return s}async connect(){Y(\"start connect ice\");if(!this.localCandidatesEnd){if(!this.localCandidatesStart){throw new Error(\"Local candidates gathering was not performed\")}}if(!this.remoteUsername||!this.remotePassword){throw new Error(\"Remote username or password is missing\")}for(const t of this.remoteCandidates){this.pairRemoteCandidate(t)}this.sortCheckList();if(!this.iceLite){this.unfreezeInitial()}Y(\"earlyChecks\",this.localPassword,this.earlyChecks.length);for(const t of this.earlyChecks){this.checkIncoming(...t)}this.earlyChecks=[];this.earlyChecksDone=true;if(this.iceLite){if(!this.nominated){let t=uo;while(!this.checkListDone&&this.state!==\"closed\"){t=await this.checkListState.get();Y(\"checkListState\",t);if(t===Uc){break}}if(t!==Uc&&!this.nominated){throw new Error(\"ICE negotiation failed\")}}this.setState(\"connected\");return}this.noPairDeadline=Date.now()+Mk;for(;;){if(this.state===\"closed\")break;if(!this.schedulingChecks())break;await hR.setTimeout(20)}let e=uo;while(this.checkList.length>0&&e===uo&&this.state!==\"closed\"){e=await this.checkListState.get();Y(\"checkListState\",e)}for(const t of this.checkList){t.handle?.resolve?.()}if(e!==Uc){throw new Error(\"ICE negotiation failed\")}this.queryConsent();this.setState(\"connected\")}unfreezeInitial(){const[e]=this.checkList;if(!e)return;if(e.state===ae.FROZEN){e.updateState(ae.WAITING)}const t=new Set(e.localCandidate.foundation);for(const s of this.checkList){if(s.component===e.component&&!t.has(s.localCandidate.foundation)&&s.state===ae.FROZEN){s.updateState(ae.WAITING);t.add(s.localCandidate.foundation)}}}schedulingChecks(){if(this.nominating&&!this.nominated)return true;{const e=this.checkList.filter(t=>{if(this.options.forceTurn&&t.protocol.type===An.type)return false;return true}).find(t=>t.state===ae.WAITING);if(e){e.handle=this.checkStart(e);return true}}{const e=this.checkList.find(t=>t.state===ae.FROZEN);if(e){e.handle=this.checkStart(e);return true}}if(!this.remoteCandidatesEnd||this.resolvingRemoteCandidates>0||!this.checkList.length&&Date.now()<this.noPairDeadline){return!this.checkListDone}return false}stopConsentLifecycle(){this.consentSessionId++;this.consentFresh=false;if(this.consentExpiryTimer!==void 0){clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0}this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;const e=this.queryConsentHandle;this.queryConsentHandle=void 0;e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){if(!this.nominated){return false}if(this.state===\"closed\"||this.state===\"failed\"){return false}if(this.iceLite){return true}return this.consentFresh}abortableDelay(e,t){return new Promise((s,n)=>{if(t.aborted){n(new DOMException(\"The operation was aborted\",\"AbortError\"));return}const i=setTimeout(()=>{t.removeEventListener(\"abort\",o);s()},e);const o=a(()=>{clearTimeout(i);n(new DOMException(\"The operation was aborted\",\"AbortError\"))},\"onAbort\");t.addEventListener(\"abort\",o,{once:true})})}async close(){this.setState(\"closed\");this.stopConsentLifecycle();if(this.checkList&&!this.checkListDone){this.checkListState.put(new Promise(t=>{t(uo)}))}this.nominated=void 0;const e=this.protocols;this.protocols=[];this.relays.clear();await Promise.all(e.map(async t=>{await t.close?.()}));this.localCandidates=[];this.lookup?.close?.();this.lookup=void 0}setState(e){this.state=e;this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=true;return}if(e.host.includes(\".local\")){void this.resolveRemoteCandidate(e);return}this.addResolvedRemoteCandidate(e)}async resolveRemoteCandidate(e){const t=this.generation;this.resolvingRemoteCandidates++;try{if(!this.lookup){this.lookup=new Bf}e.host=await this.lookup.lookup(e.host)}catch{return}finally{this.resolvingRemoteCandidates--}if(t!==this.generation||this.state===\"closed\")return;this.addResolvedRemoteCandidate(e)}addResolvedRemoteCandidate(e){try{Km(e)}catch(t){return}if(this._remoteCandidates.some(t=>t.host===e.host&&t.port===e.port&&t.component===e.component&&t.type===e.type&&t.transport.toLowerCase()===e.transport.toLowerCase())){return}Y(\"addRemoteCandidate\",e);this._remoteCandidates.push(e);this.pairRemoteCandidate(e);this.sortCheckList()}getDefaultCandidate(){const e=this.localCandidates.sort((s,n)=>s.priority-n.priority);const[t]=e;return t}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw new Error(\"Cannot set remote candidates after end-of-candidates.\");this._remoteCandidates=[];for(const t of e){try{Km(t)}catch(s){continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=true}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){iR(this.checkList,this.iceControlling)}findPair(e,t){const s=this.checkList.find(n=>n.protocol===e&&n.remoteCandidate===t);return s}applyIceControlling(e){this._iceControlling=e;for(const t of this.checkList){t.iceControlling=e}}switchRole(e){Y(\"switch role\",e);if(this.iceLite){e=false}this.applyIceControlling(e);this.sortCheckList()}checkComplete(e){e.handle=void 0;if(e.state===ae.SUCCEEDED){if(e.nominated&&(e.remoteCandidate.ufrag==void 0||e.remoteCandidate.ufrag===this.remoteUsername)&&this.nominated==void 0){Y(\"nominated\",e.toJSON());this.nominated=e;this.nominating=false;this.pruneTcpConnections(e);e.protocol.connectTo?.(e.remoteAddr);if(!this.iceLite&&(this.state===\"connected\"||this.state===\"completed\")){this.queryConsent()}for(const t of this.checkList){if(t.component===e.component&&[ae.WAITING,ae.FROZEN].includes(t.state)){t.updateState(ae.FAILED)}}}if(this.nominated){if(!this.checkListDone){Y(\"ICE completed\");this.checkListState.put(new Promise(t=>t(Uc)));this.checkListDone=true}return}Y(\"not completed\",e.toJSON());for(const t of this.checkList){if(t.localCandidate.foundation===e.localCandidate.foundation&&t.state===ae.FROZEN){t.updateState(ae.WAITING)}}}this.nominateTcpPairIfReady();if(this.nominating){return}{const t=[ae.SUCCEEDED,ae.FAILED];if(this.checkList.find(({state:s})=>!t.includes(s))){return}}if(!this.iceControlling){const t=ae.SUCCEEDED;if(this.checkList.find(({state:s})=>s===t)){return}}if(!this.checkListDone){Y(\"ICE failed\");this.checkListState.put(new Promise(t=>{t(uo)}))}}isTcpPair(e){return e.localCandidate.transport.toLowerCase()===\"tcp\"}usesTcpRegularNomination(e){return this.iceControlling&&!this.remoteIsLite&&this.isTcpPair(e)}checkRequestOptions(e){const t=a(s=>{if(s>0){e.retransmissionsSent++}},\"onRequestSent\");if(this.isTcpPair(e)){return{retransmissions:0,responseTimeout:Ex,onRequestSent:t}}return{retransmissions:4,onRequestSent:t}}nominateTcpPairIfReady(){if(!this.iceControlling||this.remoteIsLite||this.nominated||this.nominating){return}for(const e of this.checkList){if(!this.isTcpPair(e)){continue}if(e.state===ae.SUCCEEDED){this.nominateTcpPair(e);return}if(e.state!==ae.FAILED){return}}}nominateTcpPair(e){this.nominating=true;const{generation:t}=this;const s=this.buildRequest({nominate:true,localUsername:e.localCandidate.ufrag??this.localUsername,remoteUsername:this.remoteUsername,iceControlling:this.iceControlling,localCandidate:e.localCandidate});e.requestsSent++;e.protocol.request(s,e.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(e)).then(()=>{if(this.isStaleNomination(e,t)){return}e.responsesReceived++;e.nominated=true;this.nominating=false;this.checkComplete(e)},n=>{if(this.isStaleNomination(e,t)){return}Y(\"tcp nomination failed\",e.toJSON(),n);this.nominating=false;e.updateState(ae.FAILED);this.checkComplete(e)})}isStaleNomination(e,t){return this.state===\"closed\"||this.generation!==t||!this.checkList.includes(e)}addPair(e){this.checkList.push(e);this.sortCheckList()}checkIncoming(e,t,s){const n=e.getAttributeValue(\"USERNAME\");const{remoteUsername:i}=fR(n);let o;const[c,l]=t;for(const f of this.remoteCandidates){if(f.host===c&&f.port===l){o=f;break}}if(!o){o=new it(lo(10),1,s.localCandidate?.transport??\"udp\",e.getAttributeValue(\"PRIORITY\"),c,l,\"prflx\",void 0,void 0,s.localCandidate?.transport===\"tcp\"?Vx(s.localCandidate.tcptype):void 0,void 0,void 0);this._remoteCandidates.push(o)}let u=this.findPair(s,o);if(!u){u=new Bc(s,o,this.iceControlling);u.updateState(ae.WAITING);this.addPair(u)}u.noteIncomingRequest(e.transactionIdHex);u.requestsReceived++;u.responsesSent++;u.localCandidate.ufrag=i;Y(\"Triggered Checks\",e.toJSON(),u.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation});if(this.iceLite){if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){u.remoteNominated=true;u.nominated=true;u.updateState(ae.SUCCEEDED);this.checkComplete(u)}return}if([ae.WAITING,ae.FAILED].includes(u.state)){u.handle=this.checkStart(u)}if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){u.remoteNominated=true;if(u.state===ae.SUCCEEDED){u.nominated=true;this.checkComplete(u)}}}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&!(e.localCandidate.transport.toLowerCase()===\"tcp\"&&e.localCandidate.tcptype===\"passive\"&&t.type!==\"prflx\")&&!this.findPair(e,t)){const s=new Bc(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(s)){return}s.updateState(ae.WAITING);this.addPair(s)}}pairLocalProtocol(e){for(const t of this.remoteCandidates){this.tryPair(e,t)}}buildRequest({nominate:e,remoteUsername:t,localUsername:s,iceControlling:n,localCandidate:i}){const o=jk({remoteUsername:t,localUsername:s});const c=new Ke(Ge.BINDING,ie.REQUEST);c.setAttribute(\"USERNAME\",o).setAttribute(\"PRIORITY\",Os(\"prflx\",{transport:i?.transport,tcptype:i?.tcptype}));if(n){c.setAttribute(\"ICE-CONTROLLING\",this.tieBreaker);if(e){c.setAttribute(\"USE-CANDIDATE\",null)}}else{c.setAttribute(\"ICE-CONTROLLED\",this.tieBreaker)}return c}pruneTcpConnections(e){for(const t of this.protocols){if(t.localCandidate?.transport.toLowerCase()!==\"tcp\"){continue}if(\"pruneForSelection\"in t&&typeof t.pruneForSelection===\"function\"){void t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}}}respondError(e,t,s,n){const i=new Ke(e.messageMethod,ie.ERROR,e.transactionId);i.setAttribute(\"ERROR-CODE\",n).addMessageIntegrity(Buffer.from(this.localPassword,\"utf8\")).addFingerprint();s.sendStun(i,t).catch(o=>{Y(\"sendStun error\",o)})}};var jk=a(({remoteUsername:r,localUsername:e})=>{return`${r}:${e}`},\"encodeTxUsername\");var fR=a(r=>{const[e,t]=r.split(\":\");return{remoteUsername:e,localUsername:t}},\"decodeTxUsername\");var bo=require(\"node:crypto\");var $f=class extends Map{static{a(this,\"RTCStatsReport\")}constructor(e){super();if(e){for(const t of e){this.set(t.id,t)}}}};function ue(r,...e){const t=e.filter(s=>s!==void 0);return`${r}_${t.join(\"_\")}`}a(ue,\"generateStatsId\");function fo(r,e,t){return ue(\"codec\",r,e,t)}a(fo,\"generateCodecStatsId\");function Qe(){return performance.timeOrigin+performance.now()}a(Qe,\"getStatsTimestamp\");function $k(r){const e=[];for(const[t,s]of Object.entries(r)){if(t===\"id\"){continue}if(t.endsWith(\"Id\")){if(typeof s===\"string\"){e.push(s)}continue}if(t.endsWith(\"Ids\")&&Array.isArray(s)){for(const n of s){if(typeof n===\"string\"){e.push(n)}}}}return e}a($k,\"getReferencedStatsIds\");function On(r,e){const t=new Map;for(const i of r){t.set(i.id,i)}if(!e){return new $f([...t.values()])}const s=new Set;const n=[...new Set(Array.from(e))];while(n.length>0){const i=n.shift();if(!i||s.has(i)){continue}const o=t.get(i);if(!o){continue}s.add(i);n.push(...$k(o))}return new $f([...s].map(i=>t.get(i)).filter(i=>!!i))}a(On,\"buildStatsReport\");var RR=require(\"node:crypto\");var gR=require(\"node:crypto\");var Jm=require(\"node:perf_hooks\");var pR=require(\"node:crypto\");var Ff=class{static{a(this,\"RTCRtpTransceiver\")}set codecs(e){this._codecs=e}get codecs(){return this._codecs}get codecPreferences(){return this._codecPreferences}setCodecPreferences(e){if(!Array.isArray(e)){throw rr(\"codecs must be an array\")}const t=e.length===0?void 0:e.map(ME);if(Fk(this._codecPreferences,t))return;this._codecPreferences=t;this.codecPreferencesNeedResolution=true;this._codecs=[];this.onCodecPreferencesChanged.execute()}constructor(e,t,s,n,i){this.kind=e;this.receiver=s;this.sender=n;this._direction=i;this.id=(0,pR.randomUUID)().toString();this.onTrack=new O;this.mid=null;this.usedForSender=false;this._codecs=[];this.headerExtensions=[];this.onCodecPreferencesChanged=new O;this.codecPreferencesNeedResolution=false;this.options={};this.stopping=false;this.stopped=false;this.rejected=false;this.pendingRejection=false;this.firedReceiving=false;this.addedByAddTrack=false;this.onStopRequested=new O;this.onRelease=new O;this.onDirectionChanged=new O;if(t){this.setDtlsTransport(t)}}get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){const t=e!==this._direction;this.setDirection(e);if(t)this.onDirectionChanged.execute()}setDirection(e){this._direction=e;if(this._currentDirection&&this._currentDirection!==\"stopped\"&&Rn.includes(this._currentDirection)){this.usedForSender=true}}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e;if(e&&e!==\"stopped\"&&Rn.includes(e)&&this.sender.track){this.usedForSender=true}}setDtlsTransport(e){this.receiver.setDtlsTransport(e);this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){const t=this.receiver.addTrack(e);if(t){this.onTrack.execute(e,this)}}get associated(){return this.mid!=null&&this.mLineIndex!=void 0}stop(){if(this.stopping){return}this.stopping=true;this.releaseMedia();if(!this.associated){this.markStopped()}this.onStopRequested.execute()}commitStopped({rejected:e}){if(e&&!this.stopping){this.rejected=true}this.pendingRejection=false;this.stopping=true;this.releaseMedia();this.markStopped()}markStopped(){this.stopped=true;this.setCurrentDirection(\"stopped\")}releaseMedia(){this.sender.stop({keepTrack:true});this.receiver.stop();this.receiver.endTracks();this.onRelease.execute()}forceStop(){if(this.stopped&&this.sender.stopped&&this.receiver.stopped){return}this.stopping=true;this.stopped=true;this.setCurrentDirection(\"stopped\");this.receiver.stop();this.sender.stop();this.onRelease.execute()}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){const e=Qe();return this.collectCodecStats(e)}collectCodecStats(e){const t=[];if(!this.dtlsTransport){return t}const s=ue(\"transport\",this.dtlsTransport.id);for(const n of this.codecs){const i={type:\"codec\",id:fo(s,n.payloadType,this.id),timestamp:e,payloadType:n.payloadType,transportId:s,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,sdpFmtpLine:n.parameters};t.push(i)}return t}};function Fk(r,e){if(r===e)return true;if(r==void 0||e==void 0||r.length!==e.length){return false}return Hf(r)===Hf(e)}a(Fk,\"sameCodecPreferences\");function Hf(r){if(Array.isArray(r)){return`[${r.map(Hf).join(\",\")}]`}if(r!=void 0&&typeof r===\"object\"){const e=Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[s])=>t.localeCompare(s));return`{${e.map(([t,s])=>`${JSON.stringify(t)}:${Hf(s)}`).join(\",\")}}`}return JSON.stringify(r)??\"undefined\"}a(Hf,\"stableCodecValue\");var Hk=\"inactive\";var Vm=\"sendonly\";var Xm=\"recvonly\";var Ym=\"sendrecv\";var qf=[Hk,Vm,Xm,Ym];var qk=P(\"webrtc/peer/utils\");function Zm(r,e){const t=a(i=>i.toUpperCase(),\"upper\");const s=a(i=>i.match(/(.{2})/g).join(\":\"),\"colon\");const n=(0,gR.createHash)(e).update(r).digest(\"hex\");return s(t(n))}a(Zm,\"fingerprint\");var zk={sha1:\"sha1\",\"sha-1\":\"sha1\",sha224:\"sha224\",\"sha-224\":\"sha224\",sha256:\"sha256\",\"sha-256\":\"sha256\",sha384:\"sha384\",\"sha-384\":\"sha384\",sha512:\"sha512\",\"sha-512\":\"sha512\"};function Qm(r){return zk[r.trim().toLowerCase()]}a(Qm,\"normalizeFingerprintAlgorithm\");function zf(r){return r.replace(/[^0-9a-f]/gi,\"\").toLowerCase()}a(zf,\"normalizeFingerprintValue\");function yR(r){const e=r[0];return e>19&&e<64}a(yR,\"isDtls\");var Gf=a((r,e)=>qf[qf.indexOf(r)&qf.indexOf(e)],\"andDirection\");function bR(r){if(r===\"sendonly\")return\"recvonly\";if(r===\"recvonly\")return\"sendonly\";return r}a(bR,\"reverseDirection\");var ho=Date.now;var Gk=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n;var SR=a(()=>{return Gk+process.hrtime.bigint()/1000n},\"microTime\");var po=a(()=>Date.now()/1e3,\"timestampSeconds\");var eg=Date.UTC(1900,0,1);var wR=a((r=Jm.performance.timeOrigin+Jm.performance.now())=>{const e=r-eg;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);return BigInt(t)<<32n|BigInt(s)},\"ntpTime\");var tg=a(r=>{const e=r-eg;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);const n=Buffer.allocUnsafe(3);n.writeUIntBE((t&63)<<18|s>>>14,0,3);return n},\"absSendTimeOf\");var ER=a(r=>{const e=Number(r>>32n);const t=Number(r&0xffffffffn);return e*1e3+t/2**32*1e3+eg},\"ntpTimeToEpochMs\");var Kf=a(r=>{return Number(r>>16n&0xffffffffn)},\"compactNtp\");function TR(r){const e={stunServers:[],turnServers:[]};for(const t of r){const s=Array.isArray(t.urls)?t.urls:[t.urls];for(const n of s){const i=Kk(n);if(!i){continue}if(i.kind===\"stun\"){e.stunServer??=i.address;e.stunServers.push(i.address)}if(i.kind===\"turn\"){if(!e.turnServer){e.turnServer=i.address;e.turnTransport=i.transport;e.turnUsername=t.username;e.turnPassword=t.credential}if(t.username&&t.credential){e.turnServers.push({address:i.address,username:t.username,password:t.credential,transport:i.transport})}}}}qk(\"iceOptions\",e);return e}a(TR,\"parseIceServers\");function rg({configuredTurnTransport:r,forceTurnTCP:e,parsedTurnTransport:t}){if(t){return t}if(r){return r}if(e){return\"tcp\"}return void 0}a(rg,\"resolveTurnTransport\");function Kk(r){const e=/^(stun|stuns|turn|turns):(.+)$/i.exec(r.trim());if(!e){return}const[,t,s]=e;const n=t.toLowerCase();const[i]=s.split(\"?\",1);const[,o=\"\"]=s.split(\"?\");const c=Xk(i,Vk(n));if(!c){return}if(n===\"stun\"||n===\"stuns\"){return{kind:\"stun\",address:c}}const l=new URLSearchParams(o);const u=l.get(\"transport\");const f=Wk({scheme:n,transportParam:u});if(f===\"invalid\"){return}return{kind:\"turn\",address:c,transport:f}}a(Kk,\"parseIceServerUrl\");function Wk({scheme:r,transportParam:e}){if(e==null){return r===\"turns\"?\"tls\":void 0}if(e===\"udp\"){return r===\"turns\"?\"invalid\":\"udp\"}if(e===\"tcp\"){return r===\"turns\"?\"tls\":\"tcp\"}return\"invalid\"}a(Wk,\"resolveParsedTurnTransport\");function Vk(r){if(r===\"stuns\"||r===\"turns\"){return 5349}return 3478}a(Vk,\"defaultPort\");function Xk(r,e){const t=r.startsWith(\"//\")?r.slice(2):r;if(!t){return}if(t.startsWith(\"[\")){const i=t.indexOf(\"]\");if(i===-1){return}const o=t.slice(1,i);const c=mR(t.slice(i+1),e);return[o,c]}const s=t.indexOf(\":\");const n=t.lastIndexOf(\":\");if(s!==-1&&s===n){return[t.slice(0,s),mR(t.slice(s+1),e)]}return[t,e]}a(Xk,\"parseAddress\");function mR(r,e){const t=r.startsWith(\":\")?r.slice(1):r;const s=Number.parseInt(t,10);return Number.isFinite(s)?s:e}a(mR,\"parsePort\");var VZ=Hr.createSelfSignedCertificateWithKey;var xR=a((r,e)=>{if(!r||typeof r!==\"object\"){if(e!==null&&typeof e===\"object\"){return e}else{return r}}if(!e||typeof e!==\"object\"){if(e==void 0){return r}return e}for(const t in e){if(Object.prototype.hasOwnProperty.call(e,t)){const s=e[t];if(s!=void 0){r[t]=s}}}return r},\"deepMerge\");var Yk=P(\"webrtc/peer/media/receiver/receiverTwcc\");var Jk=100;var Zk=500;var Qk=1<<15;function eP(r){const e=[];let t=0;while(t<r.length){let s=1;while(t+s<r.length&&r[t+s]===r[t]&&s<8191)s++;if(s>=7){e.push(new Ei({packetStatus:r[t],runLength:s}));t+=s;continue}const n=r.slice(t,t+14);const i=n.includes(Te.TypeTCCPacketReceivedLargeDelta)?r.slice(t,t+7):n;const o=i===n?14:7;e.push(new Ga({type:vs.TypeTCCStatusVectorChunk,symbolSize:o===14?0:1,symbolList:[...i,...Array(o-i.length).fill(Te.TypeTCCPacketNotReceived)]}));t+=o}return e}a(eP,\"packetChunksOf\");var Wf=class{static{a(this,\"ReceiverTWCC\")}constructor(e){this.dtlsTransport=e;this.arrivals=new Map;this.fbPktCount=0;this.rtcpSsrc=(0,RR.randomBytes)(4).readUInt32BE();this.mediaSourceSsrc=0}handleTWCC(e,t,s=Number(SR())){const n=this.unwrap(e);if(this.nextSequenceNumber!==void 0&&n<this.nextSequenceNumber)return;if(!this.arrivals.has(n))this.arrivals.set(n,s);if(this.arrivals.size>Qk){let i=n;for(const o of this.arrivals.keys())i=Math.min(i,o);this.arrivals.delete(i);this.nextSequenceNumber=i+1}this.mediaSourceSsrc=t;if(!this.timer){this.timer=setInterval(()=>this.sendTWCC(),Jk);this.timer.unref()}}stop(){clearInterval(this.timer);this.timer=void 0;this.arrivals.clear()}sendTWCC(){if(this.arrivals.size===0)return;let e=this.nextSequenceNumber??Infinity;if(e===Infinity){for(const s of this.arrivals.keys())e=Math.min(e,s)}const t=this.highestSequenceNumber;while(e<=t){const{feedback:s,next:n}=this.buildFeedback(e,t);this.dtlsTransport.sendRtcp([new nt({feedback:s})]).catch(i=>Yk(i));e=n}this.arrivals.clear();this.nextSequenceNumber=t+1}unwrap(e){if(this.highestSequenceNumber===void 0){this.highestSequenceNumber=e;return e}let t=e-this.highestSequenceNumber&65535;if(t>=32768)t-=65536;const s=this.highestSequenceNumber+t;if(s>this.highestSequenceNumber)this.highestSequenceNumber=s;return s}buildFeedback(e,t){let s=e;while(!this.arrivals.has(s))s++;const n=Math.floor(this.arrivals.get(s)/64e3);let i=n*64e3;const o=[];const c=[];let l=e;for(;l<=t&&o.length<Zk;l++){const f=this.arrivals.get(l);if(f===void 0){o.push(Te.TypeTCCPacketNotReceived);continue}const d=Math.round((f-i)/250);if(d<-32768||d>32767)break;const h=d>=0&&d<=255?Te.TypeTCCPacketReceivedSmallDelta:Te.TypeTCCPacketReceivedLargeDelta;o.push(h);c.push(new sn({type:h,delta:d*250}));i+=d*250}const u=new Mr({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:e&65535,packetStatusCount:o.length,referenceTime:n&16777215,fbPktCount:this.fbPktCount,packetChunks:eP(o),recvDeltas:c});this.fbPktCount=Vw(this.fbPktCount,1);return{feedback:u,next:l}}};var Vf=class{static{a(this,\"CumulativeResult\")}constructor(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}addPacket(e,t,s){if(this.numPackets===0){this.firstPacketSentAtMs=t;this.firstPacketReceivedAtMs=s;this.lastPacketSentAtMs=t;this.lastPacketReceivedAtMs=s}else{if(t<this.firstPacketSentAtMs)this.firstPacketSentAtMs=t;if(s<this.firstPacketReceivedAtMs)this.firstPacketReceivedAtMs=s;if(t>this.lastPacketSentAtMs)this.lastPacketSentAtMs=t;if(s>this.lastPacketReceivedAtMs)this.lastPacketReceivedAtMs=s}this.numPackets++;this.totalSize+=e}reset(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}get receiveBitrate(){const e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;const t=this.totalSize/e*8*1e3;return wi(t)}get sendBitrate(){const e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;const t=this.totalSize/e*8*1e3;return wi(t)}};var mo=20;var tP=10;var rP=8192;var Xf=class{static{a(this,\"SenderBandwidthEstimator\")}get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e;this.onCongestionScore.execute(e)}get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e;this.onAvailableBitrate.execute(e)}constructor(){this.congestion=false;this.onAvailableBitrate=new O;this.onCongestion=new O;this.onCongestionScore=new O;this.congestionCounter=0;this.cumulativeResult=new Vf;this.sentInfos=new Map;this._congestionScore=1;this._availableBitrate=0}receiveTWCC(e){const t=ho();const s=this.cumulativeResult.numPackets?t-this.cumulativeResult.firstPacketSentAtMs:0;if(s>1e3){this.cumulativeResult.reset();if(this.congestionCounter<mo){this.congestionCounter++}else if(this.congestionScore<tP){this.congestionScore++}if(this.congestionCounter>=mo&&!this.congestion){this.congestion=true;this.onCongestion.execute(this.congestion)}}for(const n of e.packetResults){if(!n.received)continue;const i=n.sequenceNumber;const o=this.sentInfos.get(i);if(!o)continue;if(!n.receivedAtMs)continue;this.cumulativeResult.addPacket(o.size,o.sendingAtMs,n.receivedAtMs)}if(s>=100&&this.cumulativeResult.numPackets>=20){this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate);this.cumulativeResult.reset();if(this.congestionCounter>-mo){const n=wi(mo/2)+1;const i=wi(mo/4)+1;const o=n-(n-i)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-o}if(this.congestionCounter<=-mo){if(this.congestionScore>1){this.congestionScore--;this.onCongestion.execute(false)}this.congestionCounter=0}if(this.congestionCounter<=0&&this.congestion){this.congestion=false;this.onCongestion.execute(this.congestion)}}}rtpPacketSent(e){this.sentInfos.delete(e.wideSeq-rP&65535);this.sentInfos.set(e.wideSeq,e)}};var Ut=P(\"webrtc/peer/transport/dtls\");var sP=a(()=>void 0,\"ignoreSendFailure\");function nP(r){if(!r){return}if(r.major===254&&r.minor===253){return\"DTLS 1.2\"}if(r.major===254&&r.minor===255){return\"DTLS 1.0\"}}a(nP,\"formatDtlsVersion\");function iP(r){switch(r){case 1:return\"AES_CM_128_HMAC_SHA1_80\";case 7:return\"AEAD_AES_128_GCM\";default:return}}a(iP,\"formatSrtpCipher\");var jc=class r{static{a(this,\"RTCDtlsTransport\")}#e;#t;constructor(e,t,s,n=[]){this.config=e;this.iceTransport=t;this.localCertificate=s;this.srtpProfiles=n;this.id=(0,bo.randomUUID)().toString();this.state=\"new\";this.role=\"auto\";this.srtpStarted=false;this.transportSequenceNumber=0;this.receiverTWCC=new Wf(this);this.senderBWE=new Xf;this.bytesSent=0;this.bytesReceived=0;this.packetsSent=0;this.packetsReceived=0;this.dataReceiver=()=>{};this.onStateChange=new O;this.onRtcp=new O;this.onRtp=new O;this.events=new kt;this.addEventListener=(i,o,c)=>{this.events.addEventListener(i,o,c)};this.removeEventListener=(i,o)=>{this.events.removeEventListener(i,o)};this.dispatchEvent=i=>this.events.dispatchEvent(i);this.sendData=async i=>{if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return}if(!this.dtls){throw new Error(\"dtls not established\")}await this.dtls.send(i)};this.localCertificate??=r.localCertificate;this.#e=lP(t.connection)}get localParameters(){return new yo(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){if(this.localCertificate){return this.localCertificate}if(this.localCertificatePromise){return this.localCertificatePromise}this.localCertificatePromise=(async()=>{const{certPem:e,keyPem:t,signatureHash:s}=await Hr.createSelfSignedCertificateWithKey({signature:Tt.ecdsa_3,hash:Ku.sha256_4},jr.secp256r1_23);this.localCertificate=new $c(t,e,s);return this.localCertificate})();return this.localCertificatePromise}setRemoteParams(e){const t=oP([...this.remoteParameters?.fingerprints??[],...e.fingerprints]);const s=e.role===\"auto\"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new yo(t,s)}async start(){if(this.#t){return await this.#t}if(this.state!==\"new\"){throw new Error(\"state must be new\")}this.#t=this.#r();await this.#t}async#r(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}if(this.role===\"auto\"){if(this.iceTransport.role===\"controlling\"){this.role=\"server\"}else{this.role=\"client\"}}this.setState(\"connecting\");await new Promise((e,t)=>{if(this.role===\"server\"){this.dtls=new _c({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true,certificateRequest:true})}else{this.dtls=new eo({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true})}this.dtls.onData.subscribe(s=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}this.dataReceiver(s)});this.dtls.onClose.subscribe(()=>{if(this.state!==\"failed\"){this.setState(\"closed\")}});this.dtls.onConnect.once(e);this.dtls.onError.once(s=>{this.setState(\"failed\");Ut(\"dtls failed\",s);t(s)});if(this.dtls instanceof eo){this.dtls.connect().catch(s=>{this.setState(\"failed\");Ut(\"dtls connect failed\",s);t(s)})}});try{this.verifyRemoteCertificateFingerprint()}catch(e){this.setState(\"failed\");this.dtls?.close();throw e}if(this.srtpProfiles.length>0){this.startSrtp()}this.setState(\"connected\");Ut(\"dtls connected\")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}const e=this.dtls?.remoteCertificate;if(!e){throw new Error(\"remote certificate not available\")}const t=this.remoteParameters.fingerprints.flatMap(({algorithm:c,value:l})=>{const u=Qm(c);if(!u){return[]}const f=zf(l);if(!f){throw new Error(\"remote fingerprint value is empty\")}return[{normalizedAlgorithm:u,normalizedValue:f}]});if(t.length===0){throw new Error(\"no supported remote fingerprint algorithms\")}const s=cP(t);const n=t.filter(({normalizedAlgorithm:c})=>c===s);const i=n.reduce((c,{normalizedAlgorithm:l})=>{if(!c.has(l)){c.set(l,zf(Zm(e,l)))}return c},new Map);const o=n.some(({normalizedAlgorithm:c,normalizedValue:l})=>i.get(c)===l);if(!o){throw new Error(\"remote certificate fingerprint mismatch\")}}updateSrtpSession(){if(!this.dtls)throw new Error;const e=this.dtls.srtp.srtpProfile;if(!e){throw new Error(\"need srtpProfile\")}Ut(\"selected SRTP Profile\",e);const{localKey:t,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(lE(e),uE(e));const o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new Ou(o);this.srtcp=new Au(o)}startSrtp(){if(this.srtpStarted)return;this.srtpStarted=true;this.updateSrtpSession();this.iceTransport.connection.onData.subscribe(e=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}if(!hE(e))return;this.bytesReceived+=e.length;this.packetsReceived++;if(mE(e)){let t;try{t=this.srtcp.decrypt(e)}catch(n){if(n instanceof Nt){Ut(\"dropping invalid SRTCP packet\",n);return}throw n}let s;try{s=bu.deSerialize(t)}catch(n){Ut(\"dropping malformed SRTCP packet\",n);return}for(const n of s){try{if(n instanceof nt&&n.feedback instanceof Mr){this.senderBWE.receiveTWCC(n.feedback);continue}this.onRtcp.execute(n)}catch(i){Ut(\"RTCP error\",i)}}}else{let t;try{t=this.srtp.decrypt(e)}catch(n){if(n instanceof Nt){Ut(\"dropping invalid SRTP packet\",n);return}throw n}let s;try{s=Le.deSerialize(t)}catch(n){Ut(\"dropping malformed SRTP packet\",n);return}try{this.onRtp.execute(s)}catch(n){Ut(\"RTP error\",n)}}})}async sendRtp(e,t){try{const s=this.srtp.encrypt(e,t);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return s.length}this.bytesSent+=s.length;this.packetsSent++;await this.iceTransport.connection.send(s).catch(sP);return s.length}catch(s){Ut(\"failed to send\",s);return 0}}async sendRtcp(e){if(!this.srtcp){return}const t=Buffer.concat(e.map(n=>n.serialize()));const s=this.srtcp.encrypt(t);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return s.length}this.bytesSent+=s.length;this.packetsSent++;await this.iceTransport.connection.send(s).catch(()=>{})}setState(e,t=true){if(e!=this.state){this.state=e;if(e===\"closed\"||e===\"failed\")this.receiverTWCC.stop();this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}async stop(){this.setState(\"closed\",false);this.dtls?.close();await this.iceTransport.stop()}async getStats(e=Qe()){const t=[];const s=ue(\"transport\",this.id);const n={type:\"transport\",id:s,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===\"unknown\"?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?ue(\"candidate-pair\",this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?ue(\"certificate\",this.id,\"local\"):void 0,remoteCertificateId:this.dtls?.remoteCertificate?ue(\"certificate\",this.id,\"remote\"):void 0,dtlsRole:this.role===\"auto\"?void 0:this.role,tlsVersion:nP(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:iP(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};t.push(n);if(this.localCertificate){const o=this.localCertificate.getFingerprints();if(o.length>0){const c={type:\"certificate\",id:ue(\"certificate\",this.id,\"local\"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(\"base64\")};t.push(c)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){const o={type:\"certificate\",id:ue(\"certificate\",this.id,\"remote\"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(\"base64\")};t.push(o)}const i=await this.iceTransport.getStats(e,s);t.push(...i);return t}};var $c=class{static{a(this,\"RTCCertificate\")}constructor(e,t,s){this.certPem=t;this.signatureHash=s;this.publicKey=new bo.X509Certificate(t).publicKey.export({type:\"spki\",format:\"pem\"});this.privateKey=(0,bo.createPrivateKey)(e).export({type:\"pkcs8\",format:\"pem\"})}getFingerprints(){return[new go(\"sha-256\",Zm(Ju(this.certPem),\"sha256\"))]}};var go=class{static{a(this,\"RTCDtlsFingerprint\")}constructor(e,t){this.algorithm=e;this.value=t}};var yo=class{static{a(this,\"RTCDtlsParameters\")}constructor(e=[],t){this.fingerprints=e;this.role=t}};var oP=a(r=>{const e=new Set;return r.filter(({algorithm:t,value:s})=>{const n=`${Qm(t)??t.trim().toLowerCase()}:${zf(s)}`;if(e.has(n)){return false}e.add(n);return true})},\"deduplicateFingerprints\");var aP=[\"sha512\",\"sha384\",\"sha256\",\"sha224\",\"sha1\"];var cP=a(r=>{return aP.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm},\"selectPreferredFingerprintAlgorithm\");var sg=class{static{a(this,\"IceTransport\")}#e;#t;constructor(e){this.ice=e;this.closed=false;this.#e=[];this.type=\"ice\";this.send=t=>{return this.ice.send(t)};e.onData.subscribe(t=>{if(!yR(t))return;if(this.#t)this.#t(t);else if(this.#e&&this.#e.length<16)this.#e.push(t)})}get onData(){return this.#t??(()=>void 0)}set onData(e){const t=this.#e;if(!t){this.#t=e;return}queueMicrotask(()=>{this.#e=void 0;this.#t=e;t.forEach(s=>e(s))})}get address(){return{}}async close(){this.closed=true;Ne(()=>this.ice.close(),e=>Ut(\"close failed\",e))}};var lP=a(r=>new sg(r),\"createIceTransport\");var _R=require(\"node:crypto\");var Yf=P(\"webrtc/peer/transport/ice\");function uP(r){switch(r){case 0:return\"frozen\";case 1:return\"waiting\";case 2:return\"in-progress\";case 3:return\"succeeded\";case 4:return\"failed\";default:return\"failed\"}}a(uP,\"mapCandidatePairState\");var Jf=class{static{a(this,\"RTCIceTransport\")}constructor(e){this.iceGather=e;this.id=(0,_R.randomUUID)().toString();this.state=\"new\";this.component=\"rtp\";this.iceRestarts=0;this.renominating=false;this.events=new kt;this.onStateChange=new O;this.onIceCandidate=new O;this.onNegotiationNeeded=new O;this.addEventListener=(t,s,n)=>{this.events.addEventListener(t,s,n)};this.removeEventListener=(t,s)=>{this.events.removeEventListener(t,s)};this.dispatchEvent=t=>this.events.dispatchEvent(t);this.addRemoteCandidate=async t=>{if(!this.connection.remoteCandidatesEnd){await this.connection.addRemoteCandidate(t?fP(t):void 0)}};this.connection=this.iceGather.connection;this.connection.stateChanged.subscribe(t=>{this.setState(t)});this.iceGather.onIceCandidate=t=>{this.onIceCandidate.execute(t)};this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.();this.events.emit(\"gatheringstatechange\")})}get role(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return\"unknown\"}if(this.connection.iceControlling)return\"controlling\";else return\"controlled\"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==\"prflx\").map(e=>Yr(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>Yr(e).toJSON())}getSelectedCandidatePair(){const e=this.connection.candidatePairs.find(t=>t.nominated)??this.connection.candidatePairs.find(t=>t.state===3);if(!e){return null}return{local:Yr(e.localCandidate).toJSON(),remote:Yr(e.remoteCandidate).toJSON()}}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return null}return new So({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=true){if(e!==this.state){this.state=e;this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}gather(){return this.iceGather.gather()}setIceServers(e){this.iceGather.setIceServers(e)}setRemoteParams(e,t=false){if(t){this.renominating=true}if(this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)){if(this.renominating){Yf(\"renomination\",e);this.connection.resetNominatedPair();this.checking=void 0;this.renominating=false}else{Yf(\"restart\",e);this.restart()}}this.connection.setRemoteParams(e)}restart(){this.iceRestarts++;this.connection.restart().catch(e=>Yf(\"restart failed\",e));this.setState(\"new\");this.iceGather.setGatheringState(\"new\");this.checking=void 0;this.onNegotiationNeeded.execute()}async start(){if(this.state===\"closed\"){throw new Error(\"RTCIceTransport is closed\")}if(!this.connection.remotePassword||!this.connection.remoteUsername){throw new Error(\"remoteParams missing\")}this.checking??=this.check();await this.checking}async check(){this.setState(\"checking\");try{await this.connection.connect()}catch(e){if(this.state!==\"closed\")this.setState(\"failed\");throw e}}async stop(){if(this.state!==\"closed\"){this.setState(\"closed\",false);await this.connection.close()}this.onStateChange.complete();this.onIceCandidate.complete();this.onNegotiationNeeded.complete()}async getStats(e=Qe(),t=ue(\"transport\",this.id)){const s=[];for(const i of this.connection.localCandidates){const o={type:\"local-candidate\",id:ue(\"local-candidate\",i.id),timestamp:e,transportId:t,address:i.host,port:i.port,protocol:i.transport,candidateType:i.type,priority:i.priority,foundation:i.foundation,relatedAddress:i.relatedAddress,relatedPort:i.relatedPort,usernameFragment:i.ufrag,tcpType:i.tcptype};s.push(o)}for(const i of this.connection.remoteCandidates){const o={type:\"remote-candidate\",id:ue(\"remote-candidate\",i.id),timestamp:e,transportId:t,address:i.host,port:i.port,protocol:i.transport,candidateType:i.type,priority:i.priority,foundation:i.foundation,relatedAddress:i.relatedAddress,relatedPort:i.relatedPort,usernameFragment:i.ufrag,tcpType:i.tcptype};s.push(o)}const n=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(i=>i.nominated),...this.connection.candidatePairs.filter(i=>!i.nominated)]:[];for(const i of n){const o={type:\"candidate-pair\",id:ue(\"candidate-pair\",i.id),timestamp:e,transportId:t,localCandidateId:ue(\"local-candidate\",i.localCandidate.id),remoteCandidateId:ue(\"remote-candidate\",i.remoteCandidate.id),state:uP(i.state),nominated:i.nominated,packetsSent:i.packetsSent,packetsReceived:i.packetsReceived,bytesSent:i.bytesSent,bytesReceived:i.bytesReceived,currentRoundTripTime:i.rtt,totalRoundTripTime:i.totalRoundTripTime,roundTripTimeMeasurements:i.roundTripTimeMeasurements,requestsReceived:i.requestsReceived,requestsSent:i.requestsSent,responsesReceived:i.responsesReceived,responsesSent:i.responsesSent,retransmissionsReceived:i.retransmissionsReceived,retransmissionsSent:i.retransmissionsSent,consentRequestsSent:i.consentRequestsSent};s.push(o)}return s}};var Zf=class{static{a(this,\"RTCIceGatherer\")}constructor(e={}){this.options=e;this.onIceCandidate=()=>{};this.gatheringState=\"new\";this.onGatheringStateChange=new O;this.connection=new jf(false,this.options);this.connection.onIceCandidate.subscribe(t=>{this.onIceCandidate(Yr(t))})}async gather(){if(this.gatheringState===\"new\"){this.setState(\"gathering\");await this.connection.gatherCandidates();this.onIceCandidate(void 0);this.setState(\"complete\")}}setIceServers(e){this.connection.setIceServers(e)}setGatheringState(e){this.setState(e)}get localCandidates(){return this.connection.localCandidates.map(Yr)}get localParameters(){const e=new So({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword});return e}setState(e){if(e!==this.gatheringState){this.gatheringState=e;this.onGatheringStateChange.execute(e)}}};function Yr(r){const e=new Fc(r.component,r.foundation,r.host,r.port,r.priority,r.transport,r.type,r.generation,r.ufrag);e.relatedAddress=r.relatedAddress;e.relatedPort=r.relatedPort;e.tcpType=r.tcptype;return e}a(Yr,\"candidateFromIce\");function fP(r){return new it(r.foundation,r.component,r.protocol,r.priority,r.ip,r.port,r.type,r.relatedAddress,r.relatedPort,r.tcpType,r.generation,r.ufrag)}a(fP,\"candidateToIce\");var ng=class{static{a(this,\"RTCIceCandidate\")}constructor(e){Object.assign(this,e)}static fromSdp(e){const t=it.fromSdp(e);const s=Yr(t);return s.toJSON()}static isThis(e){if(typeof e?.candidate===\"string\")return true}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};var Fc=class{static{a(this,\"IceCandidate\")}constructor(e,t,s,n,i,o,c,l,u){this.component=e;this.foundation=t;this.ip=s;this.port=n;this.priority=i;this.protocol=o;this.type=c;this.generation=l;this.ufrag=u}toJSON(){return new ng({candidate:ig(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate){throw new Error(\"candidate is required\")}const t=e.candidate.startsWith(\"candidate:\")?e.candidate.slice(\"candidate:\".length):e.candidate;const s=og(t);s.sdpMLineIndex=e.sdpMLineIndex??void 0;s.sdpMid=e.sdpMid??void 0;return s}catch(t){Yf(\"candidate not parsed\",t)}}};var So=class{static{a(this,\"RTCIceParameters\")}constructor(e={}){this.iceLite=false;Object.assign(this,e)}};var AR=require(\"node:crypto\");var CR=require(\"node:crypto\");var Qf=P(\"webrtc/peer/dataChannel\");function vR(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}a(vR,\"getDataChannelMessageSize\");var wo=class extends kt{static{a(this,\"RTCDataChannel\")}constructor(e,t,s=true){super();this.sctp=e;this.parameters=t;this.sendOpen=s;this.statsId=(0,CR.randomUUID)().toString();this.stateChange=new O;this.stateChanged=new O;this.onMessage=new O;this.error=new O;this.bufferedAmountLow=new O;this.bufferedAmountChanged=new O;this.isCreatedByRemote=false;this.readyState=\"connecting\";this.bufferedAmount=0;this._bufferedAmountLowThreshold=0;this.messagesSent=0;this.bytesSent=0;this.messagesReceived=0;this.bytesReceived=0;this.id=this.parameters.id;if(t.negotiated){if(this.id==void 0||this.id<0||this.id>65534){throw new Error(\"ID must be in range 0-65534 if data channel is negotiated out-of-band\")}this.sctp.dataChannelAddNegotiated(this)}else{if(s){this.sendOpen=false;this.sctp.dataChannelOpen(this)}}}get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){if(e<0||e>4294967295){throw new Error(\"bufferedAmountLowThreshold must be in range 0 - 4294967295\")}this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){this.readyState=e;this.stateChange.execute(e);this.stateChanged.execute(e);switch(e){case\"open\":if(this.onopen)Ne(()=>this.onopen(),t=>Qf(\"onopen failed\",t));this.emit(\"open\");break;case\"closed\":if(this.onclose)Ne(()=>this.onclose(),t=>Qf(\"onclose failed\",t));this.emit(\"close\");break;case\"closing\":if(this.onclosing)Ne(()=>this.onclosing(),t=>Qf(\"onclosing failed\",t));break}Qf(\"change state\",e)}}addBufferedAmount(e){const t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e;this.bufferedAmountChanged.execute();if(t){this.bufferedAmountLow.execute();this.emit(\"bufferedamountlow\")}}send(e){const t=this.sctp.datachannelSend(this,e);this.messagesSent++;this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}};var Eo=class{static{a(this,\"RTCDataChannelParameters\")}constructor(e={}){this.label=\"\";this.ordered=true;this.protocol=\"\";this.negotiated=false;Object.assign(this,e)}};var pt=P(\"webrtc/peer/transport/sctp\");var To=65536;var ed=class r{static{a(this,\"RTCSctpTransport\")}constructor(e=5e3,t=To,s={}){this.port=e;this.maxMessageSize=t;this.sctpOptions=s;this.onDataChannel=new O;this.id=(0,AR.randomUUID)().toString();this.bundled=false;this.dataChannels={};this.remoteMaxMessageSize=To;this.dataChannelQueue=[];this.eventDisposer=[];this.datachannelReceive=async(n,i,o)=>{if(i===ro&&o.length>0){pt(\"DCEP\",n,i,o);switch(o[0]){case Em:{if(o.length<12){pt(\"DATA_CHANNEL_OPEN data.length not enough\");return}if(!Object.keys(this.dataChannels).includes(n.toString())){const u=o.readUInt8(1);const f=o.readUInt32BE(4);const d=o.readUInt16BE(8);const h=o.readUInt16BE(10);let p=12;const m=o.slice(p,p+d).toString(\"utf8\");p+=d;const y=o.slice(p,p+h).toString(\"utf8\");pt(\"DATA_CHANNEL_OPEN\",{channelType:u,reliability:f,streamId:n,label:m,protocol:y});const w=(u&3)===1?f:void 0;const S=(u&3)===2?f:void 0;const T=new Eo({label:m,ordered:(u&128)===0,maxPacketLifeTime:S,maxRetransmits:w,protocol:y,id:n});const _=new wo(this,T,false);_.isCreatedByRemote=true;this.dataChannels[n]=_;this.onDataChannel.execute(_);_.setReadyState(\"open\")}else{pt(\"datachannel already opened\",\"retransmit ack\")}const c=this.dataChannels[n];const l=Buffer.allocUnsafe(1);l.writeUInt8(wm,0);this.dataChannelQueue.push([c,ro,l]);await this.dataChannelFlush()}break;case wm:{pt(\"DATA_CHANNEL_ACK\",n,i);const c=this.dataChannels[n];if(!c){throw new Error(\"channel not found\")}c.setReadyState(\"open\")}break}}else{const c=this.dataChannels[n];if(c){const l=(()=>{switch(i){case Tm:return o.toString(\"utf8\");case Tf:return\"\";case xm:return o;case xf:return Buffer.from([]);default:throw new Error}})();c.messagesReceived++;c.bytesReceived+=o.length;c.onMessage.execute(l);c.emit(\"message\",{data:l});if(c.onmessage){Ne(()=>c.onmessage({data:l}),u=>pt(\"onmessage failed\",u))}}}};this.datachannelSend=(n,i)=>{const o=vR(i);this.assertSendableMessageSize(o);n.addBufferedAmount(o);if(o===0){this.dataChannelQueue.push([n,typeof i===\"string\"?Tf:xf,Buffer.from([0])])}else{const c=Buffer.isBuffer(i)?i:Buffer.from(i);this.dataChannelQueue.push(typeof i===\"string\"?[n,Tm,c]:[n,xm,c])}if(this.sctp.associationState!==Q.ESTABLISHED){pt(\"sctp not established\",this.sctp.associationState)}this.dataChannelFlush().catch(c=>pt(\"flush failed\",c));return o}}get transport(){return this.dtlsTransport}setDtlsTransport(e){if(this.dtlsTransport&&this.dtlsTransport.id===e.id){return}this.eventDisposer.forEach(t=>t());this.dtlsTransport=e;this.sctp=new lc(new ag(this.dtlsTransport),this.port,this.sctpOptions);this.eventDisposer=[...[this.sctp.onReceive.subscribe(Vt(this.datachannelReceive,t=>pt(\"receive failed\",t))),this.sctp.onReconfigStreams.subscribe(t=>{t.forEach(s=>{const n=this.dataChannels[s];if(!n)return;n.setReadyState(\"closing\");n.setReadyState(\"closed\");delete this.dataChannels[s]})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{if(t.negotiated&&t.readyState!==\"open\"){t.setReadyState(\"open\")}});this.dataChannelFlush().catch(t=>pt(\"flush failed\",t))}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.setReadyState(\"closed\")});this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"closed\"){this.sctp.setState(Q.CLOSED)}})].map(t=>t.unSubscribe),()=>this.sctp.onSackReceived=async()=>{},()=>this.sctp.onSent=void 0];this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()};this.sctp.onSent=(t,s,n)=>{if(s===ro||s===Tf||s===xf){return}this.dataChannels[t]?.addBufferedAmount(-n)}}holdReceived(e){this.sctp.holdReceived(e)}releaseReceived(e){this.sctp.releaseReceived(e)}get isServer(){return this.dtlsTransport.iceTransport.role!==\"controlling\"}channelByLabel(e){return Object.values(this.dataChannels).find(t=>t.label===e)}dataChannelAddNegotiated(e){if(e.id==void 0){throw new Error}if(this.dataChannels[e.id]){throw new Error}this.dataChannels[e.id]=e;if(this.sctp.associationState===Q.ESTABLISHED){e.setReadyState(\"open\")}}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=hx;const s=0;let n=0;if(e.maxRetransmits!==null){t=1;n=e.maxRetransmits}else if(e.maxPacketLifeTime!==null){t=2;n=e.maxPacketLifeTime}if(!e.ordered){t|=128}const i=Buffer.allocUnsafe(12);i.writeUInt8(Em,0);i.writeUInt8(t,1);i.writeUInt16BE(s,2);i.writeUInt32BE(n,4);const o=Buffer.from(e.label,\"utf8\");const c=Buffer.from(e.protocol,\"utf8\");i.writeUInt16BE(o.length,8);i.writeUInt16BE(c.length,10);const l=Buffer.concat([i,o,c]);this.dataChannelQueue.push([e,ro,l]);this.dataChannelFlush().catch(u=>pt(\"flush failed\",u))}async dataChannelFlush(){if(this.sctp.associationState!=Q.ESTABLISHED)return;while(this.dataChannelQueue.length>0){const[e,t,s]=this.dataChannelQueue.shift();let n=e.id;if(n===void 0){n=this.dataChannelId;while(Object.keys(this.dataChannels).includes(n.toString())){n+=2}this.dataChannels[n]=e;e.setId(n)}if(t===ro){this.sctp.send(n,t,s,{ordered:true}).catch(i=>pt(\"send dcep failed\",i.message))}else{const i=e.maxPacketLifeTime!==null?Date.now()+e.maxPacketLifeTime/1e3:void 0;this.sctp.send(n,t,s,{expiry:i,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered}).catch(o=>pt(\"send data failed\",o.message))}}this.dataChannelQueue=[]}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize){throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}}getCapabilities(){return r.getCapabilities(this.maxMessageSize)}static getCapabilities(e=To){return new Hc(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??To}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.dataChannelId=this.dtlsTransport.role===\"server\"?1:0;this.sctp.isServer=this.isServer;await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{};await this.sctp.stop()}dataChannelClose(e){if(![\"closing\",\"closed\"].includes(e.readyState)){e.setReadyState(\"closing\");if(this.sctp.associationState===Q.ESTABLISHED){if(!this.sctp.reconfigQueue.includes(e.id)){this.sctp.reconfigQueue.push(e.id)}if(this.sctp.reconfigQueue.length===1){this.sctp.transmitReconfigRequest().catch(t=>pt(\"reconfig failed\",t))}}else{this.dataChannelQueue=this.dataChannelQueue.filter(t=>t[0].id!==e.id);this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id);if(e.id!==void 0){delete this.dataChannels[e.id]}e.setReadyState(\"closed\")}}}};var Hc=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};var ag=class{static{a(this,\"BridgeDtls\")}constructor(e){this.dtls=e;this.send=t=>{return this.dtls.sendData(t)}}set onData(e){this.dtls.dataReceiver=e}close(){}};var Jr=class r{static{a(this,\"SessionDescription\")}constructor(){this.version=0;this.name=\"-\";this.time=\"0 0\";this.group=[];this.extMapAllowMixed=true;this.msidSemantic=[];this.media=[];this.dtlsFingerprints=[]}static parse(e){const[t,s]=dP(e);const n=new r;t.forEach(c=>{if(c.startsWith(\"v=\")){n.version=Number.parseInt(c.slice(2),10)}else if(c.startsWith(\"o=\")){n.origin=c.slice(2)}else if(c.startsWith(\"s=\")){n.name=c.slice(2)}else if(c.startsWith(\"c=\")){n.host=cg(c.slice(2))}else if(c.startsWith(\"t=\")){n.time=c.slice(2)}else if(c.startsWith(\"a=\")){const[l,u]=lg(c);switch(l){case\"fingerprint\":{const[f,d]=u?.split(\" \")||[];n.dtlsFingerprints.push(new go(f,d))}break;case\"ice-lite\":n.iceLite=true;break;case\"ice-options\":n.iceOptions=u;break;case\"ice-pwd\":n.icePassword=u;break;case\"ice-ufrag\":n.iceUsernameFragment=u;break;case\"group\":ug(n.group,u);break;case\"msid-semantic\":ug(n.msidSemantic,u);break;case\"setup\":n.dtlsRole=Cm[u];break;case\"extmap-allow-mixed\":n.extMapAllowMixed=true;break}}});const i=n.group.find(c=>c.semantic===\"BUNDLE\");s.forEach(c=>{const l=c[0];const u=l.match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!u){throw new Error(\"m line not found\")}const f=u[1];const d=u[4].split(\" \");const h=[\"audio\",\"video\"].includes(f)?d.map(y=>Number(y)):void 0;const p=new kn(f,Number.parseInt(u[2]),u[3],h||d);p.dtlsParams=new yo([...n.dtlsFingerprints],n.dtlsRole);p.iceParams=new So({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword});p.iceOptions=n.iceOptions;n.media.push(p);c.slice(1).forEach(y=>{if(y.startsWith(\"c=\")){p.host=cg(y.slice(2))}else if(y.startsWith(\"a=\")){const[w,S]=lg(y);switch(w){case\"candidate\":if(!S)throw new Error;p.iceCandidates.push(og(S));break;case\"end-of-candidates\":p.iceCandidatesComplete=true;break;case\"extmap\":{let[T,_]=S.split(\" \");if(T.includes(\"/\")){[T]=T.split(\"/\")}p.rtp.headerExtensions.push(new Qt({id:Number.parseInt(T),uri:_}))}break;case\"fingerprint\":{if(!S)throw new Error;const[T,_]=S.split(\" \");p.dtlsParams?.fingerprints.push(new go(T,_))}break;case\"ice-options\":p.iceOptions=S;break;case\"ice-pwd\":p.iceParams.password=S;break;case\"ice-ufrag\":p.iceParams.usernameFragment=S;break;case\"ice-lite\":p.iceParams.iceLite=true;break;case\"max-message-size\":p.sctpCapabilities=new Hc(Number.parseInt(S,10));break;case\"mid\":p.rtp.muxId=S;break;case\"msid\":p.msids.push(S);break;case\"rtcp\":{const[T,_]=yr(S,\" \");p.rtcpPort=Number.parseInt(T);p.rtcpHost=cg(_)}break;case\"rtcp-mux\":p.rtcpMux=true;break;case\"bundle-only\":p.bundleOnly=true;break;case\"setup\":p.dtlsParams.role=Cm[S];break;case\"recvonly\":case\"sendonly\":case\"sendrecv\":case\"inactive\":p.direction=w;break;case\"rtpmap\":{const[T,_]=yr(S,\" \");const[x,k,N]=_.split(\"/\");let A;if(p.kind===\"audio\"){A=N?Number.parseInt(N):1}const B=new ft({mimeType:p.kind+\"/\"+x,channels:A,clockRate:Number.parseInt(k),payloadType:Number.parseInt(T)});p.rtp.codecs.push(B)}break;case\"sctpmap\":{if(!S)throw new Error;const[T,_]=yr(S,\" \");p.sctpMap[Number.parseInt(T)]=_;p.sctpPort=Number.parseInt(T)}break;case\"sctp-port\":if(!S)throw new Error;p.sctpPort=Number.parseInt(S);break;case\"ssrc\":{const[T,_]=yr(S,\" \");const x=Number.parseInt(T);const[k,N]=yr(_,\":\");let A=p.ssrc.find(B=>B.ssrc===x);if(!A){A=new xo({ssrc:x});p.ssrc.push(A)}if(vm.includes(k)){A[k]=N}}break;case\"ssrc-group\":ug(p.ssrcGroup,S);break;case\"rid\":{const[T,_]=yr(S,\" \");p.simulcastParameters.push(new Ii({rid:T,direction:_}))}break}}});if(!p.iceParams.usernameFragment||!p.iceParams.password){if(p.rtp.muxId&&i&&i.items.includes(p.rtp.muxId)){for(let y=0;y<i.items.length;y++){if(!i.items.includes(y.toString()))continue;const w=n.media[y];if(w.iceParams?.usernameFragment&&w.iceParams.password){p.iceParams={...w.iceParams};break}}}}if(!p.dtlsParams.role){p.dtlsParams=void 0}const m=a(y=>p.rtp.codecs.find(w=>w.payloadType===y),\"findCodec\");c.slice(1).forEach(y=>{if(y.startsWith(\"a=\")){const[w,S]=lg(y);if(w===\"fmtp\"){const[T,_]=yr(S,\" \");const x=m(Number(T));x.parameters=_}else if(w===\"rtcp-fb\"){const[T,_,x]=S.split(\" \");p.rtp.codecs.forEach(k=>{if([\"*\",k.payloadType.toString()].includes(T)){k.rtcpFeedback.push(new Lu({type:_,parameter:x}))}})}}})});const o=i?n.media.find(c=>c.rtp.muxId===i.items[0]):void 0;if(i&&o?.port){for(const c of n.media){if(c.port===0&&c.bundleOnly&&c.rtp.muxId&&i.items.includes(c.rtp.muxId))c.port=o.port}}return n}webrtcTrackId(e){if(e.msid?.includes(\" \")){const t=e.msid.split(\" \");for(const s of this.msidSemantic){if(s.semantic===\"WMS\"&&(s.items.includes(t[0])||s.items.includes(\"*\"))){return t[1]}}}return}get string(){const e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];if(this.host){e.push(`c=${fg(this.host)}`)}e.push(`t=${this.time}`);this.group.forEach(n=>e.push(`a=group:${n.str}`));if(this.extMapAllowMixed){e.push(`a=extmap-allow-mixed`)}this.msidSemantic.forEach(n=>e.push(`a=msid-semantic:${n.str}`));const t=this.media.map(n=>n.toString()).join(\"\");const s=e.join(\"\\r\\n\")+\"\\r\\n\"+t;return s}toJSON(){const e=this.string;if(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type){this.cachedJson=new dg(e,this.type)}return this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}};var kn=class{static{a(this,\"MediaDescription\")}constructor(e,t,s,n){this.kind=e;this.port=t;this.profile=s;this.fmt=n;this.msids=[];this.rtcpMux=false;this.bundleOnly=false;this.ssrc=[];this.ssrcGroup=[];this.rtp={codecs:[],headerExtensions:[]};this.sctpMap={};this.iceCandidates=[];this.iceCandidatesComplete=false;this.simulcastParameters=[]}get msid(){return this.msids[0]}set msid(e){this.msids=e?[e]:[]}toString(){const e=[];e.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(t=>t.toString()).join(\" \")}`);if(this.host){e.push(`c=${fg(this.host)}`)}this.iceCandidates.forEach(t=>{e.push(`a=candidate:${ig(t)}`)});if(this.iceCandidatesComplete){e.push(\"a=end-of-candidates\")}if(this.iceParams?.usernameFragment){e.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`)}if(this.iceParams?.password){e.push(`a=ice-pwd:${this.iceParams.password}`)}if(this.iceParams?.iceLite){e.push(`a=ice-lite`)}if(this.iceOptions){e.push(`a=ice-options:${this.iceOptions}`)}if(this.dtlsParams){this.dtlsParams.fingerprints.forEach(t=>{e.push(`a=fingerprint:${t.algorithm} ${t.value}`)});e.push(`a=setup:${Ef[this.dtlsParams.role]}`)}if(this.direction){e.push(`a=${this.direction}`)}if(this.rtp.muxId){e.push(`a=mid:${this.rtp.muxId}`)}this.msids.forEach(t=>e.push(`a=msid:${t}`));if(this.rtcpPort&&this.rtcpHost){e.push(`a=rtcp:${this.rtcpPort} ${fg(this.rtcpHost)}`);if(this.rtcpMux){e.push(\"a=rtcp-mux\")}}this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)});this.ssrc.forEach(t=>{vm.forEach(s=>{const n=t[s];if(n!==void 0){e.push(`a=ssrc:${t.ssrc} ${s}:${n}`)}})});this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`);t.rtcpFeedback.forEach(s=>{let n=s.type;if(s.parameter)n+=` ${s.parameter}`;e.push(`a=rtcp-fb:${t.payloadType} ${n}`)});if(t.parameters){e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)}});Object.keys(this.sctpMap).forEach(t=>{const s=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${s}`)});if(this.sctpPort){e.push(`a=sctp-port:${this.sctpPort}`)}if(this.sctpCapabilities){e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`)}this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`));if(this.simulcastParameters.length){this.simulcastParameters.forEach(i=>{e.push(`a=rid:${i.rid} ${i.direction}`)});let t=`a=simulcast:`;const s=this.simulcastParameters.filter(i=>i.direction===\"recv\");if(s.length){t+=`recv ${s.map(i=>i.rid).join(\";\")} `}const n=this.simulcastParameters.filter(i=>i.direction===\"send\");if(n.length){t+=`send ${n.map(i=>i.rid).join(\";\")}`}e.push(t)}return e.join(\"\\r\\n\")+\"\\r\\n\"}};var ks=class{static{a(this,\"GroupDescription\")}constructor(e,t){this.semantic=e;this.items=t}get str(){return`${this.semantic} ${this.items.join(\" \")}`}};function cg(r){const e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error(\"exception\");return e[2]}a(cg,\"ipAddressFromSdp\");function fg(r){const e=(0,OR.isIPv4)(r)?4:6;return`IN IP${e} ${r}`}a(fg,\"ipAddressToSdp\");function ig(r){let e=`${r.foundation} ${r.component} ${r.protocol} ${r.priority} ${r.ip} ${r.port} typ ${r.type}`;if(r.relatedAddress!=void 0){e+=` raddr ${r.relatedAddress}`}if(r.relatedPort!=void 0){e+=` rport ${r.relatedPort}`}if(r.tcpType!=void 0){e+=` tcptype ${r.tcpType}`}if(r.generation!=void 0){e+=` generation ${r.generation}`}if(r.ufrag!=void 0){e+=` ufrag ${r.ufrag}`}return e}a(ig,\"candidateToSdp\");function dP(r){const e=[];const t=[];let s=r.split(\"\\r\\n\");if(s.length===1){s=r.split(\"\\n\")}s.forEach(n=>{if(n.startsWith(\"m=\")){t.push([n])}else if(t.length>0){t[t.length-1].push(n)}else{e.push(n)}});return[e,t]}a(dP,\"groupLines\");function lg(r){if(r.includes(\":\")){const e=yr(r.slice(2),\":\");return[e[0],e[1]]}else{return[r.slice(2),void 0]}}a(lg,\"parseAttr\");function ug(r,e,t=s=>s.toString()){const s=e.split(\" \");if(s.length>0){r.push(new ks(s[0],s.slice(1).map(t)))}}a(ug,\"parseGroup\");function og(r){const e=it.fromSdp(r);const t=Yr(e);return t}a(og,\"candidateFromSdp\");var dg=class{static{a(this,\"RTCSessionDescription\")}constructor(e,t){Object.defineProperties(this,{sdp:{configurable:true,enumerable:true,value:e,writable:false},type:{configurable:true,enumerable:true,value:t,writable:false}})}static isThis(e){if(typeof e?.sdp===\"string\")return true}toSdp(){return{sdp:this.sdp,type:this.type}}};function hg(r,e){const t=\"-\";const s=(0,IR.randomBytes)(8).readBigUInt64BE(0).toString().slice(0,8);const n=0;e.origin=`${t} ${s} ${n} IN IP4 0.0.0.0`;e.msidSemantic.push(new ks(\"WMS\",[\"*\"]));e.type=r}a(hg,\"addSDPHeader\");function or(r){const e={};r.split(\";\").forEach(t=>{if(t.length===0)return;if(t.includes(\"=\")){const[s,n]=yr(t,\"=\");if(px.includes(s)){e[s]=Number(n)}else{e[s]=n}}else if(t.includes(\":\")){const[s,n]=t.split(\":\");e[s]=Number.isNaN(Number(n))?n:Number(n)}else{e[t]=void 0}});return e}a(or,\"codecParametersFromString\");var xo=class{static{a(this,\"SsrcDescription\")}constructor(e){Object.assign(this,e)}};function zc(r){return r.name.toLowerCase()}a(zc,\"codecName\");function td(r,e){return r==void 0||e==void 0||r===e}a(td,\"optionalEqual\");function kR(r){const e=or(r.parameters??\"\");return{packetizationMode:e[\"packetization-mode\"],profileLevelId:e[\"profile-level-id\"]?.toString().toLowerCase()}}a(kR,\"h264Parameters\");function Ro(r,e){if(r.mimeType.toLowerCase()!==e.mimeType.toLowerCase()){return false}if(r.clockRate!==e.clockRate)return false;if(!td(r.channels,e.channels))return false;if(zc(r)!==\"h264\")return true;const t=kR(r);const s=kR(e);if(!td(t.packetizationMode,s.packetizationMode)){return false}return td(t.profileLevelId,s.profileLevelId)}a(Ro,\"isCodecCompatible\");function Pn(r){return[\"rtx\",\"red\"].includes(zc(r))}a(Pn,\"isAuxiliary\");function rd(r,e,t){if(r!==\"audio\"||e==void 0||zc(e)!==\"red\"){return e}const[s]=pg(e);return t.find(n=>!Pn(n)&&n.payloadType===s)??t.find(n=>!Pn(n))??e}a(rd,\"deliveredTrackCodec\");function PR(r,e){return r.some(t=>!Pn(t)&&e.some(s=>s.mimeType.toLowerCase()===t.mimeType.toLowerCase()))}a(PR,\"hasCommonPrimaryMimeType\");function pg(r){const e=r.parameters??\"\";if(zc(r)===\"rtx\"){const t=Number(or(e).apt);return Number.isNaN(t)?[]:[t]}if(zc(r)===\"red\"){return e.split(\"/\").map(Number).filter(t=>!Number.isNaN(t))}return[]}a(pg,\"referencedPayloadTypes\");function NR(r,e){const t=new Set(e.map(n=>n.payloadType));const s=r.filter(n=>{if(!Pn(n))return false;const i=pg(n);return i.length>0&&i.every(o=>t.has(o))});return r.filter(n=>e.includes(n)||s.includes(n))}a(NR,\"withAuxiliaryCodecs\");function LR(r,e){const t=r.filter(s=>!Pn(s)&&e.some(n=>Ro(n,s)));return NR(r,t)}a(LR,\"intersectCodecs\");function hP(r,e){return r.mimeType.toLowerCase()===e.mimeType.toLowerCase()&&td(r.clockRate,e.clockRate)}a(hP,\"matchesPreference\");function MR(r,e){if(e==void 0)return r;const t=e.flatMap(c=>{const l=r.find(u=>hP(u,c));return l?[l]:[]});const s=[...new Set(t)];const n=new Set(s.filter(Pn).flatMap(pg));const i=r.filter(c=>!Pn(c)&&(s.includes(c)||n.has(c.payloadType)));const o=NR(r,i);return[...s.filter(c=>o.includes(c)),...o.filter(c=>!s.includes(c))]}a(MR,\"applyCodecPreferences\");function mg(r,e,t){return MR(e==void 0?r:LR(r,e),t)}a(mg,\"resolveCodecs\");function qc(r){return r?.map(e=>e.mimeType).join(\", \")||\"(none)\"}a(qc,\"list\");function Nn(r){const{kind:e,configured:t,source:s,preferences:n}=r;const i=s==void 0?t:LR(t,s);if(s!=void 0&&i.length===0){throw ne(\"NotSupportedError\",`Track codec ${qc(s)} is not supported by this RTCPeerConnection. Configured ${e} codecs: ${qc(t)}`)}const o=MR(i,n);if(o.length===0){throw ne(\"NotSupportedError\",`No codec remains after applying codec preferences. Source codecs: ${qc(s)} Configured codecs: ${qc(t)} Preferred codecs: ${qc(n)}`)}return o}a(Nn,\"assertCodecsSupported\");function gg(){return new Qt({uri:pe.sdesMid})}a(gg,\"useSdesMid\");function yg(){return new Qt({uri:pe.transportWideCC})}a(yg,\"useTransportWideCC\");function bg(){return new Qt({uri:pe.absSendTime})}a(bg,\"useAbsSendTime\");function DR(){return new Qt({uri:pe.audioLevelIndication})}a(DR,\"useAudioLevelIndication\");var UR=require(\"node:crypto\");var id=require(\"node:timers/promises\");var pP=P(\"webrtc/peer/media/receiver/nack\");var BR=30*5;var sd=class{static{a(this,\"NackHandler\")}constructor(e){this.receiver=e;this.newEstSeqNum=0;this._lost={};this.onPacketLost=new O;this.retryCount=10;this.closed=false;this.sendNack=()=>new Promise((t,s)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){const n=new Lr({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers});const i=new nt({feedback:n});this.receiver.dtlsTransport.sendRtcp([i]).then(t).catch(s);this.updateRetryCount();this.onPacketLost.execute(n)}})}get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t;if(this.nackLoop||this.closed){return}this.nackLoop=setInterval(Vt(async()=>{await this.sendNack();if(!Object.keys(this._lost).length){clearInterval(this.nackLoop);this.nackLoop=void 0}},s=>pP(\"failed to send nack\",s)),5)}removeLost(e){delete this._lost[e]}addPacket(e){const{sequenceNumber:t,ssrc:s}=e.header;this.mediaSourceSsrc=s;if(this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===$e(this.newEstSeqNum,1)){this.newEstSeqNum=t}else if(t>$e(this.newEstSeqNum,1)){for(let n=$e(this.newEstSeqNum,1);n<t;n=$e(n,1)){this.setLost(n,1)}this.newEstSeqNum=t;this.pruneLost()}}pruneLost(){if(this.lostSeqNumbers.length>BR){this._lost=Object.entries(this._lost).slice(-BR).reduce((e,[t,s])=>{e[t]=s;return e},{})}}close(){this.closed=true;clearInterval(this.nackLoop);this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{const t=this._lost[e]++;if(t>this.retryCount){this.removeLost(e);return e}})}};var nd=class{static{a(this,\"StreamStatistics\")}constructor(e){this.cycles=0;this.packets_received=0;this.bytesReceived=0;this.headerBytesReceived=0;this.jitter_q4=0;this.expected_prior=0;this.received_prior=0;this.clockRate=e}add(e,t=Date.now()/1e3){const s=this.max_seq==void 0||lu(e.header.sequenceNumber,this.max_seq);this.packets_received++;this.bytesReceived+=e.payload.length;this.headerBytesReceived+=e.header.serializeSize;this.lastPacketReceivedTimestamp=Qe();if(this.base_seq==void 0){this.base_seq=e.header.sequenceNumber}if(s){const n=_s(t*this.clockRate);if(this.max_seq!=void 0&&e.header.sequenceNumber<this.max_seq){this.cycles+=1<<16}this.max_seq=e.header.sequenceNumber;if(e.header.timestamp!==this.last_timestamp&&this.packets_received>1){const i=Math.abs(n-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=i-(this.jitter_q4+8>>4)}this.last_arrival=n;this.last_timestamp=e.header.timestamp}}get fraction_lost(){const e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;const t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;const s=e-t;if(e==0||s<=0){return 0}else{return Math.floor((s<<8)/e)}}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){const e=this.packets_expected-this.packets_received;return e<0?0:e}};var _o=P(\"webrtc/peer/media/rtpReceiver\");var Co=class{static{a(this,\"RTCRtpReceiver\")}get codecArray(){this.sortedCodecs??=Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType);return this.sortedCodecs}constructor(e,t,s){this.config=e;this.kind=t;this.rtcpSsrc=s;this.codecs={};this.ssrcByRtx={};this.nack=new sd(this);this.audioRedHandler=new Eu;this.type=\"receiver\";this.uuid=(0,UR.randomUUID)().toString();this.tracks=[];this.trackBySSRC={};this.trackByRID={};this.lastSRtimestamp={};this.receiveLastSRTimestamp={};this.onPacketLost=this.nack.onPacketLost;this.onRtcp=new O;this.stopped=false;this.remoteStreamIds=[];this.rtcpRunning=false;this.rtcpCancel=new AbortController;this.remoteStreams={};this.senderReportsReceivedBySsrc={};this.remoteTimestampsBySsrc={};this.remotePacketCountBySsrc={};this.remoteOctetCountBySsrc={};this.nackCountBySsrc={};this.pliCountBySsrc={};this.handleRtpBySsrc=(n,i)=>{const o=this.trackBySSRC[n.header.ssrc];this.handleRTP(n,i,o)};this.handleRtpByRid=(n,i,o)=>{const c=this.trackByRID[i];if(!this.trackBySSRC[n.header.ssrc]){this.trackBySSRC[n.header.ssrc]=c}this.handleRTP(n,o,c)};this.defaultTrack=new Zt({kind:t,remote:true});this.onPacketLost.subscribe(n=>{this.nackCountBySsrc[n.mediaSourceSsrc]=(this.nackCountBySsrc[n.mediaSourceSsrc]??0)+1})}get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===\"nack\")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===Nu().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===an().type)}prepareReceive(e){e.codecs.forEach(t=>{this.codecs[t.payloadType]=t});this.sortedCodecs=void 0;e.encodings.forEach(t=>{if(t.rtx){this.ssrcByRtx[t.rtx.ssrc]=t.ssrc}})}resyncCodecs(e){for(const s of Object.keys(this.codecs)){delete this.codecs[Number(s)]}this.sortedCodecs=void 0;for(const s of Object.keys(this.ssrcByRtx)){delete this.ssrcByRtx[Number(s)]}this.prepareReceive(e);const t=rd(this.kind,e.codecs[0],e.codecs);if(t){for(const s of this.tracks){s.codec=t}}}addTrack(e){const t=this.tracks.find(s=>{if(s.rid){return s.rid===e.rid}if(s.ssrc){return s.ssrc===e.ssrc}});if(t){return false}this.tracks.push(e);if(e.ssrc){this.trackBySSRC[e.ssrc]=e}if(e.rid){this.trackByRID[e.rid]=e}return true}stop(){this.stopped=true;this.rtcpRunning=false;this.rtcpCancel.abort();this.nack.close()}endTracks(){for(const e of[...this.tracks,this.defaultTrack]){e.stop()}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,id.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=Object.entries(this.remoteStreams).map(([s,n])=>{let i=0,o=0;if(this.lastSRtimestamp[s]){i=this.lastSRtimestamp[s];const c=po()-this.receiveLastSRTimestamp[s];if(c>0&&c<65536){o=_s(c*65536)}}return new rn({ssrc:Number(s),fractionLost:n.fraction_lost,packetsLost:n.packets_lost,highestSequence:n.max_seq,jitter:n.jitter,lsr:i,dlsr:o})});const t=new Yt({ssrc:this.rtcpSsrc,reports:e});try{if(this.config.debug.receiverReportDelay){await(0,id.setTimeout)(this.config.debug.receiverReportDelay)}await this.dtlsTransport.sendRtcp([t])}catch(s){_o(\"sendRtcp failed\",s);await(0,id.setTimeout)(500+Math.random()*1e3)}}}catch(e){_o(\"rtcp loop ended\",e)}}getInboundRtpStatsId(e){return ue(\"inbound-rtp\",e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return ue(\"remote-outbound-rtp\",e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e?true:t===e).filter(t=>t.ssrc).map(t=>this.getInboundRtpStatsId(t))}collectStats(e){const t=[];const s=this.dtlsTransport?ue(\"transport\",this.dtlsTransport.id):void 0;const n=this.codecArray[0];const i=new Set;for(const o of this.tracks){if(!o.ssrc)continue;const c=this.remoteStreams[o.ssrc];const l=this.remoteTimestampsBySsrc[o.ssrc]!==void 0;const u=this.lastSRtimestamp[o.ssrc]!==void 0||l?this.getRemoteOutboundRtpStatsId(o):void 0;const f=n&&s?fo(s,n.payloadType,o.id??o.uuid):void 0;if(n&&s&&f&&!i.has(f)){i.add(f);const h={type:\"codec\",id:f,timestamp:e,payloadType:n.payloadType,transportId:s,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,sdpFmtpLine:n.parameters};t.push(h)}const d={type:\"inbound-rtp\",id:this.getInboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:f,mid:this.sdesMid,trackIdentifier:o.id??o.uuid,packetsReceived:c?.packets_received??0,bytesReceived:c?.bytesReceived??0,headerBytesReceived:c?.headerBytesReceived??0,packetsLost:c?.packets_lost??0,jitter:c?.clockRate?c.jitter/c.clockRate:void 0,lastPacketReceivedTimestamp:c?.lastPacketReceivedTimestamp,remoteId:u,nackCount:this.nackCountBySsrc[o.ssrc]||void 0,pliCount:this.pliCountBySsrc[o.ssrc]||void 0};t.push(d);if(u){const h={type:\"remote-outbound-rtp\",id:this.getRemoteOutboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:d.codecId,localId:d.id,remoteTimestamp:this.remoteTimestampsBySsrc[o.ssrc],reportsSent:this.senderReportsReceivedBySsrc[o.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[o.ssrc],bytesSent:this.remoteOctetCountBySsrc[o.ssrc]};t.push(h)}}return t}async getStats(){const e=Qe();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return On(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){_o(\"pli not supported\",{mediaSsrc:e});return}if(this.stopped){return}_o(\"sendRtcpPLI\",{mediaSsrc:e});const t=new Xt({feedback:new Pr({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1;await this.dtlsTransport.sendRtcp([t])}catch(s){_o(s)}}handleRtcpPacket(e){switch(e.type){case Pt.type:{const t=e;this.lastSRtimestamp[t.ssrc]=Kf(t.senderInfo.ntpTimestamp);this.receiveLastSRTimestamp[t.ssrc]=po();this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1;this.remoteTimestampsBySsrc[t.ssrc]=ER(t.senderInfo.ntpTimestamp);this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount;this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;const s=this.trackBySSRC[e.ssrc];if(s){s.onReceiveRtcp.execute(e)}}break}this.onRtcp.execute(e)}handleRTP(e,t,s){if(this.stopped){return}const n=this.codecs[e.header.payloadType];if(!n){return}this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new nd(n.clockRate);this.remoteStreams[e.header.ssrc].add(e);if(this.twccEnabled){const o=t[pe.transportWideCC];if(o!==void 0){this.dtlsTransport.receiverTWCC.handleTWCC(o,e.header.ssrc)}}if(n.name.toLowerCase()===\"rtx\"){const o=this.ssrcByRtx[e.header.ssrc];const c=or(n.parameters??\"\");const l=this.codecs[c[\"apt\"]];if(e.payload.length<2)return;e=_E(e,l.payloadType,o);s=this.trackBySSRC[o]}let i;if(n.name.toLowerCase()===\"red\"){i=Ti.deSerialize(e.payload);if(!Object.keys(this.codecs).includes(i.header.fields[0].blockPT.toString())){return}}if(s?.kind===\"video\"&&this.nackEnabled){this.nack.addPacket(e)}if(s){if(i){if(s.kind===\"audio\"){const o=this.audioRedHandler.push(i,e);for(const c of o){s.onReceiveRtp.execute(c.clone(),t)}}}else{s.onReceiveRtp.execute(e.clone(),t)}}this.runRtcp().catch(o=>_o(\"rtcp failed\",o))}};var Gc=P(\"webrtc/peer/media/router\");var od=class{static{a(this,\"RtpRouter\")}constructor(){this.ssrcTable={};this.ridTable={};this.extIdUriMap={};this.routeRtp=e=>{const t=gE(e.header.extensions,this.extIdUriMap);let s=this.ssrcTable[e.header.ssrc];const n=t[pe.sdesRTPStreamID];if(typeof n===\"string\"){s=this.ridTable[n];if(s){s.latestRid=n;s.handleRtpByRid(e,n,t)}}else if(s){s.handleRtpBySsrc(e,t)}else{s=Object.values(this.ridTable).filter(c=>c instanceof Co).find(c=>c.trackBySSRC[e.header.ssrc]);if(s){Gc(\"simulcast register receiver by ssrc\",e.header.ssrc);this.registerRtpReceiver(s,e.header.ssrc);s.handleRtpBySsrc(e,t)}else{}}if(!s){Gc(\"ssrcReceiver not found\");return}const i=t[pe.sdesMid];if(typeof i===\"string\"){s.sdesMid=i}const o=t[pe.repairedRtpStreamId];if(typeof o===\"string\"){s.latestRepairedRid=o}};this.routeRtcp=e=>{const t=[];switch(e.type){case Pt.type:{e=e;t.push(this.ssrcTable[e.ssrc])}break;case Yt.type:{e=e;e.reports.forEach(s=>{t.push(this.ssrcTable[s.ssrc])})}break;case Dr.type:break;case nt.type:{const s=e;if(s.feedback){t.push(this.ssrcTable[s.feedback.mediaSourceSsrc])}}break;case Xt.type:{const s=e;switch(s.feedback.count){case Nr.count:{const n=s.feedback;t.push(this.ssrcTable[n.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[s.feedback.mediaSsrc]||this.ssrcTable[s.feedback.senderSsrc])}}break}t.filter(s=>s).forEach(s=>s.handleRtcpPacket(e))}}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){Gc(\"registerRtpReceiver\",t);this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){Gc(\"registerRtpReceiverBySsrc\",t);t.encodings.filter(s=>s.ssrc!=void 0).forEach((s,n)=>{this.registerRtpReceiver(e.receiver,s.ssrc);e.addTrack(new Zt({ssrc:s.ssrc,kind:e.kind,id:e.sender.trackId,remote:true,codec:rd(e.kind,t.codecs[n],t.codecs)}));if(s.rtx){this.registerRtpReceiver(e.receiver,s.rtx.ssrc)}});t.headerExtensions.forEach(s=>{this.extIdUriMap[s.id]=s.uri})}registerRtpReceiverByRid(e,t,s){const[n]=s.codecs;Gc(\"registerRtpReceiverByRid\",t);e.addTrack(new Zt({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:true,codec:n}));this.ridTable[t.rid]=e.receiver}unregisterTransceiver(e){const t=[e.sender,e.receiver];for(const[s,n]of Object.entries(this.ssrcTable)){if(t.includes(n)){delete this.ssrcTable[Number(s)]}}for(const[s,n]of Object.entries(this.ridTable)){if(t.includes(n)){delete this.ridTable[s]}}}};var Kc=require(\"node:crypto\");var wg=require(\"node:timers/promises\");var ad=class{static{a(this,\"SDPManager\")}constructor({cname:e,midSuffix:t,bundlePolicy:s,mLineReuse:n}){this.seenMid=new Set;this.cname=e;this.midSuffix=t??false;this.bundlePolicy=s;this.mLineReuse=n??\"compatible\"}get localDescription(){if(!this._localDescription){return void 0}return this._localDescription.toJSON()}get remoteDescription(){if(!this._remoteDescription){return void 0}return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(e=>e.direction===\"inactive\")}createMediaDescriptionForTransceiver(e,t){const s=new kn(e.kind,9,\"UDP/TLS/RTP/SAVPF\",e.codecs.map(n=>n.payloadType));s.direction=t;s.msids=e.msids;s.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0};s.rtcpHost=\"0.0.0.0\";s.rtcpPort=9;s.rtcpMux=true;s.ssrc=[new xo({ssrc:e.sender.ssrc,cname:this.cname})];if(e.options.simulcast){s.simulcastParameters=e.options.simulcast.map(n=>new Ii(n))}if(s.rtp.codecs.find(n=>n.name.toLowerCase()===\"rtx\")){s.ssrc.push(new xo({ssrc:e.sender.rtxSsrc,cname:this.cname}));s.ssrcGroup=[new ks(\"FID\",[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]}this.addTransportDescription(s,e.dtlsTransport);return s}createRejectedMediaDescription(e,t){const s=e.fmt[0]??e.codecs[0]?.payloadType??0;const n=new kn(e.kind,0,e.profile,[s]);n.host=Rm;n.direction=\"inactive\";n.rtp={codecs:e.codecs.filter(i=>i.payloadType?.toString()===s.toString()),headerExtensions:[],muxId:e.mid};n.rtcpMux=true;if(t){n.iceParams=t.iceTransport.localParameters;n.dtlsParams=t.localParameters}return n}createMediaDescriptionForSctp(e){const t=new kn(\"application\",_m,\"UDP/DTLS/SCTP\",[\"webrtc-datachannel\"]);t.sctpPort=e.port;t.rtp.muxId=e.mid;t.sctpCapabilities=e.getCapabilities();this.addTransportDescription(t,e.dtlsTransport);return t}addTransportDescription(e,t){const s=t.iceTransport;e.iceCandidates=s.localCandidates;e.iceCandidatesComplete=s.gatheringState===\"complete\";e.iceParams=s.localParameters;e.iceOptions=\"trickle\";e.host=Rm;e.port=_m;if(e.direction===\"inactive\"){if(this.mLineReuse===\"aggressive\"){e.port=0}e.msids=[]}if(!e.dtlsParams){e.dtlsParams=t.localParameters;if(!e.dtlsParams.fingerprints){e.dtlsParams.fingerprints=t.localParameters.fingerprints}}}allocateMid(e=\"\"){let t;for(let s=0;;){t=(s++).toString()+e;if(!this.seenMid.has(t))break}this.seenMid.add(t);return t}parseSdp({sdp:e,isLocal:t,signalingState:s,type:n}){const i=Jr.parse(e);this.validateDescription({description:i,isLocal:t,signalingState:s,type:n});i.type=n;return i}validateDescription({isLocal:e,signalingState:t,type:s}){if(e){if(s===\"offer\"){if(![\"stable\",\"have-local-offer\"].includes(t))throw ne(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}else{if(s===\"offer\"){if(![\"stable\",\"have-remote-offer\",\"have-local-offer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-local-offer\",\"have-remote-pranswer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}}buildOfferSdp(e,t){const s=new Jr;hg(\"offer\",s);const n=this.findLiveDtlsTransport(e,t);const i=this.currentLocalDescription?.media??[];const o=new Set;i.forEach((c,l)=>{const u=c.rtp.muxId;if(!u){return}if(c.kind===\"application\"){if(!t){throw new Error(\"sctpTransport not found\")}t.mLineIndex=l;s.media.push(this.createMediaDescriptionForSctp(t))}else{const f=e.find(d=>d.mid===u);if(!f){o.add(l);s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:u},n));return}f.mLineIndex=l;if(f.stopping||f.stopped){s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:u},this.liveTransportOr(f.dtlsTransport,n)));return}s.media.push(this.createMediaDescriptionForTransceiver(f,f.direction))}});for(const c of e.filter(l=>!l.stopping&&!l.stopped&&!s.media.find(u=>u.rtp.muxId===l.mid))){if(c.mid==void 0){c.mid=this.allocateMid(this.midSuffix?\"av\":\"\")}const l=this.createMediaDescriptionForTransceiver(c,c.direction);const u=c.mLineIndex;if(u!=void 0&&o.has(u)&&s.media[u]?.kind===c.kind){o.delete(u);s.media[u]=l}else{c.mLineIndex=s.media.length;s.media.push(l)}}if(t&&!s.media.find(c=>c.kind===\"application\")){t.mLineIndex=s.media.length;if(t.mid==void 0){t.mid=this.allocateMid(this.midSuffix?\"dc\":\"\")}s.media.push(this.createMediaDescriptionForSctp(t))}if(this.bundlePolicy!==\"disable\"){const c=s.media.filter(l=>l.port!==0).map(l=>l.rtp.muxId).filter(l=>l);if(c.length){const l=new ks(\"BUNDLE\",jR(c,this.negotiatedBundleTag));s.group.push(l)}}return s}liveTransportOr(e,t){return e&&e.state!==\"closed\"?e:t}findLiveDtlsTransport(e,t){return[...e.filter(s=>!s.stopped&&!s.pendingRejection).map(s=>s.dtlsTransport),t?.dtlsTransport,...e.map(s=>s.dtlsTransport)].find(s=>!!s&&s.state!==\"closed\")}get negotiatedBundleTag(){const e=[this.currentLocalDescription,this.currentRemoteDescription].find(t=>t?.type===\"answer\");return e?.group.find(t=>t.semantic===\"BUNDLE\")?.items[0]}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:s}){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(s)){throw new Error(\"createAnswer failed\")}if(!this._remoteDescription){throw new Error(\"wrong state\")}const n=new Jr;hg(\"answer\",n);const i=this._remoteDescription;const o=this.findLiveDtlsTransport(e,t);for(const c of i.media){let l;let u;let f=true;if([\"audio\",\"video\"].includes(c.kind)){const d=e.find(h=>h.mid!=void 0&&h.mid===c.rtp.muxId);if(!d&&c.port!==0){throw new Error(`Transceiver with mid=${c.rtp.muxId} not found`)}if(!d||c.port===0||d.stopped||d.pendingRejection){f=false;l=this.liveTransportOr(d?.dtlsTransport,o);u=this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:c.rtp.muxId},l)}else{u=this.createMediaDescriptionForTransceiver(d,d.stopping?\"inactive\":Gf(d.direction,d.offerDirection));l=d.dtlsTransport}}else if(c.kind===\"application\"){if(!t||!t.mid){throw new Error(\"sctpTransport not found\")}u=this.createMediaDescriptionForSctp(t);l=t.dtlsTransport}else{throw new Error(\"invalid kind\")}if(u.dtlsParams&&l){if(l.role===\"auto\"){u.dtlsParams.role=\"client\"}else{u.dtlsParams.role=l.role}}if(f&&c.simulcastParameters&&c.simulcastParameters.length>0){u.simulcastParameters=c.simulcastParameters.map(d=>({...d,direction:d.direction===\"send\"?\"recv\":\"send\"}))}n.media.push(u)}if(this.bundlePolicy!==\"disable\"){n.group.push(...this.buildAnswerBundleGroups(i,n))}return n}buildAnswerBundleGroups(e,t){const s=new Set(t.media.filter(i=>i.port!==0&&i.rtp.muxId).map(i=>i.rtp.muxId));const n=this.negotiatedBundleTag;return e.group.filter(i=>i.semantic===\"BUNDLE\").map(i=>i.items.filter((o,c,l)=>{return s.has(o)&&l.indexOf(o)===c})).filter(i=>i.length>0).map(i=>new ks(\"BUNDLE\",jR(i,n)))}assertRemoteAnswerCodecs(e){if(![\"answer\",\"pranswer\"].includes(e.type)){return}const t=this.pendingLocalDescription;if(!t){return}e.media.forEach((s,n)=>{if(![\"audio\",\"video\"].includes(s.kind)||s.port===0){return}const i=t.media[n];if(!i||i.port===0||i.kind!==s.kind){return}const o=s.rtp.codecs.some(c=>c.name.toLowerCase()!==\"rtx\"&&i.rtp.codecs.some(l=>l.mimeType.toLowerCase()===c.mimeType.toLowerCase()));if(!o){throw ne(\"InvalidAccessError\",`No common codec for m-line ${n} (mid=${s.rtp.muxId}) in remote ${e.type}`)}})}assertBundlePreserved(e){if(e.type!==\"offer\"||this.bundlePolicy===\"disable\"){return}const t=[this.currentLocalDescription,this.currentRemoteDescription].find(n=>n?.type===\"answer\")?.group.filter(n=>n.semantic===\"BUNDLE\")??[];const s=e.group.filter(n=>n.semantic===\"BUNDLE\");for(const n of t){let i;for(const o of n.items){const c=e.media.find(u=>u.rtp.muxId===o);if(!c||c.port===0){continue}const l=s.find(u=>u.items.includes(o));if(!l){throw ne(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be preserved by the remote offer`)}i??=l;if(l!==i){throw ne(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be split into another BUNDLE group by the remote offer`)}}}}setLocalDescription(e){if(e.type===\"offer\"||e.type===\"pranswer\"){this.pendingLocalDescription=e;return}this.currentLocalDescription=e;if(this.pendingRemoteDescription){this.currentRemoteDescription=this.pendingRemoteDescription}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type){throw new Error(\"invalid sessionDescription\")}if(e.type===\"rollback\"){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw ne(\"InvalidStateError\",\"Cannot rollback remote description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0;return}if(!e.sdp){throw new Error(\"invalid sessionDescription\")}const s=this.parseSdp({sdp:e.sdp,isLocal:false,signalingState:t,type:e.type});this.assertRemoteAnswerCodecs(s);this.assertBundlePreserved(s);if(s.type===\"offer\"||s.type===\"pranswer\"){this.pendingRemoteDescription=s}else{if(this.pendingLocalDescription){this.currentLocalDescription=this.pendingLocalDescription}this.currentRemoteDescription=s;this.pendingRemoteDescription=void 0;this.pendingLocalDescription=void 0}return s}rollbackLocalDescription(e){if(![\"have-local-offer\",\"have-local-pranswer\"].includes(e)){throw ne(\"InvalidStateError\",\"Cannot rollback local description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){const e=this._remoteDescription;if(!e){return void 0}const t=e.group.find(s=>s.semantic===\"BUNDLE\"&&this.bundlePolicy!==\"disable\");return t}setLocal(e,t,s){const n=new Map(t.map(c=>[c?.mLineIndex,c]));const i=t.find(c=>c?.dtlsTransport)?.dtlsTransport??s?.dtlsTransport;e.media.forEach((c,l)=>{if(![\"audio\",\"video\"].includes(c.kind)){return}const u=t.find(h=>h?.mid!=void 0&&h.mid===c.rtp.muxId)??n.get(l);if(c.port===0){const h=u&&!u.stopping&&!u.stopped&&!u.pendingRejection;if(!h){return}}const f=u?.dtlsTransport??i;if(!f){throw new Error(`dtls transport not found for media index ${l}`)}const d=c.port;this.addTransportDescription(c,f);if(d===0){c.port=0}});const o=e.media.find(c=>c.kind===\"application\");if(s&&o){this.addTransportDescription(o,s.dtlsTransport)}this.setLocalDescription(e)}};function jR(r,e){if(!e||!r.includes(e)){return r}return[e,...r.filter(t=>t!==e)]}a(jR,\"orderBundleMids\");var Ln=P(\"webrtc/peer/media/rtpSender\");var $R=128;var Sg=256;var FR=.85;function mP(r){if(r===true){return{enabled:true,maxLength:Sg}}if(r==void 0||r===false){return{enabled:false,maxLength:Sg}}const e=typeof r.maxLength===\"number\"&&Number.isFinite(r.maxLength)&&r.maxLength>=1?Math.floor(r.maxLength):Sg;return{enabled:r.enabled??true,maxLength:e}}a(mP,\"resolvePendingRtpOptions\");function gP(r,e,t,s,n){return{seqOffset:$e($e(r,1),-t),timestampOffset:gr(gr(e,n),-s)}}a(gP,\"freezeRtpContinuityOffsets\");var cd=class{static{a(this,\"RTCRtpSender\")}constructor(e,t={}){this.trackOrKind=e;this.type=\"sender\";this.ssrc=(0,Kc.randomBytes)(4).readUInt32BE(0);this.rtxSsrc=(0,Kc.randomBytes)(4).readUInt32BE(0);this.trackId=(0,Kc.randomUUID)().toString();this.onReady=new O;this.onRtcp=new O;this.onPictureLossIndication=new O;this.onGenericNack=new O;this.onStreamsChanged=new O;this.rtxSequenceNumber=Lp();this._redDistance=2;this.redEncoder=new wu(this._redDistance);this.headerExtensions=[];this.sendEncodings=[{}];this.rtpTimestamp=0;this.octetCount=0;this.packetCount=0;this.headerBytesSent=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.retransmittedPacketsSent=0;this.retransmittedBytesSent=0;this.nackCount=0;this.pliCount=0;this.firCount=0;this.receiverEstimatedMaxBitrate=0n;this.timestampOffset=0;this.seqOffset=0;this.rtpContinuityPending=false;this.pendingTimestampStep=1;this.rtpCache=[];this.pendingRtp=[];this.drainingPendingRtp=false;this.negotiatedCodecs=[];this.dtlsDisposer=[];this.track=null;this.streamIds=[];this.stopped=false;this.rtcpRunning=false;this.rtcpCancel=new AbortController;const s=mP(t.pendingRtp);this.pendingRtpEnabled=s.enabled;this.pendingRtpMaxLength=s.maxLength;this.kind=typeof this.trackOrKind===\"string\"?this.trackOrKind:this.trackOrKind.kind;if(typeof e!==\"string\"){this.registerTrack(e)}}get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){if(this.dtlsTransport){this.dtlsDisposer.forEach(t=>t())}this.dtlsTransport=e;this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"connected\"){this.onReady.execute();void this.drainPendingRtp()}}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e;this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname;this.mid=e.muxId;this.headerExtensions=e.headerExtensions;this.rtpStreamId=e.rtpStreamId??this.rtpStreamId;this.repairedRtpStreamId=e.repairedRtpStreamId;this.negotiatedCodecs=[...e.codecs];this.selectCodec(this.track?br(this.track):void 0);if(this.track){this.track.codec=this.codec}void this.drainPendingRtp()}selectCodec(e){const t=this.negotiatedCodecs;const s=a(o=>{if(o?.name.toLowerCase()!==\"red\")return o;const c=Number((o.parameters??\"\").split(\"/\")[0]);return t.find(l=>![\"red\",\"rtx\"].includes(l.name.toLowerCase())&&l.payloadType===c)},\"primaryOf\");const n=a(o=>{const c=s(o);return!!c&&(!e||e.some(l=>Ro(l,c)))},\"compatible\");const i=t.find(o=>o.name.toLowerCase()!==\"rtx\")??t[0];this.codec=t.find(o=>o.name.toLowerCase()!==\"rtx\"&&n(o))??i;this.sendPrimaryCodec=s(this.codec);this.rtxPayloadType=void 0;this.redRedundantPayloadType=void 0;t.forEach(o=>{const c=or(o.parameters??\"\");if(o.name.toLowerCase()===\"rtx\"&&this.sendPrimaryCodec?.payloadType===c[\"apt\"]){this.rtxPayloadType=o.payloadType}});if(this.codec?.name.toLowerCase()===\"red\"&&this.sendPrimaryCodec!=void 0){this.redRedundantPayloadType=this.sendPrimaryCodec.payloadType}}canSendRtp(){return!this.stopped&&this.dtlsTransport?.state===\"connected\"&&!!this.codec}settlePendingRtp(e,t){if(t==void 0){e.resolve();return}e.reject(t)}discardPendingRtp(){const e=this.pendingRtp.splice(0);for(const t of e){this.settlePendingRtp(t)}}enqueuePendingRtp(e,t,s){const n=Buffer.isBuffer(e)?Le.deSerialize(e):e.clone();this.pendingRtp.push({packet:n,resolve:t,reject:s});while(this.pendingRtp.length>this.pendingRtpMaxLength){const i=this.pendingRtp.shift();if(i){this.settlePendingRtp(i)}}}async drainPendingRtp(){if(this.drainingPendingRtp){return}this.drainingPendingRtp=true;try{while(this.pendingRtp.length>0&&this.canSendRtp()){const e=this.pendingRtp.shift();if(!this.canSendRtp()){this.settlePendingRtp(e);continue}try{await this.dispatchRtp(e.packet);this.settlePendingRtp(e)}catch(t){this.settlePendingRtp(e,t)}}}finally{this.drainingPendingRtp=false}if(this.pendingRtp.length>0&&this.canSendRtp()){await this.drainPendingRtp()}}registerTrack(e){if(e.stopped)throw new Error(\"track is ended\");on(e);if(this.disposeTrack){this.disposeTrack()}e.id=this.trackId;const{unSubscribe:t}=e.onReceiveRtp.subscribe(Vt((n,i)=>e.remote?this.sendRtp(this.relayedRtp(n,i),true):this.sendRtp(n),n=>Ln(\"send rtp failed\",n)));const{unSubscribe:s}=e.onSourceChanged.subscribe(n=>{this.replaceRTP(n)});this.track=e;this.disposeTrack=()=>{t();s()};if(this.codec){e.codec=this.codec}}relayedRtp(e,t={}){const s=e.clone();s.header.extensions=this.headerExtensions.flatMap(n=>{switch(n.uri){case pe.audioLevelIndication:{const i=t[n.uri];return i?[{id:n.id,payload:Buffer.from([(i.v?128:0)|i.level&127])}]:[]}case pe.videoOrientation:{const i=t[n.uri];return i?[{id:n.id,payload:Buffer.from([i.c<<3|i.f<<2|i.r1<<1|i.r0])}]:[]}default:return[]}});return s}setStreams(e=[]){const t=[...new Set(e.map(n=>n.id))];const s=t.join(\"\\n\")!==(this.streamIds??[]).join(\"\\n\");this.streamIds=t;if(s)this.onStreamsChanged.execute()}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(s=>({...s})):[{}];const t=this.sendEncodings.find(s=>typeof s.rid===\"string\")?.rid;if(typeof t===\"string\"){this.rtpStreamId=t}}async replaceTrack(e){if(e===null){this.detachTrack();return}if(e.stopped)throw new Error(\"track is ended\");on(e);const t=br(e);if(this.sendPrimaryCodec!=void 0&&t!=void 0&&!this.negotiatedCodecs.some(s=>![\"red\",\"rtx\"].includes(s.name.toLowerCase())&&t.some(n=>Ro(n,s)))){throw ne(\"InvalidModificationError\",`Track codec ${t.map(s=>s.mimeType).join(\", \")} is incompatible with negotiated codecs ${this.negotiatedCodecs.map(s=>s.mimeType).join(\", \")}`)}if(this.negotiatedCodecs.length)this.selectCodec(t);if(this.sequenceNumber!=void 0){this.scheduleRtpContinuity()}this.registerTrack(e);Ln(\"replaceTrack\",\"ssrc\",e.ssrc,\"rid\",e.rid)}detachTrack(){this.rtpContinuityPending=false;this.discardPendingRtp();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}this.track=null}stop({keepTrack:e=false}={}){this.stopped=true;this.rtpContinuityPending=false;this.discardPendingRtp();this.rtcpRunning=false;this.rtcpCancel.abort();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}if(!e){this.track=null}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,wg.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=this.sentAtEpochMs===void 0?0n:wR(this.sentAtEpochMs);const t=[new Pt({ssrc:this.ssrc,senderInfo:new Va({ntpTimestamp:e,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=Kf(e);this.lastSentSRTimestamp=po();if(this.cname){t.push(new Dr({chunks:[new Ka({source:this.ssrc,items:[new Wa({type:1,text:this.cname})]})]}))}try{await this.dtlsTransport.sendRtcp(t)}catch(s){Ln(\"sendRtcp failed\",s);await(0,wg.setTimeout)(500+Math.random()*1e3)}}}catch(e){Ln(\"rtcp loop ended\",e)}}async sendRtp(e,t=false){if(this.stopped){return}if(!this.pendingRtpEnabled){if(!this.canSendRtp()){return}await this.dispatchRtp(e,t);return}await new Promise((s,n)=>{this.enqueuePendingRtp(e,s,n);void this.drainPendingRtp()})}replaceRTP(e,t=false,s=1){this.scheduleRtpContinuity(s);Ln(\"replaceRTP\",this.sequenceNumber,e.sequenceNumber,t,s)}scheduleRtpContinuity(e=1){this.rtpContinuityPending=true;this.pendingTimestampStep=e;this.rtpCache=[]}async dispatchRtp(e,t=false){if(!this.canSendRtp()){return}const s=this.codec;if(!s){return}e=Buffer.isBuffer(e)?Le.deSerialize(e):t?e:e.clone();const{header:n,payload:i}=e;const o=n.sequenceNumber;const c=n.timestamp;if(this.rtpContinuityPending){if(this.sequenceNumber!=void 0&&this.timestamp!=void 0){const m=gP(this.sequenceNumber,this.timestamp,o,c,this.pendingTimestampStep);this.seqOffset=m.seqOffset;this.timestampOffset=m.timestampOffset}this.rtpContinuityPending=false;this.pendingTimestampStep=1}n.ssrc=this.ssrc;n.payloadType=s.payloadType;n.timestamp=gr(n.timestamp,this.timestampOffset);n.sequenceNumber=$e(n.sequenceNumber,this.seqOffset);this.timestamp=n.timestamp;this.sequenceNumber=n.sequenceNumber;const l=performance.timeOrigin+performance.now();let u;const f=[];for(const m of this.headerExtensions){let y;switch(m.uri){case pe.sdesMid:if(this.mid)y=yE(this.mid);break;case pe.sdesRTPStreamID:if(this.rtpStreamId)y=bE(this.rtpStreamId);break;case pe.repairedRtpStreamId:if(this.repairedRtpStreamId)y=SE(this.repairedRtpStreamId);break;case pe.transportWideCC:u=this.nextTransportSequenceNumber();y=Kp(u);break;case pe.absSendTime:y=tg(l);break}if(y)f.push({id:m.id,payload:y})}for(const m of n.extensions){let y;for(const w of f){if(w.id===m.id){y=w;break}}if(y){y.payload=m.payload}else{f.push(m)}}for(let m=1;m<f.length;m++){if(f[m-1].id>f[m].id){f.sort((y,w)=>y.id-w.id);break}}n.extensions=f;this.sentAtEpochMs=l;this.rtpTimestamp=n.timestamp;this.octetCount+=i.length;this.headerBytesSent+=n.serializeSize;this.packetCount=gr(this.packetCount,1);this.rtpCache[n.sequenceNumber%$R]=e;let d=i;if(this.redRedundantPayloadType){this.redEncoder.push({block:d,timestamp:n.timestamp,blockPT:this.redRedundantPayloadType});const m=this.redEncoder.build();d=m.serialize()}const h=ho();const p=await this.dtlsTransport.sendRtp(d,n);if(!this.rtcpRunning&&!this.stopped)this.runRtcp().catch(m=>Ln(\"rtcp failed\",m));if(u!==void 0){this.packetSent(u,p,h)}}nextTransportSequenceNumber(){this.dtlsTransport.transportSequenceNumber=$e(this.dtlsTransport.transportSequenceNumber,1);return this.dtlsTransport.transportSequenceNumber}packetSent(e,t,s){const n={wideSeq:e,size:t,sendingAtMs:s,sentAtMs:ho()};this.dtlsTransport.senderBWE.rtpPacketSent(n)}async resendRtp(e){let t;const s=e.header.extensions.map(c=>{const l=this.headerExtensions.find(u=>u.id===c.id)?.uri;switch(l){case pe.transportWideCC:t=this.nextTransportSequenceNumber();return{id:c.id,payload:Kp(t)};case pe.absSendTime:return{id:c.id,payload:tg(performance.timeOrigin+performance.now())};default:return c}});let n=new Le(new Xe({...e.header,extensions:s}),e.payload);if(this.rtxPayloadType!=void 0){n=CE(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc);this.rtxSequenceNumber=$e(this.rtxSequenceNumber,1)}this.retransmittedPacketsSent++;this.retransmittedBytesSent+=n.payload.length;this.headerBytesSent+=n.header.serializeSize;const i=ho();const o=await this.dtlsTransport.sendRtp(n.payload,n.header);if(t!==void 0){this.packetSent(t,o,i)}}handleRtcpPacket(e){switch(e.type){case Pt.type:case Yt.type:{const t=e;t.reports.filter(s=>s.ssrc===this.ssrc).forEach(s=>{this.remotePacketsLost=s.packetsLost;this.remoteFractionLost=s.fractionLost/256;if(this.lastSRtimestamp===s.lsr&&s.dlsr){if(this.lastSentSRTimestamp){const n=po()-this.lastSentSRTimestamp-s.dlsr/65536;this.totalRoundTripTime+=n;this.roundTripTimeMeasurements++;if(this.rtt===void 0){this.rtt=n}else{this.rtt=FR*this.rtt+(1-FR)*n}}}})}break;case nt.type:{const t=e;switch(t.feedback.count){case Lr.count:{const s=t.feedback;this.nackCount++;s.lost.forEach(Vt(async n=>{const i=this.rtpCache[n%$R];if(i&&i.header.sequenceNumber===n){await this.resendRtp(i)}},n=>Ln(\"retransmission failed\",n)));this.onGenericNack.execute(s)}break}}break;case Xt.type:{const t=e;switch(t.feedback.count){case Nr.count:{const s=t.feedback;this.receiverEstimatedMaxBitrate=s.bitrate}break;case Pr.count:{this.pliCount++;this.onPictureLossIndication.execute()}break}}break}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){if(e.encodings){this.setSendEncodings(e.encodings)}}get outboundRtpStatsId(){return ue(\"outbound-rtp\",this.trackId)}get mediaSourceStatsId(){return ue(\"media-source\",this.trackId)}get remoteInboundRtpStatsId(){return ue(\"remote-inbound-rtp\",this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){const t=[];const s=this.dtlsTransport?ue(\"transport\",this.dtlsTransport.id):void 0;const n=this.codec&&s?fo(s,this.codec.payloadType,this.trackId):void 0;const i={type:\"outbound-rtp\",id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:n,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};t.push(i);if(this.track){const o={type:\"media-source\",id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(o)}if(this.codec&&s){const o={type:\"codec\",id:n,timestamp:e,payloadType:this.codec.payloadType,transportId:s,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(o)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){const o={type:\"remote-inbound-rtp\",id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:i.codecId,localId:i.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(o)}return t}async getStats(){const e=Qe();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return On(t,this.getStatsRootIds())}};var HR=P(\"webrtc/peer/transceiverManager\");function yP(r){if(!r||r.length<2){return void 0}const e=r.map(t=>t.rid).filter(t=>typeof t===\"string\"&&t.length>0);if(e.length<2){return void 0}return e.map(t=>({rid:t,direction:\"send\"}))}a(yP,\"simulcastFromSendEncodings\");var ld=class{static{a(this,\"TransceiverManager\")}constructor(e,t,s){this.cname=e;this.config=t;this.router=s;this.transceivers=[];this.watched=new WeakSet;this.stableState=new Map;this.onTransceiverAdded=new O;this.onRemoteTransceiverAdded=new O;this.onTrack=new O;this.onNegotiationNeeded=new O}getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.watchTransceiver(e);this.transceivers.push(e)}replaceTransceiver(e,t){this.watchTransceiver(e);this.transceivers[t]=e}unwatchTransceiver(e){this.watched.delete(e);e.onRelease.allUnsubscribe();e.onStopRequested.allUnsubscribe();e.onDirectionChanged.allUnsubscribe();e.sender.onStreamsChanged.allUnsubscribe()}watchTransceiver(e){if(this.watched.has(e)){return}this.watched.add(e);e.onRelease.subscribe(()=>{this.router.unregisterTransceiver(e)});e.onStopRequested.subscribe(()=>{if(!e.stopped){this.onNegotiationNeeded.execute()}});e.onDirectionChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()});e.sender.onStreamsChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()})}findReusableTransceiver(e){return this.transceivers.find(t=>t.stopped&&t.kind===e&&t.mLineIndex!=void 0&&!this.transceivers.some(s=>s!==t&&s.mLineIndex===t.mLineIndex))}takeOverMLine(e,t){const s=this.transceivers.indexOf(e);t.mLineIndex=e.mLineIndex;e.mid=null;e.mLineIndex=void 0;this.unwatchTransceiver(e);this.replaceTransceiver(t,s)}associateMLine(e,t){const s=this.transceivers.find(n=>n!==e&&n.stopped&&n.mLineIndex===t);if(!s){return}this.transceivers.splice(this.transceivers.indexOf(e),1);this.takeOverMLine(s,e)}releaseUnassociatedReservations(e,t){for(const s of this.transceivers){if(!e.has(s)&&s.mid==null&&s.mLineIndex!=void 0&&s.mLineIndex<t){s.mLineIndex=void 0}}}addTransceiver(e,t,s={},{remoteMLineIndex:n}={}){const i=typeof e===\"string\"?e:e.kind;const o=s.direction||\"sendrecv\";if(typeof e!==\"string\"){on(e);Nn({kind:i,configured:this.filterCodecsByDirection(i,o),source:br(e),preferences:void 0})}const c=new cd(e,{pendingRtp:this.config.pendingRtp});const l=new Co(this.config,i,c.ssrc);const u=new Ff(i,t,l,c,o);u.onCodecPreferencesChanged.subscribe(()=>{this.onNegotiationNeeded.execute()});u.options={...s,simulcast:s.simulcast??yP(s.sendEncodings)};u.sender.setStreams(s.streams??[]);u.sender.setSendEncodings((s.sendEncodings??[]).map(d=>({...d})));this.router.registerRtpSender(u.sender);const f=n==void 0?this.findReusableTransceiver(i):this.transceivers.find(d=>d.stopped&&d.mLineIndex===n);if(f){this.takeOverMLine(f,u)}else{this.pushTransceiver(u)}if(n!=void 0){this.remoteOfferSnapshot?.remoteCreated.add(u)}this.onTransceiverAdded.execute(u);return u}reusableForTrack(e,t){return e.sender.track==void 0&&e.kind===t&&!e.usedForSender&&!e.stopping&&!e.stopped&&!e.rejected&&!e.pendingRejection}addTrack(e,t=[],s){if(this.getSenders().find(c=>c.track?.uuid===e.uuid)){throw ne(\"InvalidAccessError\",\"Track already added\")}const n=a(c=>this.reusableForTrack(c,e.kind)&&(s===void 0||c===s),\"reusableForTrack\");const i=s===null?void 0:this.transceivers.find(c=>n(c)&&Rn.includes(c.direction));if(i){this.validateTrackForTransceiver(e,i);const c=i.sender;c.setStreams(t);c.registerTrack(e);i.options={...i.options,streams:t};i.codecs=[];return i}const o=s===null?void 0:this.transceivers.find(c=>n(c)&&!Rn.includes(c.direction));if(o){const c=o.direction===\"recvonly\"?\"sendrecv\":o.direction===\"inactive\"?\"sendonly\":o.direction;this.validateTrackForTransceiver(e,o,c);const l=o.sender;l.setStreams(t);l.registerTrack(e);o.options={...o.options,streams:t};switch(o.direction){case\"recvonly\":o.setDirection(\"sendrecv\");break;case\"inactive\":o.setDirection(\"sendonly\");break}o.codecs=[];return o}else{const c=this.addTransceiver(e,void 0,{direction:\"sendrecv\",streams:t});c.addedByAddTrack=true;return c}}removeTrack(e){if(!this.getSenders().find(({ssrc:s})=>e.ssrc===s)){throw ne(\"InvalidAccessError\",\"Sender does not exist\")}const t=this.transceivers.find(({sender:{ssrc:s}})=>e.ssrc===s);if(!t)throw new Error(\"No matching transceiver found\");if(t.stopping||t.stopped){return false}if(e.track==void 0){return false}e.detachTrack();if(t.direction===\"sendrecv\"){t.setDirection(\"recvonly\")}else if(t.direction===\"sendonly\"){t.setDirection(\"inactive\")}return true}assignTransceiverCodecs(e){const t=this.filterCodecsByDirection(e.kind,e.direction);e.codecs=Nn({kind:e.kind,configured:t,source:br(e.sender.track),preferences:e.codecPreferences});e.codecPreferencesNeedResolution=false}filterCodecsByDirection(e,t){return this.config.codecs[e].filter(s=>{switch(s.direction){case\"recvonly\":{if(mx.includes(t))return true;return false}case\"sendonly\":{if(Rn.includes(t))return true;return false}case\"sendrecv\":{if([Ym,Xm,Vm].includes(t))return true;return false}case\"all\":{return true}default:return false}})}validateTrackForTransceiver(e,t,s=t.direction){on(e);Nn({kind:e.kind,configured:this.filterCodecsByDirection(e.kind,s),source:br(e),preferences:t.codecPreferences})}getLocalRtpParams(e){if(e.mid==void 0)throw new Error(\"mid not assigned\");const t={codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:true}};return t}getRemoteRtpParams(e,t){const s={muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((n,i)=>{if(i.name.toLowerCase()===\"rtx\"){const o=or(i.parameters??\"\");const c=n[o[\"apt\"]];if(c&&e.ssrc.length===2){c.rtx=new Mu({ssrc:e.ssrc[1].ssrc})}return n}n[i.payloadType]=new Du({ssrc:e.ssrc[0]?.ssrc,payloadType:i.payloadType});return n},{}))};return s}resyncAnswerCodecs(e,t){this.refreshAnswerCodecs(e,t);const s=this.getLocalRtpParams(e);e.sender.prepareSend(s);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const n=this.getRemoteRtpParams(t,e);for(const i of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,i,n)}e.receiver.resyncCodecs(n);this.router.registerRtpReceiverBySsrc(e,n)}}resolveRemoteCodecSet(e,t,s,n){const i=a(f=>f.name.toLowerCase(),\"codecName\");const o=a(f=>(f.parameters??\"\").split(\"/\").map(Number).filter(d=>!Number.isNaN(d)),\"redPayloadTypes\");const c=new Map;const l=new Set;for(const f of e){if([\"red\",\"rtx\"].includes(i(f)))continue;const d=t.rtp.codecs.find(h=>!l.has(h)&&h.mimeType.toLowerCase()===f.mimeType.toLowerCase()&&(n==void 0||n.some(p=>Ro(p,h))));if(d){c.set(f,d);l.add(d)}}const u=e.flatMap(f=>{if(i(f)===\"red\"){const y=o(f).flatMap(S=>{const T=e.find(x=>x.payloadType===S);const _=T?c.get(T):void 0;return _?[_.payloadType]:[]});const w=t.rtp.codecs.find(S=>{if(i(S)!==\"red\"||l.has(S))return false;const T=o(S);return T.length===y.length&&T.every((_,x)=>_===y[x])});if(!w)return[];l.add(w);return[w]}if(i(f)!==\"rtx\"){const y=c.get(f);return y?[y]:[]}const d=or(f.parameters??\"\").apt;const h=e.find(y=>y.payloadType===d);if(!h)return[];const p=c.get(h);if(!p)return[];const m=t.rtp.codecs.find(y=>{if(i(y)!==\"rtx\"||l.has(y)){return false}return or(y.parameters??\"\").apt===p.payloadType});if(!m)return[];l.add(m);return[m]});if(s===\"remote\"){const f=new Map(t.rtp.codecs.map((d,h)=>[d,h]));u.sort((d,h)=>f.get(d)-f.get(h))}if(u.length===0){throw ne(\"NotSupportedError\",\"No compatible codec remains after remote negotiation.\")}return u}refreshAnswerCodecs(e,t){const s=this.config.codecs[t.kind]||[];const n=br(e.sender.track);Nn({kind:t.kind,configured:s,source:n,preferences:e.codecPreferences});const i=mg(s,n,e.codecPreferences);e.codecs=this.resolveRemoteCodecSet(i,t,\"local\",n);e.codecPreferencesNeedResolution=false;HR(\"negotiated codecs\",e.codecs)}planRemoteRtpCodecs(e,t){const s=new Map;const n=e.type===\"offer\";for(const[i,o]of e.media.entries()){if(![\"audio\",\"video\"].includes(o.kind))continue;const c=t(o,i);if(o.port===0||c?.stopped||c?.stopping){s.set(i,[]);continue}const l=br(c?.sender.track);const u=this.config.codecs[o.kind]||[];const f=n?u:c?.pendingLocalOfferCodecs||[];if(!PR(f,o.rtp.codecs)){s.set(i,[]);continue}if(n){Nn({kind:o.kind,configured:u,source:l,preferences:c?.codecPreferences})}const d=this.resolveRemoteCodecSet(n?mg(u,l,c?.codecPreferences):f,o,n?\"local\":\"remote\",l);if(l!=void 0){Nn({kind:o.kind,configured:d,source:l,preferences:void 0})}s.set(i,d)}return s}setRemoteRTP(e,t,s,n,i){if(!e.mid){e.mid=t.rtp.muxId??null}e.mLineIndex=n;if(s===\"answer\")e.pendingLocalOfferCodecs=void 0;if(e.stopped){return false}if(e.stopping){if(s===\"answer\"&&t.port===0){e.commitStopped({rejected:false})}return false}HR(\"negotiated codecs\",i);if(t.port===0||i.length===0){if(s===\"answer\"){e.commitStopped({rejected:true})}else{e.pendingRejection=true}return false}e.pendingRejection=false;e.codecs=i;e.headerExtensions=t.rtp.headerExtensions.filter(u=>(this.config.headerExtensions[t.kind]||[]).find(f=>f.uri===u.uri));const o=t.direction??\"inactive\";const c=bR(o);if([\"answer\",\"pranswer\"].includes(s)){e.setCurrentDirection(c)}else{e.offerDirection=c}const l=this.getLocalRtpParams(e);e.sender.prepareSend(l);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const u=this.getRemoteRtpParams(t,e);for(const f of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,f,u)}e.receiver.resyncCodecs(u);this.router.registerRtpReceiverBySsrc(e,u)}if([\"sendonly\",\"sendrecv\"].includes(o)){const u=[...new Set(t.msids.map(d=>d.split(\" \")[0]))];const f=t.msids[0]?.split(\" \")[1];e.receiver.remoteStreamId=u[0];e.receiver.remoteStreamIds=u;e.receiver.remoteTrackId=f;if(!e.firedReceiving){e.firedReceiving=true;this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:u.map(d=>new Br({id:d,tracks:[e.receiver.track]}))})}}else{e.firedReceiving=false}return true}markStable(){this.stableState=new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex}]))}rollbackLocalOffer(){for(const e of this.transceivers){const t=this.stableState.get(e);e.mid=t?.mid??null;e.mLineIndex=t?.mLineIndex}}beginRemoteOffer(){if(this.remoteOfferSnapshot){return}this.remoteOfferSnapshot={transceivers:[...this.transceivers],remoteCreated:new Set,states:new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex,pendingRejection:e.pendingRejection,firedReceiving:e.firedReceiving}]))}}commitRemoteOffer(){this.remoteOfferSnapshot=void 0;for(const e of this.transceivers){if(e.pendingRejection){e.commitStopped({rejected:true})}}}rollbackRemoteOffer(){const e=this.remoteOfferSnapshot;this.remoteOfferSnapshot=void 0;if(!e){return}for(const t of this.transceivers){if(e.states.has(t)){continue}if(!e.remoteCreated.has(t)||t.sender.track){t.mid=null;t.mLineIndex=void 0;e.transceivers.push(t);continue}t.forceStop();this.unwatchTransceiver(t)}this.transceivers.splice(0,this.transceivers.length,...e.transceivers);e.transceivers.forEach(t=>this.watchTransceiver(t));for(const[t,s]of e.states){t.mid=s.mid;t.mLineIndex=s.mLineIndex;t.pendingRejection=s.pendingRejection;t.firedReceiving=s.firedReceiving}}settleStoppingTransceivers(e){for(const t of this.transceivers){if(!t.stopping||t.stopped){continue}if(t.mid==void 0||!e.has(t.mid)){t.commitStopped({rejected:false})}}return this.transceivers.some(t=>t.stopping&&!t.stopped)}collectStats(e){const t=[];for(const s of this.transceivers){if(s.sender){t.push(...s.sender.collectStats(e))}if(s.receiver){t.push(...s.receiver.collectStats(e))}const n=s.collectCodecStats(e);if(n){t.push(...n)}}return t}getStatsRootIds(e){if(!e){return[]}const t=[];for(const s of this.transceivers){if(s.sender.track===e){t.push(...s.sender.getStatsRootIds())}if(s.receiver.tracks.includes(e)){t.push(...s.receiver.getStatsRootIds(e))}}return t}close(){for(const e of this.transceivers){e.forceStop();this.unwatchTransceiver(e)}this.onTransceiverAdded.allUnsubscribe();this.onRemoteTransceiverAdded.allUnsubscribe();this.onTrack.allUnsubscribe();this.onNegotiationNeeded.allUnsubscribe()}};var bP=P(\"webrtc/peer/sctpManager\");var ud=class{static{a(this,\"SctpTransportManager\")}constructor(){this.dataChannelsOpened=0;this.dataChannelsClosed=0;this.dataChannels=[];this.onDataChannel=new O}createSctpTransport(e,t){const s=new ed(5e3,e,t);s.mid=void 0;s.onDataChannel.subscribe(n=>{this.dataChannelsOpened++;this.dataChannels.push(n);this.onDataChannel.execute(n)});this.sctpTransport=s;return s}createDataChannel(e,t={}){const s=qR(t.maxPacketLifeTime,\"maxPacketLifeTime\");const n=qR(t.maxRetransmits,\"maxRetransmits\");const i={protocol:\"\",ordered:true,negotiated:false};const o={...i,...t,maxPacketLifeTime:s,maxRetransmits:n};if(o.maxPacketLifeTime!=null&&o.maxRetransmits!=null){throw rr(\"maxPacketLifeTime and maxRetransmits cannot both be set\")}if(!this.sctpTransport){this.sctpTransport=this.createSctpTransport()}const c=new Eo({id:o.id,label:e,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits,negotiated:o.negotiated,ordered:o.ordered,protocol:o.protocol});const l=new wo(this.sctpTransport,c);this.dataChannelsOpened++;this.dataChannels.push(l);l.stateChange.subscribe(u=>{if(u===\"closed\"){this.dataChannelsClosed++;const f=this.dataChannels.indexOf(l);if(f!==-1){this.dataChannels.splice(f,1)}}});return l}async connectSctp(){if(!this.sctpTransport||!this.sctpRemotePort){return}await this.sctpTransport.start(this.sctpRemotePort);await this.sctpTransport.sctp.stateChanged.connected.asPromise();bP(\"sctp connected\")}setRemoteSCTP(e,t){if(!this.sctpTransport){return}this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize);this.sctpRemotePort=e.sctpPort;if(!this.sctpRemotePort){throw new Error(\"sctpRemotePort not exist\")}this.sctpTransport.setRemotePort(this.sctpRemotePort);this.sctpTransport.mLineIndex=t;if(!this.sctpTransport.mid){this.sctpTransport.mid=e.rtp.muxId}}async close(){if(this.sctpTransport){await this.sctpTransport.stop();await new Promise(e=>setImmediate(e))}this.onDataChannel.allUnsubscribe()}async getStats(e=Qe()){const t=[];for(const s of this.dataChannels){const n={type:\"data-channel\",id:ue(\"data-channel\",s.id??s.statsId),timestamp:e,label:s.label,protocol:s.protocol,dataChannelIdentifier:s.id??void 0,state:s.readyState,messagesSent:s.messagesSent||0,bytesSent:s.bytesSent||0,messagesReceived:s.messagesReceived||0,bytesReceived:s.bytesReceived||0};t.push(n)}return t}};function qR(r,e){if(r===void 0){return void 0}const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw rr(`${e} must be an unsigned short`)}return t}a(qR,\"coerceUnsignedShortOption\");var Eg=P(\"webrtc/peer/secureTransportManager\");var fd=class{static{a(this,\"SecureTransportManager\")}constructor({config:e,transceiverManager:t,sctpManager:s}){this.connectionState=\"new\";this.iceConnectionState=\"new\";this.iceGatheringState=\"new\";this.iceGatheringStateChange=new O;this.iceConnectionStateChange=new O;this.onIceCandidate=new O;this.connectionStateChange=new O;this.createdTransports=new Set;this.config=e;this.transceiverManager=t;this.sctpManager=s;if(this.config.dtls){const{keys:n}=this.config.dtls;if(this.config.certificates[0]){this.certificate=this.config.certificates[0]}else if(n){this.setupCertificate(n)}}}get dtlsTransports(){return Tg([...this.transceiverManager.getTransceivers().filter(e=>!e.stopped).map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get allDtlsTransports(){return Tg([...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new $c(e.keyPem,e.certPem,e.signatureHash)}resolveIceServerOptions(){const e=TR(this.config.iceServers);const t=rg({parsedTurnTransport:e.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP});return{stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:t,stunServers:e.stunServers,turnServers:e.turnServers.map(s=>({...s,transport:rg({parsedTurnTransport:s.transport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP})}))}}updateIceServers(){const e={...this.resolveIceServerOptions(),forceTurn:this.config.iceTransportPolicy===\"relay\",useTcp:this.config.iceUseTcp,turnUdpFamily:this.config.turnUdpFamily};for(const t of this.iceTransports){if(t.gatheringState===\"new\"){t.setIceServers(e)}}}createTransport({inheritCredentials:e=true}={}){const t=e?this.iceTransports.find(o=>o.state!==\"closed\"):void 0;const s=new Zf({...this.resolveIceServerOptions(),iceLite:this.config.iceLite,forceTurn:this.config.iceTransportPolicy===\"relay\",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,useTcp:this.config.iceUseTcp,tcpPassive:this.config.iceTcpPassive,stunGatherTimeout:this.config.iceStunGatherTimeout,turnConnectTimeout:this.config.iceTurnConnectTimeout,turnTlsOptions:this.config.turnTlsOptions,turnUdpFamily:this.config.turnUdpFamily,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});if(t){s.connection.localUsername=t.connection.localUsername;s.connection.localPassword=t.connection.localPassword}s.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()});this.updateIceGatheringState();const n=new Jf(s);n.onStateChange.subscribe(()=>{this.updateIceConnectionState()});const i=new jc(this.config,n,this.certificate,SP);this.createdTransports.add(i);return i}handleNewIceCandidate({candidate:e,sdpMid:t,sdpMLineIndex:s}){e.sdpMid=t;e.sdpMLineIndex=s;if(e.foundation&&!e.foundation.startsWith(\"candidate:\")){e.foundation=\"candidate:\"+e.foundation}this.onIceCandidate.execute(e);return e}async addIceCandidate(e,t){const s=t?.candidate;const n=t?.sdpMid;const i=t?.sdpMLineIndex;const o=t?.usernameFragment;const c=t==null||s==null||s===\"\";const l=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:c,sdpMid:n,sdpMLineIndex:i,usernameFragment:o});if(c){const p=l.map(m=>this.getTransportByMLineIndex(e,m)).filter(m=>!!m).reduce((m,y)=>{if(!m.find(({id:w})=>w===y.id)){m.push(y)}return m},[]);await Promise.all(p.map(m=>m.addRemoteCandidate(void 0)));return{kind:\"end-of-candidates\",mediaIndices:l}}const u=Fc.fromJSON(t);if(!u){throw ne(\"OperationError\",\"Failed to parse ICE candidate\")}const f=l[0];const d=e.media[f];if(!d){throw ne(\"OperationError\",\"ICE media section not found\")}u.sdpMid=d.rtp.muxId??void 0;u.sdpMLineIndex=f;const h=this.getTransportByMLineIndex(e,f);if(!h){if(this.isRejectedMedia(d)){return{kind:\"candidate\",candidate:u,mediaIndices:[f]}}throw ne(\"OperationError\",\"ICE transport not found for candidate\")}await h.addRemoteCandidate(u);return{kind:\"candidate\",candidate:u,mediaIndices:[f]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:s,sdpMLineIndex:n,usernameFragment:i}){let o;if(typeof s===\"string\"){const c=e.media.findIndex(l=>l.rtp.muxId===s);if(c<0){throw ne(\"OperationError\",\"Media section for sdpMid was not found\")}o=[c]}else if(typeof n===\"number\"){if(n<0||n>=e.media.length){throw ne(\"OperationError\",\"Media section for sdpMLineIndex was not found\")}o=[n]}else if(t){o=e.media.map((c,l)=>l)}else{throw rr(\"sdpMid or sdpMLineIndex must be provided with a candidate\")}if(typeof i===\"string\"){const c=o.filter(l=>e.media[l]?.iceParams?.usernameFragment===i);if(c.length===0){throw ne(\"OperationError\",\"No media section matched the ICE usernameFragment\")}o=c}return o}isRejectedMedia(e){if(e.port===0){return true}if(![\"audio\",\"video\"].includes(e.kind)){return false}const t=this.transceiverManager.getTransceivers().find(s=>s.mid!=void 0&&s.mid===e.rtp.muxId);return!t||t.stopped||t.stopping||t.pendingRejection}getTransportByMid(e){if(!e){return}let t;const s=this.transceiverManager.getTransceivers().find(n=>n.mid===e);if(s){t=s.dtlsTransport?.iceTransport}else if(!t&&this.sctpManager.sctpTransport?.mid===e){t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport}if(t?.state===\"closed\"){return}return t}getTransportByMLineIndex(e,t){const s=e.media[t];if(!s){return}const n=this.getTransportByMid(s.rtp.muxId);return n}restartIce(){for(const e of this.iceTransports){e.restart()}this.updateIceGatheringState()}setLocalRole({type:e,role:t,roleOfTransport:s}){for(const n of this.dtlsTransports){const i=n.iceTransport;if(i.state===\"new\"){if(i.connection.iceLite){i.connection.iceControlling=false}else if(i.connection.remoteIsLite){i.connection.iceControlling=true}else{i.connection.iceControlling=e===\"offer\"}}if(e===\"answer\"){const o=s?.get(n)??t;if(o){n.role=o}}}}updateIceGatheringState(){const e=this.iceTransports;function t(...n){return e.filter(i=>n.includes(i.gatheringState)).length===e.length}a(t,\"allMatch\");let s;if(e.length&&t(\"complete\")){s=\"complete\"}else if(!e.length||t(\"new\",\"complete\")){s=\"new\"}else if(e.map(n=>n.gatheringState).includes(\"gathering\")){s=\"gathering\"}else{s=\"new\"}if(this.iceGatheringState===s){return}this.iceGatheringState=s;this.iceGatheringStateChange.execute(s)}updateIceConnectionState(){const e=this.iceTransports;let t;function s(...i){return e.filter(o=>i.includes(o.state)).length===e.length}a(s,\"allMatch\");function n(...i){return e.some(o=>i.includes(o.state))}a(n,\"anyMatch\");if(this.connectionState===\"closed\"){t=\"closed\"}else if(n(\"failed\")){t=\"failed\"}else if(n(\"disconnected\")){t=\"disconnected\"}else if(s(\"new\",\"closed\")){t=\"new\"}else if(n(\"new\",\"checking\")){t=\"checking\"}else if(s(\"completed\",\"closed\")){t=\"completed\"}else if(s(\"connected\",\"completed\",\"closed\")){t=\"connected\"}else{t=\"new\"}if(this.iceConnectionState===t){return}Eg(\"iceConnectionStateChange\",t);this.iceConnectionState=t;this.iceConnectionStateChange.execute(t);if(t===\"failed\"&&this.connectionState!==\"closed\"){this.setConnectionState(\"failed\")}else if(t===\"disconnected\"&&this.connectionState===\"connected\"){this.setConnectionState(\"disconnected\")}}async gatherCandidates(){await Promise.allSettled(this.iceTransports.filter(e=>e.state!==\"closed\").map(e=>e.gather())).catch(e=>{Eg(\"gatherCandidates failed\",e)})}setConnectionState(e){if(this.connectionState===e||this.connectionState===\"closed\"){return}Eg(\"connectionStateChange\",e);this.connectionState=e;this.connectionStateChange.execute(e)}async getStats(e){const t=[];for(const s of this.dtlsTransports){const n=await s.getStats(e);if(n){t.push(...n)}}return t}async ensureCerts(){if(!this.certificate){this.certificate=await jc.SetupCertificate()}for(const e of this.dtlsTransports){e.localCertificate=this.certificate}}async close(){this.setConnectionState(\"closed\");await Promise.allSettled(Tg([...this.allDtlsTransports,...this.createdTransports]).map(e=>e.stop()));this.createdTransports.clear();this.iceGatheringStateChange.allUnsubscribe();this.iceConnectionStateChange.allUnsubscribe();this.onIceCandidate.allUnsubscribe();this.connectionStateChange.allUnsubscribe()}};function Tg(r){return r.reduce((e,t)=>{if(t&&!e.map(s=>s.id).includes(t.id)){e.push(t)}return e},[])}a(Tg,\"uniqueTransports\");var SP=[Am.SRTP_AEAD_AES_128_GCM,Am.SRTP_AES128_CM_HMAC_SHA1_80];var ye=P(\"webrtc/peer/peerConnection\");var dd=class extends kt{static{a(this,\"RTCPeerConnection\")}get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super();this.id=(0,xg.randomUUID)().toString();this.cname=(0,xg.randomUUID)().toString();this.config=GR();this.signalingState=\"stable\";this.negotiationneeded=false;this.negotiationneededScheduled=false;this.negotiationChangeSeq=0;this.negotiatedChangeSeq=0;this.lastCreatedOfferChangeSeq=0;this.needRestart=false;this.router=new od;this.isClosed=false;this.shouldNegotiationneeded=false;this.pendingRemoteCandidates=[];this.iceGatheringStateChange=new O;this.iceConnectionStateChange=new O;this.signalingStateChange=new O;this.connectionStateChange=new O;this.onDataChannel=new O;this.onRemoteTransceiverAdded=new O;this.onTransceiverAdded=new O;this.onIceCandidate=new O;this.onNegotiationneeded=new O;this.onTrack=new O;this.eventHandlers={};this.needNegotiation=()=>{this.negotiationChangeSeq++;this.scheduleNegotiationneeded()};this.setConfiguration(e);this.sdpManager=new ad({cname:this.cname,bundlePolicy:this.config.bundlePolicy,mLineReuse:this.config.mLineReuse});this.transceiverManager=new ld(this.cname,this.config,this.router);this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);this.transceiverManager.onTrack.subscribe(({track:t,streams:s,transceiver:n})=>{const i=new Rg({track:t,streams:s,transceiver:n,receiver:n.receiver});this.onTrack.execute(t);this.emit(\"track\",i);if(this.ontrack){Ne(()=>this.ontrack(i),o=>ye(\"event handler failed\",o))}});this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation());this.sctpManager=new ud;this.sctpManager.onDataChannel.subscribe(t=>{this.onDataChannel.execute(t);const s={type:\"datachannel\",channel:t};if(this.ondatachannel)Ne(()=>this.ondatachannel(s),n=>ye(\"event handler failed\",n));this.emit(\"datachannel\",s)});this.secureManager=new fd({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager});this.secureManager.iceGatheringStateChange.subscribe(t=>{this.iceGatheringStateChange.execute(t);if(this.onicegatheringstatechange){Ne(()=>this.onicegatheringstatechange(new globalThis.Event(\"icegatheringstatechange\")),s=>ye(\"event handler failed\",s))}this.emit(\"icegatheringstatechange\")});this.secureManager.iceConnectionStateChange.subscribe(t=>{if(t===\"closed\"){this.close().catch(s=>ye(\"close failed\",s))}this.iceConnectionStateChange.execute(t);if(this.oniceconnectionstatechange)Ne(()=>this.oniceconnectionstatechange(),s=>ye(\"event handler failed\",s));this.emit(\"iceconnectionstatechange\")});this.secureManager.connectionStateChange.subscribe(t=>{this.connectionStateChange.execute(t);if(this.onconnectionstatechange)Ne(()=>this.onconnectionstatechange(),s=>ye(\"event handler failed\",s));this.emit(\"connectionstatechange\")});this.secureManager.onIceCandidate.subscribe(t=>{const s=t?t.toJSON():void 0;this.onIceCandidate.execute(s);const n={type:\"icecandidate\",candidate:s};if(this.onicecandidate)Ne(()=>this.onicecandidate(n),i=>ye(\"event handler failed\",i));this.emit(\"icecandidate\",n)})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctp(){return this.sctpTransport??null}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){const e=this.sdpManager._remoteDescription;if(!e){return null}const t=[e.iceOptions,...e.media.map(s=>s.iceOptions)].filter(s=>!!s).join(\" \");return t.split(/\\s+/).includes(\"trickle\")}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(e){const t=EP(e);const s=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==\"require\"){throw new Error(\"rtcpMuxPolicy must be require\")}if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0)){throw new Error(\"iceCandidatePoolSize must be a non-negative integer\")}if(s&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy){throw new Error(\"bundlePolicy cannot be changed\")}if(t.mLineReuse!==void 0&&!zR.includes(t.mLineReuse)){throw rr(`mLineReuse must be one of ${zR.join(\", \")}`)}if(s&&t.mLineReuse!==void 0&&t.mLineReuse!==this.config.mLineReuse){throw ne(\"InvalidModificationError\",\"mLineReuse cannot be changed\")}if(s&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy){throw new Error(\"rtcpMuxPolicy cannot be changed\")}if(s&&t.certificates!==void 0&&!xP(t.certificates,this.config.certificates)){throw new Error(\"certificates cannot be changed\")}if(s&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize){throw new Error(\"iceCandidatePoolSize cannot be changed after setLocalDescription\")}if((t.iceCandidatePoolSize??0)>0){throw new Error(\"iceCandidatePoolSize > 0 is not supported\")}if(t.sctp!==void 0){const o=t.sctp.mtu??ji;Gu(o);if(this.sctpManager?.sctpTransport&&o!==this.config.sctp.mtu){throw new Error(\"sctp.mtu cannot be changed after SCTP transport creation\")}}xR(this.config,t);this.config.sctp={mtu:this.config.sctp?.mtu??ji};if(this.config.icePortRange){const[o,c]=this.config.icePortRange;if(o===c)throw new Error(\"should not be same value\");if(o>=c)throw new Error(\"The min must be less than max\")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0){throw new Error(\"maxMessageSize must be a non-negative integer\")}if(this.sctpManager?.sctpTransport){this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize}wP(this.config);const n=new Map;const i=[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]];i.forEach(o=>{if(!n.has(o.uri))n.set(o.uri,n.size+1);o.id=n.get(o.uri)});if(s&&this.secureManager&&(t.iceServers!==void 0||t.turnUdpFamily!==void 0)){this.secureManager.updateIceServers()}}getConfiguration(){return RP(this.config)}headerExtensionsFor(e){const t=new Map;for(const n of this.transceiverManager.getTransceivers()){for(const i of n.headerExtensions)t.set(i.uri,i.id)}const s=new Set(t.values());return(this.config.headerExtensions[e]??[]).flatMap(n=>{let i=t.get(n.uri);if(i===void 0){i=s.has(n.id)?Array.from({length:14},(o,c)=>c+1).find(o=>!s.has(o)):n.id;if(i===void 0)return[];s.add(i);t.set(n.uri,i)}return[new Qt({uri:n.uri,id:i})]})}async createOffer({iceRestart:e}={}){if(e||this.needRestart){this.needRestart=false;this.secureManager.restartIce()}await this.secureManager.ensureCerts();for(const n of this.transceiverManager.getTransceivers()){if(n.codecs.length===0||n.codecPreferencesNeedResolution){this.transceiverManager.assignTransceiverCodecs(n)}if(n.headerExtensions.length===0){n.headerExtensions=this.headerExtensionsFor(n.kind)}}const t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);const s=t.toJSON();this.lastCreatedOffer=s;this.lastCreatedOfferChangeSeq=this.negotiationChangeSeq;return s}createSctpTransport(){const e=this.sctpManager.createSctpTransport(this.config.maxMessageSize,this.config.sctp);const t=this.findOrCreateTransport();e.setDtlsTransport(t);return e}createDataChannel(e,t={}){if(!this.sctpTransport){this.createSctpTransport();this.needNegotiation()}const s=this.sctpManager.createDataChannel(e,t);if(!s.sctp.dtlsTransport){const n=this.findOrCreateTransport();s.sctp.setDtlsTransport(n)}return s}removeTrack(e){if(this.isClosed){throw ne(\"InvalidStateError\",\"peer closed\")}if(this.transceiverManager.removeTrack(e)){this.needNegotiation()}}scheduleNegotiationneeded(){this.invalidateLastCreatedDescriptions();this.shouldNegotiationneeded=true;if(this.negotiationneeded||this.negotiationneededScheduled||this.signalingState!==\"stable\"){return}this.shouldNegotiationneeded=false;this.negotiationneededScheduled=true;setImmediate(()=>{this.negotiationneededScheduled=false;if(this.negotiatedChangeSeq>=this.negotiationChangeSeq){return}if(this.signalingState!==\"stable\"){this.shouldNegotiationneeded=true;return}this.negotiationneeded=true;this.onNegotiationneeded.execute();if(this.onnegotiationneeded){Ne(()=>this.onnegotiationneeded(new globalThis.Event(\"negotiationneeded\")),e=>ye(\"event handler failed\",e))}this.emit(\"negotiationneeded\")})}invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0;this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed();await Promise.resolve();if(this.isClosed){await new Promise(()=>void 0)}}findOrCreateTransport(){const e=this.dtlsTransports.find(t=>t.state!==\"closed\");if(this.sdpManager.bundlePolicy===\"max-bundle\"||this.sdpManager.bundlePolicy!==\"disable\"&&this.remoteIsBundled){if(e){return e}}return this.createDtlsTransport()}createDtlsTransport({inheritCredentials:e=true}={}){const t=this.secureManager.createTransport({inheritCredentials:e});t.onRtp.subscribe(n=>{this.router.routeRtp(n)});t.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});const s=t.iceTransport;s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()});s.onIceCandidate.subscribe(n=>{if(!this.localDescription){ye(\"localDescription not found when ice candidate was gathered\");return}if(!n){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport);this.onIceCandidate.execute(void 0);if(this.onicecandidate){Ne(()=>this.onicecandidate({candidate:void 0}),o=>ye(\"event handler failed\",o))}this.emit(\"icecandidate\",{candidate:void 0});return}if(!this._localDescription){ye(\"localDescription not found when ice candidate was gathered\");return}const i=this.resolveLocalCandidateOwner(s);if(!i){ye(\"no accepted m-line owns the ice transport\",s.id);return}this.secureManager.handleNewIceCandidate({candidate:n,sdpMid:i.mid,sdpMLineIndex:i.index})});return t}resolveLocalCandidateOwner(e){const t=this._localDescription;if(!t){return}const s=t.media.map((o,c)=>({media:o,index:c})).filter(({media:o})=>{if(o.port===0){return false}const c=o.rtp.muxId;if(o.kind===\"application\"){return!!this.sctpTransport&&this.sctpTransport.mid===c&&this.sctpTransport.dtlsTransport?.iceTransport.id===e.id}const l=this.transceiverManager.getTransceivers().find(u=>u.mid!=void 0&&u.mid===c);return!!l&&!l.stopped&&l.dtlsTransport?.iceTransport.id===e.id});const n=t.group.filter(o=>o.semantic===\"BUNDLE\").map(o=>o.items[0]);const i=s.find(({media:o})=>n.includes(o.rtp.muxId))??s[0];if(!i){return}return{mid:i.media.rtp.muxId,index:i.index}}settleStoppingTransceivers(){const e=new Set((this.sdpManager.currentLocalDescription?.media??[]).filter(s=>s.port!==0&&s.rtp.muxId).map(s=>s.rtp.muxId));const t=this.transceiverManager.settleStoppingTransceivers(e);this.closeIdleTransports();return t}closeIdleTransports(e=this.transceiverManager.getTransceivers().filter(t=>t.stopped).map(t=>t.dtlsTransport)){const t=new Set(this.dtlsTransports.map(s=>s.id));for(const s of new Set(e)){if(!s||s.state===\"closed\"||t.has(s.id)){continue}s.stop().catch(n=>{ye(\"failed to close idle transport\",n)})}}async setLocalDescription(e){const t=[\"stable\",\"have-local-offer\",\"have-remote-pranswer\"];await this.waitForPendingDescriptionTask();if(e?.type===\"rollback\"){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const d of this.transceiverManager.getTransceivers()){d.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}const s=!e?.type||!e.sdp||e.sdp.length===0;const n=s?e?.type===\"offer\"?this.lastCreatedOffer??await this.createOffer():e?.type===\"answer\"||e?.type===\"pranswer\"?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;e={type:e?.type??n.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:n.sdp};if(e.type===\"offer\"&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp){throw ne(\"InvalidModificationError\",\"setLocalDescription must use the latest created offer\")}const i=e.type;const o=e.sdp;const c=this.sdpManager.parseSdp({sdp:o,isLocal:true,signalingState:this.signalingState,type:i});if(c.type===\"offer\"){this.pendingOfferChangeSeq=this.lastCreatedOffer?.sdp===e.sdp?this.lastCreatedOfferChangeSeq:void 0;this.setSignalingState(\"have-local-offer\")}else if(c.type===\"answer\"){this.setSignalingState(\"stable\")}else if(c.type===\"pranswer\"){this.setSignalingState(\"have-local-pranswer\")}if(c.type===\"answer\"){this.transceiverManager.commitRemoteOffer();for(const d of c.media){if(![\"audio\",\"video\"].includes(d.kind)||d.port!==0){continue}const h=this.transceiverManager.getTransceivers().find(p=>p.mid===d.rtp.muxId&&!p.stopped);h?.commitStopped({rejected:true})}this.closeIdleTransports()}for(const[d,h]of Fp(c.media)){const p=h.rtp.muxId;this.sdpManager.registerMid(p);if([\"audio\",\"video\"].includes(h.kind)&&h.port!==0){const m=this.transceiverManager.getTransceivers().find(y=>y.mLineIndex===d&&!y.stopped&&y.kind===h.kind&&(y.mid==null||y.mid===p));if(m){m.mid=p;if(c.type===\"offer\"){m.pendingLocalOfferCodecs=[...h.rtp.codecs]}}}if(h.kind===\"application\"&&this.sctpTransport){this.sctpTransport.mid=p}}const l=c.media.find(d=>d.dtlsParams)?.dtlsParams?.role;const u=new Map;for(const d of c.media){const h=d.rtp.muxId;const p=d.dtlsParams?.role;if(d.port===0||h==void 0||!p){continue}const m=d.kind===\"application\"?this.sctpTransport?.mid===h?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(y=>y.mid===h&&!y.stopped);if(m?.dtlsTransport&&!u.has(m.dtlsTransport)){u.set(m.dtlsTransport,p)}}this.secureManager.setLocalRole({type:c.type===\"offer\"?\"offer\":\"answer\",role:l,roleOfTransport:u});if([\"answer\",\"pranswer\"].includes(c.type)){for(const d of c.media){const h=this.transceiverManager.getTransceivers().find(m=>m.mid!=void 0&&m.mid===d.rtp.muxId);if(!h||h.stopped||h.pendingRejection){continue}const p=h.stopping?\"inactive\":Gf(h.direction,h.offerDirection);h.setCurrentDirection(p)}}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);await this.gatherCandidates().catch(d=>{ye(\"gatherCandidates failed\",d)});if(c.type===\"answer\"){this.connect().catch(d=>{ye(\"connect failed\",d);this.secureManager.setConnectionState(\"failed\")})}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);const f=c.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||f){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return c}async gatherCandidates(){await this.secureManager.gatherCandidates()}async addIceCandidate(e={}){if(this.isClosed){throw ne(\"InvalidStateError\",\"is closed\")}if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){const t=this.sdpManager._remoteDescription;if(!t){return}const s=await this.secureManager.addIceCandidate(t,e);const n=this.sdpManager._remoteDescription;if(!n||!s){return}if(s.kind===\"end-of-candidates\"){for(const i of s.mediaIndices){const o=n.media[i];if(o){o.iceCandidatesComplete=true}}return}for(const i of s.mediaIndices){const o=n.media[i];if(!o){continue}o.iceCandidates.push(s.candidate)}}async flushPendingRemoteCandidates(){while(this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription){const e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){ye(\"start connect\");const e=await Promise.allSettled(this.dtlsTransports.map(async t=>{const{iceTransport:s}=t;if(s.state===\"connected\"){return}if(!s.connection.remoteUsername||!s.connection.remotePassword){return}const n=a(()=>t.state===\"connected\",\"checkDtlsConnected\");if(n()){if(!s.connection.nominated){await s.start().catch(i=>{ye(\"iceTransport.start failed\",i);throw i})}return}this.secureManager.setConnectionState(\"connecting\");await s.start().catch(i=>{ye(\"iceTransport.start failed\",i);throw i});if(n()){return}await t.start().catch(i=>{ye(\"dtlsTransport.start failed\",i);throw i});if(this.sctpTransport&&this.sctpTransport.dtlsTransport.id===t.id){await this.sctpManager.connectSctp()}}));if(e.find(t=>t.status===\"rejected\")){this.secureManager.setConnectionState(\"failed\")}else{this.secureManager.setConnectionState(\"connected\")}}restartIce(){this.needRestart=true;this.needNegotiation()}async setRemoteDescription(e){if(e instanceof Jr){e=e.toSdp()}await this.waitForPendingDescriptionTask();const t=e.type===\"offer\"&&[\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState);if(t){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const S of this.transceiverManager.getTransceivers()){S.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.shouldNegotiationneeded=true;this.setSignalingState(\"stable\");await Promise.resolve()}let s=new Map;if(e.type&&e.type!==\"rollback\"&&e.sdp){const S=this.sdpManager.parseSdp({sdp:e.sdp,isLocal:false,signalingState:this.signalingState,type:e.type});const T=new Set;s=this.transceiverManager.planRemoteRtpCodecs(S,(_,x)=>{const k=this.findTransceiverForRemoteMedia(_,x,T,e.type===\"offer\");if(k)T.add(k);return k})}this.assertAnswerKeepsSharedTransports(e);const n=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!n){const S=this.transceiverManager.getTransceivers().map(T=>T.dtlsTransport);this.transceiverManager.rollbackRemoteOffer();this.closeIdleTransports(S);this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}if(n.type===\"offer\"){this.transceiverManager.beginRemoteOffer()}const i=this.config.bundlePolicy===\"disable\"?[]:n.group.filter(S=>S.semantic===\"BUNDLE\");const o=a(S=>S==void 0?void 0:i.find(T=>T.items.includes(S)),\"groupOfMid\");const c=new Set;const l=n.media.map((S,T)=>{if([\"audio\",\"video\"].includes(S.kind)){let _=this.findTransceiverForRemoteMedia(S,T,c,n.type===\"offer\");if(!_){if(S.port===0){return{remoteMedia:S,index:T}}_=this.addRemoteTransceiver(S,T)}else if(_.mid==null){this.transceiverManager.associateMLine(_,T)}c.add(_);return{remoteMedia:S,index:T,transceiver:_}}else if(S.kind===\"application\"){let _=this.sctpTransport;if(!_){_=this.createSctpTransport();_.mid=S.rtp.muxId}return{remoteMedia:S,index:T,sctpTransport:_}}else{throw new Error(\"invalid media kind\")}});if(n.type===\"offer\"){this.transceiverManager.releaseUnassociatedReservations(c,n.media.length)}const u=a(S=>S.transceiver??S.sctpTransport,\"ownerOf\");const f=n.type===\"offer\";const d=a(S=>!!S&&S.state!==\"closed\",\"liveTransport\");const h=new Map;const p=new Set;for(const S of i){const T=l.filter(x=>!!u(x)&&S.items.includes(x.remoteMedia.rtp.muxId));if(T.length===0){continue}let _=T.map(x=>u(x).dtlsTransport).find(x=>d(x)&&(!f||!p.has(x)));if(!_){_=this.createDtlsTransport({inheritCredentials:false})}h.set(S,_);p.add(_);for(const x of T){const k=u(x);if(k.dtlsTransport!==_){k.setDtlsTransport(_)}}}if(f){for(const S of l){const T=u(S);if(!T||S.remoteMedia.port===0||o(S.remoteMedia.rtp.muxId)){continue}if(!d(T.dtlsTransport)||p.has(T.dtlsTransport)){T.setDtlsTransport(this.createDtlsTransport({inheritCredentials:false}))}p.add(T.dtlsTransport)}}const m=new Set;for(const S of l){const{remoteMedia:T,index:_}=S;if(S.transceiver){if(this.transceiverManager.setRemoteRTP(S.transceiver,T,n.type,_,s.get(_)??[])){m.add(S)}}else if(S.sctpTransport){this.sctpManager.setRemoteSCTP(T,_);m.add(S)}}const y=new Map;for(const S of i){for(const T of S.items){const _=l.find(x=>x.remoteMedia.rtp.muxId===T&&x.remoteMedia.port!==0&&m.has(x));if(_){y.set(S,_);break}}}for(const S of l){const{remoteMedia:T}=S;const _=u(S);if(!_){continue}const x=m.has(S);const k=_.dtlsTransport;const N=o(T.rtp.muxId);if(T.port===0||!k||k.state===\"closed\"||!x&&!N){continue}const A=k.iceTransport;const B=!N||y.get(N)===S;if(B){if(T.iceParams){const ee=!!this.sdpManager.inactiveRemoteMedia;A.setRemoteParams(T.iceParams,ee);if(T.iceParams.iceLite&&!A.connection.iceLite){A.connection.iceControlling=true}}if(T.dtlsParams){k.setRemoteParams(T.dtlsParams)}}for(const ee of T.iceCandidates){A.addRemoteCandidate(ee).catch(fe=>ye(\"add candidate failed\",fe))}if(T.iceCandidatesComplete){A.addRemoteCandidate(void 0).catch(ee=>ye(\"end of candidates failed\",ee))}if(n.type===\"answer\"&&T.dtlsParams?.role){k.role=T.dtlsParams.role===\"client\"?\"server\":\"client\"}}if(n.type===\"answer\"){for(const S of this.transceiverManager.getTransceivers()){if(!c.has(S)&&S.mid!=void 0&&!S.stopped){S.commitStopped({rejected:true})}}this.closeIdleTransports()}if(n.type===\"offer\"){this.setSignalingState(\"have-remote-offer\")}else if(n.type===\"answer\"){this.setSignalingState(\"stable\")}else if(n.type===\"pranswer\"){this.setSignalingState(\"have-remote-pranswer\")}await this.flushPendingRemoteCandidates();if(n.type===\"answer\"){ye(\"caller start connect\");this.connect().catch(S=>{ye(\"connect failed\",S);this.secureManager.setConnectionState(\"failed\")})}this.negotiationneeded=false;if(n.type===\"answer\"&&this.pendingOfferChangeSeq!=void 0){this.negotiatedChangeSeq=Math.max(this.negotiatedChangeSeq,this.pendingOfferChangeSeq);this.pendingOfferChangeSeq=void 0}const w=n.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||w){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions()}assertAnswerKeepsSharedTransports(e){if(![\"answer\",\"pranswer\"].includes(e.type??\"\")||![\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState)||!e.sdp||this.config.bundlePolicy===\"disable\"){return}const t=Jr.parse(e.sdp);const s=t.group.filter(i=>i.semantic===\"BUNDLE\");const n=new Map;for(const i of t.media){const o=i.rtp.muxId;if(i.port===0||o==void 0){continue}const c=i.kind===\"application\"?this.sctpTransport?.mid===o?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(h=>h.mid===o&&!h.stopped);const l=c?.dtlsTransport;if(!l){continue}const u={group:s.find(h=>h.items.includes(o)),credentials:`${i.iceParams?.usernameFragment}:${i.iceParams?.password}`};const f=n.get(l);if(!f){n.set(l,u);continue}const d=!!u.group&&u.group===f.group;if(!d&&u.credentials!==f.credentials){throw ne(\"InvalidAccessError\",`mid=${o} shares a transport in the local offer but the remote ${e.type} moves it out of that BUNDLE group`)}}}findTransceiverForRemoteMedia(e,t,s,n){const i=this.transceiverManager.getTransceivers().filter(u=>!s.has(u)&&u.kind===e.kind);const o=e.rtp.muxId;const c=o!=void 0?i.find(u=>u.mid===o):void 0;if(c){return c}if(e.port===0){return}const l=i.filter(u=>u.mid==null&&!u.stopping&&!u.stopped&&(!n||u.addedByAddTrack&&[\"sendrecv\",\"recvonly\"].includes(e.direction??\"sendrecv\")));return l.find(u=>u.mLineIndex===t)??l[0]}addRemoteTransceiver(e,t){const s=this.findOrCreateTransport();const n=this.transceiverManager.addTransceiver(e.kind,s,{direction:\"recvonly\"},{remoteMLineIndex:t});n.mid=e.rtp.muxId??null;this.secureManager.updateIceConnectionState();this.onRemoteTransceiverAdded.execute(n);return n}addTransceiver(e,t={}){const s=this.findOrCreateTransport();const n=this.transceiverManager.addTransceiver(e,s,t);this.secureManager.updateIceConnectionState();this.needNegotiation();return n}addTrack(e,...t){return this.addTrackOn(void 0,e,...t)}reusableForTrack(e){return this.transceiverManager.reusableForTrack(e,e.kind)}addTrackOn(e,t,...s){if(this.isClosed){throw ne(\"InvalidStateError\",\"is closed\")}const n=this.transceiverManager.addTrack(t,s,e);if(!n.dtlsTransport){const i=this.findOrCreateTransport();n.setDtlsTransport(i)}this.needNegotiation();return n.sender}async createAnswer(){this.assertNotClosed();await this.secureManager.ensureCerts();for(const s of this.transceiverManager.getTransceivers()){if(s.codecs.length!==0&&!s.codecPreferencesNeedResolution){continue}if(s.pendingRejection||s.stopping||s.stopped){continue}const n=this.sdpManager._remoteDescription;const i=n?.media.find(o=>o.rtp.muxId!=void 0&&o.rtp.muxId===s.mid&&o.kind===s.kind)??(s.mLineIndex!=void 0?n?.media[s.mLineIndex]:void 0);if(i&&[\"audio\",\"video\"].includes(i.kind)){this.transceiverManager.resyncAnswerCodecs(s,i)}else{this.transceiverManager.assignTransceiverCodecs(s)}if(s.headerExtensions.length===0){s.headerExtensions=this.headerExtensionsFor(s.kind)}}const e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState});const t=e.toJSON();this.lastCreatedAnswer=t;return t}assertNotClosed(){if(this.isClosed){throw ne(\"InvalidStateError\",\"RTCPeerConnection is closed\")}}markStable(){this.transceiverManager.markStable();const e=this.sctpTransport;this.stableSctp=e?{mid:e.mid,mLineIndex:e.mLineIndex}:void 0}rollbackLocalOffer(){this.transceiverManager.rollbackLocalOffer();const e=this.sctpTransport;if(e){e.mid=this.stableSctp?.mid;e.mLineIndex=this.stableSctp?.mLineIndex}}setSignalingState(e){if(this.signalingState===e){return}ye(\"signalingStateChange\",e);this.signalingState=e;if(e===\"stable\")this.markStable();this.signalingStateChange.execute(e);if(this.onsignalingstatechange){Ne(()=>this.onsignalingstatechange(new globalThis.Event(\"signalingstatechange\")),t=>ye(\"event handler failed\",t))}this.emit(\"signalingstatechange\")}createPeerConnectionStats(e){return{type:\"peer-connection\",id:ue(\"peer-connection\",this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){const t=Qe();const s=[];if(!e){s.push(this.createPeerConnectionStats(t))}s.push(...this.transceiverManager.collectStats(t));const n=await this.secureManager.getStats(t);s.push(...n);if(!e&&this.sctpTransport){const i=await this.sctpManager.getStats(t);if(i){s.push(...i)}}if(!e){return On(s)}return On(s,this.transceiverManager.getStatsRootIds(e))}async close(){this.closing??=this.closeOnce();return this.closing}async closeOnce(){this.isClosed=true;this.pendingRemoteCandidates.length=0;this.setSignalingState(\"closed\");this.transceiverManager.close();await this.sctpManager.close();await this.secureManager.close();this.completePeerEvents();ye(\"peerConnection closed\")}completePeerEvents(){const e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(const t of e){if(!t.ended){t.complete()}}}};var zR=[\"compatible\",\"aggressive\"];function wP(r){for(const[e,t]of Fp([...r.codecs.audio||[],...r.codecs.video||[]])){if(t.payloadType!=void 0){continue}t.payloadType=96+e;switch(t.name.toLowerCase()){case\"rtx\":{t.parameters=`apt=${t.payloadType-1}`}break;case\"red\":{if(t.contentType===\"audio\"){const s=t.payloadType+1;t.parameters=`${s}/${s}`;t.payloadType=63}}break}}}a(wP,\"assignDynamicPayloadTypes\");function GR(){return{codecs:LE(),headerExtensions:{audio:[],video:[]},iceTransportPolicy:\"all\",iceLite:false,iceServers:[],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:true,iceUseIpv6:true,iceUseTcp:false,iceTcpPassive:true,iceStunGatherTimeout:void 0,iceTurnConnectTimeout:void 0,turnTransport:void 0,turnTlsOptions:void 0,turnUdpFamily:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:\"max-compat\",rtcpMuxPolicy:\"require\",iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:false,forceTurnTCP:false,maxMessageSize:To,sctp:{mtu:ji},pendingRtp:false,mLineReuse:\"compatible\"}}a(GR,\"generateDefaultPeerConfig\");var rre=GR();function EP(r){const e=Object(r??{});const t={...e};if(e.sctp!==void 0){t.sctp={...e.sctp}}if(e.bundlePolicy===\"balanced\"){t.bundlePolicy=\"max-compat\"}if(\"certificates\"in e){if(e.certificates===void 0){t.certificates=void 0}else if(!Array.isArray(e.certificates)||e.certificates.some(s=>s==null)){throw rr(\"certificates must be an array of RTCCertificate\")}else{t.certificates=[...e.certificates]}}if(\"iceCandidatePoolSize\"in e){t.iceCandidatePoolSize=TP(e.iceCandidatePoolSize,\"iceCandidatePoolSize\")}return t}a(EP,\"normalizePeerConfiguration\");function TP(r,e){const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw rr(`${e} must be an unsigned short`)}return t}a(TP,\"coerceUnsignedShort\");function xP(r,e){return r.length===e.length&&r.every((t,s)=>t===e[s])}a(xP,\"hasSameCertificates\");function RP(r){return{...r,codecs:{audio:r.codecs.audio?[...r.codecs.audio]:void 0,video:r.codecs.video?[...r.codecs.video]:void 0},headerExtensions:{audio:r.headerExtensions.audio?[...r.headerExtensions.audio]:void 0,video:r.headerExtensions.video?[...r.headerExtensions.video]:void 0},iceServers:r.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:r.icePortRange?[...r.icePortRange]:void 0,iceAdditionalHostAddresses:r.iceAdditionalHostAddresses?[...r.iceAdditionalHostAddresses]:void 0,dtls:{...r.dtls},certificates:[...r.certificates],debug:{...r.debug},sctp:{...r.sctp},pendingRtp:typeof r.pendingRtp===\"object\"&&r.pendingRtp!=void 0?{...r.pendingRtp}:r.pendingRtp}}a(RP,\"clonePeerConfiguration\");var Rg=class{static{a(this,\"RTCTrackEvent\")}constructor(e){this.type=\"track\";this.track=e.track;this.streams=[...e.streams];this.transceiver=e.transceiver;this.receiver=e.receiver}};function KR(r){const e={iceServers:r.iceServers,iceTransportPolicy:r.iceTransportPolicy,iceUseIpv4:r.iceUseIpv4,iceUseIpv6:r.iceUseIpv6,codecs:jE(r.codecs),maxMessageSize:262144};if(r.icePortRange)e.icePortRange=r.icePortRange;if(r.iceAdditionalHostAddresses)e.iceAdditionalHostAddresses=r.iceAdditionalHostAddresses;if(r.headerExtensions){e.headerExtensions={audio:[DR(),bg(),yg(),gg()],video:[bg(),yg(),gg()]};for(const t of[...e.codecs.audio,...e.codecs.video])t.rtcpFeedback.push(Nu())}return e}a(KR,\"engineConfigOf\");var _g=new WeakMap;function Cg(r){return _g.get(r)}a(Cg,\"engineConnectionOf\");var vg=new WeakMap;function WR(r){return vg.get(r)}a(WR,\"engineChannelOf\");var VR=require(\"node:events\");var vo=class{static{a(this,\"Events\")}#e=new EventTarget;#t=new VR.EventEmitter;#r=new Map;#s;constructor(e){this.#s=e;this.#t.setMaxListeners(0)}fire(e,t,...s){const n=e===\"message\"?new MessageEvent(\"message\",{data:t.data}):new Event(e);for(const[o,c]of Object.entries(t)){if(o!==\"data\")Object.defineProperty(n,o,{value:c,enumerable:true})}Object.defineProperty(n,\"currentTarget\",{value:this.#s});this.#e.dispatchEvent(n);const i=this.#r.get(e);if(i)i.call(this.#s,n);if(e!==\"error\"||this.#t.listenerCount(\"error\"))this.#t.emit(e,...s)}dispatch(e,...t){const s=this.#e.dispatchEvent(e);this.#r.get(e.type)?.call(this.#s,e);if(e.type!==\"error\"||this.#t.listenerCount(\"error\"))this.#t.emit(e.type,...t);return s&&!e.defaultPrevented}addEventListener(e,t,s){this.#e.addEventListener(e,t,s)}removeEventListener(e,t,s){this.#e.removeEventListener(e,t,s)}on(e,t){this.#t.on(e,t)}once(e,t){this.#t.once(e,t)}off(e,t){this.#t.off(e,t)}handler(e){return this.#r.get(e)??null}setHandler(e,t){if(t){this.#r.set(e,t)}else{this.#r.delete(e)}}};var hd=class{static{a(this,\"PeerChannel\")}#e;#t=new vo(this);#r=\"nodebuffer\";constructor(e){this.#e=e;vg.set(this,e);e.stateChanged.subscribe(t=>{this.#t.fire(t===\"closed\"?\"close\":t,{})});e.onMessage.subscribe(t=>{const s=typeof t===\"string\"||this.#r===\"nodebuffer\"?t:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.#t.fire(\"message\",{data:s},s)});e.bufferedAmountLow.subscribe(()=>this.#t.fire(\"bufferedamountlow\",{}));e.error.subscribe(t=>this.#t.fire(\"error\",{error:t},t))}get label(){return this.#e.label}get id(){return this.#e.id??null}get protocol(){return this.#e.protocol}get ordered(){return this.#e.ordered}get maxRetransmits(){return this.#e.maxRetransmits??null}get maxPacketLifeTime(){return this.#e.maxPacketLifeTime??null}get negotiated(){return this.#e.negotiated}get readyState(){return this.#e.readyState}get bufferedAmount(){return this.#e.bufferedAmount}get bufferedAmountLowThreshold(){return this.#e.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this.#e.bufferedAmountLowThreshold=e}get binaryType(){return this.#r}set binaryType(e){if(e!==\"nodebuffer\"&&e!==\"arraybuffer\")throw new TypeError(`Unsupported binaryType: ${e}`);this.#r=e}get onopen(){return this.#t.handler(\"open\")}set onopen(e){this.#t.setHandler(\"open\",e)}get onmessage(){return this.#t.handler(\"message\")}set onmessage(e){this.#t.setHandler(\"message\",e)}get onclosing(){return this.#t.handler(\"closing\")}set onclosing(e){this.#t.setHandler(\"closing\",e)}get onclose(){return this.#t.handler(\"close\")}set onclose(e){this.#t.setHandler(\"close\",e)}get onbufferedamountlow(){return this.#t.handler(\"bufferedamountlow\")}set onbufferedamountlow(e){this.#t.setHandler(\"bufferedamountlow\",e)}get onerror(){return this.#t.handler(\"error\")}set onerror(e){this.#t.setHandler(\"error\",e)}send(e){if(this.#e.readyState!==\"open\")throw new DOMException(`The channel ${this.label} is ${this.#e.readyState}`,\"InvalidStateError\");if(typeof e===\"string\")return this.#e.send(e);const t=ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);this.#e.send(t)}close(){if(this.#e.readyState===\"closing\"||this.#e.readyState===\"closed\")return;this.#e.close()}addEventListener(e,t,s){this.#t.addEventListener(e,t,s)}removeEventListener(e,t,s){this.#t.removeEventListener(e,t,s)}dispatchEvent(e){return this.#t.dispatch(e,...e instanceof MessageEvent?[e.data]:[])}on(e,t){this.#t.on(e,t);return this}once(e,t){this.#t.once(e,t);return this}off(e,t){this.#t.off(e,t);return this}};var ZR=new WeakMap;var Ag=class{static{a(this,\"RtpSender\")}#e;constructor(e){this.#e=e;ZR.set(this,e)}get track(){return this.#e.track?cn(this.#e.track):null}async replaceTrack(e){await this.#e.replaceTrack(e?er(e):null)}setStreams(...e){this.#e.setStreams(e.map(t=>new Br({id:t})))}};var Ig=class{static{a(this,\"RtpReceiver\")}#e;constructor(e){this.#e=e}get track(){return cn(this.#e.track,this.#e)}};var XR=new WeakMap;var YR=new WeakMap;var JR=new WeakMap;var Og=class{static{a(this,\"RtpTransceiver\")}#e;constructor(e){this.#e=e}get mid(){return this.#e.mid}get kind(){return this.#e.kind}get direction(){return this.#e.direction}set direction(e){this.#e.direction=e}get currentDirection(){return this.#e.currentDirection}get sender(){return pd(this.#e.sender)}get receiver(){return md(this.#e.receiver)}stop(){this.#e.stop()}};function pd(r){let e=XR.get(r);if(!e){e=new Ag(r);XR.set(r,e)}return e}a(pd,\"senderOf\");function Wc(r){return ZR.get(r)}a(Wc,\"engineSenderOf\");function md(r){let e=YR.get(r);if(!e){e=new Ig(r);YR.set(r,e)}return e}a(md,\"receiverOf\");function gd(r){let e=JR.get(r);if(!e){e=new Og(r);JR.set(r,e)}return e}a(gd,\"transceiverOf\");var Rr=function(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect===\"object\"&&typeof Reflect.decorate===\"function\")i=Reflect.decorate(r,e,t,s);else for(var c=r.length-1;c>=0;c--)if(o=r[c])i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i;return n>3&&i&&Object.defineProperty(e,t,i),i};var Zr=function(r,e){if(typeof Reflect===\"object\"&&typeof Reflect.metadata===\"function\")return Reflect.metadata(r,e)};var kg=class{static{a(this,\"IceCandidate\")}constructor(e){this.candidate=e.candidate;this.sdpMid=e.sdpMid??null;this.sdpMLineIndex=e.sdpMLineIndex??null;this.usernameFragment=e.usernameFragment??null}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};function yd(r){return r?{type:r.type,sdp:r.sdp}:null}a(yd,\"plainDescription\");var xt=class Nre extends Ys{static{a(this,\"PeerConnection\")}#e=new vo(this);#t=new WeakMap;#r;#s=false;async init(){const e={iceServers:this.iceServers,iceTransportPolicy:this.iceTransportPolicy,iceUseIpv4:this.iceUseIpv4,iceUseIpv6:this.iceUseIpv6,codecs:this.codecs,headerExtensions:this.headerExtensions,...this.icePortRange?{icePortRange:this.icePortRange}:{},...this.iceAdditionalHostAddresses?{iceAdditionalHostAddresses:this.iceAdditionalHostAddresses}:{}};let t;if(this.threads){t=await(await this.getObject(this.threads)).open(e)}else{t=new dd(KR(e));_g.set(this,t)}this.#r=t;t.onIceCandidate.subscribe(s=>{const n=s?new kg(s):null;this.#n(\"icecandidate\",{candidate:n},n?n.toJSON():null)});t.onDataChannel.subscribe(s=>{const n=this.#u(s);this.#n(\"datachannel\",{channel:n},n)});t.on(\"track\",s=>{const n=cn(s.track,s.receiver);const i=s.streams.map(c=>c.id);const o=gd(s.transceiver);this.#n(\"track\",{track:n,streams:i.map(c=>({id:c})),receiver:md(s.receiver),transceiver:o},n,i,o)});t.onTransceiverAdded.subscribe(s=>{s.sender.onPictureLossIndication.subscribe(()=>{if(s.sender.track)WE(cn(s.sender.track))})});t.onNegotiationneeded.subscribe(()=>this.#n(\"negotiationneeded\",{}));t.connectionStateChange.subscribe(s=>this.#n(\"connectionstatechange\",{},s));t.iceConnectionStateChange.subscribe(s=>this.#n(\"iceconnectionstatechange\",{},s));t.iceGatheringStateChange.subscribe(s=>this.#n(\"icegatheringstatechange\",{},s));t.signalingStateChange.subscribe(s=>this.#n(\"signalingstatechange\",{},s))}async destroy(){this.#s=true;await this.#r?.close()}get connectionState(){return this.#r.connectionState}get iceConnectionState(){return this.#r.iceConnectionState}get iceGatheringState(){return this.#r.iceGatheringState}get signalingState(){return this.#r.signalingState}get localDescription(){return yd(this.#r.localDescription)}get remoteDescription(){return yd(this.#r.remoteDescription)}get sctp(){const e=this.#r.sctpTransport;return e?{maxMessageSize:e.remoteMaxMessageSize}:null}get onicecandidate(){return this.#e.handler(\"icecandidate\")}set onicecandidate(e){this.#e.setHandler(\"icecandidate\",e)}get ondatachannel(){return this.#e.handler(\"datachannel\")}set ondatachannel(e){this.#e.setHandler(\"datachannel\",e)}get ontrack(){return this.#e.handler(\"track\")}set ontrack(e){this.#e.setHandler(\"track\",e)}get onnegotiationneeded(){return this.#e.handler(\"negotiationneeded\")}set onnegotiationneeded(e){this.#e.setHandler(\"negotiationneeded\",e)}get onconnectionstatechange(){return this.#e.handler(\"connectionstatechange\")}set onconnectionstatechange(e){this.#e.setHandler(\"connectionstatechange\",e)}get oniceconnectionstatechange(){return this.#e.handler(\"iceconnectionstatechange\")}set oniceconnectionstatechange(e){this.#e.setHandler(\"iceconnectionstatechange\",e)}get onicegatheringstatechange(){return this.#e.handler(\"icegatheringstatechange\")}set onicegatheringstatechange(e){this.#e.setHandler(\"icegatheringstatechange\",e)}get onsignalingstatechange(){return this.#e.handler(\"signalingstatechange\")}set onsignalingstatechange(e){this.#e.setHandler(\"signalingstatechange\",e)}async createOffer(e={}){return yd(await this.#r.createOffer(e))}async createAnswer(){return yd(await this.#r.createAnswer())}async setLocalDescription(e){await this.#r.setLocalDescription(e)}async setRemoteDescription(e){await this.#r.setRemoteDescription(e)}async addIceCandidate(e){if(!e?.candidate)return;await this.#r.addIceCandidate({candidate:e.candidate,sdpMid:e.sdpMid??void 0,sdpMLineIndex:e.sdpMLineIndex??void 0,usernameFragment:e.usernameFragment??void 0})}createDataChannel(e,t={}){return this.#u(this.#r.createDataChannel(e,t))}addTrack(e,...t){const s=t.map(n=>new Br({id:n}));return pd(this.#r.addTrack(er(e),...s))}removeTrack(e){this.#r.removeTrack(Wc(e))}addTransceiver(e,t={}){const s=(t.streams??[]).map(n=>new Br({id:n}));return gd(this.#r.addTransceiver(typeof e===\"string\"?e:er(e),{direction:t.direction??\"sendrecv\",streams:s}))}getTransceivers(){return this.#r.getTransceivers().map(gd)}getSenders(){return this.#r.getSenders().map(pd)}getReceivers(){return this.#r.getReceivers().map(md)}restartIce(){this.#r.restartIce()}getConfiguration(){const e=this.#r.getConfiguration();return{iceServers:e.iceServers,iceTransportPolicy:e.iceTransportPolicy}}setConfiguration(e){const t={};if(e.iceServers)t.iceServers=e.iceServers;if(e.iceTransportPolicy)t.iceTransportPolicy=e.iceTransportPolicy;this.#r.setConfiguration(t)}close(){if(this.#s)return;this.#s=true;this.#r.close().catch(()=>void 0);void this.dispose().catch(()=>void 0)}addEventListener(e,t,s){this.#e.addEventListener(e,t,s)}removeEventListener(e,t,s){this.#e.removeEventListener(e,t,s)}on(e,t){this.#e.on(e,t);return this}once(e,t){this.#e.once(e,t);return this}off(e,t){this.#e.off(e,t);return this}#u(e){let t=this.#t.get(e);if(!t){t=new hd(e);this.#t.set(e,t)}return t}#n(e,t,...s){if(this.#s&&e!==\"connectionstatechange\"&&e!==\"iceconnectionstatechange\"&&e!==\"signalingstatechange\")return;this.#e.fire(e,t,...s)}};Rr([Ve(I.Array().items(I.Object({urls:I.Alternatives(I.String(),I.Array().items(I.String())).required(),username:I.String().optional(),credential:I.String().optional()})).optional().default([])),Zr(\"design:type\",Array)],xt.prototype,\"iceServers\",void 0);Rr([Ve(I.String().valid(\"all\",\"relay\").optional().default(\"all\")),Zr(\"design:type\",String)],xt.prototype,\"iceTransportPolicy\",void 0);Rr([Ve(I.Array().items(I.Number().port()).length(2).optional()),Zr(\"design:type\",Array)],xt.prototype,\"icePortRange\",void 0);Rr([Ve(I.Array().items(I.String()).optional()),Zr(\"design:type\",Array)],xt.prototype,\"iceAdditionalHostAddresses\",void 0);Rr([Ve(I.Boolean().optional().default(true)),Zr(\"design:type\",Boolean)],xt.prototype,\"iceUseIpv4\",void 0);Rr([Ve(I.Boolean().optional().default(true)),Zr(\"design:type\",Boolean)],xt.prototype,\"iceUseIpv6\",void 0);Rr([Ve(I.Array().items(I.String().valid(...$u).insensitive()).optional().default(BE)),Zr(\"design:type\",Array)],xt.prototype,\"codecs\",void 0);Rr([Ve(I.Boolean().optional().default(false)),Zr(\"design:type\",Boolean)],xt.prototype,\"headerExtensions\",void 0);Rr([Ve(I.String().optional()),Zr(\"design:type\",String)],xt.prototype,\"threads\",void 0);xt=Rr([sm(),fa()],xt);var _P=5e3;function bd(r,e=_P){if(r.iceGatheringState===\"complete\")return Promise.resolve();return new Promise(t=>{const s=a(()=>{clearTimeout(i);r.off(\"icegatheringstatechange\",n);t()},\"done\");const n=a(o=>{if(o===\"complete\")s()},\"changed\");const i=setTimeout(s,e);r.on(\"icegatheringstatechange\",n)})}a(bd,\"gathered\");function CP(r){const e={candidates:[]};for(const t of r.split(/^(?=m=)/m)){const s=t.split(/\\r?\\n/);const n=s.find(i=>i.startsWith(\"a=mid:\"))?.slice(\"a=mid:\".length).trim();for(const i of s){if(i.startsWith(\"a=ice-ufrag:\"))e.ufrag??=i.slice(\"a=ice-ufrag:\".length).trim();else if(i.startsWith(\"a=ice-pwd:\"))e.pwd??=i.slice(\"a=ice-pwd:\".length).trim();else if(i.startsWith(\"a=candidate:\"))e.candidates.push({candidate:i.slice(2).trim(),...n===void 0?{}:{sdpMid:n}})}}return e}a(CP,\"iceOf\");async function Pg(r,e,t){const s=CP(e);const n=r.remoteDescription?.sdp??\"\";const i=[...n.matchAll(/^a=mid:(\\S+)/gm)].map(u=>u[1]);const o=a(async()=>{for(const{candidate:u,sdpMid:f}of s.candidates)await r.addIceCandidate({candidate:u,sdpMid:f??i[0]??null})},\"add\");const c=!!s.ufrag&&s.ufrag!==/^a=ice-ufrag:(\\S+)/m.exec(n)?.[1];if(c&&!t)return null;if(!c){if(!s.ufrag&&!s.candidates.length&&!/^a=end-of-candidates/m.test(e))throw new Error(\"The fragment has no ICE\");await o();return void 0}if(!s.pwd)throw new Error(\"The fragment of an ICE restart has no password\");const l=n.replace(/^a=ice-ufrag:.*$/gm,`a=ice-ufrag:${s.ufrag}`).replace(/^a=ice-pwd:.*$/gm,`a=ice-pwd:${s.pwd}`).replace(/^a=(candidate:.*|end-of-candidates)\\r?\\n/gm,\"\");await r.setRemoteDescription({type:\"offer\",sdp:l});await r.setLocalDescription();await o();await bd(r);return vP(r.localDescription?.sdp??\"\")}a(Pg,\"patchConnection\");function vP(r){const e=(r.split(/^(?=m=)/m)[1]??\"\").split(/\\r?\\n/);return[`a=ice-ufrag:${/^a=ice-ufrag:(\\S+)/m.exec(r)?.[1]??\"\"}`,`a=ice-pwd:${/^a=ice-pwd:(\\S+)/m.exec(r)?.[1]??\"\"}`,...e[0]?[e[0],...e.filter(t=>t.startsWith(\"a=mid:\")),...e.filter(t=>t.startsWith(\"a=candidate:\")),\"a=end-of-candidates\"]:[]].join(\"\\r\\n\")+\"\\r\\n\"}a(vP,\"fragmentOf\");var Vc={peerJoined:\"webrtc:peer-joined\",peerLeft:\"webrtc:peer-left\",signal:\"webrtc:signal\"};var Xc={label:\"webrtc.control\",id:1023};var Sd=class{static{a(this,\"Emitter\")}#e=new Map;on(e,t){let s=this.#e.get(e);if(!s){s=new Set;this.#e.set(e,s)}s.add(t);return this}once(e,t){const s=a((...n)=>{this.off(e,s);t(...n)},\"wrapper\");return this.on(e,s)}off(e,t){this.#e.get(e)?.delete(t);return this}emit(e,...t){const s=this.#e.get(e);if(!s?.size)return false;for(const n of[...s]){try{n(...t)}catch(i){queueMicrotask(()=>{throw i})}}return true}listened(e){return!!this.#e.get(e)?.size}};function QR(r){r.unref?.();return r}a(QR,\"unrefTimer\");var AP=200;function e_(r){return new Set([...(r??\"\").matchAll(/^a=ice-ufrag:(\\S+)/gm)].map(e=>e[1]))}a(e_,\"ufragsOf\");var IP=5e3;var Yc=class extends Sd{static{a(this,\"Peer\")}#e;#t;#r;#s;#u;#n;#a=false;#o=false;#c=false;#i=[];#f=0;#m=[];#l=false;#d=false;#h=false;#g;#w;#E;#y=new Set;#I;#L=new Promise(e=>{this.#I=e});constructor(e,t,s,n){super();this.#e=e;this.id=t;this.#t=s;this.#r=n;this.polite=e.polite??e.localId<t;this.#n=this.#u=this.#P()}get connection(){return this.#s}get metadata(){return this.#t}get session(){return this.#r}get away(){return this.#d}get closed(){return this.#l}get ready(){return this.#u}get negotiated(){return this.#L}createDataChannel(e,t){if(!this.#e.relay)return this.#s.createDataChannel(e,t);if(t?.negotiated||t?.protocol)throw new TypeError(\"A channel through the media server has no protocol of its own and is not negotiated\");return this.#O(this.#s.createDataChannel(e,{...t,protocol:this.id}))}pause(e){this.#b(e,false)}resume(e){this.#b(e,true)}restartIce(){if(this.#l)return;if(this.#e.relay)return this.#e.relay.restartIce();if(!this.#e.signalingUp){this.#h=true;return}this.#h=false;this.#s.restartIce()}close(){if(this.#l)return;this.#l=true;clearTimeout(this.#g);if(this.#e.relay){if(this.#w)this.#E?.off(\"connectionstatechange\",this.#w);for(const e of[...this.#y]){try{e.close()}catch{}}this.#y.clear()}else{try{this.#s?.close()}catch{}}this.emit(\"close\");this.#e.closed(this)}receive(e){if(this.#e.relay)return;this.#T(()=>this.#_(e))}#T(e){this.#n=this.#n.then(e).catch(t=>this.#A(t))}rejoined(e){this.#d=false;this.#t=e;this.emit(\"metadata\",e)}left(){if(!this.#e.relay&&this.#s?.connectionState===\"connected\"){this.#d=true}else{this.close()}}async#p(e){this.#E=e;await e.ready;await e.negotiated;if(this.#l)return;this.#s=e.connection;this.#w=t=>void this.emit(\"connectionstatechange\",t);e.on(\"connectionstatechange\",this.#w)}#O(e){this.#y.add(e);e.addEventListener(\"close\",()=>this.#y.delete(e));return e}signalingUp(){if(this.#h)this.restartIce()}relayedTrack(e){if(!this.#l)this.emit(\"track\",e)}relayedChannel(e){if(this.#l)return e.close();this.emit(\"datachannel\",this.#O(e))}#b(e,t){if(this.#l||!this.#s)return;const s=this.#s.getTransceivers().find(o=>o.receiver.track===e);if(!s)return;if(this.#e.relay){if(s.mid!==null)this.#e.control?.({type:t?\"resume\":\"pause\",mid:s.mid});return}const n=s.direction===\"sendrecv\"||s.direction===\"sendonly\";const i=t?n?\"sendrecv\":\"recvonly\":n?\"sendonly\":\"inactive\";if(s.direction!==\"stopped\"&&s.direction!==i)s.direction=i}async#P(){if(this.#e.relay)return await this.#p(this.#e.relay);const e=await this.#e.create();this.#s=e;if(this.#l){e.close();return}e.addEventListener(\"negotiationneeded\",()=>this.#T(()=>this.#R()));e.addEventListener(\"icecandidate\",t=>{const s=t.candidate;if(!s?.candidate)return;const n=typeof s.toJSON===\"function\"?s.toJSON():s;const i={candidate:n.candidate,sdpMid:n.sdpMid??null,sdpMLineIndex:n.sdpMLineIndex??null,usernameFragment:n.usernameFragment??null};if(this.#f){this.#m.push(i)}else{void this.#k({candidate:i})}});e.addEventListener(\"connectionstatechange\",()=>this.#M());e.addEventListener(\"datachannel\",t=>void this.emit(\"datachannel\",t.channel));e.addEventListener(\"track\",t=>void this.emit(\"track\",t))}#k(e){return this.#e.send(this.id,e).catch(t=>this.#A(t))}async#x(){this.#f++;try{await this.#s.setLocalDescription();const e=this.#s.localDescription;if(e)await this.#k({description:{type:e.type,sdp:e.sdp}})}finally{this.#f--;if(!this.#f)for(const e of this.#m.splice(0))void this.#k({candidate:e})}}async#R(){if(this.#l)return;if(this.#s.signalingState!==\"stable\"){this.#a=true;return}this.#a=false;try{this.#o=true;await this.#x()}catch(e){this.#A(e)}finally{this.#o=false}}async#_(e){if(this.#l)return;const t=this.#s;if(e.description){const s=e.description;const n=s.type===\"offer\"&&(this.#o||t.signalingState!==\"stable\");this.#c=!this.polite&&n;if(this.#c)return;await t.setRemoteDescription(s);const i=e_(s.sdp);const o=this.#i;this.#i=[];for(const c of o){if(!c.usernameFragment||i.has(c.usernameFragment)){await this.#C(c)}else{this.#i.push(c)}}if(s.type===\"offer\")await this.#x();if(t.signalingState===\"stable\"){this.#I();if(this.#a)await this.#R()}}else if(e.candidate){const s=t.remoteDescription;const n=e.candidate.usernameFragment;if(!s||n&&!e_(s.sdp).has(n)){if(!this.#c){this.#i.push(e.candidate);if(this.#i.length>AP)this.#i.shift()}return}await this.#C(e.candidate)}}async#C(e){try{await this.#s.addIceCandidate(e)}catch(t){if(!this.#c)throw t}}#M(){if(this.#l)return;const e=this.#s.connectionState;clearTimeout(this.#g);this.emit(\"connectionstatechange\",e);if(e===\"failed\"){this.#v()}else if(e===\"disconnected\"){this.#g=QR(setTimeout(()=>{if(this.#s.connectionState===\"disconnected\")this.#v()},IP))}else if(e===\"closed\"){this.close()}}#v(){if(this.#d)return this.close();this.restartIce()}#A(e){if(!this.#l)this.emit(\"error\",e)}};function Ps(r,e){return JSON.stringify([r,e])}a(Ps,\"trackKey\");var OP=5e3;var kP=1e3;function PP(r){try{const e=JSON.parse(r);return Array.isArray(e)&&e.length===2&&e.every(t=>typeof t===\"string\")?e:void 0}catch{return void 0}}a(PP,\"routeOf\");var wd=1024*1024;function t_(r,e,t=[]){const s=WR(r).sctp;const n=r.maxRetransmits===null&&r.maxPacketLifeTime===null;const i=[];let o=0;let c=0;e.bufferedAmountLowThreshold=wd/2;const l=a(()=>{while(i.length&&e.readyState===\"open\"&&e.bufferedAmount<wd){const{data:f,size:d}=i.shift();c-=d;e.send(f);if(n){o-=d;s.releaseReceived(d)}}},\"drain\");const u=a(f=>{const d=typeof f===\"string\"||Buffer.isBuffer(f)?f:Buffer.from(f);if(e.readyState===\"closing\"||e.readyState===\"closed\")return;if(!i.length&&e.readyState===\"open\"&&e.bufferedAmount<wd)return e.send(d);const h=typeof d===\"string\"?Buffer.byteLength(d):d.length;if(!n&&(e.readyState===\"open\"||c+h>wd))return;i.push({data:d,size:h});c+=h;if(n){o+=h;s.holdReceived(h)}},\"relayed\");t.forEach(u);r.on(\"message\",u);e.on(\"open\",l);e.on(\"bufferedamountlow\",l);e.on(\"close\",()=>{i.length=0;c=0;if(o)s.releaseReceived(o);o=0})}a(t_,\"relay\");function r_(r,e){const t=Cg(r);return e.mid===null?void 0:t.getTransceivers().find(s=>s.mid===e.mid)}a(r_,\"engineTransceiverOf\");var Ed=class{static{a(this,\"SFURoom\")}#e;#t=new Map;#r=new Map;#s=new Set;#u=new WeakSet;#n=new Map;#a=new Map;#o=new Map;#c=new Set;#i=false;constructor(e,t){this.#e=e;this.name=t;this.ready=this.#d()}get empty(){return!this.members.length&&!this.#r.size}get viewers(){return this.#r.size}get closed(){return this.#i}get members(){return[...this.#t.values()].filter(e=>!e.cascade).map(e=>e.id)}get tracks(){return[...this.#s].filter(e=>!e.remote).map(e=>e.track)}track(e,t){for(const o of this.#s){if(!o.remote&&o.track.peerId===e&&o.track.id===t)return o.media}const s=Ps(e,t);const n=this.#z(s);if(!n)return void 0;let i=this.#o.get(s);if(!i){const o=n.codec??{mimeType:n.track.codec,clockRate:n.track.kind===\"audio\"?48e3:9e4};const c=VE(n.track.kind,new ft(o),t,{requestKeyFrame:a(()=>this.#F(s)?.media.requestKeyFrame(),\"requestKeyFrame\"),wanted:a(l=>{const u=this.#o.get(s);if(!u)return;u.wanted=l;this.#U(s);this.#S()},\"wanted\")});i={track:c.track,receive:c.receive,wanted:false};this.#o.set(s,i)}return i.track}cascades(){return Object.fromEntries([...this.#t.values()].filter(e=>!!e.cascade).map(e=>[e.id,{sends:e.subscriptions.size,receives:e.publications.size}]))}async close(){if(this.#i)return;this.#i=true;for(const e of[...this.#t.values()])this.#p(e);for(const e of[...this.#r.values()])this.#l(e);for(const e of[...this.#o.keys()])this.#j(e);for(const e of[...this.#c])e.channel.close();await this.#e.signaling.leave(this.#e.id,this.name).catch(()=>void 0)}async play(e,t,s){const n=await this.#e.connect();const i=[];let o=false;const c={connection:n,ready:Promise.resolve(),get closed(){return o},close:a(()=>{if(o)return;o=true;n.close();for(const u of i.splice(0))u()},\"close\")};const l={id:e,leg:c,transceivers:new Map,attached:new Map,select:s,feeding:Promise.resolve()};n.on(\"connectionstatechange\",u=>{if(u===\"failed\"||u===\"closed\")this.#l(l)});try{await n.setRemoteDescription(t);for(const u of n.getTransceivers()){if(l.transceivers.has(u.kind))continue;l.transceivers.set(u.kind,u);u.direction=\"sendonly\"}if(!l.transceivers.size)throw new Error(\"The offer has no audio and no video\");await n.setLocalDescription();await bd(n);if(o)throw new Error(`The connection is ${n.connectionState}`)}catch(u){c.close();throw u}this.#r.set(e,l);this.#e.changed?.(this);await this.#f(l);return{answer:n.localDescription,patch:a((u,f)=>Pg(n,u,f),\"patch\"),ended:a(u=>o?u():i.push(u),\"ended\"),close:a(()=>this.#l(l),\"close\"),source:a(()=>l.source,\"source\")}}#f(e){e.feeding=e.feeding.then(()=>this.#m(e)).catch(()=>void 0);return e.feeding}async#m(e){if(e.leg.closed)return;const t=[...this.tracks,...[...this.#D()].map(c=>c.track)];const s=e.select?await e.select(t):void 0;if(e.leg.closed)return;const n=[...new Set(t.map(c=>c.peerId))];const i=s??n.filter(c=>c.startsWith(\"whip:\")).at(-1)??n[0];const o=e.source;e.source=i!==void 0&&n.includes(i)?i:void 0;if(e.source!==o){this.#e.sourced?.(e.id,e.source);this.#S()}for(const[c,l]of e.transceivers){const u=e.source===void 0?void 0:[...this.#s].find(f=>f.track.peerId===e.source&&f.track.kind===c);if(e.attached.get(c)===u)continue;e.attached.delete(c);try{await l.sender.replaceTrack(u?.media??null)}catch{this.#e.emit(\"unsupported\",this.name,e.id,u.track);await l.sender.replaceTrack(null).catch(()=>void 0);continue}if(!u)continue;e.attached.set(c,u);if(c===\"video\")u.media.requestKeyFrame()}}#l(e){if(this.#r.get(e.id)!==e)return e.leg.close();this.#r.delete(e.id);e.leg.close();if(!this.#i)this.#e.changed?.(this);if(!this.#i&&this.empty)this.#e.emptied(this)}async publish(e,t){const s=await this.#e.connect();const n=[];let i=false;const o={connection:s,ready:Promise.resolve(),get closed(){return i},close:a(()=>{if(i)return;i=true;s.close();for(const l of n.splice(0))l()},\"close\")};const c={id:e,leg:o,metadata:void 0,publications:new Map,subscriptions:new Map,streams:new Map,streamIds:new Map,transceivers:new Set};this.#t.set(e,c);this.#e.changed?.(this);s.addEventListener(\"track\",l=>this.#x(c,l));s.on(\"connectionstatechange\",l=>{if(l===\"failed\"||l===\"closed\")this.#p(c)});s.on(\"signalingstatechange\",l=>{if(l===\"stable\")setImmediate(()=>this.#v(c))});try{await s.setRemoteDescription(t);await s.setLocalDescription();await bd(s);if(i)throw new Error(`The connection is ${s.connectionState}`);await this.#e.signaling.join(e,this.name,{role:\"whip\",receive:a(()=>void 0,\"receive\")})}catch(l){this.#p(c);throw l}return{answer:s.localDescription,patch:a((l,u)=>Pg(s,l,u),\"patch\"),ended:a(l=>i?l():n.push(l),\"ended\"),close:a(()=>this.#p(c),\"close\")}}async#d(){const e=await this.#e.signaling.join(this.#e.id,this.name,{role:\"sfu\",receive:a((t,s)=>this.#w(t,s),\"receive\")});for(const t of e.peers){if(this.#g(t))this.#E(t.peerId,t.metadata,t.session);else this.#h(t)}}#h(e){if(e.role===\"sfu\"){if(e.peerId!==this.#e.id&&!this.#t.has(e.peerId))this.#$(e.peerId)}else if(!e.role&&e.sfu){this.#n.set(e.peerId,e.sfu)}this.#T()}#g(e){return!e.role&&e.sfu===this.#e.id}#w(e,t){if(this.#i)return;switch(e){case Vc.peerJoined:{const s=t;const n=this.#t.get(s.peerId);if(!this.#g(s)){if(!s.role&&n?.peer)this.#p(n);this.#h(s);return}this.#n.delete(s.peerId);if(n&&s.session!==void 0&&n.session!==s.session)this.#p(n);if(n&&this.#t.get(s.peerId)===n){const i=JSON.stringify(n.metadata)!==JSON.stringify(s.metadata);n.metadata=s.metadata;if(i)this.#G(n);return}this.#E(s.peerId,s.metadata,s.session);return}case Vc.peerLeft:{const s=t.peerId;this.#n.delete(s);const n=this.#t.get(s);if(n)this.#p(n);return}case Vc.signal:{const s=t;let n=this.#t.get(s.from);if(!n){if(this.#n.has(s.from))return;n=s.from.startsWith(\"sfu:\")?this.#$(s.from):this.#E(s.from,void 0,s.session)}if(n.cascade)for(const o of s.streams??[])n.cascade.received.set(o.id,o);const i={};if(s.description)i.description=s.description;if(s.candidate)i.candidate=s.candidate;n.peer?.receive(i);return}}}#E(e,t,s){const n={localId:this.#e.id,create:a(()=>this.#e.connect(),\"create\"),send:a((c,l)=>this.#O(o,l),\"send\"),signalingUp:true,closed:a(()=>void 0,\"closed\"),polite:false};const i=new Yc(n,e,t,s);const o={id:e,leg:i,peer:i,metadata:t,session:s,publications:new Map,subscriptions:new Map,streams:new Map,streamIds:new Map,transceivers:new Set};this.#t.set(e,o);this.#e.changed?.(this);this.#B();this.#T();i.on(\"error\",()=>void 0);i.on(\"track\",c=>this.#x(o,c));i.on(\"datachannel\",c=>this.#y(o,c));i.ready.then(async()=>{if(i.closed)return;const c=i.connection;c.on(\"signalingstatechange\",h=>{if(h===\"stable\")setImmediate(()=>this.#v(o))});c.on(\"connectionstatechange\",h=>{if(h===\"connected\")this.#K(o)});const l=o.metadata;const u=new Map([...this.#s].map(h=>[h,this.#P(o,h)]));const f=[...u.values()].some(h=>h instanceof Promise)?await this.#k(u):new Map;if(i.closed||this.#t.get(o.id)!==o)return;const d=c.createDataChannel(Xc.label,{negotiated:true,id:Xc.id});d.on(\"message\",h=>this.#A(o,h));o.control=d;for(const[h,p]of u){if(!this.#s.has(h))continue;if(o.metadata===l)this.#b(o,h,f.get(h)??p);else this.#b(o,h)}},()=>this.#p(o));return o}#y(e,t){let s=e.id;let n=t.protocol;if(e.cascade){const c=PP(t.protocol);if(!c)return t.close();[s,n]=c}const i=[];const o=a(c=>i.push(c),\"keep\");t.on(\"message\",o);this.#I({member:e,channel:t,source:s,target:n,early:i,keep:o})}#I(e){const{member:t,channel:s,source:n,target:i,early:o,keep:c}=e;if(s.readyState===\"closing\"||s.readyState===\"closed\")return;const l=this.#t.get(i);let u;let f;if(l?.cascade||i.startsWith(\"sfu:\"))return s.close();if(l){if(l===t||!l.peer||l.leg.closed)return s.close();u=l;f=n}else{const h=this.#n.get(i);if(t.cascade&&h!==void 0)return s.close();u=t.cascade||h===void 0?void 0:this.#t.get(h);f=JSON.stringify([n,i])}if(!u)return this.#L(e);const d=u;d.leg.ready.then(()=>d.cascade?d.peer.negotiated:void 0).then(()=>{s.off(\"message\",c);if(d.leg.closed||s.readyState===\"closed\")return s.close();const h=d.leg.connection.createDataChannel(s.label,{protocol:f,ordered:s.ordered,...s.maxRetransmits!==null?{maxRetransmits:s.maxRetransmits}:{},...s.maxPacketLifeTime!==null?{maxPacketLifeTime:s.maxPacketLifeTime}:{}});t_(s,h,o);t_(h,s);s.on(\"close\",()=>h.close());h.on(\"close\",()=>s.close())},()=>s.close())}#L(e){if(this.#c.has(e))return;this.#c.add(e);e.timer=setTimeout(()=>{this.#c.delete(e);e.channel.close()},OP);e.timer.unref();e.channel.on(\"close\",()=>{clearTimeout(e.timer);this.#c.delete(e)})}#T(){for(const e of[...this.#c]){const t=this.#t.has(e.target)||this.#t.has(this.#n.get(e.target)??\"\");if(!t)continue;this.#c.delete(e);clearTimeout(e.timer);this.#I(e)}}#p(e){if(this.#t.get(e.id)!==e)return;this.#t.delete(e.id);for(const t of[...e.publications.values()])this.#R(t);e.leg.close();if(!e.peer)this.#e.signaling.leave(e.id,this.name).catch(()=>void 0);if(e.cascade){for(const t of e.cascade.offered.keys())this.#j(t);for(const t of[...this.#c])if(this.#n.get(t.target)===e.id)t.channel.close();if(!this.#i)this.#H()}else{this.#a.delete(e.id);if(!this.#i)this.#S()}if(!this.#i)this.#e.changed?.(this);if(!this.#i&&this.empty)this.#e.emptied(this)}async#O(e,t){await this.#e.signaling.signal(this.#e.id,this.name,e.id,{...t,...t.description?{streams:[...e.streams.values()]}:{}})}#b(e,t,s=this.#P(e,t)){if(e===t.publisher||!e.peer||e.leg.closed)return;if(e.cascade){if(!t.remote&&e.cascade.wanted.has(Ps(t.track.peerId,t.track.id)))this.#_(e,t).catch(()=>void 0);return}const n=s;if(n===void 0)return;if(typeof n===\"boolean\"){if(n)this.#_(e,t).catch(()=>void 0);return}n.then(i=>i&&this.#t.get(e.id)===e&&!e.leg.closed&&this.#s.has(t)?this.#_(e,t):void 0).catch(()=>void 0)}#P(e,t){if(e===t.publisher||!e.peer||e.leg.closed||e.cascade)return void 0;return this.#e.select({peerId:e.id,metadata:e.metadata,session:e.session},t.track)}async#k(e){const t=new Map;const s=[];for(const[i,o]of e){if(o instanceof Promise)s.push(o.then(c=>void t.set(i,c),()=>void t.set(i,false)))}if(!s.length)return t;let n;await Promise.race([Promise.all(s),new Promise(i=>{n=setTimeout(i,kP)})]);clearTimeout(n);return t}#x(e,t){const s=e.publications.get(t.transceiver);if(s)this.#R(s);const n=r_(e.leg.connection,t.transceiver);let i=e.id;let o=t.streams[0]?.id??\"\";if(e.cascade){const u=e.cascade.received.get(o);if(!u)return;i=u.peerId;o=u.stream}const c={room:this.name,peerId:i,id:n?.receiver.remoteTrackId??t.transceiver.mid??t.track.id,kind:t.track.kind,codec:t.track.codec??\"\",stream:o};const l={track:c,media:t.track,transceiver:t.transceiver,publisher:e,remote:!!e.cascade};e.publications.set(t.transceiver,l);this.#s.add(l);if(l.remote){this.#U(Ps(c.peerId,c.id))}else{this.#e.emit(\"publish\",c);this.#N()}for(const u of this.#t.values())this.#b(u,l);for(const u of this.#r.values())void this.#f(u)}#R(e){if(!this.#s.delete(e))return;if(e.publisher.publications.get(e.transceiver)===e)e.publisher.publications.delete(e.transceiver);for(const t of this.#t.values())this.#C(t,e);if(e.remote){this.#U(Ps(e.track.peerId,e.track.id))}else{this.#e.emit(\"unpublish\",e.track);this.#N()}for(const t of this.#r.values())void this.#f(t)}async#_(e,t){if(e.subscriptions.has(t))return;const s=e.leg.connection;const n=this.#M(e,t.track);const i=new Set([...e.subscriptions.values()].map(c=>c.transceiver));const o=s.getTransceivers().find(c=>e.transceivers.has(c)&&!i.has(c)&&!c.sender.track&&c.direction===\"inactive\"&&c.currentDirection===\"inactive\"&&c.kind===t.track.kind&&r_(s,c)?.sender.codec?.mimeType.toLowerCase()===t.track.codec.toLowerCase());if(!o){const c=s.addTransceiver(t.media,{direction:\"sendonly\",streams:[n]});if(e.cascade)Wc(c.sender).trackId=t.track.id;e.transceivers.add(c);e.subscriptions.set(t,{transceiver:c,started:false,paused:false});return}e.subscriptions.set(t,{transceiver:o,started:false,paused:false});if(e.cascade)Wc(o.sender).trackId=t.track.id;await o.sender.replaceTrack(t.media);o.sender.setStreams(n);o.direction=\"sendonly\"}#C(e,t){const s=e.subscriptions.get(t);if(!s)return;e.subscriptions.delete(t);if(e.leg.closed)return;try{s.transceiver.direction=\"inactive\";s.transceiver.sender.replaceTrack(null).catch(()=>void 0)}catch{}}#M(e,t){const s=JSON.stringify([t.peerId,t.stream||t.id]);let n=e.streamIds.get(s);if(!n){n=`s${e.streamIds.size+1}`;e.streamIds.set(s,n);e.streams.set(n,{id:n,peerId:t.peerId,stream:t.stream})}return n}#v(e){if(e.leg.closed||e.leg.connection.signalingState!==\"stable\")return;for(const t of[...e.publications.values()]){const s=t.transceiver.currentDirection;if(s===\"inactive\"||s===\"sendonly\"||s===\"stopped\")this.#R(t)}for(const[t,s]of[...e.subscriptions]){const n=s.transceiver.currentDirection;if(n===\"stopped\"){e.subscriptions.delete(t);this.#e.emit(\"unsupported\",this.name,e.id,t.track)}else if(!s.started&&(n===\"sendonly\"||n===\"sendrecv\")){s.started=true;if(t.track.kind===\"video\")t.media.requestKeyFrame()}}}#A(e,t){let s;try{s=JSON.parse(typeof t===\"string\"?t:Buffer.from(t).toString())}catch{return}if(e.cascade)return this.#q(e,e.cascade,s);if(s?.type!==\"pause\"&&s?.type!==\"resume\")return;for(const[n,i]of e.subscriptions){if(i.transceiver.mid!==s.mid)continue;const o=s.type===\"pause\";if(i.paused===o)return;i.paused=o;i.transceiver.sender.replaceTrack(o?null:n.media).catch(()=>void 0);if(!o&&n.track.kind===\"video\")n.media.requestKeyFrame();return}}#$(e){const t={localId:this.#e.id,create:a(()=>this.#e.connect(),\"create\"),send:a((o,c)=>this.#O(i,c),\"send\"),signalingUp:true,closed:a(()=>void 0,\"closed\"),polite:this.#e.id>e};const s=new Yc(t,e,void 0,void 0);const n={offered:new Map,wanted:new Set,received:new Map};const i={id:e,leg:s,peer:s,metadata:void 0,publications:new Map,subscriptions:new Map,streams:new Map,streamIds:new Map,transceivers:new Set,cascade:n};this.#t.set(e,i);this.#T();s.on(\"error\",()=>void 0);s.on(\"track\",o=>this.#x(i,o));s.on(\"datachannel\",o=>this.#y(i,o));s.ready.then(()=>s.polite?s.negotiated:void 0).then(()=>{if(s.closed)return;const o=s.connection;o.on(\"signalingstatechange\",l=>{if(l===\"stable\")setImmediate(()=>this.#v(i))});const c=o.createDataChannel(Xc.label,{negotiated:true,id:Xc.id});c.on(\"message\",l=>this.#A(i,l));c.on(\"open\",()=>{n.toldTracks=void 0;n.toldWants=void 0;this.#N();this.#S()});i.control=c},()=>this.#p(i));return i}#q(e,t,s){if(!t.heard){t.heard=true;t.toldTracks=void 0;t.toldWants=void 0;this.#N();this.#S()}if(s?.type===\"tracks\"&&Array.isArray(s.tracks)){const n=t.offered;t.offered=new Map(s.tracks.filter(i=>typeof i?.track?.peerId===\"string\"&&typeof i.track.id===\"string\").map(i=>[Ps(i.track.peerId,i.track.id),{track:{...i.track,room:this.name},...i.codec?{codec:i.codec}:{}}]));for(const i of n.keys())if(!t.offered.has(i))this.#j(i);this.#H();this.#B();for(const i of this.#r.values())void this.#f(i)}else if(s?.type===\"want\"&&Array.isArray(s.keys)){t.wanted=new Set(s.keys.filter(n=>typeof n===\"string\"));for(const n of[...this.#s]){if(n.remote)continue;if(t.wanted.has(Ps(n.track.peerId,n.track.id)))this.#b(e,n);else this.#C(e,n)}}}*#D(){for(const e of this.#t.values())if(e.cascade)yield*e.cascade.offered.values()}#z(e){for(const t of this.#t.values()){const s=t.cascade?.offered.get(e);if(s)return s}return void 0}#F(e){for(const t of this.#s){if(t.remote&&Ps(t.track.peerId,t.track.id)===e)return t}return void 0}#H(){this.#e.known?.(this,[...this.#D()])}#N(){const e=[...this.#s].filter(s=>!s.remote).map(s=>{const n=er(s.media).codec;return{track:s.track,...n?{codec:{payloadType:n.payloadType,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,parameters:n.parameters}}:{}}});const t=JSON.stringify({type:\"tracks\",tracks:e});for(const s of this.#t.values()){if(!s.cascade||s.control?.readyState!==\"open\"||s.cascade.toldTracks===t)continue;s.cascade.toldTracks=t;s.control.send(t)}}#S(){if(this.#i)return;const e=new Set([...this.#r.values()].map(t=>t.source).filter(t=>t!==void 0));for(const t of this.#t.values()){const s=t.cascade;if(!s||t.control?.readyState!==\"open\")continue;const n=[];for(const[o,{track:c}]of s.offered){const l=[...this.#t.values()].some(u=>!!u.peer&&!u.cascade&&!u.leg.closed&&u.id!==c.peerId&&this.#a.get(u.id)?.get(o)===true);if(l||e.has(c.peerId)||this.#o.get(o)?.wanted)n.push(o)}const i=JSON.stringify({type:\"want\",keys:n.sort()});if(s.toldWants===i)continue;s.toldWants=i;t.control.send(i)}}#G(e){if(!e.peer||e.cascade)return;this.#a.delete(e.id);this.#B();if(!e.control)return;const t={peerId:e.id,metadata:e.metadata,session:e.session};for(const s of[...this.#s]){if(s.publisher===e)continue;const n=a(o=>{if(this.#t.get(e.id)!==e||e.leg.closed||!this.#s.has(s))return;if(o)this.#_(e,s).catch(()=>void 0);else this.#C(e,s)},\"apply\");const i=this.#e.select(t,s.track);if(typeof i===\"boolean\")n(i);else i.then(n,()=>void 0)}}#B(){for(const e of this.#t.values()){if(!e.peer||e.cascade)continue;let t=this.#a.get(e.id);if(!t){t=new Map;this.#a.set(e.id,t)}const s=t;for(const n of this.#D()){const i=Ps(n.track.peerId,n.track.id);if(s.has(i)||n.track.peerId===e.id)continue;const o=this.#e.select({peerId:e.id,metadata:e.metadata,session:e.session},n.track);if(typeof o===\"boolean\"){s.set(i,o);continue}s.set(i,false);o.then(c=>{if(!c||this.#a.get(e.id)!==s)return;s.set(i,true);this.#S()},()=>void 0)}}this.#S()}#U(e){const t=this.#o.get(e);if(!t)return;const s=t.wanted?this.#F(e):void 0;if(t.source===s)return;t.unpipe?.();t.unpipe=void 0;t.source=s;if(!s)return;t.unpipe=er(s.media).onReceiveRtp.subscribe((n,i)=>t.receive(n,i)).unSubscribe;if(s.track.kind===\"video\")s.media.requestKeyFrame()}#j(e){const t=this.#o.get(e);if(!t)return;this.#o.delete(e);t.unpipe?.();t.track.stop()}#K(e){const t=Cg(e.leg.connection).dtlsTransports[0];if(!t||this.#u.has(t))return;this.#u.add(t);t.senderBWE.onCongestion.subscribe(s=>{if(!e.leg.closed)this.#e.emit(\"congestion\",this.name,e.id,s,t.senderBWE.availableBitrate)})}};var Td=class{static{a(this,\"SFUWorkerChannel\")}#e;#t=new Map;#r=1;#s;constructor(e,t){this.#e=e;e.on(\"message\",s=>{const n=s;if(n.type===\"reply\"){const{reply:o,result:c,error:l}=n;const u=this.#t.get(o);this.#t.delete(o);if(l===void 0)u?.resolve(c);else u?.reject(new Error(l));return}const i=n.request;if(i===void 0){try{const o=t(n);if(o instanceof Promise)o.catch(()=>void 0)}catch{}return}Promise.resolve().then(()=>t(n)).then(o=>this.#u({type:\"reply\",reply:i,result:o}),o=>this.#u({type:\"reply\",reply:i,error:o instanceof Error?o.message:String(o)}))})}request(e){if(this.#s)return Promise.reject(this.#s);const t=this.#r++;return new Promise((s,n)=>{this.#t.set(t,{resolve:s,reject:n});try{this.#e.postMessage({...e,request:t})}catch(i){this.#t.delete(t);n(i)}})}post(e,t){if(!this.#s)this.#e.postMessage(e,t)}close(e){this.#s??=e;for(const{reject:t}of this.#t.values())t(e);this.#t.clear()}#u(e){if(this.#s)return;try{this.#e.postMessage(e)}catch(t){this.#e.postMessage({type:\"reply\",reply:e.reply,error:t.message})}}};function Jc(...r){return r.join(\"\\n\")}a(Jc,\"keyOf\");function n_(){if(!Zc.parentPort)throw new Error(\"The media server forwards in a worker thread only\");const r=Zc.workerData;const e=new Wt;const t=new Map;const s=new Map;const n=new Map;const i=new Map;const o=new Td(Zc.parentPort,h=>d(h));const c=a(h=>{const p=t.get(h);if(!p)throw new Error(\"The room is not served any more\");return p},\"roomOf\");const l=a((h,p)=>{n.set(h,p);p.ended(()=>{if(n.get(h)===p)n.delete(h);o.post({type:\"ended\",leg:h})})},\"keep\");const u=a((h,p,m,y)=>{const w=Jc(h,p,m);i.get(w)?.();i.delete(w);const S=y?t.get(h)?.track(p,m):void 0;if(!S)return;i.set(w,er(S).onReceiveRtp.subscribe((T,_)=>{const x=new Uint8Array(T.serialize());o.post({type:\"rtp\",ref:h,peerId:p,trackId:m,packet:x,extensions:_},[x.buffer])}).unSubscribe)},\"stream\");const f=a((h,p)=>({id:p,signaling:{join:a(async(m,y,w)=>{s.set(Jc(h,m),w.receive);try{return await o.request({type:\"join\",ref:h,peerId:m,role:w.role})}catch(S){s.delete(Jc(h,m));throw S}},\"join\"),leave:a(async m=>{s.delete(Jc(h,m));await o.request({type:\"leave\",ref:h,peerId:m})},\"leave\"),signal:a((m,y,w,S)=>o.request({type:\"signal\",ref:h,peerId:m,to:w,signal:S}),\"signal\")},connect:a(()=>e.get(xt,r.connection),\"connect\"),select:r.select?(m,y)=>o.request({type:\"select\",subscriber:m,track:y}):()=>true,emit:a((m,...y)=>{const w=m===\"publish\"||m===\"unpublish\"?y[0]:void 0;let S;const T=m===\"publish\"&&w?t.get(h)?.track(w.peerId,w.id):void 0;if(T){const _=er(T).codec;S={id:T.id,..._?{codec:{payloadType:_.payloadType,mimeType:_.mimeType,clockRate:_.clockRate,channels:_.channels,parameters:_.parameters}}:{}}}if(m===\"unpublish\"&&w)u(h,w.peerId,w.id,false);o.post({type:\"emit\",ref:h,event:m,args:y,...S?{media:S}:{}})},\"emit\"),emptied:a(()=>o.post({type:\"emptied\",ref:h}),\"emptied\"),changed:a(m=>o.post({type:\"state\",ref:h,members:m.members,viewers:m.viewers}),\"changed\"),sourced:a((m,y)=>o.post({type:\"source\",leg:m,source:y}),\"sourced\"),known:a((m,y)=>o.post({type:\"known\",ref:h,tracks:y}),\"known\")}),\"hostOf\");const d=a(async h=>{switch(h.type){case\"open\":{const p=new Ed(f(h.ref,h.id),h.room);t.set(h.ref,p);try{await p.ready}catch(m){if(t.get(h.ref)===p)t.delete(h.ref);throw m}return void 0}case\"close\":{const p=t.get(h.ref);t.delete(h.ref);await p?.close();return void 0}case\"publish\":{const p=await c(h.ref).publish(h.peerId,h.offer);l(h.peerId,p);return{answer:p.answer}}case\"play\":{const p=h.viewerId;const m=await c(h.ref).play(p,h.offer,h.select?y=>o.request({type:\"choose\",leg:p,tracks:y}):void 0);l(p,m);return{answer:m.answer,source:m.source()}}case\"patch\":{const p=n.get(h.leg);if(!p)throw new Error(\"There is no such session\");return await p.patch(h.fragment,h.restart)}case\"end\":return n.get(h.leg)?.close();case\"receive\":return s.get(Jc(h.ref,h.peerId))?.(h.event,h.payload);case\"stream\":return u(h.ref,h.peerId,h.trackId,h.wanted);case\"keyframe\":return t.get(h.ref)?.track(h.peerId,h.trackId)?.requestKeyFrame();case\"debug\":return Fw(h.enabled?(p,m)=>o.post({type:\"log\",namespace:p,message:`[thread ${r.thread}] ${(0,s_.format)(...m)}`}):void 0);case\"stop\":{const p=[...t.values()];t.clear();await Promise.all(p.map(m=>m.close()));await e.destroy();return void 0}}},\"handle\");o.post({type:\"ready\"})}a(n_,\"runSFUWorker\");n_();\n";