sunuid-sdk 1.0.21 → 1.0.23

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,16 +1,11 @@
1
- !function(e,t,s,r,n,i,o,a,c,h,u,l){"use strict";function d(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(s){if("default"!==s&&!(s in e)){var r=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,r.get?r:{enumerable:!0,get:function(){return t[s]}})}})}),Object.freeze(e)}function f(e,t,s,r,n,i,o){try{var a=e[i](o),c=a.value}catch(e){return void s(e)}a.done?t(c):Promise.resolve(c).then(r,n)}function p(e){return function(){var t=this,s=arguments;return new Promise(function(r,n){var i=e.apply(t,s);function o(e){f(i,r,n,o,a,"next",e)}function a(e){f(i,r,n,o,a,"throw",e)}o(void 0)})}}function _(e,t){for(var s=0;s<t.length;s++){var r=t[s];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,E(r.key),r)}}function y(e,t,s){return(t=E(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function m(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,r)}return s}function g(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?m(Object(s),!0).forEach(function(t){y(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):m(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}function v(){
1
+ !function(){"use strict";function e(e,n,t,r,i,o,c){try{var s=e[o](c),a=s.value}catch(e){return void t(e)}s.done?n(a):Promise.resolve(a).then(r,i)}function n(n){return function(){var t=this,r=arguments;return new Promise(function(i,o){var c=n.apply(t,r);function s(n){e(c,i,o,s,a,"next",n)}function a(n){e(c,i,o,s,a,"throw",n)}s(void 0)})}}function t(e,n){for(var t=0;t<n.length;t++){var r=n[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,a(r.key),r)}}function r(e,n,t){return(n=a(n))in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function i(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),t.push.apply(t,r)}return t}function o(e){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{};n%2?i(Object(t),!0).forEach(function(n){r(e,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):i(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})}return e}function c(){
2
2
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3
- var e,t,s="function"==typeof Symbol?Symbol:{},r=s.iterator||"@@iterator",n=s.toStringTag||"@@toStringTag";function i(s,r,n,i){var c=r&&r.prototype instanceof a?r:a,h=Object.create(c.prototype);return b(h,"_invoke",function(s,r,n){var i,a,c,h=0,u=n||[],l=!1,d={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,s){return i=t,a=0,c=e,d.n=s,o}};function f(s,r){for(a=s,c=r,t=0;!l&&h&&!n&&t<u.length;t++){var n,i=u[t],f=d.p,p=i[2];s>3?(n=p===r)&&(c=i[(a=i[4])?5:(a=3,3)],i[4]=i[5]=e):i[0]<=f&&((n=s<2&&f<i[1])?(a=0,d.v=r,d.n=i[1]):f<p&&(n=s<3||i[0]>r||r>p)&&(i[4]=s,i[5]=r,d.n=p,a=0))}if(n||s>1)return o;throw l=!0,r}return function(n,u,p){if(h>1)throw TypeError("Generator is already running");for(l&&1===u&&f(u,p),a=u,c=p;(t=a<2?e:c)||!l;){i||(a?a<3?(a>1&&(d.n=-1),f(a,c)):d.n=c:d.v=c);try{if(h=2,i){if(a||(n="next"),t=i[n]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,a<2&&(a=0)}else 1===a&&(t=i.return)&&t.call(i),a<2&&(c=TypeError("The iterator does not provide a '"+n+"' method"),a=1);i=e}else if((t=(l=d.n<0)?c:s.call(r,d))!==o)break}catch(t){i=e,a=1,c=t}finally{h=1}}return{value:t,done:l}}}(s,n,i),!0),h}var o={};function a(){}function c(){}function h(){}t=Object.getPrototypeOf;var u=[][r]?t(t([][r]())):(b(t={},r,function(){return this}),t),l=h.prototype=a.prototype=Object.create(u);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,h):(e.__proto__=h,b(e,n,"GeneratorFunction")),e.prototype=Object.create(l),e}return c.prototype=h,b(l,"constructor",h),b(h,"constructor",c),c.displayName="GeneratorFunction",b(h,n,"GeneratorFunction"),b(l),b(l,n,"Generator"),b(l,r,function(){return this}),b(l,"toString",function(){return"[object Generator]"}),(v=function(){return{w:i,m:d}})()}function b(e,t,s,r){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}b=function(e,t,s,r){function i(t,s){b(e,t,function(e){return this._invoke(t,s,e)})}t?n?n(e,t,{value:s,enumerable:!r,configurable:!r,writable:!r}):e[t]=s:(i("next",0),i("throw",1),i("return",2))},b(e,t,s,r)}function E(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var r=s.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function k(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}
3
+ var e,n,t="function"==typeof Symbol?Symbol:{},r=t.iterator||"@@iterator",i=t.toStringTag||"@@toStringTag";function o(t,r,i,o){var c=r&&r.prototype instanceof u?r:u,l=Object.create(c.prototype);return s(l,"_invoke",function(t,r,i){var o,c,s,u=0,l=i||[],f=!1,d={p:0,n:0,v:e,a:h,f:h.bind(e,4),d:function(n,t){return o=n,c=0,s=e,d.n=t,a}};function h(t,r){for(c=t,s=r,n=0;!f&&u&&!i&&n<l.length;n++){var i,o=l[n],h=d.p,p=o[2];t>3?(i=p===r)&&(s=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=h&&((i=t<2&&h<o[1])?(c=0,d.v=r,d.n=o[1]):h<p&&(i=t<3||o[0]>r||r>p)&&(o[4]=t,o[5]=r,d.n=p,c=0))}if(i||t>1)return a;throw f=!0,r}return function(i,l,p){if(u>1)throw TypeError("Generator is already running");for(f&&1===l&&h(l,p),c=l,s=p;(n=c<2?e:s)||!f;){o||(c?c<3?(c>1&&(d.n=-1),h(c,s)):d.n=s:d.v=s);try{if(u=2,o){if(c||(i="next"),n=o[i]){if(!(n=n.call(o,s)))throw TypeError("iterator result is not an object");if(!n.done)return n;s=n.value,c<2&&(c=0)}else 1===c&&(n=o.return)&&n.call(o),c<2&&(s=TypeError("The iterator does not provide a '"+i+"' method"),c=1);o=e}else if((n=(f=d.n<0)?s:t.call(r,d))!==a)break}catch(n){o=e,c=1,s=n}finally{u=1}}return{value:n,done:f}}}(t,i,o),!0),l}var a={};function u(){}function l(){}function f(){}n=Object.getPrototypeOf;var d=[][r]?n(n([][r]())):(s(n={},r,function(){return this}),n),h=f.prototype=u.prototype=Object.create(d);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,f):(e.__proto__=f,s(e,i,"GeneratorFunction")),e.prototype=Object.create(h),e}return l.prototype=f,s(h,"constructor",f),s(f,"constructor",l),l.displayName="GeneratorFunction",s(f,i,"GeneratorFunction"),s(h),s(h,i,"Generator"),s(h,r,function(){return this}),s(h,"toString",function(){return"[object Generator]"}),(c=function(){return{w:o,m:p}})()}function s(e,n,t,r){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}s=function(e,n,t,r){function o(n,t){s(e,n,function(e){return this._invoke(n,t,e)})}n?i?i(e,n,{value:t,enumerable:!r,configurable:!r,writable:!r}):e[n]=t:(o("next",0),o("throw",1),o("return",2))},s(e,n,t,r)}function a(e){var n=function(e,n){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,n||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(e)}(e,"string");return"symbol"==typeof n?n:n+""}
4
4
  /**
5
- * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object.
6
- *
7
- * This can be used with JS designed for browsers to improve reuse of code and
8
- * allow the use of existing libraries.
9
- *
10
- * Usage: include("XMLHttpRequest.js") and use XMLHttpRequest per W3C specs.
11
- *
12
- * @author Dan DeFelippi <dan@driverdan.com>
13
- * @contributor David Ellis <d.f.ellis@ieee.org>
5
+ * SunuID SDK - Package d'intégration pour partenaires
6
+ *
7
+ * @version 1.0.0
8
+ * @author SunuID Team
14
9
  * @license MIT
15
- */var w=e,S=t,O=s.spawn,T=x;function x(e){e=e||{};var t,s,i=this,o=r,a=n,c={},h=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},u),d=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],f=["TRACE","TRACK","CONNECT"],p=!1,_=!1,y=!1,m={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;this.open=function(e,t,s,r,n){if(this.abort(),_=!1,y=!1,!function(e){return e&&-1===f.indexOf(e)}(e))throw new Error("SecurityError: Request method not allowed");c={method:e,url:t.toString(),async:"boolean"!=typeof s||s,user:r||null,password:n||null},g(this.OPENED)},this.setDisableHeaderCheck=function(e){h=e},this.setRequestHeader=function(e,t){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!function(e){return h||e&&-1===d.indexOf(e.toLowerCase())}(e))return console.warn('Refused to set unsafe header "'+e+'"'),!1;if(p)throw new Error("INVALID_STATE_ERR: send flag is true");return l[e]=t,!0},this.getResponseHeader=function(e){return"string"==typeof e&&this.readyState>this.OPENED&&s.headers[e.toLowerCase()]&&!_?s.headers[e.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||_)return"";var e="";for(var t in s.headers)"set-cookie"!==t&&"set-cookie2"!==t&&(e+=t+": "+s.headers[t]+"\r\n");return e.substr(0,e.length-2)},this.getRequestHeader=function(e){return"string"==typeof e&&l[e]?l[e]:""},this.send=function(r){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(p)throw new Error("INVALID_STATE_ERR: send has already been called");var n,h=!1,u=!1,d=S.parse(c.url);switch(d.protocol){case"https:":h=!0;case"http:":n=d.hostname;break;case"file:":u=!0;break;case void 0:case"":n="localhost";break;default:throw new Error("Protocol not supported.")}if(u){if("GET"!==c.method)throw new Error("XMLHttpRequest: Only GET method is supported");if(c.async)w.readFile(unescape(d.pathname),function(e,t){e?i.handleError(e,e.errno||-1):(i.status=200,i.responseText=t.toString("utf8"),i.response=t,g(i.DONE))});else try{this.response=w.readFileSync(unescape(d.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,g(i.DONE)}catch(e){this.handleError(e,e.errno||-1)}}else{var f=d.port||(h?443:80),y=d.pathname+(d.search?d.search:"");if(l.Host=n,h&&443===f||80===f||(l.Host+=":"+d.port),c.user){void 0===c.password&&(c.password="");var m=new Buffer(c.user+":"+c.password);l.Authorization="Basic "+m.toString("base64")}if("GET"===c.method||"HEAD"===c.method)r=null;else if(r){l["Content-Length"]=Buffer.isBuffer(r)?r.length:Buffer.byteLength(r),Object.keys(l).some(function(e){return"content-type"===e.toLowerCase()})||(l["Content-Type"]="text/plain;charset=UTF-8")}else"POST"===c.method&&(l["Content-Length"]=0);var v=e.agent||!1,b={host:n,port:f,path:y,method:c.method,headers:l,agent:v};if(h&&(b.pfx=e.pfx,b.key=e.key,b.passphrase=e.passphrase,b.cert=e.cert,b.ca=e.ca,b.ciphers=e.ciphers,b.rejectUnauthorized=!1!==e.rejectUnauthorized),_=!1,c.async){var E=h?a.request:o.request;p=!0,i.dispatchEvent("readystatechange");var k=function(r){if(302===(s=r).statusCode||303===s.statusCode||307===s.statusCode){c.url=s.headers.location;var o=S.parse(c.url);n=o.hostname;var a={hostname:o.hostname,port:o.port,path:o.path,method:303===s.statusCode?"GET":c.method,headers:l};return h&&(a.pfx=e.pfx,a.key=e.key,a.passphrase=e.passphrase,a.cert=e.cert,a.ca=e.ca,a.ciphers=e.ciphers,a.rejectUnauthorized=!1!==e.rejectUnauthorized),void(t=E(a,k).on("error",T)).end()}g(i.HEADERS_RECEIVED),i.status=s.statusCode,s.on("data",function(e){if(e){var t=Buffer.from(e);i.response=Buffer.concat([i.response,t])}p&&g(i.LOADING)}),s.on("end",function(){p&&(p=!1,g(i.DONE),i.responseText=i.response.toString("utf8"))}),s.on("error",function(e){i.handleError(e)})},T=function(e){if(t.reusedSocket&&"ECONNRESET"===e.code)return E(b,k).on("error",T);i.handleError(e)};t=E(b,k).on("error",T),e.autoUnref&&t.on("socket",e=>{e.unref()}),r&&t.write(r),t.end(),i.dispatchEvent("loadstart")}else{var x=".node-xmlhttprequest-content-"+process.pid,R=".node-xmlhttprequest-sync-"+process.pid;w.writeFileSync(R,"","utf8");for(var N="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(h?"s":"")+".request;var options = "+JSON.stringify(b)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+x+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+R+"');});response.on('error', function(error) {fs.writeFileSync('"+x+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});}).on('error', function(error) {fs.writeFileSync('"+x+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});"+(r?"req.write('"+JSON.stringify(r).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",C=O(process.argv[0],["-e",N]);w.existsSync(R););if(i.responseText=w.readFileSync(x,"utf8"),C.stdin.end(),w.unlinkSync(x),i.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var L=JSON.parse(i.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));i.handleError(L,503)}else{i.status=i.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var A=JSON.parse(i.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:i.status,headers:A.data.headers},i.responseText=A.data.text,i.response=Buffer.from(A.data.data,"base64"),g(i.DONE)}}}},this.handleError=function(e,t){this.status=t||0,this.statusText=e,this.responseText=e.stack,_=!0,g(this.DONE)},this.abort=function(){t&&(t.abort(),t=null),l=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),_=y=!0,this.readyState===this.UNSENT||this.readyState===this.OPENED&&!p||this.readyState===this.DONE||(p=!1,g(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(e,t){e in m||(m[e]=[]),m[e].push(t)},this.removeEventListener=function(e,t){e in m&&(m[e]=m[e].filter(function(e){return e!==t}))},this.dispatchEvent=function(e){if("function"==typeof i["on"+e]&&(this.readyState===this.DONE&&c.async?setTimeout(function(){i["on"+e]()},0):i["on"+e]()),e in m)for(let t=0,s=m[e].length;t<s;t++)this.readyState===this.DONE?setTimeout(function(){m[e][t].call(i)},0):m[e][t].call(i)};var g=function(e){if(!(i.readyState===e||i.readyState===i.UNSENT&&y)&&(i.readyState=e,(c.async||i.readyState<i.OPENED||i.readyState===i.DONE)&&i.dispatchEvent("readystatechange"),i.readyState===i.DONE)){let e;e=y?"abort":_?"error":"load",i.dispatchEvent(e),i.dispatchEvent("loadend")}}}x.XMLHttpRequest=x;var R=k(T),N=d({__proto__:null,default:R},[T]);const C=Object.create(null);C.open="0",C.close="1",C.ping="2",C.pong="3",C.message="4",C.upgrade="5",C.noop="6";const L=Object.create(null);Object.keys(C).forEach(e=>{L[C[e]]=e});const A={type:"error",data:"parser error"},B=({type:e,data:t},s,r)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?r(s?t:"b"+P(t,!0).toString("base64")):r(C[e]+(t||"")),P=(e,t)=>Buffer.isBuffer(e)||e instanceof Uint8Array&&!t?e:e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength);let I;const D=(e,t)=>{if("string"!=typeof e)return{type:"message",data:q(e,t)};const s=e.charAt(0);if("b"===s){const s=Buffer.from(e.substring(1),"base64");return{type:"message",data:q(s,t)}}return L[s]?e.length>1?{type:L[s],data:e.substring(1)}:{type:L[s]}:A},q=(e,t)=>"arraybuffer"===t?e instanceof ArrayBuffer?e:Buffer.isBuffer(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e.buffer:Buffer.isBuffer(e)?e:Buffer.from(e),U=String.fromCharCode(30);function j(){return new TransformStream({transform(e,t){!function(e,t){if(e.data instanceof ArrayBuffer||ArrayBuffer.isView(e.data))return t(P(e.data,!1));B(e,!0,e=>{I||(I=new TextEncoder),t(I.encode(e))})}(e,s=>{const r=s.length;let n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(s)})}})}let M;function F(e){return e.reduce((e,t)=>e+t.length,0)}function W(e,t){if(e[0].length===t)return e.shift();const s=new Uint8Array(t);let r=0;for(let n=0;n<t;n++)s[n]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),s}function $(e){if(e)return function(e){for(var t in $.prototype)e[t]=$.prototype[t];return e}(e)}$.prototype.on=$.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},$.prototype.once=function(e,t){function s(){this.off(e,s),t.apply(this,arguments)}return s.fn=t,this.on(e,s),this},$.prototype.off=$.prototype.removeListener=$.prototype.removeAllListeners=$.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<r.length;n++)if((s=r[n])===t||s.fn===t){r.splice(n,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},$.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),s=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(s){r=0;for(var n=(s=s.slice(0)).length;r<n;++r)s[r].apply(this,t)}return this},$.prototype.emitReserved=$.prototype.emit,$.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},$.prototype.hasListeners=function(e){return!!this.listeners(e).length};const V=process.nextTick,H=global;class G{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(e=>{const t=function(e){const t=e.split("; "),s=t[0].indexOf("=");if(-1===s)return;const r=t[0].substring(0,s).trim();if(!r.length)return;let n=t[0].substring(s+1).trim();34===n.charCodeAt(0)&&(n=n.slice(1,-1));const i={name:r,value:n};for(let e=1;e<t.length;e++){const s=t[e].split("=");if(2!==s.length)continue;const r=s[0].trim(),n=s[1].trim();switch(r){case"Expires":i.expires=new Date(n);break;case"Max-Age":const e=new Date;e.setUTCSeconds(e.getUTCSeconds()+parseInt(n,10)),i.expires=e}}return i}(e);t&&this._cookies.set(t.name,t)})}get cookies(){const e=Date.now();return this._cookies.forEach((t,s)=>{var r;(null===(r=t.expires)||void 0===r?void 0:r.getTime())<e&&this._cookies.delete(s)}),this._cookies.entries()}addCookies(e){const t=[];for(const[e,s]of this.cookies)t.push(`${e}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(const[t,s]of this.cookies)e.append("cookie",`${t}=${s.value}`)}}function z(e,...t){return t.reduce((t,s)=>(e.hasOwnProperty(s)&&(t[s]=e[s]),t),{})}const Q=H.setTimeout,Y=H.clearTimeout;function K(e,t){t.useNativeTimers?(e.setTimeoutFn=Q.bind(H),e.clearTimeoutFn=Y.bind(H)):(e.setTimeoutFn=H.setTimeout.bind(H),e.clearTimeoutFn=H.clearTimeout.bind(H))}function X(e){return"string"==typeof e?function(e){let t=0,s=0;for(let r=0,n=e.length;r<n;r++)t=e.charCodeAt(r),t<128?s+=1:t<2048?s+=2:t<55296||t>=57344?s+=3:(r++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))}function J(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Z extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class ee extends ${constructor(e){super(),this.writable=!1,K(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new Z(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=D(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let s in e)e.hasOwnProperty(s)&&(t.length&&(t+="&"),t+=encodeURIComponent(s)+"="+encodeURIComponent(e[s]));return t}(e);return t.length?"?"+t:""}}class te extends ee{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const s=e.split(U),r=[];for(let e=0;e<s.length;e++){const n=D(s[e],t);if(r.push(n),"error"===n.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const s=e.length,r=new Array(s);let n=0;e.forEach((e,i)=>{B(e,!1,e=>{r[i]=e,++n===s&&t(r.join(U))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=J()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let se=!1;try{se="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const re=se;function ne(){}class ie extends te{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let s=location.port;s||(s=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class oe extends ${constructor(e,t,s){super(),this.createRequest=e,K(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var e;const t=z(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&s.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{s.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var e;3===s.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof s.status?s.status:0)},0))},s.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=oe.requestsCount++,oe.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=ne,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete oe.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(oe.requestsCount=0,oe.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ae);else if("function"==typeof addEventListener){addEventListener("onpagehide"in H?"pagehide":"unload",ae,!1)}function ae(){for(let e in oe.requests)oe.requests.hasOwnProperty(e)&&oe.requests[e].abort()}!function(){const e=function(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||re))return new XMLHttpRequest}catch(e){}if(!t)try{return new(H[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}({xdomain:!1});e&&e.responseType}();const ce=R||N;var he={exports:{}},ue={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:le}=ue,de=Buffer[Symbol.species];function fe(e,t,s,r,n){for(let i=0;i<n;i++)s[r+i]=e[i]^t[3&i]}function pe(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}if(he.exports={concat:function(e,t){if(0===e.length)return le;if(1===e.length)return e[0];const s=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const n=e[t];s.set(n,r),r+=n.length}return r<t?new de(s.buffer,s.byteOffset,r):s},mask:fe,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let s;return t instanceof ArrayBuffer?s=new de(t):ArrayBuffer.isView(t)?s=new de(t.buffer,t.byteOffset,t.byteLength):(s=Buffer.from(t),e.readOnly=!1),s},unmask:pe},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");he.exports.mask=function(t,s,r,n,i){i<48?fe(t,s,r,n,i):e.mask(t,s,r,n,i)},he.exports.unmask=function(t,s){t.length<32?pe(t,s):e.unmask(t,s)}}catch(e){}var _e=he.exports;const ye=Symbol("kDone"),me=Symbol("kRun");const ge=o,ve=_e,be=class{constructor(e){this[ye]=()=>{this.pending--,this[me]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[me]()}[me](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[ye])}}},{kStatusCode:Ee}=ue,ke=Buffer[Symbol.species],we=Buffer.from([0,0,255,255]),Se=Symbol("permessage-deflate"),Oe=Symbol("total-length"),Te=Symbol("callback"),xe=Symbol("buffers"),Re=Symbol("error");let Ne;var Ce=class{constructor(e,t,s){if(this._maxPayload=0|s,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Ne){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Ne=new be(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Te];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,s=e.find(e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:!0!==s.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete s.client_max_window_bits,s}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==s)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}e[t]=s})}),e}decompress(e,t,s){Ne.add(r=>{this._decompress(e,t,(e,t)=>{r(),s(e,t)})})}compress(e,t,s){Ne.add(r=>{this._compress(e,t,(e,t)=>{r(),s(e,t)})})}_decompress(e,t,s){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?ge.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=ge.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Se]=this,this._inflate[Oe]=0,this._inflate[xe]=[],this._inflate.on("error",Be),this._inflate.on("data",Ae)}this._inflate[Te]=s,this._inflate.write(e),t&&this._inflate.write(we),this._inflate.flush(()=>{const e=this._inflate[Re];if(e)return this._inflate.close(),this._inflate=null,void s(e);const n=ve.concat(this._inflate[xe],this._inflate[Oe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Oe]=0,this._inflate[xe]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,n)})}_compress(e,t,s){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?ge.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=ge.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Oe]=0,this._deflate[xe]=[],this._deflate.on("data",Le)}this._deflate[Te]=s,this._deflate.write(e),this._deflate.flush(ge.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=ve.concat(this._deflate[xe],this._deflate[Oe]);t&&(e=new ke(e.buffer,e.byteOffset,e.length-4)),this._deflate[Te]=null,this._deflate[Oe]=0,this._deflate[xe]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,e)})}};function Le(e){this[xe].push(e),this[Oe]+=e.length}function Ae(e){this[Oe]+=e.length,this[Se]._maxPayload<1||this[Oe]<=this[Se]._maxPayload?this[xe].push(e):(this[Re]=new RangeError("Max payload size exceeded"),this[Re].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Re][Ee]=1009,this.removeListener("data",Ae),this.reset())}function Be(e){this[Se]._inflate=null,e[Ee]=1007,this[Te](e)}var Pe={exports:{}};const{isUtf8:Ie}=a;function De(e){const t=e.length;let s=0;for(;s<t;)if(128&e[s])if(192==(224&e[s])){if(s+1===t||128!=(192&e[s+1])||192==(254&e[s]))return!1;s+=2}else if(224==(240&e[s])){if(s+2>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||224===e[s]&&128==(224&e[s+1])||237===e[s]&&160==(224&e[s+1]))return!1;s+=3}else{if(240!=(248&e[s]))return!1;if(s+3>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||128!=(192&e[s+3])||240===e[s]&&128==(240&e[s+1])||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}else s++;return!0}if(Pe.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:De,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},Ie)Pe.exports.isValidUTF8=function(e){return e.length<24?De(e):Ie(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Pe.exports.isValidUTF8=function(t){return t.length<32?De(t):e(t)}}catch(e){}var qe=Pe.exports;const{Writable:Ue}=i,je=Ce,{BINARY_TYPES:Me,EMPTY_BUFFER:Fe,kStatusCode:We,kWebSocket:$e}=ue,{concat:Ve,toArrayBuffer:He,unmask:Ge}=_e,{isValidStatusCode:ze,isValidUTF8:Qe}=qe,Ye=Buffer[Symbol.species];var Ke=class extends Ue{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Me[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[$e]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(8===this._opcode&&0==this._state)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Ye(t.buffer,t.byteOffset+e,t.length-e),new Ye(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0],r=t.length-e;e>=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new Ye(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const s=!(64&~t[0]);if(s&&!this._extensions[je.extensionName]){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(s){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=s}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(s){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),s=t.readUInt32BE(0);if(s>Math.pow(2,21)-1){return void e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){return void e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=Fe;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&Ge(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[je.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(s)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Ve(s,t):"arraybuffer"===this._binaryType?He(Ve(s,t)):s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)}))}else{const r=Ve(s,t);if(!this._skipUTF8Validation&&!Qe(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,Fe),this.end();else{const s=e.readUInt16BE(0);if(!ze(s)){const e=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ye(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Qe(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=0}}createError(e,t,s,r,n){this._loop=!1,this._errored=!0;const i=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=n,i[We]=r,i}};const{randomFillSync:Xe}=c,Je=Ce,{EMPTY_BUFFER:Ze}=ue,{isValidStatusCode:et}=qe,{mask:tt,toBuffer:st}=_e,rt=Symbol("kByteLength"),nt=Buffer.alloc(4),it=8192;let ot,at=it;var ct=class e{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let s,r,n=!1,i=2,o=!1;t.mask&&(s=t.maskBuffer||nt,t.generateMask?t.generateMask(s):(at===it&&(void 0===ot&&(ot=Buffer.alloc(it)),Xe(ot,0,it),at=0),s[0]=ot[at++],s[1]=ot[at++],s[2]=ot[at++],s[3]=ot[at++]),o=0===(s[0]|s[1]|s[2]|s[3]),i=6),"string"==typeof e?r=t.mask&&!o||void 0===t[rt]?(e=Buffer.from(e)).length:t[rt]:(r=e.length,n=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(i+=8,a=127):r>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(n?r+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[i-4]=s[0],c[i-3]=s[1],c[i-2]=s[2],c[i-1]=s[3],o?[c,e]:n?(tt(e,s,c,i,r),[c]):(tt(e,s,e,0,r),[c,e])):[c,e]}close(t,s,r,n){let i;if(void 0===t)i=Ze;else{if("number"!=typeof t||!et(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==s&&s.length){const e=Buffer.byteLength(s);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof s?i.write(s,2):i.set(s,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const o={[rt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,i,!1,o,n]):this.sendFrame(e.frame(i,o),n)}ping(t,s,r){let n,i;if("string"==typeof t?(n=Buffer.byteLength(t),i=!1):(n=(t=st(t)).length,i=st.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[rt]:n,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};this._deflating?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,s,r){let n,i;if("string"==typeof t?(n=Buffer.byteLength(t),i=!1):(n=(t=st(t)).length,i=st.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[rt]:n,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};this._deflating?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(t,s,r){const n=this._extensions[Je.extensionName];let i,o,a=s.binary?2:1,c=s.compress;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):(i=(t=st(t)).length,o=st.readOnly),this._firstFragment?(this._firstFragment=!1,c&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(c=i>=n._threshold),this._compress=c):(c=!1,a=0),s.fin&&(this._firstFragment=!0),n){const e={[rt]:i,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:o,rsv1:c};this._deflating?this.enqueue([this.dispatch,t,this._compress,e,r]):this.dispatch(t,this._compress,e,r)}else this.sendFrame(e.frame(t,{[rt]:i,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:o,rsv1:!1}),r)}dispatch(t,s,r,n){if(!s)return void this.sendFrame(e.frame(t,r),n);const i=this._extensions[Je.extensionName];this._bufferedBytes+=r[rt],this._deflating=!0,i.compress(t,r.fin,(t,s)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const s=this._queue[t],r=s[s.length-1];"function"==typeof r&&r(e)}return}this._bufferedBytes-=r[rt],this._deflating=!1,r.readOnly=!1,this.sendFrame(e.frame(s,r),n),this.dequeue()})}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][rt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][rt],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};const{kForOnEventAttribute:ht,kListener:ut}=ue,lt=Symbol("kCode"),dt=Symbol("kData"),ft=Symbol("kError"),pt=Symbol("kMessage"),_t=Symbol("kReason"),yt=Symbol("kTarget"),mt=Symbol("kType"),gt=Symbol("kWasClean");class vt{constructor(e){this[yt]=null,this[mt]=e}get target(){return this[yt]}get type(){return this[mt]}}Object.defineProperty(vt.prototype,"target",{enumerable:!0}),Object.defineProperty(vt.prototype,"type",{enumerable:!0});class bt extends vt{constructor(e,t={}){super(e),this[lt]=void 0===t.code?0:t.code,this[_t]=void 0===t.reason?"":t.reason,this[gt]=void 0!==t.wasClean&&t.wasClean}get code(){return this[lt]}get reason(){return this[_t]}get wasClean(){return this[gt]}}Object.defineProperty(bt.prototype,"code",{enumerable:!0}),Object.defineProperty(bt.prototype,"reason",{enumerable:!0}),Object.defineProperty(bt.prototype,"wasClean",{enumerable:!0});class Et extends vt{constructor(e,t={}){super(e),this[ft]=void 0===t.error?null:t.error,this[pt]=void 0===t.message?"":t.message}get error(){return this[ft]}get message(){return this[pt]}}Object.defineProperty(Et.prototype,"error",{enumerable:!0}),Object.defineProperty(Et.prototype,"message",{enumerable:!0});class kt extends vt{constructor(e,t={}){super(e),this[dt]=void 0===t.data?null:t.data}get data(){return this[dt]}}Object.defineProperty(kt.prototype,"data",{enumerable:!0});const wt={addEventListener(e,t,s={}){for(const r of this.listeners(e))if(!s[ht]&&r[ut]===t&&!r[ht])return;let r;if("message"===e)r=function(e,s){const r=new kt("message",{data:s?e:e.toString()});r[yt]=this,Ot(t,this,r)};else if("close"===e)r=function(e,s){const r=new bt("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[yt]=this,Ot(t,this,r)};else if("error"===e)r=function(e){const s=new Et("error",{error:e,message:e.message});s[yt]=this,Ot(t,this,s)};else{if("open"!==e)return;r=function(){const e=new vt("open");e[yt]=this,Ot(t,this,e)}}r[ht]=!!s[ht],r[ut]=t,s.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const s of this.listeners(e))if(s[ut]===t&&!s[ht]){this.removeListener(e,s);break}}};var St={CloseEvent:bt,ErrorEvent:Et,Event:vt,EventTarget:wt,MessageEvent:kt};function Ot(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}const{tokenChars:Tt}=qe;function xt(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}var Rt={format:function(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){const t=Object.create(null);let s,r,n=Object.create(null),i=!1,o=!1,a=!1,c=-1,h=-1,u=-1,l=0;for(;l<e.length;l++)if(h=e.charCodeAt(l),void 0===s)if(-1===u&&1===Tt[h])-1===c&&(c=l);else if(0===l||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===u&&(u=l);const r=e.slice(c,u);44===h?(xt(t,r,n),n=Object.create(null)):s=r,c=u=-1}}else-1===u&&-1!==c&&(u=l);else if(void 0===r)if(-1===u&&1===Tt[h])-1===c&&(c=l);else if(32===h||9===h)-1===u&&-1!==c&&(u=l);else if(59===h||44===h){if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===u&&(u=l),xt(n,e.slice(c,u),!0),44===h&&(xt(t,s,n),n=Object.create(null),s=void 0),c=u=-1}else{if(61!==h||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${l}`);r=e.slice(c,l),c=u=-1}else if(o){if(1!==Tt[h])throw new SyntaxError(`Unexpected character at index ${l}`);-1===c?c=l:i||(i=!0),o=!1}else if(a)if(1===Tt[h])-1===c&&(c=l);else if(34===h&&-1!==c)a=!1,u=l;else{if(92!==h)throw new SyntaxError(`Unexpected character at index ${l}`);o=!0}else if(34===h&&61===e.charCodeAt(l-1))a=!0;else if(-1===u&&1===Tt[h])-1===c&&(c=l);else if(-1===c||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===u&&(u=l);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),xt(n,r,o),44===h&&(xt(t,s,n),n=Object.create(null),s=void 0),r=void 0,c=u=-1}}else-1===u&&(u=l);if(-1===c||a||32===h||9===h)throw new SyntaxError("Unexpected end of input");-1===u&&(u=l);const d=e.slice(c,u);return void 0===s?xt(t,d,n):(void 0===r?xt(n,d,!0):xt(n,r,i?d.replace(/\\/g,""):d),xt(t,s,n)),t}};const Nt=h,Ct=n,Lt=r,At=u,Bt=l,{randomBytes:Pt,createHash:It}=c,{URL:Dt}=t,qt=Ce,Ut=Ke,jt=ct,{BINARY_TYPES:Mt,EMPTY_BUFFER:Ft,GUID:Wt,kForOnEventAttribute:$t,kListener:Vt,kStatusCode:Ht,kWebSocket:Gt,NOOP:zt}=ue,{EventTarget:{addEventListener:Qt,removeEventListener:Yt}}=St,{format:Kt,parse:Xt}=Rt,{toBuffer:Jt}=_e,Zt=Symbol("kAborted"),es=[8,13],ts=["CONNECTING","OPEN","CLOSING","CLOSED"],ss=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class rs extends Nt{constructor(e,t,s){super(),this._binaryType=Mt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ft,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=rs.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(s=t,t=[]):t=[t]),ns(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,s){const r=new Ut({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation});this._sender=new jt(e,this._extensions,s.generateMask),this._receiver=r,this._socket=e,r[Gt]=this,e[Gt]=this,r.on("conclude",us),r.on("drain",ls),r.on("error",ds),r.on("message",ps),r.on("ping",_s),r.on("pong",ys),e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",gs),e.on("data",vs),e.on("end",bs),e.on("error",Es),this._readyState=rs.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=rs.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[qt.extensionName]&&this._extensions[qt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=rs.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==rs.CLOSED){if(this.readyState===rs.CONNECTING){const e="WebSocket was closed before the connection was established";return void cs(this,this._req,e)}this.readyState!==rs.CLOSING?(this._readyState=rs.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==rs.CONNECTING&&this.readyState!==rs.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===rs.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===rs.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||Ft,t,s)):hs(this,e,s)}pong(e,t,s){if(this.readyState===rs.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===rs.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||Ft,t,s)):hs(this,e,s)}resume(){this.readyState!==rs.CONNECTING&&this.readyState!==rs.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===rs.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==rs.OPEN)return void hs(this,e,s);const r={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[qt.extensionName]||(r.compress=!1),this._sender.send(e||Ft,r,s)}terminate(){if(this.readyState!==rs.CLOSED){if(this.readyState===rs.CONNECTING){const e="WebSocket was closed before the connection was established";return void cs(this,this._req,e)}this._socket&&(this._readyState=rs.CLOSING,this._socket.destroy())}}}function ns(e,t,s,r){const n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:es[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=n.autoPong,!es.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${es.join(", ")})`);let i;if(t instanceof Dt)i=t;else try{i=new Dt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===i.protocol?i.protocol="ws:":"https:"===i.protocol&&(i.protocol="wss:"),e._url=i.href;const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void is(e,t)}const h=o?443:80,u=Pt(16).toString("base64"),l=o?Ct.request:Lt.request,d=new Set;let f,p;if(n.createConnection=n.createConnection||(o?as:os),n.defaultPort=n.defaultPort||h,n.port=i.port||h,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(f=new qt(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Kt({[qt.extensionName]:f.offer()})),s.length){for(const e of s){if("string"!=typeof e||!ss.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(e)}n.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?n.socketPath:i.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,s]of Object.entries(t))r.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),p=e._req=l(n),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=l(n);n.timeout&&p.on("timeout",()=>{cs(e,p,"Opening handshake has timed out")}),p.on("error",t=>{null===p||p[Zt]||(p=e._req=null,is(e,t))}),p.on("response",i=>{const o=i.headers.location,a=i.statusCode;if(o&&n.followRedirects&&a>=300&&a<400){if(++e._redirects>n.maxRedirects)return void cs(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new Dt(o,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${o}`);return void is(e,s)}ns(e,i,s,r)}else e.emit("unexpected-response",p,i)||cs(e,p,`Unexpected server response: ${i.statusCode}`)}),p.on("upgrade",(t,s,r)=>{if(e.emit("upgrade",t),e.readyState!==rs.CONNECTING)return;p=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void cs(e,s,"Invalid Upgrade header");const o=It("sha1").update(u+Wt).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void cs(e,s,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?d.size?d.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":d.size&&(c="Server sent no subprotocol"),c)return void cs(e,s,c);a&&(e._protocol=a);const h=t.headers["sec-websocket-extensions"];if(void 0!==h){if(!f){return void cs(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Xt(h)}catch(t){return void cs(e,s,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==qt.extensionName){return void cs(e,s,"Server indicated an extension that was not requested")}try{f.accept(t[qt.extensionName])}catch(t){return void cs(e,s,"Invalid Sec-WebSocket-Extensions header")}e._extensions[qt.extensionName]=f}e.setSocket(s,r,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(p,e):p.end()}function is(e,t){e._readyState=rs.CLOSING,e.emit("error",t),e.emitClose()}function os(e){return e.path=e.socketPath,At.connect(e)}function as(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=At.isIP(e.host)?"":e.host),Bt.connect(e)}function cs(e,t,s){e._readyState=rs.CLOSING;const r=new Error(s);Error.captureStackTrace(r,cs),t.setHeader?(t[Zt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(is,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function hs(e,t,s){if(t){const s=Jt(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ts[e.readyState]})`);process.nextTick(s,t)}}function us(e,t){const s=this[Gt];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[Gt]&&(s._socket.removeListener("data",vs),process.nextTick(ms,s._socket),1005===e?s.close():s.close(e,t))}function ls(){const e=this[Gt];e.isPaused||e._socket.resume()}function ds(e){const t=this[Gt];void 0!==t._socket[Gt]&&(t._socket.removeListener("data",vs),process.nextTick(ms,t._socket),t.close(e[Ht])),t.emit("error",e)}function fs(){this[Gt].emitClose()}function ps(e,t){this[Gt].emit("message",e,t)}function _s(e){const t=this[Gt];t._autoPong&&t.pong(e,!this._isServer,zt),t.emit("ping",e)}function ys(e){this[Gt].emit("pong",e)}function ms(e){e.resume()}function gs(){const e=this[Gt];let t;this.removeListener("close",gs),this.removeListener("data",vs),this.removeListener("end",bs),e._readyState=rs.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Gt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",fs),e._receiver.on("finish",fs))}function vs(e){this[Gt]._receiver.write(e)||this.pause()}function bs(){const e=this[Gt];e._readyState=rs.CLOSING,e._receiver.end(),this.end()}function Es(){const e=this[Gt];this.removeListener("error",Es),this.on("error",zt),e&&(e._readyState=rs.CLOSING,this.destroy())}Object.defineProperty(rs,"CONNECTING",{enumerable:!0,value:ts.indexOf("CONNECTING")}),Object.defineProperty(rs.prototype,"CONNECTING",{enumerable:!0,value:ts.indexOf("CONNECTING")}),Object.defineProperty(rs,"OPEN",{enumerable:!0,value:ts.indexOf("OPEN")}),Object.defineProperty(rs.prototype,"OPEN",{enumerable:!0,value:ts.indexOf("OPEN")}),Object.defineProperty(rs,"CLOSING",{enumerable:!0,value:ts.indexOf("CLOSING")}),Object.defineProperty(rs.prototype,"CLOSING",{enumerable:!0,value:ts.indexOf("CLOSING")}),Object.defineProperty(rs,"CLOSED",{enumerable:!0,value:ts.indexOf("CLOSED")}),Object.defineProperty(rs.prototype,"CLOSED",{enumerable:!0,value:ts.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(rs.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(rs.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[$t])return t[Vt];return null},set(t){for(const t of this.listeners(e))if(t[$t]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[$t]:!0})}})}),rs.prototype.addEventListener=Qt,rs.prototype.removeEventListener=Yt;var ks=k(rs);const ws="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Ss extends ee{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=ws?{}:z(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;B(s,this.supportsBinary,e=>{try{this.doWrite(s,e)}catch(e){}r&&V(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=J()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Os={websocket:class extends Ss{createSocket(e,t,s){var r;if(null===(r=this.socket)||void 0===r?void 0:r._cookieJar){s.headers=s.headers||{},s.headers.cookie="string"==typeof s.headers.cookie?[s.headers.cookie]:s.headers.cookie||[];for(const[e,t]of this.socket._cookieJar.cookies)s.headers.cookie.push(`${e}=${t.value}`)}return new ks(e,t,s)}doWrite(e,t){const s={};if(e.options&&(s.compress=e.options.compress),this.opts.perMessageDeflate){("string"==typeof t?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(s.compress=!1)}this.ws.send(t,s)}},webtransport:class extends ee{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){M||(M=new TextDecoder);const s=[];let r=0,n=-1,i=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===r){if(F(s)<1)break;const e=W(s,1);i=!(128&~e[0]),n=127&e[0],r=n<126?3:126===n?1:2}else if(1===r){if(F(s)<2)break;const e=W(s,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(F(s)<8)break;const e=W(s,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(A);break}n=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(F(s)<n)break;const e=W(s,n);a.enqueue(D(i?e:M.decode(e),t)),r=0}if(0===n||n>e){a.enqueue(A);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=j();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const n=()=>{s.read().then(({done:e,value:t})=>{e||(this.onPacket(t),n())}).catch(e=>{})};n();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&V(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends ie{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:null===(t=this.socket)||void 0===t?void 0:t._cookieJar},this.opts),new oe(e=>new ce(e),this.uri(),e)}}},Ts=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,xs=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Rs(e){if(e.length>8e3)throw"URI too long";const t=e,s=e.indexOf("["),r=e.indexOf("]");-1!=s&&-1!=r&&(e=e.substring(0,s)+e.substring(s,r).replace(/:/g,";")+e.substring(r,e.length));let n=Ts.exec(e||""),i={},o=14;for(;o--;)i[xs[o]]=n[o]||"";return-1!=s&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const s=/\/{2,9}/g,r=t.replace(s,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(e,t){const s={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(s[t]=r)}),s}(0,i.query),i}const Ns="function"==typeof addEventListener&&"function"==typeof removeEventListener,Cs=[];Ns&&addEventListener("offline",()=>{Cs.forEach(e=>e())},!1);class Ls extends ${constructor(e,t){if(super(),this.binaryType="nodebuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const s=Rs(e);t.hostname=s.host,t.secure="https"===s.protocol||"wss"===s.protocol,t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=Rs(t.host).host);K(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},s=e.split("&");for(let e=0,r=s.length;e<r;e++){let r=s[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),Ns&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Cs.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=new G),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Ls.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Ls.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const s=this.writeBuffer[t].data;if(s&&(e+=X(s)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,V(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:e,data:t,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(Ls.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ns&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Cs.indexOf(this._offlineEventListener);-1!==e&&Cs.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Ls.protocol=4;class As extends Ls{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;Ls.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!s)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Ls.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function n(){s||(s=!0,h(),t.close(),t=null)}const i=e=>{const s=new Error("probe error: "+e);s.transport=t.name,n(),this.emitReserved("upgradeError",s)};function o(){i("transport closed")}function a(){i("socket closed")}function c(e){t&&e.name!==t.name&&n()}const h=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",r),t.once("error",i),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let Bs=class extends As{constructor(e,t={}){const s="object"==typeof e?e:t;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(e=>Os[e]).filter(e=>!!e)),super(e,s)}};const Ps="function"==typeof ArrayBuffer,Is=Object.prototype.toString,Ds="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Is.call(Blob),qs="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Is.call(File);function Us(e){return Ps&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Ds&&e instanceof Blob||qs&&e instanceof File}function js(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,s=e.length;t<s;t++)if(js(e[t]))return!0;return!1}if(Us(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return js(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&js(e[t]))return!0;return!1}function Ms(e){const t=[],s=e.data,r=e;return r.data=Fs(s,t),r.attachments=t.length,{packet:r,buffers:t}}function Fs(e,t){if(!e)return e;if(Us(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=Fs(e[r],t);return s}if("object"==typeof e&&!(e instanceof Date)){const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=Fs(e[r],t));return s}return e}function Ws(e,t){return e.data=$s(e.data,t),delete e.attachments,e}function $s(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let s=0;s<e.length;s++)e[s]=$s(e[s],t);else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e[s]=$s(e[s],t));return e}const Vs=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Hs;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Hs||(Hs={}));function Gs(e){return"[object Object]"===Object.prototype.toString.call(e)}class zs extends ${constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===Hs.BINARY_EVENT;s||t.type===Hs.BINARY_ACK?(t.type=s?Hs.EVENT:Hs.ACK,this.reconstructor=new Qs(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Us(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(void 0===Hs[s.type])throw new Error("unknown packet type "+s.type);if(s.type===Hs.BINARY_EVENT||s.type===Hs.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(r,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");s.attachments=Number(n)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}s.nsp=e.substring(r,t)}else s.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const s=e.charAt(t);if(null==s||Number(s)!=s){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!zs.isPayloadValid(s.type,r))throw new Error("invalid payload");s.data=r}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Hs.CONNECT:return Gs(t);case Hs.DISCONNECT:return void 0===t;case Hs.CONNECT_ERROR:return"string"==typeof t||Gs(t);case Hs.EVENT:case Hs.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Vs.indexOf(t[0]));case Hs.ACK:case Hs.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Qs{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Ws(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Ys=Object.freeze({__proto__:null,Decoder:zs,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Hs.EVENT&&e.type!==Hs.ACK||!js(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Hs.EVENT?Hs.BINARY_EVENT:Hs.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Hs.BINARY_EVENT&&e.type!==Hs.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Ms(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}},get PacketType(){return Hs},protocol:5});function Ks(e,t,s){return e.on(t,s),function(){e.off(t,s)}}const Xs=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Js extends ${constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Ks(e,"open",this.onopen.bind(this)),Ks(e,"packet",this.onpacket.bind(this)),Ks(e,"error",this.onerror.bind(this)),Ks(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,r,n;if(Xs.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:Hs.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,s=t.pop();this._registerAckCallback(e,s),i.id=e}const o=null===(r=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var s;const r=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((s,r)=>{const n=(e,t)=>e?r(e):s(t);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(s!==this._queue[0])return;return null!==e?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue()}),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Hs.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Hs.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Hs.EVENT:case Hs.BINARY_EVENT:this.onevent(e);break;case Hs.ACK:case Hs.BINARY_ACK:this.onack(e);break;case Hs.DISCONNECT:this.ondisconnect();break;case Hs.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:Hs.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Hs.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function Zs(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Zs.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),s=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+s:e-s}return 0|Math.min(e,this.max)},Zs.prototype.reset=function(){this.attempts=0},Zs.prototype.setMin=function(e){this.ms=e},Zs.prototype.setMax=function(e){this.max=e},Zs.prototype.setJitter=function(e){this.jitter=e};class er extends ${constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,K(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=t.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new Zs({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||Ys;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Bs(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=Ks(t,"open",function(){s.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=Ks(t,"error",n);if(!1!==this._timeout){const e=this._timeout,s=this.setTimeoutFn(()=>{r(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Ks(e,"ping",this.onping.bind(this)),Ks(e,"data",this.ondata.bind(this)),Ks(e,"error",this.onerror.bind(this)),Ks(e,"close",this.onclose.bind(this)),Ks(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){V(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Js(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const tr={};function sr(e,t){"object"==typeof e&&(t=e,e=void 0);const s=function(e,t="",s){let r=e;s=s||"undefined"!=typeof location&&location,null==e&&(e=s.protocol+"//"+s.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?s.protocol+e:s.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==s?s.protocol+"//"+e:"https://"+e),r=Rs(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port+t,r.href=r.protocol+"://"+n+(s&&s.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=s.source,n=s.id,i=s.path,o=tr[n]&&i in tr[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new er(r,t):(tr[n]||(tr[n]=new er(r,t)),a=tr[n]),s.query&&!t.query&&(t.query=s.queryKey),a.socket(s.path,t)}Object.assign(sr,{Manager:er,Socket:Js,io:sr,connect:sr}),function(e,t){var s={apiUrl:(null===(t=e.SunuIDConfig)||void 0===t?void 0:t.apiUrl)||"https://api.sunuid.fayma.sn",clientId:null,secretId:null,type:1,theme:"light",language:"fr",autoRefresh:!0,refreshInterval:3e4,onSuccess:null,onError:null,onStatusUpdate:null,onExpired:null},r=function(){return t=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=g(g({},s),t),this.qrCode=null,this.refreshTimer=null,this.isInitialized=!1,this.socket=null,this.init()},r=[{key:"init",value:function(){if(!this.config.clientId||!this.config.secretId)throw new Error("SunuID: clientId et secretId sont requis");this.isInitialized=!0,console.log("SunuID SDK initialisé avec succès"),this.initWebSocket()}},{key:"initWebSocket",value:function(){var e=this;try{var t=this.getClientIP();this.socket||(this.socket=sr("wss://samasocket.fayma.sn:9443",{query:{token:this.config.clientId,type:"web",userId:this.config.clientId,username:t}}),this.socket.on("connect",function(){console.log("🌐 WebSocket connecté avec succès"),console.log("📊 Socket ID:",e.socket.id)}),this.socket.on("disconnect",function(e){console.log("❌ WebSocket déconnecté:",e)}),this.socket.on("connect_error",function(e){console.error("❌ Erreur connexion WebSocket:",e)}),this.socket.on("qr_status_update",function(t){console.log("📱 Mise à jour statut QR reçue:",t),e.handleQRStatusUpdate(t)}),this.socket.on("qr_scan_success",function(t){console.log("✅ Scan QR réussi reçu:",t),e.handleQRScanSuccess(t)}),this.socket.on("qr_expired",function(t){console.log("⏰ QR expiré reçu:",t),e.handleQRExpired(t)}))}catch(e){console.error("❌ Erreur initialisation WebSocket:",e)}}},{key:"getClientIP",value:function(){return"127.0.0.1"}},{key:"handleQRStatusUpdate",value:function(e){this.config.onStatusUpdate&&this.config.onStatusUpdate(e)}},{key:"handleQRScanSuccess",value:function(e){this.config.onSuccess&&this.config.onSuccess(e)}},{key:"handleQRExpired",value:function(e){this.config.onExpired&&this.config.onExpired(e)}},{key:"emitWebSocketEvent",value:function(e,t){this.socket&&this.socket.connected?(this.socket.emit(e,t),console.log("📤 Événement WebSocket émis: ".concat(e),t)):console.warn("⚠️ WebSocket non connecté, impossible d'émettre l'événement:",e)}},{key:"getWebSocketStatus",value:function(){return this.socket?this.socket.connected?"connected":"disconnected":"not_initialized"}},{key:"generateQR",value:(l=p(v().m(function e(t){var s,r,n,i,o=arguments;return v().w(function(e){for(;;)switch(e.p=e.n){case 0:if(s=o.length>1&&void 0!==o[1]?o[1]:{},this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-generate",g({type:this.config.type},s));case 2:if(!(r=e.v).success){e.n=3;break}return n="".concat("https://sunuid.fayma.sn").concat(r.data.qrcode),this.displayQRCode(t,n,this.config.type,s),this.startAutoRefresh(t,this.config.type,s),this.emitWebSocketEvent("qr_generated",{serviceId:r.data.service_id,type:this.config.type,qrCodeUrl:n,timestamp:Date.now()}),e.a(2,g(g({},r.data),{},{qrCodeUrl:n,sessionId:r.data.service_id}));case 3:throw new Error(r.message||"Erreur lors de la génération du QR code");case 4:e.n=6;break;case 5:throw e.p=5,i=e.v,console.error("Erreur API détectée:",i.message),console.log('Affichage du message "Service non disponible" pour type '+this.config.type),this.displayServiceUnavailable(t,this.config.type),new Error("Service non disponible");case 6:return e.a(2)}},e,this,[[1,5]])})),function(e){return l.apply(this,arguments)})},{key:"generateCustomQR",value:(u=p(v().m(function e(t,s){var r,n,i,o,a=arguments;return v().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=a.length>2&&void 0!==a[2]?a[2]:{},this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-generate",g({type:s},r));case 2:if(!(n=e.v).success){e.n=3;break}return i="".concat("https://sunuid.fayma.sn").concat(n.data.qrcode),this.displayQRCode(t,i,s,r),this.startAutoRefresh(t,s,r),e.a(2,g(g({},n.data),{},{qrCodeUrl:i,sessionId:n.data.service_id}));case 3:throw new Error(n.message||"Erreur lors de la génération du QR code");case 4:e.n=6;break;case 5:throw e.p=5,o=e.v,console.error("Erreur API détectée:",o.message),console.log('Affichage du message "Service non disponible" pour type '+s),this.displayServiceUnavailable(t,s),new Error("Service non disponible");case 6:return e.a(2)}},e,this,[[1,5]])})),function(e,t){return u.apply(this,arguments)})},{key:"generateAuthQR",value:(h=p(v().m(function e(t){var s,r=arguments;return v().w(function(e){for(;;)if(0===e.n)return s=r.length>1&&void 0!==r[1]?r[1]:{},e.a(2,this.generateQR(t,s))},e,this)})),function(e){return h.apply(this,arguments)})},{key:"generateKYCQR",value:(c=p(v().m(function e(t){var s,r,n=arguments;return v().w(function(e){for(;;)switch(e.p=e.n){case 0:return s=n.length>1&&void 0!==n[1]?n[1]:{},r=this.config.type,this.config.type=2,e.p=1,e.n=2,this.generateQR(t,s);case 2:return e.a(2,e.v);case 3:return e.p=3,this.config.type=r,e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])})),function(e){return c.apply(this,arguments)})},{key:"checkQRStatus",value:(a=p(v().m(function e(t){var s,r;return v().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-status",{serviceId:t});case 2:if(!(s=e.v).success){e.n=3;break}return e.a(2,s.data);case 3:throw new Error(s.message||"Erreur lors de la vérification du statut");case 4:e.n=6;break;case 5:throw e.p=5,r=e.v,this.handleError(r),r;case 6:return e.a(2)}},e,this,[[1,5]])})),function(e){return a.apply(this,arguments)})},{key:"displayQRCode",value:function(e,t,s){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=document.getElementById(e);if(!n)throw new Error("Conteneur avec l'ID \"".concat(e,'" non trouvé'));n.innerHTML="";var i=document.createElement("div");i.className="sunuid-qr-code",i.innerHTML='\n <div class="sunuid-qr-header">\n <h3>'.concat(1===s?"Authentification":2===s?"Vérification KYC":3===s?"Service Type 3":"Service Type "+s,'</h3>\n </div>\n <div class="sunuid-qr-image">\n <img src="').concat(t,'" alt="QR Code SunuID" style="max-width: 300px; height: auto;">\n </div>\n <div class="sunuid-qr-instructions">\n <p>Scannez ce QR code avec l\'application SunuID pour vous connecter</p>\n </div>\n <div class="sunuid-qr-status" id="sunuid-status">\n <p>En attente de scan...</p>\n </div>\n '),n.appendChild(i),this.applyTheme(r.theme||this.config.theme)}},{key:"displayServiceUnavailable",value:function(e,t){console.log("displayServiceUnavailable appelée pour ".concat(e,", type: ").concat(t));var s=document.getElementById(e);s?s.innerHTML='\n <div class="sunuid-service-unavailable" style="\n text-align: center;\n padding: 40px 20px;\n background: #f8f9fa;\n border: 2px dashed #dee2e6;\n border-radius: 10px;\n color: #6c757d;\n font-family: Arial, sans-serif;\n ">\n <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>\n <h3 style="margin: 0 0 10px 0; color: #495057;">Service Non Disponible</h3>\n <p style="margin: 0; font-size: 14px;">\n Le service d\'authentification est temporairement indisponible.<br>\n Veuillez réessayer plus tard.\n </p>\n <div style="margin-top: 20px; font-size: 12px; color: #adb5bd;">\n Type: '.concat(t.toUpperCase(),"\n </div>\n </div>\n "):console.error("Container ".concat(e," non trouvé"))}},{key:"refreshQR",value:(o=p(v().m(function e(t){var s,r,n,i=arguments;return v().w(function(e){for(;;)switch(e.p=e.n){case 0:return s=i.length>1&&void 0!==i[1]?i[1]:{},e.p=1,e.n=2,this.generateQR(t,s);case 2:return r=e.v,e.a(2,r);case 3:throw e.p=3,n=e.v,console.error("Erreur lors du rafraîchissement:",n.message),this.displayServiceUnavailable(t,this.config.type),n;case 4:return e.a(2)}},e,this,[[1,3]])})),function(e){return o.apply(this,arguments)})},{key:"startAutoRefresh",value:function(e,t,s){var r=this;this.config.autoRefresh&&(this.refreshTimer=setInterval(p(v().m(function n(){var i;return v().w(function(n){for(;;)switch(n.p=n.n){case 0:return n.p=0,n.n=1,r.refreshQR(e,t,s);case 1:n.n=3;break;case 2:n.p=2,i=n.v,console.warn("Erreur lors du rafraîchissement automatique:",i);case 3:return n.a(2)}},n,null,[[0,2]])})),this.config.refreshInterval))}},{key:"makeRequest",value:(i=p(v().m(function t(s,r){var n,i,o,a,c,h,u,l;return v().w(function(t){for(;;)switch(t.p=t.n){case 0:return i=(null===(n=e.SunuIDConfig)||void 0===n||null===(n=n.endpoints)||void 0===n?void 0:n[s.replace("/","")])||s,o="".concat(this.config.apiUrl).concat(i),void 0!==r.type&&console.log("🌐 Envoi requête API - Type: ".concat(r.type,", Endpoint: ").concat(s)),t.p=1,t.n=2,fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.config.clientId,":").concat(this.config.secretId),Accept:"application/json"},body:JSON.stringify(g(g({},r),{},{client_id:this.config.clientId,secret_id:this.config.secretId}))});case 2:if((a=t.v).ok){t.n=4;break}return t.n=3,a.text();case 3:c=t.v;try{h=JSON.parse(c)}catch(e){h={message:c}}throw new Error(h.message||"Erreur HTTP: ".concat(a.status));case 4:return t.n=5,a.json();case 5:return u=t.v,t.a(2,u);case 6:throw t.p=6,l=t.v,console.error("Erreur API SunuID:",l),l;case 7:return t.a(2)}},t,this,[[1,6]])})),function(e,t){return i.apply(this,arguments)})},{key:"applyTheme",value:function(e){var t=document.querySelector(".sunuid-qr-code");t&&(t.className="sunuid-qr-code sunuid-theme-".concat(e))}},{key:"handleError",value:function(e){console.error("SunuID SDK Error:",e),this.config.onError&&this.config.onError(e)}},{key:"destroy",value:function(){this.refreshTimer&&clearInterval(this.refreshTimer),this.socket&&(this.socket.disconnect(),this.socket=null,console.log("🌐 WebSocket déconnecté")),this.isInitialized=!1,console.log("SunuID SDK détruit")}}],r&&_(t.prototype,r),n&&_(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,n,i,o,a,c,h,u,l}();e.SunuID=r,e.sunuidInstance=null,e.initSunuID=function(t){try{return e.sunuidInstance=new r(t),e.sunuidInstance}catch(e){throw console.error("Erreur lors de l'initialisation de SunuID:",e),e}}}(window)}(require$$0,require$$1,require$$2,require$$3,require$$4,require$$0$3,require$$0$1,require$$0$2,require$$1$1,require$$0$4,require$$3$1,require$$4$1);
10
+ */!function(e,r){var i={apiUrl:(null===(r=e.SunuIDConfig)||void 0===r?void 0:r.apiUrl)||"https://api.sunuid.fayma.sn",clientId:null,secretId:null,type:1,theme:"light",language:"fr",autoRefresh:!0,refreshInterval:3e4,onSuccess:null,onError:null,onStatusUpdate:null,onExpired:null},s=function(){return r=function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=o(o({},i),n),this.qrCode=null,this.refreshTimer=null,this.isInitialized=!1,this.socket=null,this.init()},s=[{key:"init",value:function(){if(!this.config.clientId||!this.config.secretId)throw new Error("SunuID: clientId et secretId sont requis");this.isInitialized=!0,console.log("SunuID SDK initialisé avec succès"),this.initWebSocket()}},{key:"initWebSocket",value:function(){var e=this;try{if("undefined"==typeof io)return console.warn("⚠️ Socket.IO non disponible, WebSocket sera initialisé plus tard"),void setTimeout(function(){return e.initWebSocket()},1e3);var n=this.getClientIP();this.socket||(this.socket=io("wss://samasocket.fayma.sn:9443",{query:{token:this.config.clientId,type:"web",userId:this.config.clientId,username:n}}),this.socket.on("connect",function(){console.log("🌐 WebSocket connecté avec succès"),console.log("📊 Socket ID:",e.socket.id)}),this.socket.on("disconnect",function(e){console.log("❌ WebSocket déconnecté:",e)}),this.socket.on("connect_error",function(e){console.error("❌ Erreur connexion WebSocket:",e)}),this.socket.on("qr_status_update",function(n){console.log("📱 Mise à jour statut QR reçue:",n),e.handleQRStatusUpdate(n)}),this.socket.on("qr_scan_success",function(n){console.log("✅ Scan QR réussi reçu:",n),e.handleQRScanSuccess(n)}),this.socket.on("qr_expired",function(n){console.log("⏰ QR expiré reçu:",n),e.handleQRExpired(n)}))}catch(e){console.error("❌ Erreur initialisation WebSocket:",e)}}},{key:"getClientIP",value:function(){return"127.0.0.1"}},{key:"handleQRStatusUpdate",value:function(e){this.config.onStatusUpdate&&this.config.onStatusUpdate(e)}},{key:"handleQRScanSuccess",value:function(e){this.config.onSuccess&&this.config.onSuccess(e)}},{key:"handleQRExpired",value:function(e){this.config.onExpired&&this.config.onExpired(e)}},{key:"emitWebSocketEvent",value:function(e,n){this.socket&&this.socket.connected?(this.socket.emit(e,n),console.log("📤 Événement WebSocket émis: ".concat(e),n)):"undefined"==typeof io?console.warn("⚠️ Socket.IO non disponible, impossible d'émettre l'événement:",e):console.warn("⚠️ WebSocket non connecté, impossible d'émettre l'événement:",e)}},{key:"getWebSocketStatus",value:function(){return this.socket?this.socket.connected?"connected":"disconnected":"not_initialized"}},{key:"forceWebSocketInit",value:function(){"undefined"==typeof io||this.socket||(console.log("🔄 Forçage de l'initialisation WebSocket..."),this.initWebSocket())}},{key:"generateQR",value:(v=n(c().m(function e(n){var t,r,i,s,a=arguments;return c().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t=a.length>1&&void 0!==a[1]?a[1]:{},this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-generate",o({type:this.config.type},t));case 2:if(!(r=e.v).success){e.n=3;break}return i="".concat("https://sunuid.fayma.sn").concat(r.data.qrcode),this.displayQRCode(n,i,this.config.type,t),this.startAutoRefresh(n,this.config.type,t),this.emitWebSocketEvent("qr_generated",{serviceId:r.data.service_id,type:this.config.type,qrCodeUrl:i,timestamp:Date.now()}),e.a(2,o(o({},r.data),{},{qrCodeUrl:i,sessionId:r.data.service_id}));case 3:throw new Error(r.message||"Erreur lors de la génération du QR code");case 4:e.n=6;break;case 5:throw e.p=5,s=e.v,console.error("Erreur API détectée:",s.message),console.log('Affichage du message "Service non disponible" pour type '+this.config.type),this.displayServiceUnavailable(n,this.config.type),new Error("Service non disponible");case 6:return e.a(2)}},e,this,[[1,5]])})),function(e){return v.apply(this,arguments)})},{key:"generateCustomQR",value:(p=n(c().m(function e(n,t){var r,i,s,a,u=arguments;return c().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=u.length>2&&void 0!==u[2]?u[2]:{},this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-generate",o({type:t},r));case 2:if(!(i=e.v).success){e.n=3;break}return s="".concat("https://sunuid.fayma.sn").concat(i.data.qrcode),this.displayQRCode(n,s,t,r),this.startAutoRefresh(n,t,r),e.a(2,o(o({},i.data),{},{qrCodeUrl:s,sessionId:i.data.service_id}));case 3:throw new Error(i.message||"Erreur lors de la génération du QR code");case 4:e.n=6;break;case 5:throw e.p=5,a=e.v,console.error("Erreur API détectée:",a.message),console.log('Affichage du message "Service non disponible" pour type '+t),this.displayServiceUnavailable(n,t),new Error("Service non disponible");case 6:return e.a(2)}},e,this,[[1,5]])})),function(e,n){return p.apply(this,arguments)})},{key:"generateAuthQR",value:(h=n(c().m(function e(n){var t,r=arguments;return c().w(function(e){for(;;)if(0===e.n)return t=r.length>1&&void 0!==r[1]?r[1]:{},e.a(2,this.generateQR(n,t))},e,this)})),function(e){return h.apply(this,arguments)})},{key:"generateKYCQR",value:(d=n(c().m(function e(n){var t,r,i=arguments;return c().w(function(e){for(;;)switch(e.p=e.n){case 0:return t=i.length>1&&void 0!==i[1]?i[1]:{},r=this.config.type,this.config.type=2,e.p=1,e.n=2,this.generateQR(n,t);case 2:return e.a(2,e.v);case 3:return e.p=3,this.config.type=r,e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])})),function(e){return d.apply(this,arguments)})},{key:"checkQRStatus",value:(f=n(c().m(function e(n){var t,r;return c().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-status",{serviceId:n});case 2:if(!(t=e.v).success){e.n=3;break}return e.a(2,t.data);case 3:throw new Error(t.message||"Erreur lors de la vérification du statut");case 4:e.n=6;break;case 5:throw e.p=5,r=e.v,this.handleError(r),r;case 6:return e.a(2)}},e,this,[[1,5]])})),function(e){return f.apply(this,arguments)})},{key:"displayQRCode",value:function(e,n,t){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=document.getElementById(e);if(!i)throw new Error("Conteneur avec l'ID \"".concat(e,'" non trouvé'));i.innerHTML="";var o=document.createElement("div");o.className="sunuid-qr-code",o.innerHTML='\n <div class="sunuid-qr-header">\n <h3>'.concat(1===t?"Authentification":2===t?"Vérification KYC":3===t?"Service Type 3":"Service Type "+t,'</h3>\n </div>\n <div class="sunuid-qr-image">\n <img src="').concat(n,'" alt="QR Code SunuID" style="max-width: 300px; height: auto;">\n </div>\n <div class="sunuid-qr-instructions">\n <p>Scannez ce QR code avec l\'application SunuID pour vous connecter</p>\n </div>\n <div class="sunuid-qr-status" id="sunuid-status">\n <p>En attente de scan...</p>\n </div>\n '),i.appendChild(o),this.applyTheme(r.theme||this.config.theme)}},{key:"displayServiceUnavailable",value:function(e,n){console.log("displayServiceUnavailable appelée pour ".concat(e,", type: ").concat(n));var t=document.getElementById(e);t?t.innerHTML='\n <div class="sunuid-service-unavailable" style="\n text-align: center;\n padding: 40px 20px;\n background: #f8f9fa;\n border: 2px dashed #dee2e6;\n border-radius: 10px;\n color: #6c757d;\n font-family: Arial, sans-serif;\n ">\n <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>\n <h3 style="margin: 0 0 10px 0; color: #495057;">Service Non Disponible</h3>\n <p style="margin: 0; font-size: 14px;">\n Le service d\'authentification est temporairement indisponible.<br>\n Veuillez réessayer plus tard.\n </p>\n <div style="margin-top: 20px; font-size: 12px; color: #adb5bd;">\n Type: '.concat(n.toUpperCase(),"\n </div>\n </div>\n "):console.error("Container ".concat(e," non trouvé"))}},{key:"refreshQR",value:(l=n(c().m(function e(n){var t,r,i,o=arguments;return c().w(function(e){for(;;)switch(e.p=e.n){case 0:return t=o.length>1&&void 0!==o[1]?o[1]:{},e.p=1,e.n=2,this.generateQR(n,t);case 2:return r=e.v,e.a(2,r);case 3:throw e.p=3,i=e.v,console.error("Erreur lors du rafraîchissement:",i.message),this.displayServiceUnavailable(n,this.config.type),i;case 4:return e.a(2)}},e,this,[[1,3]])})),function(e){return l.apply(this,arguments)})},{key:"startAutoRefresh",value:function(e,t,r){var i=this;this.config.autoRefresh&&(this.refreshTimer=setInterval(n(c().m(function n(){var o;return c().w(function(n){for(;;)switch(n.p=n.n){case 0:return n.p=0,n.n=1,i.refreshQR(e,t,r);case 1:n.n=3;break;case 2:n.p=2,o=n.v,console.warn("Erreur lors du rafraîchissement automatique:",o);case 3:return n.a(2)}},n,null,[[0,2]])})),this.config.refreshInterval))}},{key:"makeRequest",value:(u=n(c().m(function n(t,r){var i,s,a,u,l,f,d,h;return c().w(function(n){for(;;)switch(n.p=n.n){case 0:return s=(null===(i=e.SunuIDConfig)||void 0===i||null===(i=i.endpoints)||void 0===i?void 0:i[t.replace("/","")])||t,a="".concat(this.config.apiUrl).concat(s),void 0!==r.type&&console.log("🌐 Envoi requête API - Type: ".concat(r.type,", Endpoint: ").concat(t)),n.p=1,n.n=2,fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.config.clientId,":").concat(this.config.secretId),Accept:"application/json"},body:JSON.stringify(o(o({},r),{},{client_id:this.config.clientId,secret_id:this.config.secretId}))});case 2:if((u=n.v).ok){n.n=4;break}return n.n=3,u.text();case 3:l=n.v;try{f=JSON.parse(l)}catch(e){f={message:l}}throw new Error(f.message||"Erreur HTTP: ".concat(u.status));case 4:return n.n=5,u.json();case 5:return d=n.v,n.a(2,d);case 6:throw n.p=6,h=n.v,console.error("Erreur API SunuID:",h),h;case 7:return n.a(2)}},n,this,[[1,6]])})),function(e,n){return u.apply(this,arguments)})},{key:"applyTheme",value:function(e){var n=document.querySelector(".sunuid-qr-code");n&&(n.className="sunuid-qr-code sunuid-theme-".concat(e))}},{key:"handleError",value:function(e){console.error("SunuID SDK Error:",e),this.config.onError&&this.config.onError(e)}},{key:"destroy",value:function(){this.refreshTimer&&clearInterval(this.refreshTimer),this.socket&&(this.socket.disconnect(),this.socket=null,console.log("🌐 WebSocket déconnecté")),this.isInitialized=!1,console.log("SunuID SDK détruit")}}],s&&t(r.prototype,s),a&&t(r,a),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,s,a,u,l,f,d,h,p,v}();e.SunuID=s,e.sunuidInstance=null,e.initSunuID=function(n){try{return e.sunuidInstance=new s(n),e.sunuidInstance}catch(e){throw console.error("Erreur lors de l'initialisation de SunuID:",e),e}}}(window)}();
16
11
  //# sourceMappingURL=sunuid-sdk.min.js.map