├── .babelrc ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── example └── index.html ├── index.js ├── lib ├── index.js └── index.js.LICENSE.txt ├── mint.json ├── package.json ├── src ├── config │ └── index.js ├── index.js ├── libs │ └── libsamplerate.worklet.js ├── models │ ├── Audio │ │ ├── AudioWorklet.js │ │ └── AudioWorkletStream.js │ ├── AudioClass.js │ ├── Call.js │ ├── Device.js │ ├── DeviceEmitter.js │ ├── Microphone.js │ └── Microphone │ │ └── AudioWorkletMic.js ├── utils │ └── functions.js └── websocket │ └── index.js └── webpack.config.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ], 5 | "plugins": [ 6 | "@babel/plugin-proposal-class-properties" 7 | ] 8 | } -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: [ 3 | 'airbnb-base/legacy', 4 | 'prettier', 5 | 'plugin:vue/recommended', 6 | 'plugin:storybook/recommended', 7 | 'plugin:cypress/recommended', 8 | ], 9 | parserOptions: { 10 | parser: '@babel/eslint-parser', 11 | ecmaVersion: 2020, 12 | sourceType: 'module', 13 | }, 14 | plugins: ['html', 'prettier', 'babel'], 15 | rules: { 16 | 'prettier/prettier': ['error'], 17 | 'camelcase': 'off', 18 | 'no-param-reassign': 'off', 19 | 'import/no-extraneous-dependencies': 'off', 20 | 'import/prefer-default-export': 'off', 21 | 'import/no-named-as-default': 'off', 22 | 'import/no-unresolved': 'off', 23 | 'import/extensions': ['off'], 24 | 'no-console': 'error', 25 | }, 26 | settings: { 27 | 'import/resolver': { 28 | webpack: { 29 | config: 'config/webpack/resolve.js', 30 | }, 31 | }, 32 | }, 33 | env: { 34 | browser: true, 35 | node: true, 36 | }, 37 | globals: { 38 | bus: true, 39 | vi: true, 40 | }, 41 | }; 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | /dev 3 | /example/** -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "singleQuote": true, 4 | "trailingComma": "es5", 5 | "arrowParens": "avoid" 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "disponiveis", 4 | "whatsappid" 5 | ] 6 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 wavoip-api 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Wavoip - Biblioteca JavaScript para Chamadas de Áudio via WhatsApp 2 | 3 | A Wavoip é uma biblioteca JavaScript inovadora que possibilita a integração fácil e rápida de chamadas de áudio via WhatsApp em seus projetos. Com esta biblioteca, você pode aproveitar as funcionalidades de chamada do WhatsApp para enriquecer a experiência do usuário em seus aplicativos web. 4 | 5 | ## Recursos Principais 6 | 7 | - **Integração Simples:** Integre chamadas de áudio via WhatsApp em seus aplicativos web com apenas algumas linhas de código. 8 | 9 | - **Personalização:** Adapte as chamadas de acordo com as necessidades do seu projeto, personalizando a experiência do usuário. 10 | 11 | - **Compatibilidade:** Funciona perfeitamente em diversos navegadores, garantindo uma experiência consistente para os usuários. 12 | 13 | - **Documentação Clara:** Oferecemos uma documentação abrangente para ajudar você a começar rapidamente e explorar todos os recursos da Wavoip. 14 | 15 | ## Como Começar 16 | 17 | 1. Instale a biblioteca em seu projeto: 18 | ```bash 19 | npm install wavoip-api 20 | 21 | 2. Siga a documentação para integrar a funcionalidade de chamada de áudio em seu aplicativo. 22 | 23 | 3. Aproveite os benefícios de oferecer chamadas de áudio via WhatsApp aos seus usuários! 24 | 25 | 1. Instale a biblioteca em seu projeto: 26 | ```javascript 27 | const Wavoip = require("wavoip-api"); 28 | const WAV = new Wavoip; 29 | const whatsapp_instance = WAV.connect("my_token"); 30 | 31 | whatsapp_instance.socket.on('connect', () => { 32 | console.log('Successfully connected!'); 33 | 34 | whatsapp_instance.callStart({ 35 | whatsappid: "phone_number" 36 | }); 37 | }); 38 | ``` 39 | 40 | Explore mais recursos e exemplos na nossa documentação. 41 | 42 | ## Contribuições 43 | Contribuições são bem-vindas! Sinta-se à vontade para abrir issues, enviar pull requests ou fornecer feedback para tornar a Wavoip ainda melhor. 44 | 45 | ## Licença 46 | Este projeto está licenciado sob a Licença MIT. 47 | 48 | Lembre-se de substituir os marcadores de lugar, como `my_token` e `phone_number`, pelos valores apropriados. Boa sorte com o seu projeto! 49 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require("./src/index").default; -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Wavoip=e():t.Wavoip=e()}(window,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=21)}([function(t,e,r){"use strict";(function(t){var n=r(12);const{toString:o}=Object.prototype,{getPrototypeOf:i}=Object,s=(a=Object.create(null),t=>{const e=o.call(t);return a[e]||(a[e]=e.slice(8,-1).toLowerCase())});var a;const c=t=>(t=t.toLowerCase(),e=>s(e)===t),u=t=>e=>typeof e===t,{isArray:h}=Array,f=u("undefined");const l=c("ArrayBuffer");const p=u("string"),d=u("function"),y=u("number"),m=t=>null!==t&&"object"==typeof t,g=t=>{if("object"!==s(t))return!1;const e=i(t);return!(null!==e&&e!==Object.prototype&&null!==Object.getPrototypeOf(e)||Symbol.toStringTag in t||Symbol.iterator in t)},v=c("Date"),b=c("File"),w=c("Blob"),E=c("FileList"),_=c("URLSearchParams");function O(t,e,{allOwnKeys:r=!1}={}){if(null==t)return;let n,o;if("object"!=typeof t&&(t=[t]),h(t))for(n=0,o=t.length;n0;)if(n=r[o],e===n.toLowerCase())return n;return null}const k="undefined"==typeof self?void 0===t?void 0:t:self,A=t=>!f(t)&&t!==k;const R=(x="undefined"!=typeof Uint8Array&&i(Uint8Array),t=>x&&t instanceof x);var x;const T=c("HTMLFormElement"),P=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),j=c("RegExp"),C=(t,e)=>{const r=Object.getOwnPropertyDescriptors(t),n={};O(r,(r,o)=>{!1!==e(r,o,t)&&(n[o]=r)}),Object.defineProperties(t,n)};e.a={isArray:h,isArrayBuffer:l,isBuffer:function(t){return null!==t&&!f(t)&&null!==t.constructor&&!f(t.constructor)&&d(t.constructor.isBuffer)&&t.constructor.isBuffer(t)},isFormData:t=>t&&("function"==typeof FormData&&t instanceof FormData||"[object FormData]"===o.call(t)||d(t.toString)&&"[object FormData]"===t.toString()),isArrayBufferView:function(t){let e;return e="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&l(t.buffer),e},isString:p,isNumber:y,isBoolean:t=>!0===t||!1===t,isObject:m,isPlainObject:g,isUndefined:f,isDate:v,isFile:b,isBlob:w,isRegExp:j,isFunction:d,isStream:t=>m(t)&&d(t.pipe),isURLSearchParams:_,isTypedArray:R,isFileList:E,forEach:O,merge:function t(){const{caseless:e}=A(this)&&this||{},r={},n=(n,o)=>{const i=e&&S(r,o)||o;g(r[i])&&g(n)?r[i]=t(r[i],n):g(n)?r[i]=t({},n):h(n)?r[i]=n.slice():r[i]=n};for(let t=0,e=arguments.length;t(O(e,(e,o)=>{r&&d(e)?t[o]=Object(n.a)(e,r):t[o]=e},{allOwnKeys:o}),t),trim:t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:t=>(65279===t.charCodeAt(0)&&(t=t.slice(1)),t),inherits:(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},toFlatObject:(t,e,r,n)=>{let o,s,a;const c={};if(e=e||{},null==t)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],n&&!n(a,t,e)||c[a]||(e[a]=t[a],c[a]=!0);t=!1!==r&&i(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},kindOf:s,kindOfTest:c,endsWith:(t,e,r)=>{t=String(t),(void 0===r||r>t.length)&&(r=t.length),r-=e.length;const n=t.indexOf(e,r);return-1!==n&&n===r},toArray:t=>{if(!t)return null;if(h(t))return t;let e=t.length;if(!y(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},forEachEntry:(t,e)=>{const r=(t&&t[Symbol.iterator]).call(t);let n;for(;(n=r.next())&&!n.done;){const r=n.value;e.call(t,r[0],r[1])}},matchAll:(t,e)=>{let r;const n=[];for(;null!==(r=t.exec(e));)n.push(r);return n},isHTMLForm:T,hasOwnProperty:P,hasOwnProp:P,reduceDescriptors:C,freezeMethods:t=>{C(t,(e,r)=>{if(d(t)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=t[r];d(n)&&(e.enumerable=!1,"writable"in e?e.writable=!1:e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(t,e)=>{const r={},n=t=>{t.forEach(t=>{r[t]=!0})};return h(t)?n(t):n(String(t).split(e)),r},toCamelCase:t=>t.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,(function(t,e,r){return e.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(t,e)=>(t=+t,Number.isFinite(t)?t:e),findKey:S,global:k,isContextDefined:A,toJSONObject:t=>{const e=new Array(10),r=(t,n)=>{if(m(t)){if(e.indexOf(t)>=0)return;if(!("toJSON"in t)){e[n]=t;const o=h(t)?[]:{};return O(t,(t,e)=>{const i=r(t,n+1);!f(i)&&(o[e]=i)}),e[n]=void 0,o}}return t};return r(t,0)}}}).call(this,r(14))},function(t,e,r){"use strict";var n=r(0);function o(t,e,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o)}n.a.inherits(o,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:n.a.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const i=o.prototype,s={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{s[t]={value:t}}),Object.defineProperties(o,s),Object.defineProperty(i,"isAxiosError",{value:!0}),o.from=(t,e,r,s,a,c)=>{const u=Object.create(i);return n.a.toFlatObject(t,u,(function(t){return t!==Error.prototype}),t=>"isAxiosError"!==t),o.call(u,t.message,e,r,s,a),u.cause=t,u.name=t.name,c&&Object.assign(u,c),u},e.a=o},function(t,e,r){"use strict";r.d(e,"a",(function(){return n}));const n="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,r){"use strict";function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}r.d(e,"a",(function(){return n})),n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o(t.hasOwnProperty(r)&&(e[r]=t[r]),e),{})}const i=n.a.setTimeout,s=n.a.clearTimeout;function a(t,e){e.useNativeTimers?(t.setTimeoutFn=i.bind(n.a),t.clearTimeoutFn=s.bind(n.a)):(t.setTimeoutFn=n.a.setTimeout.bind(n.a),t.clearTimeoutFn=n.a.clearTimeout.bind(n.a))}function c(t){return"string"==typeof t?function(t){let e=0,r=0;for(let n=0,o=t.length;n=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))}},function(t,e,r){"use strict";r.d(e,"c",(function(){return o})),r.d(e,"a",(function(){return i})),r.d(e,"d",(function(){return s})),r.d(e,"b",(function(){return a}));var n=r(2);const o="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),i=n.a.WebSocket||n.a.MozWebSocket,s=!0,a="arraybuffer"},function(t,e,r){"use strict";r.d(e,"e",(function(){return b})),r.d(e,"c",(function(){return u})),r.d(e,"d",(function(){return g})),r.d(e,"a",(function(){return y})),r.d(e,"b",(function(){return v}));const n=Object.create(null);n.open="0",n.close="1",n.ping="2",n.pong="3",n.message="4",n.upgrade="5",n.noop="6";const o=Object.create(null);Object.keys(n).forEach(t=>{o[n[t]]=t});const i={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),a="function"==typeof ArrayBuffer,c=(t,e)=>{const r=new FileReader;return r.onload=function(){const t=r.result.split(",")[1];e("b"+(t||""))},r.readAsDataURL(t)};var u=({type:t,data:e},r,o)=>{return s&&e instanceof Blob?r?o(e):c(e,o):a&&(e instanceof ArrayBuffer||(i=e,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(i):i&&i.buffer instanceof ArrayBuffer))?r?o(e):c(new Blob([e]),o):o(n[t]+(e||""));var i};const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t{if(l){const r=(t=>{let e,r,n,o,i,s=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);const u=new ArrayBuffer(s),h=new Uint8Array(u);for(e=0;e>4,h[c++]=(15&n)<<4|o>>2,h[c++]=(3&o)<<6|63&i;return u})(t);return d(r,e)}return{base64:!0,data:t}},d=(t,e)=>{switch(e){case"blob":return t instanceof ArrayBuffer?new Blob([t]):t;case"arraybuffer":default:return t}};var y=(t,e)=>{if("string"!=typeof t)return{type:"message",data:d(t,e)};const r=t.charAt(0);if("b"===r)return{type:"message",data:p(t.substring(1),e)};return o[r]?t.length>1?{type:o[r],data:t.substring(1)}:{type:o[r]}:i};const m=String.fromCharCode(30),g=(t,e)=>{const r=t.length,n=new Array(r);let o=0;t.forEach((t,i)=>{u(t,!1,t=>{n[i]=t,++o===r&&e(n.join(m))})})},v=(t,e)=>{const r=t.split(m),n=[];for(let t=0;t0);return e}function u(){const t=c(+new Date);return t!==i?(s=0,i=t):t+"."+c(s++)}for(;a<64;a++)o[n[a]]=a},function(t,e,r){"use strict";function n(t,e){return function(){return t.apply(e,arguments)}}r.d(e,"a",(function(){return n}))},function(t,e,r){"use strict";(function(t){ 2 | /*! 3 | * The buffer module from node.js, for the browser. 4 | * 5 | * @author Feross Aboukhadijeh 6 | * @license MIT 7 | */ 8 | var n=r(22),o=r(23),i=r(24);function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function d(t,e){if(c.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return F(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(t).length;default:if(n)return F(t).length;e=(""+e).toLowerCase(),n=!0}}function y(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return A(this,e,r);case"ascii":return R(this,e,r);case"latin1":case"binary":return x(this,e,r);case"base64":return k(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function m(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function g(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=c.from(e,n)),c.isBuffer(e))return 0===e.length?-1:v(t,e,r,n,o);if("number"==typeof e)return e&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):v(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function v(t,e,r,n,o){var i,s=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){var h=-1;for(i=r;ia&&(r=a-c),i=r;i>=0;i--){for(var f=!0,l=0;lo&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function k(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function A(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o239?4:u>223?3:u>191?2:1;if(o+f<=r)switch(f){case 1:u<128&&(h=u);break;case 2:128==(192&(i=t[o+1]))&&(c=(31&u)<<6|63&i)>127&&(h=c);break;case 3:i=t[o+1],s=t[o+2],128==(192&i)&&128==(192&s)&&(c=(15&u)<<12|(63&i)<<6|63&s)>2047&&(c<55296||c>57343)&&(h=c);break;case 4:i=t[o+1],s=t[o+2],a=t[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(h=c)}null===h?(h=65533,f=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),o+=f}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),""},c.prototype.compare=function(t,e,r,n,o){if(!c.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),a=Math.min(i,s),u=this.slice(n,o),h=t.slice(e,r),f=0;fo)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return b(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":return E(this,t,e,r);case"latin1":case"binary":return _(this,t,e,r);case"base64":return O(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function R(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;on)&&(r=n);for(var o="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function C(t,e,r,n,o,i){if(!c.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function B(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o>>8*(n?o:1-o)}function L(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o>>8*(n?o:3-o)&255}function N(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(t,e,r,n,i){return i||N(t,0,r,4),o.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,i){return i||N(t,0,r,8),o.write(t,e,r,n,52,8),r+8}c.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(o*=256);)n+=this[t+--e]*o;return n},c.prototype.readUInt8=function(t,e){return e||j(t,1,this.length),this[t]},c.prototype.readUInt16LE=function(t,e){return e||j(t,2,this.length),this[t]|this[t+1]<<8},c.prototype.readUInt16BE=function(t,e){return e||j(t,2,this.length),this[t]<<8|this[t+1]},c.prototype.readUInt32LE=function(t,e){return e||j(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},c.prototype.readUInt32BE=function(t,e){return e||j(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},c.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||j(t,e,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*e)),n},c.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||j(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},c.prototype.readInt8=function(t,e){return e||j(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},c.prototype.readInt16LE=function(t,e){e||j(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(t,e){e||j(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(t,e){return e||j(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},c.prototype.readInt32BE=function(t,e){return e||j(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},c.prototype.readFloatLE=function(t,e){return e||j(t,4,this.length),o.read(this,t,!0,23,4)},c.prototype.readFloatBE=function(t,e){return e||j(t,4,this.length),o.read(this,t,!1,23,4)},c.prototype.readDoubleLE=function(t,e){return e||j(t,8,this.length),o.read(this,t,!0,52,8)},c.prototype.readDoubleBE=function(t,e){return e||j(t,8,this.length),o.read(this,t,!1,52,8)},c.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||C(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i=0&&(i*=256);)this[e+o]=t/i&255;return e+r},c.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,1,255,0),c.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},c.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):B(this,t,e,!0),e+2},c.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):B(this,t,e,!1),e+2},c.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):L(this,t,e,!0),e+4},c.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):L(this,t,e,!1),e+4},c.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);C(this,t,e,r,o-1,-o)}var i=0,s=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},c.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);C(this,t,e,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/s>>0)-a&255;return e+r},c.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,1,127,-128),c.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},c.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):B(this,t,e,!0),e+2},c.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):B(this,t,e,!1),e+2},c.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):L(this,t,e,!0),e+4},c.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||C(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),c.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):L(this,t,e,!1),e+4},c.prototype.writeFloatLE=function(t,e,r){return U(this,t,e,!0,r)},c.prototype.writeFloatBE=function(t,e,r){return U(this,t,e,!1,r)},c.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},c.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},c.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function q(t){return n.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(M,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}}).call(this,r(14))},function(t,e){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e,r){"use strict";var n=window.URL||window.webkitURL;t.exports=function(t){try{var e;try{(e=new(window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder)).append(t),e=e.getBlob("application/javascript; charset=utf-8")}catch(r){e=new Blob([t],{type:"application/javascript; charset=utf-8"})}return n.createObjectURL(e)}catch(e){return"data:application/javascript,"+encodeURIComponent(t)}}},function(t,e,r){"use strict";(function(t){r.d(e,"a",(function(){return h}));var n=r(8),o=r(9),i=r(11),s=r(4),a=r(5),c=r(6);const u="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class h extends n.a{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,r=u?{}:Object(s.c)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=a.d&&!u?e?new a.a(t,e):new a.a(t):new a.a(t,e,r)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||a.b,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(e){this.writable=!1;for(let r=0;r{const r={};if(!a.d&&(n.options&&(r.compress=n.options.compress),this.opts.perMessageDeflate)){("string"==typeof e?t.byteLength(e):e.length){this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let t=this.query||{};const e=this.opts.secure?"wss":"ws";let r="";this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(r=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=Object(i.a)()),this.supportsBinary||(t.b64=1);const n=Object(o.b)(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}check(){return!!a.a}}}).call(this,r(13).Buffer)},function(t,e,r){t.exports=r(15)('!function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e){class r extends AudioWorkletProcessor{constructor(t){super(t),Object.assign(this,t.processorOptions,{uint8:new Uint8Array(0)}),this.port.onmessage=this.appendBuffers.bind(this)}async appendBuffers({data:{buffer:t}}){const e=new Uint8Array(this.uint8.length+t.length);return e.set(this.uint8,0),e.set(t,this.uint8.length),this.uint8=e,!0}endOfStream(){this.port.postMessage({ended:!0,currentTime:currentTime,currentFrame:currentFrame})}process(t,e){const r=e[0];if(this.offset>=this.uint8.length)return!0;const n=new Uint8Array(256);for(let t=0;t<256&&!(this.offset>=this.uint8.length);t++,this.offset++)n[t]=this.uint8[this.offset];const o=new Uint16Array(n.buffer);for(let t=0;t=32768?-(65536-e)/32768:e/32767;r[0][t]=n}return this.uint8.length-this.offset>25e3&&(this.offset+=1e4),!0}}registerProcessor("audio-data-worklet-stream",r)}]);')},function(t,e,r){"use strict";var n=r(19),o=r.n(n);e.a=o.a},function(t,e){t.exports="object"==typeof self?self.FormData:window.FormData},function(t,e,r){t.exports=r(15)('!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t){class r extends AudioWorkletProcessor{constructor(e){super(e),this.init(),this.src=null,this.accumulatedPCM=[],this.sampleRate=e.processorOptions.sampleRate}async init(){const{create:e,ConverterType:t}=globalThis.LibSampleRate;e(1,this.sampleRate||48e3,16e3,{converterType:t.SRC_SINC_BEST_QUALITY}).then(e=>{this.src=e})}process(e,t,r){for(let r=0;r=320;){const e=this.accumulatedPCM.splice(0,320);this.port.postMessage(new Int16Array(e).buffer)}}return!0}convertToPCM(e){const t=new Int16Array(e.length);for(let r=0;r0?s-4:s;for(r=0;r>16&255,c[h++]=e>>8&255,c[h++]=255&e;2===a&&(e=o[t.charCodeAt(r)]<<2|o[t.charCodeAt(r+1)]>>4,c[h++]=255&e);1===a&&(e=o[t.charCodeAt(r)]<<10|o[t.charCodeAt(r+1)]<<4|o[t.charCodeAt(r+2)]>>2,c[h++]=e>>8&255,c[h++]=255&e);return c},e.fromByteArray=function(t){for(var e,r=t.length,o=r%3,i=[],s=0,a=r-o;sa?a:s+16383));1===o?(e=t[r-1],i.push(n[e>>2]+n[e<<4&63]+"==")):2===o&&(e=(t[r-2]<<8)+t[r-1],i.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function h(t,e,r){for(var o,i,s=[],a=e;a>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(t,e){ 9 | /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ 10 | e.read=function(t,e,r,n,o){var i,s,a=8*o-n-1,c=(1<>1,h=-7,f=r?o-1:0,l=r?-1:1,p=t[e+f];for(f+=l,i=p&(1<<-h)-1,p>>=-h,h+=a;h>0;i=256*i+t[e+f],f+=l,h-=8);for(s=i&(1<<-h)-1,i>>=-h,h+=n;h>0;s=256*s+t[e+f],f+=l,h-=8);if(0===i)i=1-u;else{if(i===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),i-=u}return(p?-1:1)*s*Math.pow(2,i-n)},e.write=function(t,e,r,n,o,i){var s,a,c,u=8*i-o-1,h=(1<>1,l=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:i-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),(e+=s+f>=1?l/c:l*Math.pow(2,1-f))*c>=2&&(s++,c/=2),s+f>=h?(a=0,s=h):s+f>=1?(a=(e*c-1)*Math.pow(2,o),s+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,o),s=0));o>=8;t[r+p]=255&a,p+=d,a/=256,o-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,u-=8);t[r+p-d]|=128*y}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict";r.r(e);var n={};r.r(n),r.d(n,"protocol",(function(){return C})),r.d(n,"PacketType",(function(){return B})),r.d(n,"Encoder",(function(){return L})),r.d(n,"Decoder",(function(){return N}));var o=r(8),i=r(11),s=r(9),a=r(6);let c=!1;try{c="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const u=c;var h=r(2);function f(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||u))return new XMLHttpRequest}catch(t){}if(!e)try{return new(h.a[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}var l=r(3),p=r(4);function d(){}const y=null!=new f({xdomain:!1}).responseType;class m extends o.a{constructor(t){if(super(t),this.polling=!1,"undefined"!=typeof location){const e="https:"===location.protocol;let r=location.port;r||(r=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||r!==t.port,this.xs=t.secure!==e}const e=t&&t.forceBase64;this.supportsBinary=y&&!e}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Object(a.b)(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,Object(a.d)(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.query||{};const e=this.opts.secure?"https":"http";let r="";!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Object(i.a)()),this.supportsBinary||t.sid||(t.b64=1),this.opts.port&&("https"===e&&443!==Number(this.opts.port)||"http"===e&&80!==Number(this.opts.port))&&(r=":"+this.opts.port);const n=Object(s.b)(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}request(t={}){return Object.assign(t,{xd:this.xd,xs:this.xs},this.opts),new g(this.uri(),t)}doWrite(t,e){const r=this.request({method:"POST",data:t});r.on("success",e),r.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class g extends l.a{constructor(t,e){super(),Object(p.b)(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.create()}create(){const t=Object(p.c)(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;const e=this.xhr=new f(t);try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&e.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),e.onreadystatechange=()=>{4===e.readyState&&(200===e.status||1223===e.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof e.status?e.status:0)},0))},e.send(this.data)}catch(t){return void this.setTimeoutFn(()=>{this.onError(t)},0)}"undefined"!=typeof document&&(this.index=g.requestsCount++,g.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=d,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete g.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(g.requestsCount=0,g.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",v);else if("function"==typeof addEventListener){const t="onpagehide"in h.a?"pagehide":"unload";addEventListener(t,v,!1)}function v(){for(let t in g.requests)g.requests.hasOwnProperty(t)&&g.requests[t].abort()}const b={websocket:r(16).a,polling:m},w=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,E=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function _(t){const e=t,r=t.indexOf("["),n=t.indexOf("]");-1!=r&&-1!=n&&(t=t.substring(0,r)+t.substring(r,n).replace(/:/g,";")+t.substring(n,t.length));let o=w.exec(t||""),i={},s=14;for(;s--;)i[E[s]]=o[s]||"";return-1!=r&&-1!=n&&(i.source=e,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(t,e){const r=e.replace(/\/{2,9}/g,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||r.splice(0,1);"/"==e.slice(-1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(t,e){const r={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(r[e]=n)})),r}(0,i.query),i}class O extends l.a{constructor(t,e={}){super(),this.writeBuffer=[],t&&"object"==typeof t&&(e=t,t=null),t?(t=_(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=_(e.host).host),Object(p.b)(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,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:!0},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=Object(s.a)(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(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"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=a.e,e.transport=t,this.id&&(e.sid=this.id);const r=Object.assign({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new b[t](r)}open(){let t;if(this.opts.rememberUpgrade&&O.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",t=>this.onClose("transport close",t))}probe(t){let e=this.createTransport(t),r=!1;O.priorWebsocketSuccess=!1;const n=()=>{r||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!r)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;O.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(u(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function o(){r||(r=!0,u(),e.close(),e=null)}const i=t=>{const r=new Error("probe error: "+t);r.transport=e.name,o(),this.emitReserved("upgradeError",r)};function s(){i("transport closed")}function a(){i("socket closed")}function c(t){e&&t.name!==e.name&&o()}const u=()=>{e.removeListener("open",n),e.removeListener("error",i),e.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};e.once("open",n),e.once("error",i),e.once("close",s),this.once("close",a),this.once("upgrading",c),e.open()}onOpen(){if(this.readyState="open",O.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let t=0;const e=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),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 t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e0&&t>this.maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}write(t,e,r){return this.sendPacket("message",t,e,r),this}send(t,e,r){return this.sendPacket("message",t,e,r),this}sendPacket(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const o={type:t,data:e,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},r=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){O.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let r=0;const n=t.length;for(;r"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||R&&t instanceof Blob||x&&t instanceof File}function P(t){const e=[],r=t.data,n=t;return n.data=function t(e,r){if(!e)return e;if(T(e)){const t={_placeholder:!0,num:r.length};return r.push(e),t}if(Array.isArray(e)){const n=new Array(e.length);for(let o=0;o=0&&e.num0;case B.ACK:case B.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class U{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=j(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function D(t,e,r){return t.on(e,r),function(){t.off(e,r)}}const M=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class I extends l.a{constructor(t,e,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[D(t,"open",this.onopen.bind(this)),D(t,"packet",this.onpacket.bind(this)),D(t,"error",this.onerror.bind(this)),D(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){if(M.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const r={type:B.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),r.id=t}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[t]=e);const o=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e{this.io.clearTimeoutFn(o),e.apply(this,[null,...t])}}emitWithAck(t,...e){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((n,o)=>{e.push((t,e)=>r?t?o(t):n(e):n(t)),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const r={id:this.ids++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...n)=>{if(r!==this._queue[0])return;return null!==t?r.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...n)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(){if(0===this._queue.length)return;const t=this._queue[0];if(t.pending)return;t.pending=!0,t.tryCount++;const e=this.ids;this.ids=t.id,this.flags=t.flags,this.emit.apply(this,t.args),this.ids=e}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:B.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case B.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 B.EVENT:case B.BINARY_EVENT:this.onevent(t);break;case B.ACK:case B.BINARY_ACK:this.onack(t);break;case B.DISCONNECT:this.ondisconnect();break;case B.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const r of e)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let r=!1;return function(...n){r||(r=!0,e.packet({type:B.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:B.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let r=0;r0&&t.jitter<=1?t.jitter:0,this.attempts=0}F.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},F.prototype.reset=function(){this.attempts=0},F.prototype.setMin=function(t){this.ms=t},F.prototype.setMax=function(t){this.max=t},F.prototype.setJitter=function(t){this.jitter=t};class q extends l.a{constructor(t,e){var r;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,Object(p.b)(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=e.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new F({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const o=e.parser||n;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new O(this.uri,this.opts);const e=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=D(e,"open",(function(){r.onopen(),t&&t()})),o=D(e,"error",e=>{r.cleanup(),r._readyState="closed",this.emitReserved("error",e),t?t(e):r.maybeReconnectOnOpen()});if(!1!==this._timeout){const t=this._timeout;0===t&&n();const r=this.setTimeoutFn(()=>{n(),e.close(),e.emit("error",new Error("timeout"))},t);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}return this.subs.push(n),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(D(t,"ping",this.onping.bind(this)),D(t,"data",this.ondata.bind(this)),D(t,"error",this.onerror.bind(this)),D(t,"close",this.onclose.bind(this)),D(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){Object(S.c)(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let r=this.nsps[t];return r||(r=new I(this,t,e),this.nsps[t]=r),this._autoConnect&&r.connect(),r}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Y={};function z(t,e){"object"==typeof t&&(e=t,t=void 0);const r=function(t,e="",r){let n=t;r=r||"undefined"!=typeof location&&location,null==t&&(t=r.protocol+"//"+r.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?r.protocol+t:r.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==r?r.protocol+"//"+t:"https://"+t),n=_(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const o=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+o+":"+n.port+e,n.href=n.protocol+"://"+o+(r&&r.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=r.source,o=r.id,i=r.path,s=Y[o]&&i in Y[o].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||s?a=new q(n,e):(Y[o]||(Y[o]=new q(n,e)),a=Y[o]),r.query&&!e.query&&(e.query=r.queryKey),a.socket(r.path,e)}Object.assign(z,{Manager:q,Socket:I,io:z,connect:z});function V(t){return(V="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function H(t,e){for(var r=0;r=0;--o){var i=this.tryEntries[o],s=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),S(r),f}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;S(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:A(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}function rt(t,e,r,n,o,i,s){try{var a=t[i](s),c=a.value}catch(t){return void r(t)}a.done?e(c):Promise.resolve(c).then(n,o)}function nt(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function s(t){rt(i,n,o,s,a,"next",t)}function a(t){rt(i,n,o,s,a,"throw",t)}s(void 0)}))}}function ot(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.sampleRate,o=r.numberOfChannels,i=void 0===o?1:o,s=r.latencyHint,a=void 0===s?0:s,c=r.workletOptions,u=void 0===c?{}:c;st(this,t),at(this,"aw",void 0),at(this,"ac",void 0),this.mediaStreamTrack=new Promise(function(){var t=nt(et().mark((function t(r){var o,s;return et().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=new AudioContext({sampleRate:n,numberOfChannels:i,latencyHint:a,channelCount:1,numberOfOutputs:1}),t.next=3,o.suspend();case 3:return o.onstatechange=function(t){console.log(t,"ac.onstatechange")},t.next=6,o.audioWorklet.addModule(Z.a);case 6:(s=new AudioWorkletNode(o,"audio-data-worklet-stream",u)).connect(o.destination),o.resume(),e.aw=s,e.ac=o,r();case 12:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}())}));function ht(t){return(ht="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function ft(t,e){for(var r=0;r{let t;return("undefined"==typeof navigator||"ReactNative"!==(t=navigator.product)&&"NativeScript"!==t&&"NS"!==t)&&("undefined"!=typeof window&&"undefined"!=typeof document)})();var Pt={isBrowser:!0,classes:{URLSearchParams:Rt,FormData:xt,Blob:Blob},isStandardBrowserEnv:Tt,protocols:["http","https","file","blob","url","data"]};var jt=function(t){function e(t,r,n,o){let i=t[o++];const s=Number.isFinite(+i),a=o>=t.length;if(i=!i&&yt.a.isArray(n)?n.length:i,a)return yt.a.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!s;n[i]&&yt.a.isObject(n[i])||(n[i]=[]);return e(t,r,n[i],o)&&yt.a.isArray(n[i])&&(n[i]=function(t){const e={},r=Object.keys(t);let n;const o=r.length;let i;for(n=0;n{e(function(t){return yt.a.matchAll(/\w+|\[(\w*)]/g,t).map(t=>"[]"===t[0]?"":t[1]||t[0])}(t),n,r,0)}),r}return null};const Ct={"Content-Type":void 0};const Bt={transitional:At,adapter:["xhr","http"],transformRequest:[function(t,e){const r=e.getContentType()||"",n=r.indexOf("application/json")>-1,o=yt.a.isObject(t);o&&yt.a.isHTMLForm(t)&&(t=new FormData(t));if(yt.a.isFormData(t))return n&&n?JSON.stringify(jt(t)):t;if(yt.a.isArrayBuffer(t)||yt.a.isBuffer(t)||yt.a.isStream(t)||yt.a.isFile(t)||yt.a.isBlob(t))return t;if(yt.a.isArrayBufferView(t))return t.buffer;if(yt.a.isURLSearchParams(t))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(t,e){return Object(gt.a)(t,new Pt.classes.URLSearchParams,Object.assign({visitor:function(t,e,r,n){return Pt.isNode&&yt.a.isBuffer(t)?(this.append(e,t.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},e))}(t,this.formSerializer).toString();if((i=yt.a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const e=this.env&&this.env.FormData;return Object(gt.a)(i?{"files[]":t}:t,e&&new e,this.formSerializer)}}return o||n?(e.setContentType("application/json",!1),function(t,e,r){if(yt.a.isString(t))try{return(e||JSON.parse)(t),yt.a.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(r||JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){const e=this.transitional||Bt.transitional,r=e&&e.forcedJSONParsing,n="json"===this.responseType;if(t&&yt.a.isString(t)&&(r&&!this.responseType||n)){const r=!(e&&e.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(t){if(r){if("SyntaxError"===t.name)throw kt.a.from(t,kt.a.ERR_BAD_RESPONSE,this,null,this.response);throw t}}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Pt.classes.FormData,Blob:Pt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};yt.a.forEach(["delete","get","head"],(function(t){Bt.headers[t]={}})),yt.a.forEach(["post","put","patch"],(function(t){Bt.headers[t]=yt.a.merge(Ct)}));var Lt=Bt;const Nt=yt.a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Ut=Symbol("internals");function Dt(t){return t&&String(t).trim().toLowerCase()}function Mt(t){return!1===t||null==t?t:yt.a.isArray(t)?t.map(Mt):String(t)}function It(t,e,r,n){return yt.a.isFunction(n)?n.call(this,e,r):yt.a.isString(e)?yt.a.isString(n)?-1!==e.indexOf(n):yt.a.isRegExp(n)?n.test(e):void 0:void 0}class Ft{constructor(t){t&&this.set(t)}set(t,e,r){const n=this;function o(t,e,r){const o=Dt(e);if(!o)throw new Error("header name must be a non-empty string");const i=yt.a.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||e]=Mt(t))}const i=(t,e)=>yt.a.forEach(t,(t,r)=>o(t,r,e));return yt.a.isPlainObject(t)||t instanceof this.constructor?i(t,e):yt.a.isString(t)&&(t=t.trim())&&!/^[-_a-zA-Z]+$/.test(t.trim())?i((t=>{const e={};let r,n,o;return t&&t.split("\n").forEach((function(t){o=t.indexOf(":"),r=t.substring(0,o).trim().toLowerCase(),n=t.substring(o+1).trim(),!r||e[r]&&Nt[r]||("set-cookie"===r?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)})),e})(t),e):null!=t&&o(e,t,r),this}get(t,e){if(t=Dt(t)){const r=yt.a.findKey(this,t);if(r){const t=this[r];if(!e)return t;if(!0===e)return function(t){const e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}(t);if(yt.a.isFunction(e))return e.call(this,t,r);if(yt.a.isRegExp(e))return e.exec(t);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,e){if(t=Dt(t)){const r=yt.a.findKey(this,t);return!(!r||e&&!It(0,this[r],r,e))}return!1}delete(t,e){const r=this;let n=!1;function o(t){if(t=Dt(t)){const o=yt.a.findKey(r,t);!o||e&&!It(0,r[o],o,e)||(delete r[o],n=!0)}}return yt.a.isArray(t)?t.forEach(o):o(t),n}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(t){const e=this,r={};return yt.a.forEach(this,(n,o)=>{const i=yt.a.findKey(r,o);if(i)return e[i]=Mt(n),void delete e[o];const s=t?function(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,e,r)=>e.toUpperCase()+r)}(o):String(o).trim();s!==o&&delete e[o],e[s]=Mt(n),r[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const e=Object.create(null);return yt.a.forEach(this,(r,n)=>{null!=r&&!1!==r&&(e[n]=t&&yt.a.isArray(r)?r.join(", "):r)}),e}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,e])=>t+": "+e).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...e){const r=new this(t);return e.forEach(t=>r.set(t)),r}static accessor(t){const e=(this[Ut]=this[Ut]={accessors:{}}).accessors,r=this.prototype;function n(t){const n=Dt(t);e[n]||(!function(t,e){const r=yt.a.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(t,r,o){return this[n].call(this,e,t,r,o)},configurable:!0})})}(r,t),e[n]=!0)}return yt.a.isArray(t)?t.forEach(n):n(t),this}}Ft.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),yt.a.freezeMethods(Ft.prototype),yt.a.freezeMethods(Ft);var qt=Ft;function Yt(t,e){const r=this||Lt,n=e||r,o=qt.from(n.headers);let i=n.data;return yt.a.forEach(t,(function(t){i=t.call(r,i,o.normalize(),e?e.status:void 0)})),o.normalize(),i}function zt(t){return!(!t||!t.__CANCEL__)}function Vt(t,e,r){kt.a.call(this,null==t?"canceled":t,kt.a.ERR_CANCELED,e,r),this.name="CanceledError"}yt.a.inherits(Vt,kt.a,{__CANCEL__:!0});var Ht=Vt;var Kt=Pt.isStandardBrowserEnv?{write:function(t,e,r,n,o,i){const s=[];s.push(t+"="+encodeURIComponent(e)),yt.a.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),yt.a.isString(n)&&s.push("path="+n),yt.a.isString(o)&&s.push("domain="+o),!0===i&&s.push("secure"),document.cookie=s.join("; ")},read:function(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function Wt(t,e){return t&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)?function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}(t,e):e}var Jt=Pt.isStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),e=document.createElement("a");let r;function n(r){let n=r;return t&&(e.setAttribute("href",n),n=e.href),e.setAttribute("href",n),{href:e.href,protocol:e.protocol?e.protocol.replace(/:$/,""):"",host:e.host,search:e.search?e.search.replace(/^\?/,""):"",hash:e.hash?e.hash.replace(/^#/,""):"",hostname:e.hostname,port:e.port,pathname:"/"===e.pathname.charAt(0)?e.pathname:"/"+e.pathname}}return r=n(window.location.href),function(t){const e=yt.a.isString(t)?n(t):t;return e.protocol===r.protocol&&e.host===r.host}}():function(){return!0};var Gt=function(t,e){t=t||10;const r=new Array(t),n=new Array(t);let o,i=0,s=0;return e=void 0!==e?e:1e3,function(a){const c=Date.now(),u=n[s];o||(o=c),r[i]=a,n[i]=c;let h=s,f=0;for(;h!==i;)f+=r[h++],h%=t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{const i=o.loaded,s=o.lengthComputable?o.total:void 0,a=i-r,c=n(a);r=i;const u={loaded:i,total:s,progress:s?i/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&i<=s?(s-i)/c:void 0,event:o};u[e?"download":"upload"]=!0,t(u)}}const Qt={http:null,xhr:"undefined"!=typeof XMLHttpRequest&&function(t){return new Promise((function(e,r){let n=t.data;const o=qt.from(t.headers).normalize(),i=t.responseType;let s;function a(){t.cancelToken&&t.cancelToken.unsubscribe(s),t.signal&&t.signal.removeEventListener("abort",s)}yt.a.isFormData(n)&&Pt.isStandardBrowserEnv&&o.setContentType(!1);let c=new XMLHttpRequest;if(t.auth){const e=t.auth.username||"",r=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";o.set("Authorization","Basic "+btoa(e+":"+r))}const u=Wt(t.baseURL,t.url);function h(){if(!c)return;const n=qt.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders());!function(t,e,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?e(new kt.a("Request failed with status code "+r.status,[kt.a.ERR_BAD_REQUEST,kt.a.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):t(r)}((function(t){e(t),a()}),(function(t){r(t),a()}),{data:i&&"text"!==i&&"json"!==i?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:n,config:t,request:c}),c=null}if(c.open(t.method.toUpperCase(),Ot(u,t.params,t.paramsSerializer),!0),c.timeout=t.timeout,"onloadend"in c?c.onloadend=h:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(h)},c.onabort=function(){c&&(r(new kt.a("Request aborted",kt.a.ECONNABORTED,t,c)),c=null)},c.onerror=function(){r(new kt.a("Network Error",kt.a.ERR_NETWORK,t,c)),c=null},c.ontimeout=function(){let e=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded";const n=t.transitional||At;t.timeoutErrorMessage&&(e=t.timeoutErrorMessage),r(new kt.a(e,n.clarifyTimeoutError?kt.a.ETIMEDOUT:kt.a.ECONNABORTED,t,c)),c=null},Pt.isStandardBrowserEnv){const e=(t.withCredentials||Jt(u))&&t.xsrfCookieName&&Kt.read(t.xsrfCookieName);e&&o.set(t.xsrfHeaderName,e)}void 0===n&&o.setContentType(null),"setRequestHeader"in c&&yt.a.forEach(o.toJSON(),(function(t,e){c.setRequestHeader(e,t)})),yt.a.isUndefined(t.withCredentials)||(c.withCredentials=!!t.withCredentials),i&&"json"!==i&&(c.responseType=t.responseType),"function"==typeof t.onDownloadProgress&&c.addEventListener("progress",$t(t.onDownloadProgress,!0)),"function"==typeof t.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",$t(t.onUploadProgress)),(t.cancelToken||t.signal)&&(s=e=>{c&&(r(!e||e.type?new Ht(null,t,c):e),c.abort(),c=null)},t.cancelToken&&t.cancelToken.subscribe(s),t.signal&&(t.signal.aborted?s():t.signal.addEventListener("abort",s)));const f=function(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}(u);f&&-1===Pt.protocols.indexOf(f)?r(new kt.a("Unsupported protocol "+f+":",kt.a.ERR_BAD_REQUEST,t)):c.send(n||null)}))}};yt.a.forEach(Qt,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(t){}Object.defineProperty(t,"adapterName",{value:e})}});var Xt=t=>{t=yt.a.isArray(t)?t:[t];const{length:e}=t;let r,n;for(let o=0;ot instanceof qt?t.toJSON():t;function re(t,e){e=e||{};const r={};function n(t,e,r){return yt.a.isPlainObject(t)&&yt.a.isPlainObject(e)?yt.a.merge.call({caseless:r},t,e):yt.a.isPlainObject(e)?yt.a.merge({},e):yt.a.isArray(e)?e.slice():e}function o(t,e,r){return yt.a.isUndefined(e)?yt.a.isUndefined(t)?void 0:n(void 0,t,r):n(t,e,r)}function i(t,e){if(!yt.a.isUndefined(e))return n(void 0,e)}function s(t,e){return yt.a.isUndefined(e)?yt.a.isUndefined(t)?void 0:n(void 0,t):n(void 0,e)}function a(r,o,i){return i in e?n(r,o):i in t?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(t,e)=>o(ee(t),ee(e),!0)};return yt.a.forEach(Object.keys(t).concat(Object.keys(e)),(function(n){const i=c[n]||o,s=i(t[n],e[n],n);yt.a.isUndefined(s)&&i!==a||(r[n]=s)})),r}const ne={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ne[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const oe={};ne.transitional=function(t,e,r){function n(t,e){return"[Axios v1.2.0] Transitional option '"+t+"'"+e+(r?". "+r:"")}return(r,o,i)=>{if(!1===t)throw new kt.a(n(o," has been removed"+(e?" in "+e:"")),kt.a.ERR_DEPRECATED);return e&&!oe[o]&&(oe[o]=!0,console.warn(n(o," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(r,o,i)}};var ie={assertOptions:function(t,e,r){if("object"!=typeof t)throw new kt.a("options must be an object",kt.a.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let o=n.length;for(;o-- >0;){const i=n[o],s=e[i];if(s){const e=t[i],r=void 0===e||s(e,i,t);if(!0!==r)throw new kt.a("option "+i+" must be "+r,kt.a.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new kt.a("Unknown option "+i,kt.a.ERR_BAD_OPTION)}},validators:ne};const se=ie.validators;class ae{constructor(t){this.defaults=t,this.interceptors={request:new St,response:new St}}request(t,e){"string"==typeof t?(e=e||{}).url=t:e=t||{},e=re(this.defaults,e);const{transitional:r,paramsSerializer:n,headers:o}=e;let i;void 0!==r&&ie.assertOptions(r,{silentJSONParsing:se.transitional(se.boolean),forcedJSONParsing:se.transitional(se.boolean),clarifyTimeoutError:se.transitional(se.boolean)},!1),void 0!==n&&ie.assertOptions(n,{encode:se.function,serialize:se.function},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase(),i=o&&yt.a.merge(o.common,o[e.method]),i&&yt.a.forEach(["delete","get","head","post","put","patch","common"],t=>{delete o[t]}),e.headers=qt.concat(i,o);const s=[];let a=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(a=a&&t.synchronous,s.unshift(t.fulfilled,t.rejected))}));const c=[];let u;this.interceptors.response.forEach((function(t){c.push(t.fulfilled,t.rejected)}));let h,f=0;if(!a){const t=[te.bind(this),void 0];for(t.unshift.apply(t,s),t.push.apply(t,c),h=t.length,u=Promise.resolve(e);f{if(!r._listeners)return;let e=r._listeners.length;for(;e-- >0;)r._listeners[e](t);r._listeners=null}),this.promise.then=t=>{let e;const n=new Promise(t=>{r.subscribe(t),e=t}).then(t);return n.cancel=function(){r.unsubscribe(e)},n},t((function(t,n,o){r.reason||(r.reason=new Ht(t,n,o),e(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){this.reason?t(this.reason):this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1)}static source(){let t;return{token:new ue((function(e){t=e})),cancel:t}}}var he=ue;const fe=function t(e){const r=new ce(e),n=Object(mt.a)(ce.prototype.request,r);return yt.a.extend(n,ce.prototype,r,{allOwnKeys:!0}),yt.a.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return t(re(e,r))},n}(Lt);fe.Axios=ce,fe.CanceledError=Ht,fe.CancelToken=he,fe.isCancel=zt,fe.VERSION="1.2.0",fe.toFormData=gt.a,fe.AxiosError=kt.a,fe.Cancel=fe.CanceledError,fe.all=function(t){return Promise.all(t)},fe.spread=function(t){return function(e){return t.apply(null,e)}},fe.isAxiosError=function(t){return yt.a.isObject(t)&&!0===t.isAxiosError},fe.AxiosHeaders=qt,fe.formToJSON=t=>jt(yt.a.isHTMLForm(t)?new FormData(t):t),fe.default=fe;var le=fe;function pe(t){return(pe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function de(t,e){for(var r=0;r=0;--o){var i=this.tryEntries[o],s=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),S(r),f}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;S(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:A(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}function _e(t,e,r,n,o,i,s){try{var a=t[i](s),c=a.value}catch(t){return void r(t)}a.done?e(c):Promise.resolve(c).then(n,o)}function Oe(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function s(t){_e(i,n,o,s,a,"next",t)}function a(t){_e(i,n,o,s,a,"throw",t)}s(void 0)}))}}var Se,ke,Ae,Re,xe,Te=[];function Pe(){return(Pe=Oe(Ee().mark((function t(e,r,n){return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:Se=e,xe=n;case 2:case"end":return t.stop()}}),t)})))).apply(this,arguments)}document.addEventListener("click",(function(){ke&&ke.resume().catch((function(){console.error("[*] - Error to get microphone access")}))}));var je=function(){var t=Oe(Ee().mark((function t(){var e,r;return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return ke||(ke=new(window.AudioContext||window.webkitAudioContext)),t.next=3,ke.audioWorklet.addModule(be.a);case 3:return t.next=5,ke.audioWorklet.addModule("https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js/dist/libsamplerate.worklet.js");case 5:return xe.emit("microphone_audioctx_change_state",{audio_context:ke,state:null===(e=ke)||void 0===e?void 0:e.state}),ke.onstatechange=function(){var t;xe.emit("microphone_audioctx_change_state",{audio_context:ke,state:null===(t=ke)||void 0===t?void 0:t.state})},t.next=9,navigator.mediaDevices.getUserMedia({audio:!0});case 9:Ae=t.sent,Re=ke.createMediaStreamSource(Ae),(r=new AudioWorkletNode(ke,"resample-processor",{processorOptions:{sampleRate:ke.sampleRate}})).port.onmessage=function(t){Se.socket_audio_transport.volatile.timeout(250).emit("microphone_buffer",t.data)},Re.connect(r);case 14:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),Ce=function(){var t=Oe(Ee().mark((function t(){return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:Re&&(Re.disconnect(),Re=null),Ae&&(Ae.getTracks().forEach((function(t){return t.stop()})),Ae=null),ke&&(ke.close(),ke=null),console.log("Microfone desconectado e stream parado.");case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}();function Be(){return Le.apply(this,arguments)}function Le(){return(Le=Oe(Ee().mark((function t(){var e;return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,navigator.mediaDevices.enumerateDevices();case 3:e=t.sent,Te=e.filter((function(t){return"audioinput"===t.kind})).map((function(t){return{label:t.label||"Unnamed Microphone",deviceId:t.deviceId}})),console.log("Microphones updated:",Te),t.next=11;break;case 8:t.prev=8,t.t0=t.catch(0),console.error("Error fetching microphones:",t.t0);case 11:case"end":return t.stop()}}),t,null,[[0,8]])})))).apply(this,arguments)}function Ne(){return Ue.apply(this,arguments)}function Ue(){return(Ue=Oe(Ee().mark((function t(){var e;return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,navigator.mediaDevices.getUserMedia({audio:!0});case 3:e=t.sent,console.log("Permissão concedida para o microfone."),e.getTracks().forEach((function(t){return t.stop()})),t.next=11;break;case 8:t.prev=8,t.t0=t.catch(0),"NotAllowedError"===t.t0.name?console.log("Permissão para o microfone foi negada."):"NotFoundError"===t.t0.name?console.log("Nenhum microfone disponível no dispositivo."):console.error("Erro ao solicitar permissão para o microfone:",t.t0);case 11:case"end":return t.stop()}}),t,null,[[0,8]])})))).apply(this,arguments)}function De(){return Me.apply(this,arguments)}function Me(){return(Me=Oe(Ee().mark((function t(){var e;return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,navigator.permissions.query({name:"microphone"});case 3:e=t.sent,t.t0=e.state,t.next="granted"===t.t0?7:"denied"===t.t0?9:"prompt"===t.t0?11:14;break;case 7:return console.log("Permissão concedida para o microfone."),t.abrupt("break",14);case 9:return console.log("Permissão negada para o microfone."),t.abrupt("break",14);case 11:return t.next=13,Ne();case 13:return t.abrupt("break",14);case 14:return t.abrupt("return",e.state);case 17:return t.prev=17,t.t1=t.catch(0),console.error("Erro ao verificar permissão:",t.t1),t.abrupt("return",!1);case 21:case"end":return t.stop()}}),t,null,[[0,17]])})))).apply(this,arguments)}function Ie(){return(Ie=Oe(Ee().mark((function t(){var e,r;return Ee().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,De();case 2:if(r=t.sent,0!==Te.length){t.next=7;break}return t.abrupt("return",{type:"no_microphone_available",message:"Não há microfone disponivel para uso"});case 7:if("granted"===r){t.next=11;break}return t.abrupt("return",{type:"no_microphone_permission",message:"Sem permissão para acessar o microfone"});case 11:if(!ke||"running"===ke.state){t.next=15;break}return t.abrupt("return",{type:"audio_context",message:"Não foi possível obter acesso ao microfone"});case 15:if(!navigator.userActivation.hasBeenActive||"running"===(null===(e=ke)||void 0===e?void 0:e.state)){t.next=19;break}return t.abrupt("return",{type:"audio_context",message:"Você precisa interagir com a página para liberar a permissão do microfone"});case 19:return console.log("[MICROPHONE] - Permission success to access microphone device"),t.abrupt("return",!1);case 21:case"end":return t.stop()}}),t)})))).apply(this,arguments)}Be(),navigator.mediaDevices.addEventListener("devicechange",Be);var Fe={init:function(t,e,r){return Pe.apply(this,arguments)},start:je,stop:Ce,requestMicrophonePermission:Ne,checkMicrophonePermission:De,fetchMicrophones:Be,getMicrophones:function(){return Te},getAudioContext:function(){return ke},checkError:function(){return Ie.apply(this,arguments)}};function qe(t){return(qe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function Ye(t,e){for(var r=0;r1?e-1:0),n=1;n { 10 | const SocketInstance = new Socket(deviceToken); 11 | const deviceEmitter = new DeviceEmitter(); 12 | 13 | const AudioInstance = new Audio(SocketInstance, deviceEmitter); 14 | const CallModel = new Call(SocketInstance.socket); 15 | const DeviceModel = new Device(SocketInstance.socket, deviceToken); 16 | 17 | Microphone.init(SocketInstance, 16000, deviceEmitter); 18 | 19 | SocketInstance.socket.on('connect', () => {}); 20 | 21 | SocketInstance.socket.on('disconnect', reason => {}); 22 | 23 | SocketInstance.socket.on('signaling', data => {}); 24 | 25 | SocketInstance.socket.on( 26 | 'audio_transport:create', 27 | ({ room, sampleRate }) => { 28 | AudioInstance.start(16000, room); 29 | 30 | Microphone.init(SocketInstance, 16000, deviceEmitter); 31 | Microphone.start(); 32 | } 33 | ); 34 | 35 | SocketInstance.socket.on('audio_transport:terminate', ({ room }) => { 36 | AudioInstance.stop(); 37 | Microphone.stop(); 38 | }); 39 | 40 | const wavoip_api = { 41 | socket: SocketInstance.socket, 42 | getCurrentDeviceStatus: function() { 43 | return DeviceModel.getCurrentDeviceStatus(); 44 | }, 45 | getCurrentQRCode: function() { 46 | return DeviceModel.getCurrentQRCode(); 47 | }, 48 | getAllInfo: function() { 49 | return DeviceModel.getAllInfo(); 50 | }, 51 | callStart: function(params) { 52 | AudioInstance.checkError(); 53 | return CallModel.callStart(params); 54 | }, 55 | endCall: () => { 56 | return CallModel.endCall(); 57 | }, 58 | acceptCall: () => { 59 | return CallModel.acceptCall(); 60 | }, 61 | rejectCall: () => { 62 | return CallModel.rejectCall(); 63 | }, 64 | mute: () => { 65 | return CallModel.mute(); 66 | }, 67 | unMute: () => { 68 | return CallModel.unMute(); 69 | }, 70 | Microphone: Microphone, 71 | Audio: AudioInstance, 72 | deviceEmitter: deviceEmitter 73 | }; 74 | 75 | if(!window.wavoip_api) { 76 | window.wavoip_api = {}; 77 | } 78 | 79 | window.wavoip_api[deviceToken] = wavoip_api; 80 | 81 | return wavoip_api; 82 | }; 83 | } 84 | 85 | export default Wavoip; 86 | -------------------------------------------------------------------------------- /src/models/Audio/AudioWorklet.js: -------------------------------------------------------------------------------- 1 | // import { CODECS } from './codecs.js'; 2 | class AudioDataWorkletStream extends AudioWorkletProcessor { 3 | constructor(options) { 4 | super(options); 5 | Object.assign(this, options.processorOptions, { 6 | uint8: new Uint8Array(0), 7 | }); 8 | this.port.onmessage = this.appendBuffers.bind(this); 9 | } 10 | 11 | async appendBuffers({ data: { buffer } }) { 12 | const result = new Uint8Array(this.uint8.length + buffer.length); 13 | result.set(this.uint8, 0); 14 | result.set(buffer, this.uint8.length); 15 | 16 | this.uint8 = result; 17 | return true; 18 | } 19 | 20 | endOfStream() { 21 | this.port.postMessage({ 22 | ended: true, 23 | currentTime, 24 | currentFrame, 25 | }); 26 | } 27 | 28 | process(inputs, outputs) { 29 | const channels = outputs[0]; 30 | 31 | if (this.offset >= this.uint8.length) { 32 | return true; 33 | } 34 | 35 | const uint8 = new Uint8Array(256); 36 | for (let i = 0; i < 256; i++, this.offset++) { 37 | if (this.offset >= this.uint8.length) { 38 | break; 39 | } 40 | uint8[i] = this.uint8[this.offset]; 41 | } 42 | const uint16 = new Uint16Array(uint8.buffer); 43 | 44 | for (let i = 0; i < uint16.length; i++) { 45 | const int = uint16[i]; 46 | // If the high bit is on, then it is a negative number, and actually counts backwards. 47 | const float = int >= 0x8000 ? -(0x10000 - int) / 0x8000 : int / 0x7fff; 48 | // interleave 49 | 50 | channels[0][i] = float; 51 | } 52 | 53 | // Atraso de 25k bytes de pacotes, não vou zerar a quantidade de pacotes mas apenas diminuir o atraso 54 | if(this.uint8.length - this.offset > 25000) { 55 | this.offset += 10000 56 | } 57 | 58 | // Retorna true para indicar que o processamento foi bem-sucedido. 59 | return true; 60 | } 61 | } 62 | registerProcessor('audio-data-worklet-stream', AudioDataWorkletStream); 63 | -------------------------------------------------------------------------------- /src/models/Audio/AudioWorkletStream.js: -------------------------------------------------------------------------------- 1 | import noiseGeneratorUrl from './AudioWorklet.js'; 2 | 3 | class AudioWorkletStream { 4 | aw; 5 | ac; 6 | 7 | constructor({ 8 | sampleRate, 9 | numberOfChannels = 1, 10 | latencyHint = 0, 11 | workletOptions = {}, 12 | } = {}) { 13 | this.mediaStreamTrack = new Promise(async resolve => { 14 | const ac = new AudioContext({ 15 | sampleRate, 16 | numberOfChannels, 17 | latencyHint, 18 | channelCount: 1, 19 | numberOfOutputs: 1, 20 | }); 21 | 22 | await ac.suspend(); 23 | ac.onstatechange = ev => { 24 | console.log(ev, "ac.onstatechange"); 25 | }; 26 | 27 | await ac.audioWorklet.addModule(noiseGeneratorUrl); 28 | 29 | const aw = new AudioWorkletNode( 30 | ac, 31 | 'audio-data-worklet-stream', 32 | workletOptions 33 | ); 34 | aw.connect(ac.destination); 35 | ac.resume(); 36 | this.aw = aw; 37 | this.ac = ac; 38 | 39 | resolve(); 40 | }); 41 | } 42 | } 43 | 44 | export default AudioWorkletStream; 45 | -------------------------------------------------------------------------------- /src/models/AudioClass.js: -------------------------------------------------------------------------------- 1 | import AudioWorkletStream from './Audio/AudioWorkletStream.js'; 2 | 3 | class Audio { 4 | audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 5 | workletStream; 6 | deviceEmitter; 7 | isStarted = false; 8 | 9 | constructor(Socket, deviceEmitter) { 10 | this.Socket = Socket; 11 | this.audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 12 | this.workletStream; 13 | this.deviceEmitter = deviceEmitter; 14 | 15 | this.isStarted = false; 16 | } 17 | 18 | start(sampleRate) { 19 | let workletStream = new AudioWorkletStream({ 20 | sampleRate: sampleRate, 21 | latencyHint: 0, 22 | workletOptions: { 23 | numberOfInputs: 1, 24 | numberOfOutputs: 1, 25 | channelCount: 1, 26 | processorOptions: { 27 | offset: 0, 28 | }, 29 | }, 30 | }); 31 | 32 | this.Socket.socket_audio_transport.on('audio_buffer', buffer => { 33 | let raw = new Uint8Array(buffer); 34 | 35 | workletStream.aw.port.postMessage({ 36 | buffer: raw, 37 | }); 38 | }); 39 | 40 | this.workletStream = workletStream; 41 | 42 | this.workletStream.mediaStreamTrack 43 | .finally(() => { 44 | this.workletStream.ac.onstatechange = () => { 45 | this.deviceEmitter.emit("audio_audioctx_change_state", { 46 | audio_context: this.workletStream.ac, 47 | state: this.workletStream?.ac?.state 48 | }) 49 | }; 50 | }) 51 | 52 | this.isStarted = true; 53 | this.checkPermission(); 54 | } 55 | 56 | stop() { 57 | console.info('[*] - Audio stream stopped'); 58 | this.workletStream = null; 59 | 60 | // this.audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 61 | if(this.Socket.socket_audio_transport) { 62 | this.Socket.socket_audio_transport.off('audio_buffer'); 63 | } 64 | 65 | this.isStarted = false; 66 | } 67 | 68 | checkPermission() { 69 | if(!this.isStarted) { 70 | return; 71 | } 72 | 73 | if(navigator.userActivation.hasBeenActive && this.workletStream?.ac) { 74 | this.workletStream?.ac.resume() 75 | .then(() => { 76 | console.log("[AUDIO] - Permission success to access audio device"); 77 | return true; 78 | }) 79 | .catch((error) => { 80 | console.error("[AUDIO] - Permission error to access audio device", error); 81 | 82 | setTimeout(() => { 83 | this.checkPermission(); 84 | }, 250) 85 | }); 86 | } else { 87 | setTimeout(() => { 88 | this.checkPermission(); 89 | }, 250) 90 | } 91 | } 92 | 93 | checkError() { 94 | if(navigator.userActivation.hasBeenActive) { 95 | if(this.workletStream?.ac) { 96 | if(this.workletStream.ac.state !== "running") { 97 | return { 98 | type: "audio_context", 99 | message: "Não foi possível obter acesso ao díspositivo de audio", 100 | }; 101 | } 102 | } 103 | } 104 | else { 105 | return { 106 | type: "audio_context", 107 | message: "Você precisa interagir com a página para liberar a permissão de áudio", 108 | }; 109 | } 110 | 111 | return null; 112 | } 113 | } 114 | 115 | export default Audio; -------------------------------------------------------------------------------- /src/models/Call.js: -------------------------------------------------------------------------------- 1 | import { checkResponseResult } from '../utils/functions.js'; 2 | 3 | class Call { 4 | constructor(Socket) { 5 | this.Socket = Socket; 6 | } 7 | 8 | callStart({ whatsappid }) { 9 | return new Promise((resolve, reject) => { 10 | try { 11 | this.Socket.emit('calls:start', whatsappid, response => { 12 | try { 13 | if (checkResponseResult(response)) { 14 | resolve(response); 15 | } else { 16 | resolve(response); 17 | } 18 | } catch (error) { 19 | reject(error); 20 | } 21 | }); 22 | } catch (error) { 23 | reject(error); 24 | } 25 | }); 26 | } 27 | 28 | endCall() { 29 | return new Promise((resolve, reject) => { 30 | this.Socket.emit('calls:end', {}, response => { 31 | if (checkResponseResult(response)) { 32 | resolve(response); 33 | } else { 34 | reject(response); 35 | } 36 | }); 37 | }); 38 | } 39 | 40 | acceptCall() { 41 | return new Promise((resolve, reject) => { 42 | this.Socket.emit('calls:accept', {}, response => { 43 | if (checkResponseResult(response)) { 44 | resolve(response); 45 | } else { 46 | reject(response); 47 | } 48 | }); 49 | }); 50 | } 51 | 52 | rejectCall() { 53 | return new Promise((resolve, reject) => { 54 | this.Socket.emit('calls:reject', {}, response => { 55 | if (checkResponseResult(response)) { 56 | resolve(response); 57 | } else { 58 | reject(response); 59 | } 60 | }); 61 | }); 62 | } 63 | 64 | mute() { 65 | return new Promise((resolve, reject) => { 66 | this.Socket.emit('calls:mute', {}, response => { 67 | if (checkResponseResult(response)) { 68 | resolve(response); 69 | } else { 70 | reject(response); 71 | } 72 | }); 73 | }); 74 | } 75 | 76 | unMute() { 77 | return new Promise((resolve, reject) => { 78 | this.Socket.emit('calls:unmute', {}, response => { 79 | if (checkResponseResult(response)) { 80 | resolve(response); 81 | } else { 82 | reject(response); 83 | } 84 | }); 85 | }); 86 | } 87 | } 88 | 89 | export default Call; 90 | -------------------------------------------------------------------------------- /src/models/Device.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | class Device { 3 | qrcode; 4 | device_status; 5 | 6 | constructor(Socket, token) { 7 | this.Socket = Socket; 8 | this.qrcode; 9 | this.device_status; 10 | this.all_info; 11 | this.token = token; 12 | 13 | this.Socket.on('qrcode', qrcode => { 14 | this.qrcode = qrcode; 15 | }); 16 | 17 | this.Socket.on('device_status', device_status => { 18 | this.device_status = device_status; 19 | }); 20 | } 21 | 22 | getCurrentQRCode() { 23 | return new Promise((resolve, reject) => { 24 | try { 25 | this.Socket.emit('whatsapp:qrcode', qrcode => { 26 | this.qrcode = qrcode; 27 | resolve(qrcode); 28 | }); 29 | } catch (error) { 30 | console.error('Error to get current qrcode', error); 31 | reject(error); 32 | } 33 | }); 34 | } 35 | 36 | getCurrentDeviceStatus() { 37 | return new Promise((resolve, reject) => { 38 | try { 39 | this.Socket.emit('whatsapp:device_status', device_status => { 40 | this.device_status = device_status; 41 | resolve(device_status); 42 | }); 43 | } catch (error) { 44 | console.error('Error to get current device status', error); 45 | reject(error); 46 | } 47 | }); 48 | } 49 | 50 | getAllInfo() { 51 | return new Promise((resolve, reject) => { 52 | try { 53 | const url = `https://devices.wavoip.com/${this.token}/whatsapp/all_info`; 54 | 55 | const config = { 56 | headers: { 57 | 'Authorization': 'Bearer SEU_TOKEN_AQUI', // Adicione o token se necessário 58 | 'Content-Type': 'application/json' 59 | }, 60 | }; 61 | 62 | axios.get(url, config) 63 | .then(response => { 64 | resolve(response.data); 65 | }) 66 | .catch(error => { 67 | reject(error) 68 | }); 69 | 70 | } catch (error) { 71 | console.error('Error to get current all infos', error); 72 | reject(error); 73 | } 74 | }); 75 | } 76 | } 77 | 78 | export default Device; 79 | -------------------------------------------------------------------------------- /src/models/DeviceEmitter.js: -------------------------------------------------------------------------------- 1 | class EventEmitter { 2 | constructor() { 3 | this.events = {}; 4 | } 5 | 6 | // Adiciona um listener para o evento 7 | on(event, listener) { 8 | if (!this.events[event]) { 9 | this.events[event] = []; 10 | } 11 | this.events[event].push(listener); 12 | } 13 | 14 | // Emite o evento, chamando todos os listeners 15 | emit(event, ...args) { 16 | if (this.events[event]) { 17 | this.events[event].forEach((listener) => listener(...args)); 18 | } 19 | } 20 | 21 | // Remove um listener específico 22 | off(event, listenerToRemove) { 23 | if (this.events[event]) { 24 | this.events[event] = this.events[event].filter( 25 | (listener) => listener !== listenerToRemove 26 | ); 27 | } 28 | } 29 | } 30 | 31 | export default EventEmitter; -------------------------------------------------------------------------------- /src/models/Microphone.js: -------------------------------------------------------------------------------- 1 | // import Recorder from 'audio-recorder-worklet-processor'; 2 | import noiseGeneratorUrl from './Microphone/AudioWorkletMic.js'; 3 | 4 | let microphonesDevicesList = []; 5 | 6 | let recorder; 7 | let socket; 8 | let audioContext; 9 | 10 | let micStream; 11 | let micSource; 12 | let deviceEmitter; 13 | 14 | document.addEventListener("click", () => { 15 | if(audioContext) { 16 | audioContext.resume() 17 | .catch(() => { 18 | console.error("[*] - Error to get microphone access"); 19 | }) 20 | } 21 | }) 22 | 23 | async function init(io, sampleRate, deviceEmitterInstance) { 24 | socket = io; 25 | deviceEmitter = deviceEmitterInstance; 26 | } 27 | 28 | const start = async () => { 29 | if (!audioContext) { 30 | audioContext = new (window.AudioContext || window.webkitAudioContext)(); 31 | } 32 | 33 | await audioContext.audioWorklet.addModule(noiseGeneratorUrl); 34 | await audioContext.audioWorklet.addModule( 35 | 'https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js/dist/libsamplerate.worklet.js' 36 | ); 37 | 38 | deviceEmitter.emit("microphone_audioctx_change_state", { 39 | audio_context: audioContext, 40 | state: audioContext?.state 41 | }) 42 | 43 | audioContext.onstatechange = () => { 44 | deviceEmitter.emit("microphone_audioctx_change_state", { 45 | audio_context: audioContext, 46 | state: audioContext?.state 47 | }) 48 | }; 49 | 50 | micStream = await navigator.mediaDevices.getUserMedia({ audio: true }); 51 | micSource = audioContext.createMediaStreamSource(micStream); 52 | 53 | const resampleNode = new AudioWorkletNode(audioContext, 'resample-processor', { 54 | processorOptions: { 55 | sampleRate: audioContext.sampleRate 56 | } 57 | }); 58 | 59 | // Adiciona um listener para capturar os buffers enviados pelo Audio Worklet 60 | resampleNode.port.onmessage = (event) => { 61 | socket.socket_audio_transport.volatile 62 | .timeout(250) 63 | .emit('microphone_buffer', event.data); 64 | }; 65 | 66 | micSource.connect(resampleNode); 67 | }; 68 | 69 | const stop = async () => { 70 | if (micSource) { 71 | micSource.disconnect(); // Desconecta o mediaStreamSource 72 | micSource = null; 73 | } 74 | 75 | if (micStream) { 76 | micStream.getTracks().forEach(track => track.stop()); // Para todos os tracks de áudio 77 | micStream = null; 78 | } 79 | 80 | if (audioContext) { 81 | audioContext.close(); // Fecha o AudioContext 82 | audioContext = null; 83 | } 84 | 85 | console.log('Microfone desconectado e stream parado.'); 86 | 87 | if (recorder) { 88 | 89 | // const duration = await recorder.stop(); 90 | 91 | // console.info('[*] - Microphone stream stopped with duration', duration); 92 | // recorder = null; 93 | // return duration; 94 | } 95 | }; 96 | 97 | async function fetchMicrophones() { 98 | try { 99 | const devices = await navigator.mediaDevices.enumerateDevices(); 100 | microphonesDevicesList = devices 101 | .filter(device => device.kind === 'audioinput') 102 | .map(mic => ({ 103 | label: mic.label || 'Unnamed Microphone', 104 | deviceId: mic.deviceId, 105 | })); 106 | console.log("Microphones updated:", microphonesDevicesList); 107 | } catch (error) { 108 | console.error("Error fetching microphones:", error); 109 | } 110 | } 111 | 112 | function getMicrophones() { 113 | return microphonesDevicesList; 114 | } 115 | 116 | function getAudioContext() { 117 | return audioContext; 118 | } 119 | 120 | async function requestMicrophonePermission() { 121 | try { 122 | const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); 123 | console.log('Permissão concedida para o microfone.'); 124 | 125 | stream.getTracks().forEach(track => track.stop()); 126 | } catch (error) { 127 | if (error.name === 'NotAllowedError') { 128 | console.log('Permissão para o microfone foi negada.'); 129 | } else if (error.name === 'NotFoundError') { 130 | console.log('Nenhum microfone disponível no dispositivo.'); 131 | } else { 132 | console.error('Erro ao solicitar permissão para o microfone:', error); 133 | } 134 | } 135 | } 136 | 137 | async function checkMicrophonePermission() { 138 | try { 139 | const permissionStatus = await navigator.permissions.query({ name: 'microphone' }); 140 | 141 | switch (permissionStatus.state) { 142 | case 'granted': 143 | console.log('Permissão concedida para o microfone.'); 144 | break; 145 | case 'denied': 146 | console.log('Permissão negada para o microfone.'); 147 | break; 148 | case 'prompt': 149 | await requestMicrophonePermission(); 150 | 151 | break; 152 | } 153 | 154 | return permissionStatus.state; 155 | } catch (error) { 156 | console.error('Erro ao verificar permissão:', error); 157 | return false; 158 | } 159 | } 160 | 161 | async function checkError() { 162 | let permission = await checkMicrophonePermission(); 163 | 164 | if(microphonesDevicesList.length === 0) { 165 | return { 166 | type: "no_microphone_available", 167 | message: "Não há microfone disponivel para uso" 168 | } 169 | } else if (permission !== "granted") { 170 | return { 171 | type: "no_microphone_permission", 172 | message: "Sem permissão para acessar o microfone" 173 | } 174 | } else if(audioContext && audioContext.state !== "running") { 175 | return { 176 | type: "audio_context", 177 | message: "Não foi possível obter acesso ao microfone" 178 | } 179 | } else if (navigator.userActivation.hasBeenActive && audioContext?.state !== "running") { 180 | return { 181 | type: "audio_context", 182 | message: "Você precisa interagir com a página para liberar a permissão do microfone" 183 | } 184 | } 185 | else { 186 | console.log("[MICROPHONE] - Permission success to access microphone device"); 187 | 188 | return false 189 | } 190 | } 191 | 192 | fetchMicrophones(); 193 | 194 | navigator.mediaDevices.addEventListener('devicechange', fetchMicrophones); 195 | 196 | export default { 197 | init, 198 | start, 199 | stop, 200 | requestMicrophonePermission, 201 | checkMicrophonePermission, 202 | fetchMicrophones, 203 | getMicrophones, 204 | getAudioContext, 205 | checkError 206 | }; -------------------------------------------------------------------------------- /src/models/Microphone/AudioWorkletMic.js: -------------------------------------------------------------------------------- 1 | class ResampleProcessor extends AudioWorkletProcessor { 2 | constructor(options) { 3 | super(options); 4 | this.init(); 5 | this.src = null; 6 | this.accumulatedPCM = []; // Buffer acumulado de PCM 7 | this.sampleRate = options.processorOptions.sampleRate; 8 | } 9 | 10 | async init() { 11 | const { create, ConverterType } = globalThis.LibSampleRate; 12 | 13 | let nChannels = 1; 14 | let inputSampleRate = this.sampleRate || 48000; 15 | let outputSampleRate = 16000; // or another target sample rate 16 | 17 | create(nChannels, inputSampleRate, outputSampleRate, { 18 | converterType: ConverterType.SRC_SINC_BEST_QUALITY, // or some other quality 19 | }).then((src) => { 20 | this.src = src; 21 | }); 22 | } 23 | 24 | process(inputs, outputs, parameters) { 25 | // copy ins to outs (gross) 26 | for (let inputNum = 0; inputNum < inputs.length; inputNum++) { 27 | let input = inputs[inputNum]; 28 | // copy channels 29 | for (let channelNum = 0; channelNum < input.length; channelNum++) { 30 | let channel = input[channelNum]; 31 | // copy samples 32 | for (let sampleNum = 0; sampleNum < channel.length; sampleNum++) { 33 | outputs[inputNum][channelNum][sampleNum] = channel[sampleNum]; 34 | } 35 | } 36 | } 37 | 38 | // do something w.r.t. resampling 39 | if (this.src != null) { 40 | const resampled = this.src.full(inputs[0][0]); 41 | // console.log( 42 | // `Resampled to ${inputs[0][0].length} samples to ${resampled.length} samples` 43 | // ); 44 | 45 | // Converte o buffer resampleado para PCM e acumula 46 | const pcmData = this.convertToPCM(resampled); 47 | this.accumulatedPCM.push(...pcmData); // Acumula os dados PCM 48 | 49 | // Verifica se acumulou pelo menos 320 amostras (640 bytes) 50 | while (this.accumulatedPCM.length >= 320) { 51 | // Envia os primeiros 320 amostras (640 bytes) 52 | const dataToSend = this.accumulatedPCM.splice(0, 320); // Remove os dados enviados 53 | 54 | this.port.postMessage(new Int16Array(dataToSend).buffer); // Envia como ArrayBuffer 55 | } 56 | } 57 | 58 | return true; 59 | } 60 | 61 | convertToPCM(floatBuffer) { 62 | const pcmBuffer = new Int16Array(floatBuffer.length); 63 | for (let i = 0; i < floatBuffer.length; i++) { 64 | // Converte de ponto flutuante (-1.0 a 1.0) para inteiro de 16 bits (-32768 a 32767) 65 | pcmBuffer[i] = Math.max(-32768, Math.min(32767, Math.floor(floatBuffer[i] * 32767))); 66 | } 67 | return pcmBuffer; // Retorna o array PCM 68 | } 69 | } 70 | 71 | 72 | registerProcessor('resample-processor', ResampleProcessor); 73 | -------------------------------------------------------------------------------- /src/utils/functions.js: -------------------------------------------------------------------------------- 1 | export const checkResponseResult = response => { 2 | if (typeof response !== 'object') { 3 | return false; 4 | } 5 | 6 | if (response?.type === 'success') { 7 | return true; 8 | } else { 9 | return false; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /src/websocket/index.js: -------------------------------------------------------------------------------- 1 | import { io } from 'socket.io-client'; 2 | 3 | import { baseURL } from '../config'; 4 | class Socket { 5 | constructor(device_token) { 6 | this.device_token = device_token; 7 | this.socket = null; 8 | this.socket_audio_transport; 9 | 10 | this.start(); 11 | } 12 | 13 | start() { 14 | this.socket = io(baseURL, { 15 | transports: ['websocket'], 16 | path: `/${this.device_token}/websocket`, 17 | }); 18 | 19 | 20 | this.socket.on('audio_transport:create', ({ room, ip, port }) => { 21 | console.info('[*] creating audio transport'); 22 | 23 | this.socket_audio_transport = io(`${ip}:${port}/call-${room}`, { 24 | transports: ['websocket'], 25 | path: `/${this.device_token}/websocket`, 26 | forceNew: true, 27 | }); 28 | }); 29 | 30 | this.socket.on('audio_transport:terminate', ({ room }) => { 31 | // console.info('[*] terminating audio transport'); 32 | }); 33 | } 34 | } 35 | 36 | export default Socket; -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | module.exports = { 4 | mode: 'production', 5 | entry: './index.js', 6 | output: { 7 | path: path.join(__dirname, 'lib'), 8 | filename: 'index.js', 9 | libraryTarget: 'umd', 10 | library: 'Wavoip' 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | loader: 'babel-loader', 16 | test: /\.js$/, 17 | exclude: /node_modules/, 18 | }, 19 | { 20 | test: /AudioWorklet\.js$/, 21 | use: [ 22 | { 23 | loader: 'worklet-loader', 24 | options: { name: 'AudioWorklet.js', inline: true } 25 | }, 26 | ], 27 | }, 28 | { 29 | test: /AudioWorkletMic\.js$/, 30 | use: [ 31 | { 32 | loader: 'worklet-loader', 33 | options: { name: 'AudioWorkletMic.js', inline: true } 34 | }, 35 | ], 36 | }, 37 | ], 38 | }, 39 | devServer: { 40 | contentBase: [path.join(__dirname, 'example'), path.join(__dirname, 'lib')], 41 | }, 42 | } --------------------------------------------------------------------------------