diff --git a/.eslintrc.js b/.eslintrc.cjs similarity index 100% rename from .eslintrc.js rename to .eslintrc.cjs diff --git a/.prettierrc.js b/.prettierrc.cjs similarity index 100% rename from .prettierrc.js rename to .prettierrc.cjs diff --git a/commitlint.config.js b/commitlint.config.cjs similarity index 100% rename from commitlint.config.js rename to commitlint.config.cjs diff --git a/dist_extensions/assets/index-BCTw1JsJ.js b/dist_extensions/assets/index-BCTw1JsJ.js new file mode 100644 index 000000000..b26007d77 --- /dev/null +++ b/dist_extensions/assets/index-BCTw1JsJ.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as vt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as bt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),ve=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!ve(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>ve(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},vn=Q("URLSearchParams"),[bn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function be(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(be(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};be(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(ve(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return be(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(ve(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:ve,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:bn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:vn,isTypedArray:Pn,isFileList:wn,forEach:be,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let v=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(v=l.toArray(h)))return g=Lt(g),v.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(v,B){(!(l.isUndefined(v)||v===null)&&o.call(e,v,l.isString(B)?B.trim():B,g,y))===!0&&O(v,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,vr=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function br(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!br(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&vr.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function v(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=v:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(v)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let v=g&&g[h];if(v)return v.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:v,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let b;try{if(K&&f&&m!=="get"&&m!=="head"&&(b=await O(S,v))!==0){let Z=new n(g,{method:"POST",body:v,duplex:"half"}),ue;if(l.isFormData(v)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(b,Le(ut(K)));v=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:v,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error)throw new Error(n.message||"Erro ao conectar à instância");if(n.instance&&n.instance.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:n.instance.instanceName,state:n.instance.state};let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const v=(await X.getConnectionState(g)).instance.state;return R.value.state=v,R.value.isConnected=v==="open",v==="open"&&(await e(g),r()),v}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(v){throw console.error("[useConnection] Error updating profile name:",v),v}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(v){throw console.error("[useConnection] Error updating profile status:",v),v}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),vt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{onClick:f,disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),vt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},vo={class:"text-2xl font-bold text-primary-500"},bo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",vo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",bo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{onClick:i[0]||(i[0]=u=>a.$emit("disconnect")),class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),window.setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||window.confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),window.setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{onClick:s,disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{onClick:a,disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);bt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,onClick:u,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-18532169"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s)),class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro"},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},vs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},bs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:v,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,b)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:b,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(b){const D=b instanceof Error?b.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",b)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await v(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error restarting:",C)}};bt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),b=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";b&&(S("info",`Parâmetro de instância detectado: ${b}`),/^[a-zA-Z0-9\-_]+$/.test(b)&&b.length>=3&&b.length<=50?(M.value=b,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(b)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,b)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[b[3]||(b[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",vs,[d("div",bs,[b[2]||(b[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:b[0]||(b[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...b[1]||(b[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/index-BLoJMiUW.css b/dist_extensions/assets/index-BLoJMiUW.css new file mode 100644 index 000000000..c7eb31256 --- /dev/null +++ b/dist_extensions/assets/index-BLoJMiUW.css @@ -0,0 +1,2 @@ +@keyframes fade-in-ad0ecda8{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in[data-v-ad0ecda8]{animation:fade-in-ad0ecda8 .3s ease-out}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.18 | MIT License | https://tailwindcss.com + */*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Open Sans,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.static{position:static}.absolute{position:absolute}.relative{position:relative}.right-4{right:1rem}.top-4{top:1rem}.z-10{z-index:10}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-4{height:1rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-full{height:100%}.max-h-full{max-height:100%}.min-h-screen{min-height:100vh}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500,.bg-primary-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-primary-50{--tw-gradient-from: #f0fdf4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-gray-100{--tw-gradient-to: #f3f4f6 var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.text-left{text-align:left}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Open Sans,system-ui,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-primary-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.opacity-25{opacity:.25}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-primary-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}::-webkit-scrollbar-thumb:hover{background:#6b7280b3}.dark ::-webkit-scrollbar-thumb{background:#4b556380}.dark ::-webkit-scrollbar-thumb:hover{background:#6b7280b3}*{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}*:focus{outline:none}::-moz-selection{background-color:#22c55e4d;color:inherit}::selection{background-color:#22c55e4d;color:inherit}:root{--primary-color: #22c55e;--primary-hover: #16a34a;--success-color: #10b981;--error-color: #ef4444;--warning-color: #f59e0b;--info-color: #3b82f6}.dark{color-scheme:dark}@keyframes fadeIn{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.fade-in{animation:fadeIn .3s ease-out}.text-gradient{background:linear-gradient(to right,#22c55e,#16a34a);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.loading{position:relative;pointer-events:none;opacity:.6}.loading:after{content:"";position:absolute;top:50%;left:50%;width:20px;height:20px;margin:-10px 0 0 -10px;border:2px solid #f3f3f3;border-top:2px solid var(--primary-color);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-primary-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-primary-200\/50:hover{--tw-shadow-color: rgb(187 247 208 / .5);--tw-shadow: var(--tw-shadow-colored)}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.active\:bg-blue-700:active{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.active\:bg-primary-700:active{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.active\:bg-red-700:active{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-red-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.dark\:border-yellow-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(133 77 14 / var(--tw-border-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-red-900\/20:is(.dark *){background-color:#7f1d1d33}.dark\:bg-yellow-900\/20:is(.dark *){background-color:#713f1233}.dark\:from-gray-900:is(.dark *){--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:to-gray-800:is(.dark *){--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.dark\:text-yellow-400:is(.dark *){--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:text-yellow-500:is(.dark *){--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-red-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))} diff --git a/dist_extensions/assets/index-BZK0AAHL.js b/dist_extensions/assets/index-BZK0AAHL.js new file mode 100644 index 000000000..0d62e2d14 --- /dev/null +++ b/dist_extensions/assets/index-BZK0AAHL.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as bt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as vt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),be=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!be(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>be(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},bn=Q("URLSearchParams"),[vn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ve(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(ve(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};ve(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(be(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return ve(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(be(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:be,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:vn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:bn,isTypedArray:Pn,isFileList:wn,forEach:ve,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let b=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(b=l.toArray(h)))return g=Lt(g),b.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(b,B){(!(l.isUndefined(b)||b===null)&&o.call(e,b,l.isString(B)?B.trim():B,g,y))===!0&&O(b,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,br=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function vr(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!vr(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&br.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function b(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=b:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(b)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let b=g&&g[h];if(b)return b.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:b,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let v;try{if(K&&f&&m!=="get"&&m!=="head"&&(v=await O(S,b))!==0){let Z=new n(g,{method:"POST",body:b,duplex:"half"}),ue;if(l.isFormData(b)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(v,Le(ut(K)));b=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:b,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error){const o=typeof n.message=="string"?n.message:"Erro ao conectar à instância";throw new Error(o)}if(n.instance&&typeof n.instance=="object"){const o=n.instance;if(o.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:String(o.instanceName||""),state:String(o.state)}}let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const b=(await X.getConnectionState(g)).instance.state;return R.value.state=b,R.value.isConnected=b==="open",b==="open"&&(await e(g),r()),b}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(b){throw console.error("[useConnection] Error updating profile name:",b),b}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(b){throw console.error("[useConnection] Error updating profile status:",b),b}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),bt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",onClick:f},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),bt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},bo={class:"text-2xl font-bold text-primary-500"},vo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",bo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",vo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2",onClick:i[0]||(i[0]=u=>a.$emit("disconnect"))},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:s},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:a},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);vt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300",onClick:u}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-fb6b6bcd"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro",onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s))},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},bs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},vs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:b,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,v)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:v,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(v){const D=v instanceof Error?v.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",v)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const v=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=v,S("error",v),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await b(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const v=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=v,S("error",v),console.error("[App] Error restarting:",C)}};vt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),v=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";v&&(S("info",`Parâmetro de instância detectado: ${v}`),/^[a-zA-Z0-9\-_]+$/.test(v)&&v.length>=3&&v.length<=50?(M.value=v,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(v)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,v)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[v[3]||(v[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",bs,[d("div",vs,[v[2]||(v[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:v[0]||(v[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...v[1]||(v[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/index-C05CmFIR.css b/dist_extensions/assets/index-C05CmFIR.css new file mode 100644 index 000000000..aea02ee67 --- /dev/null +++ b/dist_extensions/assets/index-C05CmFIR.css @@ -0,0 +1,2 @@ +@keyframes fade-in-18532169{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in[data-v-18532169]{animation:fade-in-18532169 .3s ease-out}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.18 | MIT License | https://tailwindcss.com + */*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Open Sans,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.static{position:static}.absolute{position:absolute}.relative{position:relative}.right-4{right:1rem}.top-4{top:1rem}.z-10{z-index:10}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-4{height:1rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-full{height:100%}.max-h-full{max-height:100%}.min-h-screen{min-height:100vh}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500,.bg-primary-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-primary-50{--tw-gradient-from: #f0fdf4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-gray-100{--tw-gradient-to: #f3f4f6 var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.text-left{text-align:left}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Open Sans,system-ui,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-primary-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.opacity-25{opacity:.25}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-primary-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}::-webkit-scrollbar-thumb:hover{background:#6b7280b3}.dark ::-webkit-scrollbar-thumb{background:#4b556380}.dark ::-webkit-scrollbar-thumb:hover{background:#6b7280b3}*{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}*:focus{outline:none}::-moz-selection{background-color:#22c55e4d;color:inherit}::selection{background-color:#22c55e4d;color:inherit}:root{--primary-color: #22c55e;--primary-hover: #16a34a;--success-color: #10b981;--error-color: #ef4444;--warning-color: #f59e0b;--info-color: #3b82f6}.dark{color-scheme:dark}@keyframes fadeIn{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.fade-in{animation:fadeIn .3s ease-out}.text-gradient{background:linear-gradient(to right,#22c55e,#16a34a);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.loading{position:relative;pointer-events:none;opacity:.6}.loading:after{content:"";position:absolute;top:50%;left:50%;width:20px;height:20px;margin:-10px 0 0 -10px;border:2px solid #f3f3f3;border-top:2px solid var(--primary-color);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-primary-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-primary-200\/50:hover{--tw-shadow-color: rgb(187 247 208 / .5);--tw-shadow: var(--tw-shadow-colored)}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.active\:bg-blue-700:active{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.active\:bg-primary-700:active{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.active\:bg-red-700:active{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-red-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.dark\:border-yellow-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(133 77 14 / var(--tw-border-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-red-900\/20:is(.dark *){background-color:#7f1d1d33}.dark\:bg-yellow-900\/20:is(.dark *){background-color:#713f1233}.dark\:from-gray-900:is(.dark *){--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:to-gray-800:is(.dark *){--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.dark\:text-yellow-400:is(.dark *){--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:text-yellow-500:is(.dark *){--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-red-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))} diff --git a/dist_extensions/assets/index-CoBSOXJ3.js b/dist_extensions/assets/index-CoBSOXJ3.js new file mode 100644 index 000000000..b5b98abc7 --- /dev/null +++ b/dist_extensions/assets/index-CoBSOXJ3.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as vt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as bt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),ve=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!ve(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>ve(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},vn=Q("URLSearchParams"),[bn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function be(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(be(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};be(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(ve(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return be(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(ve(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:ve,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:bn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:vn,isTypedArray:Pn,isFileList:wn,forEach:be,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let v=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(v=l.toArray(h)))return g=Lt(g),v.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(v,B){(!(l.isUndefined(v)||v===null)&&o.call(e,v,l.isString(B)?B.trim():B,g,y))===!0&&O(v,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,vr=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function br(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!br(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&vr.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function v(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=v:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(v)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let v=g&&g[h];if(v)return v.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:v,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let b;try{if(K&&f&&m!=="get"&&m!=="head"&&(b=await O(S,v))!==0){let Z=new n(g,{method:"POST",body:v,duplex:"half"}),ue;if(l.isFormData(v)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(b,Le(ut(K)));v=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:v,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error)throw new Error(n.message||"Erro ao conectar à instância");if(n.instance&&n.instance.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:n.instance.instanceName,state:n.instance.state};let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const v=(await X.getConnectionState(g)).instance.state;return R.value.state=v,R.value.isConnected=v==="open",v==="open"&&(await e(g),r()),v}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(v){throw console.error("[useConnection] Error updating profile name:",v),v}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(v){throw console.error("[useConnection] Error updating profile status:",v),v}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),vt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{onClick:f,disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),vt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},vo={class:"text-2xl font-bold text-primary-500"},bo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",vo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",bo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{onClick:i[0]||(i[0]=u=>a.$emit("disconnect")),class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:s},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:a},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);bt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,onClick:u,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-72063bc9"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s)),class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro"},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},vs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},bs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:v,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,b)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:b,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(b){const D=b instanceof Error?b.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",b)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await v(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error restarting:",C)}};bt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),b=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";b&&(S("info",`Parâmetro de instância detectado: ${b}`),/^[a-zA-Z0-9\-_]+$/.test(b)&&b.length>=3&&b.length<=50?(M.value=b,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(b)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,b)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[b[3]||(b[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",vs,[d("div",bs,[b[2]||(b[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:b[0]||(b[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...b[1]||(b[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/index-CqlQjN8d.css b/dist_extensions/assets/index-CqlQjN8d.css new file mode 100644 index 000000000..bd79d5f57 --- /dev/null +++ b/dist_extensions/assets/index-CqlQjN8d.css @@ -0,0 +1,2 @@ +@keyframes fade-in-72063bc9{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in[data-v-72063bc9]{animation:fade-in-72063bc9 .3s ease-out}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.18 | MIT License | https://tailwindcss.com + */*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Open Sans,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.static{position:static}.absolute{position:absolute}.relative{position:relative}.right-4{right:1rem}.top-4{top:1rem}.z-10{z-index:10}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-4{height:1rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-full{height:100%}.max-h-full{max-height:100%}.min-h-screen{min-height:100vh}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500,.bg-primary-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-primary-50{--tw-gradient-from: #f0fdf4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-gray-100{--tw-gradient-to: #f3f4f6 var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.text-left{text-align:left}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Open Sans,system-ui,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-primary-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.opacity-25{opacity:.25}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-primary-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}::-webkit-scrollbar-thumb:hover{background:#6b7280b3}.dark ::-webkit-scrollbar-thumb{background:#4b556380}.dark ::-webkit-scrollbar-thumb:hover{background:#6b7280b3}*{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}*:focus{outline:none}::-moz-selection{background-color:#22c55e4d;color:inherit}::selection{background-color:#22c55e4d;color:inherit}:root{--primary-color: #22c55e;--primary-hover: #16a34a;--success-color: #10b981;--error-color: #ef4444;--warning-color: #f59e0b;--info-color: #3b82f6}.dark{color-scheme:dark}@keyframes fadeIn{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.fade-in{animation:fadeIn .3s ease-out}.text-gradient{background:linear-gradient(to right,#22c55e,#16a34a);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.loading{position:relative;pointer-events:none;opacity:.6}.loading:after{content:"";position:absolute;top:50%;left:50%;width:20px;height:20px;margin:-10px 0 0 -10px;border:2px solid #f3f3f3;border-top:2px solid var(--primary-color);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-primary-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-primary-200\/50:hover{--tw-shadow-color: rgb(187 247 208 / .5);--tw-shadow: var(--tw-shadow-colored)}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.active\:bg-blue-700:active{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.active\:bg-primary-700:active{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.active\:bg-red-700:active{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-red-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.dark\:border-yellow-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(133 77 14 / var(--tw-border-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-red-900\/20:is(.dark *){background-color:#7f1d1d33}.dark\:bg-yellow-900\/20:is(.dark *){background-color:#713f1233}.dark\:from-gray-900:is(.dark *){--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:to-gray-800:is(.dark *){--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.dark\:text-yellow-400:is(.dark *){--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:text-yellow-500:is(.dark *){--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-red-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))} diff --git a/dist_extensions/assets/index-D1qdUZAv.js b/dist_extensions/assets/index-D1qdUZAv.js new file mode 100644 index 000000000..da7219466 --- /dev/null +++ b/dist_extensions/assets/index-D1qdUZAv.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as vt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as bt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),ve=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!ve(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>ve(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},vn=Q("URLSearchParams"),[bn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function be(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(be(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};be(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(ve(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return be(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(ve(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:ve,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:bn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:vn,isTypedArray:Pn,isFileList:wn,forEach:be,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let v=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(v=l.toArray(h)))return g=Lt(g),v.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(v,B){(!(l.isUndefined(v)||v===null)&&o.call(e,v,l.isString(B)?B.trim():B,g,y))===!0&&O(v,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,vr=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function br(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!br(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&vr.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function v(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=v:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(v)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let v=g&&g[h];if(v)return v.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:v,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let b;try{if(K&&f&&m!=="get"&&m!=="head"&&(b=await O(S,v))!==0){let Z=new n(g,{method:"POST",body:v,duplex:"half"}),ue;if(l.isFormData(v)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(b,Le(ut(K)));v=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:v,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error)throw new Error(n.message||"Erro ao conectar à instância");if(n.instance&&n.instance.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:n.instance.instanceName,state:n.instance.state};let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const v=(await X.getConnectionState(g)).instance.state;return R.value.state=v,R.value.isConnected=v==="open",v==="open"&&(await e(g),r()),v}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(v){throw console.error("[useConnection] Error updating profile name:",v),v}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(v){throw console.error("[useConnection] Error updating profile status:",v),v}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),vt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{onClick:f,disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),vt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},vo={class:"text-2xl font-bold text-primary-500"},bo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",vo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",bo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{onClick:i[0]||(i[0]=u=>a.$emit("disconnect")),class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{onClick:s,disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{onClick:a,disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);bt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,onClick:u,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-18532169"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s)),class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro"},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},vs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},bs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:v,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,b)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:b,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(b){const D=b instanceof Error?b.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",b)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await v(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error restarting:",C)}};bt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),b=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";b&&(S("info",`Parâmetro de instância detectado: ${b}`),/^[a-zA-Z0-9\-_]+$/.test(b)&&b.length>=3&&b.length<=50?(M.value=b,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(b)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,b)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[b[3]||(b[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",vs,[d("div",bs,[b[2]||(b[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:b[0]||(b[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...b[1]||(b[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/index-D7H2kqoD.js b/dist_extensions/assets/index-D7H2kqoD.js new file mode 100644 index 000000000..52a9d80e1 --- /dev/null +++ b/dist_extensions/assets/index-D7H2kqoD.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as vt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as bt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),ve=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!ve(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>ve(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},vn=Q("URLSearchParams"),[bn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function be(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(be(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};be(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(ve(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return be(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(ve(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:ve,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:bn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:vn,isTypedArray:Pn,isFileList:wn,forEach:be,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let v=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(v=l.toArray(h)))return g=Lt(g),v.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(v,B){(!(l.isUndefined(v)||v===null)&&o.call(e,v,l.isString(B)?B.trim():B,g,y))===!0&&O(v,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,vr=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function br(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!br(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&vr.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function v(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=v:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(v)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let v=g&&g[h];if(v)return v.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:v,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let b;try{if(K&&f&&m!=="get"&&m!=="head"&&(b=await O(S,v))!==0){let Z=new n(g,{method:"POST",body:v,duplex:"half"}),ue;if(l.isFormData(v)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(b,Le(ut(K)));v=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:v,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error)throw new Error(n.message||"Erro ao conectar à instância");if(n.instance&&n.instance.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:n.instance.instanceName,state:n.instance.state};let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const v=(await X.getConnectionState(g)).instance.state;return R.value.state=v,R.value.isConnected=v==="open",v==="open"&&(await e(g),r()),v}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(v){throw console.error("[useConnection] Error updating profile name:",v),v}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(v){throw console.error("[useConnection] Error updating profile status:",v),v}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),vt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{onClick:f,disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),vt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},vo={class:"text-2xl font-bold text-primary-500"},bo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",vo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",bo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{onClick:i[0]||(i[0]=u=>a.$emit("disconnect")),class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:s},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:a},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);bt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,onClick:u,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-18532169"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s)),class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro"},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},vs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},bs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:v,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,b)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:b,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(b){const D=b instanceof Error?b.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",b)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await v(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error restarting:",C)}};bt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),b=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";b&&(S("info",`Parâmetro de instância detectado: ${b}`),/^[a-zA-Z0-9\-_]+$/.test(b)&&b.length>=3&&b.length<=50?(M.value=b,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(b)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,b)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[b[3]||(b[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",vs,[d("div",bs,[b[2]||(b[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:b[0]||(b[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...b[1]||(b[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/index-Dim9Gszh.css b/dist_extensions/assets/index-Dim9Gszh.css new file mode 100644 index 000000000..e114eed26 --- /dev/null +++ b/dist_extensions/assets/index-Dim9Gszh.css @@ -0,0 +1,2 @@ +@keyframes fade-in-fb6b6bcd{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in[data-v-fb6b6bcd]{animation:fade-in-fb6b6bcd .3s ease-out}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.18 | MIT License | https://tailwindcss.com + */*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Open Sans,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.static{position:static}.absolute{position:absolute}.relative{position:relative}.right-4{right:1rem}.top-4{top:1rem}.z-10{z-index:10}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-4{height:1rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-full{height:100%}.max-h-full{max-height:100%}.min-h-screen{min-height:100vh}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500,.bg-primary-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-primary-50{--tw-gradient-from: #f0fdf4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-gray-100{--tw-gradient-to: #f3f4f6 var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.text-left{text-align:left}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Open Sans,system-ui,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-primary-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.opacity-25{opacity:.25}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-primary-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#9ca3af80;border-radius:4px}::-webkit-scrollbar-thumb:hover{background:#6b7280b3}.dark ::-webkit-scrollbar-thumb{background:#4b556380}.dark ::-webkit-scrollbar-thumb:hover{background:#6b7280b3}*{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}*:focus{outline:none}::-moz-selection{background-color:#22c55e4d;color:inherit}::selection{background-color:#22c55e4d;color:inherit}:root{--primary-color: #22c55e;--primary-hover: #16a34a;--success-color: #10b981;--error-color: #ef4444;--warning-color: #f59e0b;--info-color: #3b82f6}.dark{color-scheme:dark}@keyframes fadeIn{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.fade-in{animation:fadeIn .3s ease-out}.text-gradient{background:linear-gradient(to right,#22c55e,#16a34a);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.loading{position:relative;pointer-events:none;opacity:.6}.loading:after{content:"";position:absolute;top:50%;left:50%;width:20px;height:20px;margin:-10px 0 0 -10px;border:2px solid #f3f3f3;border-top:2px solid var(--primary-color);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-primary-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-primary-200\/50:hover{--tw-shadow-color: rgb(187 247 208 / .5);--tw-shadow: var(--tw-shadow-colored)}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-primary-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.active\:bg-blue-700:active{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.active\:bg-primary-700:active{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.active\:bg-red-700:active{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-red-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.dark\:border-yellow-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(133 77 14 / var(--tw-border-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-red-900\/20:is(.dark *){background-color:#7f1d1d33}.dark\:bg-yellow-900\/20:is(.dark *){background-color:#713f1233}.dark\:from-gray-900:is(.dark *){--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:to-gray-800:is(.dark *){--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.dark\:text-yellow-400:is(.dark *){--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:text-yellow-500:is(.dark *){--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-red-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))} diff --git a/dist_extensions/assets/index-_bkBiUBr.js b/dist_extensions/assets/index-_bkBiUBr.js new file mode 100644 index 000000000..5217d6f9a --- /dev/null +++ b/dist_extensions/assets/index-_bkBiUBr.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as vt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as bt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),ve=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!ve(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>ve(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},vn=Q("URLSearchParams"),[bn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function be(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(be(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};be(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(ve(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return be(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(ve(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:ve,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:bn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:vn,isTypedArray:Pn,isFileList:wn,forEach:be,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let v=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(v=l.toArray(h)))return g=Lt(g),v.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(v,B){(!(l.isUndefined(v)||v===null)&&o.call(e,v,l.isString(B)?B.trim():B,g,y))===!0&&O(v,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,vr=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function br(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!br(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&vr.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function v(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=v:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(v)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let v=g&&g[h];if(v)return v.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:v,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let b;try{if(K&&f&&m!=="get"&&m!=="head"&&(b=await O(S,v))!==0){let Z=new n(g,{method:"POST",body:v,duplex:"half"}),ue;if(l.isFormData(v)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(b,Le(ut(K)));v=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:v,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error){const o=typeof n.message=="string"?n.message:"Erro ao conectar à instância";throw new Error(o)}if(n.instance&&typeof n.instance=="object"){const o=n.instance;if(o.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:String(o.instanceName||""),state:String(o.state)}}let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const v=(await X.getConnectionState(g)).instance.state;return R.value.state=v,R.value.isConnected=v==="open",v==="open"&&(await e(g),r()),v}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(v){throw console.error("[useConnection] Error updating profile name:",v),v}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(v){throw console.error("[useConnection] Error updating profile status:",v),v}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),vt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",onClick:f},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),vt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},vo={class:"text-2xl font-bold text-primary-500"},bo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",vo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",bo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{onClick:i[0]||(i[0]=u=>a.$emit("disconnect")),class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:s},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:a},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);bt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,onClick:u,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-ad0ecda8"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro",onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s))},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},vs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},bs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:v,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,b)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:b,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(b){const D=b instanceof Error?b.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",b)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await v(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error restarting:",C)}};bt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),b=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";b&&(S("info",`Parâmetro de instância detectado: ${b}`),/^[a-zA-Z0-9\-_]+$/.test(b)&&b.length>=3&&b.length<=50?(M.value=b,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(b)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,b)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[b[3]||(b[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",vs,[d("div",bs,[b[2]||(b[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:b[0]||(b[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...b[1]||(b[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/index-eLYOUvGG.js b/dist_extensions/assets/index-eLYOUvGG.js new file mode 100644 index 000000000..1f0c85595 --- /dev/null +++ b/dist_extensions/assets/index-eLYOUvGG.js @@ -0,0 +1,6 @@ +var Jt=Object.defineProperty;var Xt=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qe=(t,e,n)=>Xt(t,typeof e!="symbol"?e+"":e,n);import{r as H,c as N,o as xt,d as ie,a as x,b as E,e as d,w as vt,v as Yt,f as Zt,u as k,t as I,g as U,h as en,i as Ie,j as Pe,k as bt,n as tn,F as nn,l as rn,m as on,p as Ee,q as sn,s as ee,x as Ct,y as rt,z as an}from"./vue-vendor-BwOErZoh.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ln="/qrcode/images/logo-se7e-light.png",cn="/qrcode/images/logo-se7e-dark.png";function Rt(t,e){return function(){return t.apply(e,arguments)}}const{toString:un}=Object.prototype,{getPrototypeOf:Je}=Object,{iterator:De,toStringTag:St}=Symbol,Ue=(t=>e=>{const n=un.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Q=t=>(t=t.toLowerCase(),e=>Ue(e)===t),Fe=t=>e=>typeof e===t,{isArray:he}=Array,pe=Fe("undefined");function xe(t){return t!==null&&!pe(t)&&t.constructor!==null&&!pe(t.constructor)&&$(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const At=Q("ArrayBuffer");function dn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&At(t.buffer),e}const fn=Fe("string"),$=Fe("function"),Tt=Fe("number"),ve=t=>t!==null&&typeof t=="object",pn=t=>t===!0||t===!1,Ne=t=>{if(Ue(t)!=="object")return!1;const e=Je(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(St in t)&&!(De in t)},hn=t=>{if(!ve(t)||xe(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},mn=Q("Date"),gn=Q("File"),yn=Q("Blob"),wn=Q("FileList"),En=t=>ve(t)&&$(t.pipe),xn=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||$(t.append)&&((e=Ue(t))==="formdata"||e==="object"&&$(t.toString)&&t.toString()==="[object FormData]"))},vn=Q("URLSearchParams"),[bn,Cn,Rn,Sn]=["ReadableStream","Request","Response","Headers"].map(Q),An=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function be(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,o;if(typeof t!="object"&&(t=[t]),he(t))for(r=0,o=t.length;r0;)if(o=n[r],e===o.toLowerCase())return o;return null}const oe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nt=t=>!pe(t)&&t!==oe;function Ke(){const{caseless:t,skipUndefined:e}=Nt(this)&&this||{},n={},r=(o,s)=>{const a=t&&kt(n,s)||s;Ne(n[a])&&Ne(o)?n[a]=Ke(n[a],o):Ne(o)?n[a]=Ke({},o):he(o)?n[a]=o.slice():(!e||!pe(o))&&(n[a]=o)};for(let o=0,s=arguments.length;o(be(e,(o,s)=>{n&&$(o)?t[s]=Rt(o,n):t[s]=o},{allOwnKeys:r}),t),kn=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Nn=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},_n=(t,e,n,r)=>{let o,s,a;const i={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)a=o[s],(!r||r(a,t,e))&&!i[a]&&(e[a]=t[a],i[a]=!0);t=n!==!1&&Je(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},On=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},In=t=>{if(!t)return null;if(he(t))return t;let e=t.length;if(!Tt(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Pn=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Je(Uint8Array)),Ln=(t,e)=>{const r=(t&&t[De]).call(t);let o;for(;(o=r.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Dn=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Un=Q("HTMLFormElement"),Fn=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ot=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Mn=Q("RegExp"),_t=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};be(n,(o,s)=>{let a;(a=e(o,s,t))!==!1&&(r[s]=a||o)}),Object.defineProperties(t,r)},Bn=t=>{_t(t,(e,n)=>{if($(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if($(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$n=(t,e)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return he(t)?r(t):r(String(t).split(e)),n},qn=()=>{},jn=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Hn(t){return!!(t&&$(t.append)&&t[St]==="FormData"&&t[De])}const zn=t=>{const e=new Array(10),n=(r,o)=>{if(ve(r)){if(e.indexOf(r)>=0)return;if(xe(r))return r;if(!("toJSON"in r)){e[o]=r;const s=he(r)?[]:{};return be(r,(a,i)=>{const u=n(a,o+1);!pe(u)&&(s[i]=u)}),e[o]=void 0,s}}return r};return n(t,0)},Kn=Q("AsyncFunction"),Qn=t=>t&&(ve(t)||$(t))&&$(t.then)&&$(t.catch),Ot=((t,e)=>t?setImmediate:e?((n,r)=>(oe.addEventListener("message",({source:o,data:s})=>{o===oe&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),oe.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$(oe.postMessage)),Vn=typeof queueMicrotask<"u"?queueMicrotask.bind(oe):typeof process<"u"&&process.nextTick||Ot,Gn=t=>t!=null&&$(t[De]),l={isArray:he,isArrayBuffer:At,isBuffer:xe,isFormData:xn,isArrayBufferView:dn,isString:fn,isNumber:Tt,isBoolean:pn,isObject:ve,isPlainObject:Ne,isEmptyObject:hn,isReadableStream:bn,isRequest:Cn,isResponse:Rn,isHeaders:Sn,isUndefined:pe,isDate:mn,isFile:gn,isBlob:yn,isRegExp:Mn,isFunction:$,isStream:En,isURLSearchParams:vn,isTypedArray:Pn,isFileList:wn,forEach:be,merge:Ke,extend:Tn,trim:An,stripBOM:kn,inherits:Nn,toFlatObject:_n,kindOf:Ue,kindOfTest:Q,endsWith:On,toArray:In,forEachEntry:Ln,matchAll:Dn,isHTMLForm:Un,hasOwnProperty:ot,hasOwnProp:ot,reduceDescriptors:_t,freezeMethods:Bn,toObjectSet:$n,toCamelCase:Fn,noop:qn,toFiniteNumber:jn,findKey:kt,global:oe,isContextDefined:Nt,isSpecCompliantForm:Hn,toJSONObject:zn,isAsyncFn:Kn,isThenable:Qn,setImmediate:Ot,asap:Vn,isIterable:Gn};function w(t,e,n,r,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),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}l.inherits(w,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});const It=w.prototype,Pt={};["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=>{Pt[t]={value:t}});Object.defineProperties(w,Pt);Object.defineProperty(It,"isAxiosError",{value:!0});w.from=(t,e,n,r,o,s)=>{const a=Object.create(It);l.toFlatObject(t,a,function(c){return c!==Error.prototype},f=>f!=="isAxiosError");const i=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return w.call(a,i,u,n,r,o),t&&a.cause==null&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};const Wn=null;function Qe(t){return l.isPlainObject(t)||l.isArray(t)}function Lt(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function st(t,e,n){return t?t.concat(e).map(function(o,s){return o=Lt(o),!n&&s?"["+o+"]":o}).join(n?".":""):e}function Jn(t){return l.isArray(t)&&!t.some(Qe)}const Xn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Me(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,m){return!l.isUndefined(m[g])});const r=n.metaTokens,o=n.visitor||c,s=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(o))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(l.isDate(h))return h.toISOString();if(l.isBoolean(h))return h.toString();if(!u&&l.isBlob(h))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(h)||l.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,m){let v=h;if(h&&!m&&typeof h=="object"){if(l.endsWith(g,"{}"))g=r?g:g.slice(0,-2),h=JSON.stringify(h);else if(l.isArray(h)&&Jn(h)||(l.isFileList(h)||l.endsWith(g,"[]"))&&(v=l.toArray(h)))return g=Lt(g),v.forEach(function(L,T){!(l.isUndefined(L)||L===null)&&e.append(a===!0?st([g],T,s):a===null?g:g+"[]",f(L))}),!1}return Qe(h)?!0:(e.append(st(m,g,s),f(h)),!1)}const p=[],y=Object.assign(Xn,{defaultVisitor:c,convertValue:f,isVisitable:Qe});function O(h,g){if(!l.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(h),l.forEach(h,function(v,B){(!(l.isUndefined(v)||v===null)&&o.call(e,v,l.isString(B)?B.trim():B,g,y))===!0&&O(v,g?g.concat(B):[B])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return O(t),e}function at(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Xe(t,e){this._pairs=[],t&&Me(t,this,e)}const Dt=Xe.prototype;Dt.append=function(e,n){this._pairs.push([e,n])};Dt.toString=function(e){const n=e?function(r){return e.call(this,r,at)}:at;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Yn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ut(t,e,n){if(!e)return t;const r=n&&n.encode||Yn;l.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(e,n):s=l.isURLSearchParams(e)?e.toString():new Xe(e,n).toString(r),s){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class it{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ft={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn=typeof URLSearchParams<"u"?URLSearchParams:Xe,er=typeof FormData<"u"?FormData:null,tr=typeof Blob<"u"?Blob:null,nr={isBrowser:!0,classes:{URLSearchParams:Zn,FormData:er,Blob:tr},protocols:["http","https","file","blob","url","data"]},Ye=typeof window<"u"&&typeof document<"u",Ve=typeof navigator=="object"&&navigator||void 0,rr=Ye&&(!Ve||["ReactNative","NativeScript","NS"].indexOf(Ve.product)<0),or=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sr=Ye&&window.location.href||"http://localhost",ar=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ye,hasStandardBrowserEnv:rr,hasStandardBrowserWebWorkerEnv:or,navigator:Ve,origin:sr},Symbol.toStringTag,{value:"Module"})),F={...ar,...nr};function ir(t,e){return Me(t,new F.classes.URLSearchParams,{visitor:function(n,r,o,s){return F.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function lr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function cr(t){const e={},n=Object.keys(t);let r;const o=n.length;let s;for(r=0;r=n.length;return a=!a&&l.isArray(o)?o.length:a,u?(l.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!i):((!o[a]||!l.isObject(o[a]))&&(o[a]=[]),e(n,r,o[a],s)&&l.isArray(o[a])&&(o[a]=cr(o[a])),!i)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,o)=>{e(lr(r),o,n,0)}),n}return null}function ur(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Ce={transitional:Ft,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=l.isObject(e);if(s&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return o?JSON.stringify(Mt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ir(e,this.formSerializer).toString();if((i=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),ur(e)):e}],transformResponse:[function(e){const n=this.transitional||Ce.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||o)){const a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?w.from(i,w.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:F.classes.FormData,Blob:F.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{Ce.headers[t]={}});const dr=l.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"]),fr=t=>{const e={};let n,r,o;return t&&t.split(` +`).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||e[n]&&dr[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},lt=Symbol("internals");function we(t){return t&&String(t).trim().toLowerCase()}function _e(t){return t===!1||t==null?t:l.isArray(t)?t.map(_e):String(t)}function pr(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const hr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function je(t,e,n,r,o){if(l.isFunction(r))return r.call(this,e,n);if(o&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function mr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function gr(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(o,s,a){return this[r].call(this,e,o,s,a)},configurable:!0})})}let q=class{constructor(e){e&&this.set(e)}set(e,n,r){const o=this;function s(i,u,f){const c=we(u);if(!c)throw new Error("header name must be a non-empty string");const p=l.findKey(o,c);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=_e(i))}const a=(i,u)=>l.forEach(i,(f,c)=>s(f,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)a(e,n);else if(l.isString(e)&&(e=e.trim())&&!hr(e))a(fr(e),n);else if(l.isObject(e)&&l.isIterable(e)){let i={},u,f;for(const c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");i[f=c[0]]=(u=i[f])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}a(i,n)}else e!=null&&s(n,e,r);return this}get(e,n){if(e=we(e),e){const r=l.findKey(this,e);if(r){const o=this[r];if(!n)return o;if(n===!0)return pr(o);if(l.isFunction(n))return n.call(this,o,r);if(l.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=we(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||je(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let o=!1;function s(a){if(a=we(a),a){const i=l.findKey(r,a);i&&(!n||je(r,r[i],i,n))&&(delete r[i],o=!0)}}return l.isArray(e)?e.forEach(s):s(e),o}clear(e){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!e||je(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const n=this,r={};return l.forEach(this,(o,s)=>{const a=l.findKey(r,s);if(a){n[a]=_e(o),delete n[s];return}const i=e?mr(s):String(s).trim();i!==s&&delete n[s],n[i]=_e(o),r[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(o=>r.set(o)),r}static accessor(e){const r=(this[lt]=this[lt]={accessors:{}}).accessors,o=this.prototype;function s(a){const i=we(a);r[i]||(gr(o,a),r[i]=!0)}return l.isArray(e)?e.forEach(s):s(e),this}};q.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(q.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(q);function He(t,e){const n=this||Ce,r=e||n,o=q.from(r.headers);let s=r.data;return l.forEach(t,function(i){s=i.call(n,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Bt(t){return!!(t&&t.__CANCEL__)}function me(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(me,w,{__CANCEL__:!0});function $t(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function yr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function wr(t,e){t=t||10;const n=new Array(t),r=new Array(t);let o=0,s=0,a;return e=e!==void 0?e:1e3,function(u){const f=Date.now(),c=r[s];a||(a=f),n[o]=u,r[o]=f;let p=s,y=0;for(;p!==o;)y+=n[p++],p=p%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),f-a{n=c,o=null,s&&(clearTimeout(s),s=null),t(...f)};return[(...f)=>{const c=Date.now(),p=c-n;p>=r?a(f,c):(o=f,s||(s=setTimeout(()=>{s=null,a(o)},r-p)))},()=>o&&a(o)]}const Le=(t,e,n=3)=>{let r=0;const o=wr(50,250);return Er(s=>{const a=s.loaded,i=s.lengthComputable?s.total:void 0,u=a-r,f=o(u),c=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:u,rate:f||void 0,estimated:f&&i&&c?(i-a)/f:void 0,event:s,lengthComputable:i!=null,[e?"download":"upload"]:!0};t(p)},n)},ct=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},ut=t=>(...e)=>l.asap(()=>t(...e)),xr=F.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,F.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,vr=F.hasStandardBrowserEnv?{write(t,e,n,r,o,s){const a=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),l.isString(r)&&a.push("path="+r),l.isString(o)&&a.push("domain="+o),s===!0&&a.push("secure"),document.cookie=a.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function br(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Cr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function qt(t,e,n){let r=!br(e);return t&&(r||n==!1)?Cr(t,e):e}const dt=t=>t instanceof q?{...t}:t;function ae(t,e){e=e||{};const n={};function r(f,c,p,y){return l.isPlainObject(f)&&l.isPlainObject(c)?l.merge.call({caseless:y},f,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function o(f,c,p,y){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f,p,y)}else return r(f,c,p,y)}function s(f,c){if(!l.isUndefined(c))return r(void 0,c)}function a(f,c){if(l.isUndefined(c)){if(!l.isUndefined(f))return r(void 0,f)}else return r(void 0,c)}function i(f,c,p){if(p in e)return r(f,c);if(p in t)return r(void 0,f)}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(f,c,p)=>o(dt(f),dt(c),p,!0)};return l.forEach(Object.keys({...t,...e}),function(c){const p=u[c]||o,y=p(t[c],e[c],c);l.isUndefined(y)&&p!==i||(n[c]=y)}),n}const jt=t=>{const e=ae({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:i}=e;if(e.headers=a=q.from(a),e.url=Ut(qt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),l.isFormData(n)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(l.isFunction(n.getHeaders)){const u=n.getHeaders(),f=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{f.includes(c.toLowerCase())&&a.set(c,p)})}}if(F.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&xr(e.url))){const u=o&&s&&vr.read(s);u&&a.set(o,u)}return e},Rr=typeof XMLHttpRequest<"u",Sr=Rr&&function(t){return new Promise(function(n,r){const o=jt(t);let s=o.data;const a=q.from(o.headers).normalize();let{responseType:i,onUploadProgress:u,onDownloadProgress:f}=o,c,p,y,O,h;function g(){O&&O(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function v(){if(!m)return;const L=q.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!i||i==="text"||i==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:L,config:t,request:m};$t(function(M){n(M),g()},function(M){r(M),g()},_),m=null}"onloadend"in m?m.onloadend=v:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(v)},m.onabort=function(){m&&(r(new w("Request aborted",w.ECONNABORTED,t,m)),m=null)},m.onerror=function(T){const _=T&&T.message?T.message:"Network Error",K=new w(_,w.ERR_NETWORK,t,m);K.event=T||null,r(K),m=null},m.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||Ft;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new w(T,_.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,m)),m=null},s===void 0&&a.setContentType(null),"setRequestHeader"in m&&l.forEach(a.toJSON(),function(T,_){m.setRequestHeader(_,T)}),l.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),i&&i!=="json"&&(m.responseType=o.responseType),f&&([y,h]=Le(f,!0),m.addEventListener("progress",y)),u&&m.upload&&([p,O]=Le(u),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",O)),(o.cancelToken||o.signal)&&(c=L=>{m&&(r(!L||L.type?new me(null,t,m):L),m.abort(),m=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const B=yr(o.url);if(B&&F.protocols.indexOf(B)===-1){r(new w("Unsupported protocol "+B+":",w.ERR_BAD_REQUEST,t));return}m.send(s||null)})},Ar=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,o;const s=function(f){if(!o){o=!0,i();const c=f instanceof Error?f:this.reason;r.abort(c instanceof w?c:new me(c instanceof Error?c.message:c))}};let a=e&&setTimeout(()=>{a=null,s(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const i=()=>{t&&(a&&clearTimeout(a),a=null,t.forEach(f=>{f.unsubscribe?f.unsubscribe(s):f.removeEventListener("abort",s)}),t=null)};t.forEach(f=>f.addEventListener("abort",s));const{signal:u}=r;return u.unsubscribe=()=>l.asap(i),u}},Tr=function*(t,e){let n=t.byteLength;if(n{const o=kr(t,e);let s=0,a,i=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:f,value:c}=await o.next();if(f){i(),u.close();return}let p=c.byteLength;if(n){let y=s+=p;n(y)}u.enqueue(new Uint8Array(c))}catch(f){throw i(f),f}},cancel(u){return i(u),o.return()}},{highWaterMark:2})},pt=64*1024,{isFunction:Se}=l,_r=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:ht,TextEncoder:mt}=l.global,gt=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Or=t=>{t=l.merge.call({skipUndefined:!0},_r,t);const{fetch:e,Request:n,Response:r}=t,o=e?Se(e):typeof fetch=="function",s=Se(n),a=Se(r);if(!o)return!1;const i=o&&Se(ht),u=o&&(typeof mt=="function"?(h=>g=>h.encode(g))(new mt):async h=>new Uint8Array(await new n(h).arrayBuffer())),f=s&&i&>(()=>{let h=!1;const g=new n(F.origin,{body:new ht,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=a&&i&>(()=>l.isReadableStream(new r("").body)),p={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(g,m)=>{let v=g&&g[h];if(v)return v.call(g);throw new w(`Response type '${h}' is not supported`,w.ERR_NOT_SUPPORT,m)})});const y=async h=>{if(h==null)return 0;if(l.isBlob(h))return h.size;if(l.isSpecCompliantForm(h))return(await new n(F.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(l.isArrayBufferView(h)||l.isArrayBuffer(h))return h.byteLength;if(l.isURLSearchParams(h)&&(h=h+""),l.isString(h))return(await u(h)).byteLength},O=async(h,g)=>{const m=l.toFiniteNumber(h.getContentLength());return m??y(g)};return async h=>{let{url:g,method:m,data:v,signal:B,cancelToken:L,timeout:T,onDownloadProgress:_,onUploadProgress:K,responseType:M,headers:S,withCredentials:le="same-origin",fetchOptions:ge}=jt(h),ye=e||fetch;M=M?(M+"").toLowerCase():"text";let ce=Ar([B,L&&L.toAbortSignal()],T),ne=null;const C=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let b;try{if(K&&f&&m!=="get"&&m!=="head"&&(b=await O(S,v))!==0){let Z=new n(g,{method:"POST",body:v,duplex:"half"}),ue;if(l.isFormData(v)&&(ue=Z.headers.get("content-type"))&&S.setContentType(ue),Z.body){const[$e,Re]=ct(b,Le(ut(K)));v=ft(Z.body,pt,$e,Re)}}l.isString(le)||(le=le?"include":"omit");const D=s&&"credentials"in n.prototype,et={...ge,signal:ce,method:m.toUpperCase(),headers:S.normalize().toJSON(),body:v,duplex:"half",credentials:D?le:void 0};ne=s&&new n(g,et);let Y=await(s?ye(ne,ge):ye(g,et));const tt=c&&(M==="stream"||M==="response");if(c&&(_||tt&&C)){const Z={};["status","statusText","headers"].forEach(nt=>{Z[nt]=Y[nt]});const ue=l.toFiniteNumber(Y.headers.get("content-length")),[$e,Re]=_&&ct(ue,Le(ut(_),!0))||[];Y=new r(ft(Y.body,pt,$e,()=>{Re&&Re(),C&&C()}),Z)}M=M||"text";let Wt=await p[l.findKey(p,M)||"text"](Y,h);return!tt&&C&&C(),await new Promise((Z,ue)=>{$t(Z,ue,{data:Wt,headers:q.from(Y.headers),status:Y.status,statusText:Y.statusText,config:h,request:ne})})}catch(D){throw C&&C(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,h,ne),{cause:D.cause||D}):w.from(D,D&&D.code,h,ne)}}},Ir=new Map,Ht=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:o}=e,s=[r,o,n];let a=s.length,i=a,u,f,c=Ir;for(;i--;)u=s[i],f=c.get(u),f===void 0&&c.set(u,f=i?new Map:Or(e)),c=f;return f};Ht();const Ge={http:Wn,xhr:Sr,fetch:{get:Ht}};l.forEach(Ge,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const yt=t=>`- ${t}`,Pr=t=>l.isFunction(t)||t===null||t===!1,zt={getAdapter:(t,e)=>{t=l.isArray(t)?t:[t];const{length:n}=t;let r,o;const s={};for(let a=0;a`adapter ${u} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=n?a.length>1?`since : +`+a.map(yt).join(` +`):" "+yt(a[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return o},adapters:Ge};function ze(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new me(null,t)}function wt(t){return ze(t),t.headers=q.from(t.headers),t.data=He.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),zt.getAdapter(t.adapter||Ce.adapter,t)(t).then(function(r){return ze(t),r.data=He.call(t,t.transformResponse,r),r.headers=q.from(r.headers),r},function(r){return Bt(r)||(ze(t),r&&r.response&&(r.response.data=He.call(t,t.transformResponse,r.response),r.response.headers=q.from(r.response.headers))),Promise.reject(r)})}const Kt="1.12.2",Be={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Be[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Et={};Be.transitional=function(e,n,r){function o(s,a){return"[Axios v"+Kt+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,i)=>{if(e===!1)throw new w(o(a," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!Et[a]&&(Et[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(s,a,i):!0}};Be.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Lr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let o=r.length;for(;o-- >0;){const s=r[o],a=e[s];if(a){const i=t[s],u=i===void 0||a(i,s,t);if(u!==!0)throw new w("option "+s+" must be "+u,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+s,w.ERR_BAD_OPTION)}}const Oe={assertOptions:Lr,validators:Be},V=Oe.validators;let se=class{constructor(e){this.defaults=e||{},this.interceptors={request:new it,response:new it}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=ae(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Oe.assertOptions(r,{silentJSONParsing:V.transitional(V.boolean),forcedJSONParsing:V.transitional(V.boolean),clarifyTimeoutError:V.transitional(V.boolean)},!1),o!=null&&(l.isFunction(o)?n.paramsSerializer={serialize:o}:Oe.assertOptions(o,{encode:V.function,serialize:V.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Oe.assertOptions(n,{baseUrl:V.spelling("baseURL"),withXsrfToken:V.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&l.merge(s.common,s[n.method]);s&&l.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=q.concat(a,s);const i=[];let u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,i.unshift(g.fulfilled,g.rejected))});const f=[];this.interceptors.response.forEach(function(g){f.push(g.fulfilled,g.rejected)});let c,p=0,y;if(!u){const h=[wt.bind(this),void 0];for(h.unshift(...i),h.push(...f),y=h.length,c=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(i=>{r.subscribe(i),s=i}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},e(function(s,a,i){r.reason||(r.reason=new me(s,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Qt(function(o){e=o}),cancel:e}}};function Ur(t){return function(n){return t.apply(null,n)}}function Fr(t){return l.isObject(t)&&t.isAxiosError===!0}const We={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(We).forEach(([t,e])=>{We[e]=t});function Vt(t){const e=new se(t),n=Rt(se.prototype.request,e);return l.extend(n,se.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(o){return Vt(ae(t,o))},n}const P=Vt(Ce);P.Axios=se;P.CanceledError=me;P.CancelToken=Dr;P.isCancel=Bt;P.VERSION=Kt;P.toFormData=Me;P.AxiosError=w;P.Cancel=P.CanceledError;P.all=function(e){return Promise.all(e)};P.spread=Ur;P.isAxiosError=Fr;P.mergeConfig=ae;P.AxiosHeaders=q;P.formToJSON=t=>Mt(l.isHTMLForm(t)?new FormData(t):t);P.getAdapter=zt.getAdapter;P.HttpStatusCode=We;P.default=P;const{Axios:_s,AxiosError:Os,CanceledError:Is,isCancel:Ps,CancelToken:Ls,VERSION:Ds,all:Us,Cancel:Fs,isAxiosError:Ms,spread:Bs,toFormData:$s,AxiosHeaders:qs,HttpStatusCode:js,formToJSON:Hs,getAdapter:zs,mergeConfig:Ks}=P,G={API_KEY_CHECK:"/qrcode/api-key",EXCHANGE_TOKEN:"/qrcode/exchange-token",CONNECT:t=>`/instance/connect/${t}`,CONNECTION_STATE:t=>`/instance/connectionState/${t}`,LOGOUT:t=>`/instance/logout/${t}`,RESTART:t=>`/instance/restart/${t}`,FETCH_INSTANCES:"/instance/fetchInstances",UPDATE_PROFILE_NAME:"/instance/updateProfileName",UPDATE_PROFILE_STATUS:"/instance/updateProfileStatus",UPDATE_PROFILE_PICTURE:"/instance/updateProfilePicture",UPDATE_PROFILE_STATUS_ENDPOINT:"/instance/updateProfileStatus"},Gt={QR_REFRESH_INTERVAL:3e4,CONNECTION_CHECK_INTERVAL:3e3},re={INSTANCE_NAME:{PATTERN:/^[a-zA-Z0-9\-_]+$/,MIN_LENGTH:3,MAX_LENGTH:50,ERROR_MESSAGE:"Apenas letras, números, hífens e underscores são permitidos"}},W={SUCCESS:{QR_GENERATED:"QR Code gerado com sucesso!",CONNECTED:"WhatsApp conectado com sucesso!",PROFILE_UPDATED:"Perfil atualizado com sucesso!",LOGOUT_SUCCESS:"Desconectado com sucesso!"},ERROR:{GENERIC:"Ocorreu um erro. Tente novamente.",API_KEY_NOT_CONFIGURED:"API Key não configurada. Entre em contato com o administrador.",INVALID_INSTANCE_NAME:"Nome da instância inválido.",INSTANCE_NOT_FOUND:"Instância não encontrada.",CONNECTION_FAILED:"Falha na conexão. Tente novamente.",RATE_LIMIT:"Muitas tentativas. Aguarde alguns segundos.",NETWORK_ERROR:"Erro de conexão com o servidor."},INFO:{LOADING:"Carregando...",GENERATING_QR:"Gerando QR Code...",CHECKING_CONNECTION:"Verificando conexão...",WAITING_SCAN:"Aguardando escaneamento..."},TUTORIAL:{TITLE:"Como Conectar seu WhatsApp",STEPS:['Clique no botão "Gerar QR Code" para gerar o QR Code.',"Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.",'Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.','Aguarde alguns segundos até o status mudar para "Conectado".']}},de={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},Ae={LIGHT:"light",DARK:"dark"},J={THEME:"qrcode-theme",API_KEY:"qrcode-api-key",SESSION_TOKEN:"qrcode-session-token",INSTANCE_NAME:"qrcode-last-instance"};class Mr{constructor(){qe(this,"axiosInstance");qe(this,"apiKey",null);this.axiosInstance=P.create({baseURL:"/",timeout:3e4,headers:{"Content-Type":"application/json"}}),this.setupInterceptors()}setupInterceptors(){this.axiosInstance.interceptors.request.use(e=>(this.apiKey&&e.headers&&(e.headers.apikey=this.apiKey),e),e=>Promise.reject(this.handleError(e))),this.axiosInstance.interceptors.response.use(e=>e,e=>Promise.reject(this.handleError(e)))}handleError(e){const n={message:"Erro desconhecido",status:0};return e.response?(n.status=e.response.status,n.message=this.getErrorMessage(e.response.status),n.details=e.response.data):e.request?(n.message="Erro de conexão com o servidor",n.code="NETWORK_ERROR"):(n.message=e.message||"Erro ao processar requisição",n.code="REQUEST_ERROR"),console.error("[API Error]",n),n}getErrorMessage(e){switch(e){case de.BAD_REQUEST:return"Requisição inválida";case de.UNAUTHORIZED:return"Não autorizado. Verifique a API key";case de.FORBIDDEN:return"Acesso negado";case de.NOT_FOUND:return"Recurso não encontrado";case de.TOO_MANY_REQUESTS:return"Muitas requisições. Aguarde alguns segundos";case de.INTERNAL_SERVER_ERROR:return"Erro interno do servidor";default:return`Erro ${e}`}}setApiKey(e){this.apiKey=e}clearApiKey(){this.apiKey=null}hasApiKey(){return this.apiKey!==null}async get(e,n){return(await this.axiosInstance.get(e,n)).data}async post(e,n,r){return(await this.axiosInstance.post(e,n,r)).data}async put(e,n,r){return(await this.axiosInstance.put(e,n,r)).data}async delete(e,n){return(await this.axiosInstance.delete(e,n)).data}async getPublic(e,n){const r=this.apiKey;this.apiKey=null;try{return await this.get(e,n)}finally{this.apiKey=r}}}const j=new Mr;class Br{async checkApiKey(){try{const e=await j.getPublic(G.API_KEY_CHECK);if(!e||typeof e!="object")throw new Error("Resposta inválida do servidor");return e}catch(e){throw console.error("[QRCodeService] Error checking API key:",e),e}}async exchangeToken(e){try{const n=await j.post(G.EXCHANGE_TOKEN,{sessionToken:e});if(!n||!("apiKey"in n))throw new Error("Token inválido ou expirado");return String(n.apiKey)}catch(n){throw console.error("[QRCodeService] Error exchanging token:",n),n}}async connect(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECT(e));if(console.log("[QRCodeService] Response from API:",JSON.stringify(n,null,2)),n.error){const o=typeof n.message=="string"?n.message:"Erro ao conectar à instância";throw new Error(o)}if(n.instance&&typeof n.instance=="object"){const o=n.instance;if(o.state==="open")return{base64:"",code:"",isConnected:!0,instanceName:String(o.instanceName||""),state:String(o.state)}}let r;if(n.base64)console.log("[QRCodeService] Format 1/3: Direct QR code"),r=n;else if(n.qrcode||n.qrCode)console.log("[QRCodeService] Format 2: Nested QR code"),r=n.qrcode||n.qrCode;else throw console.error("[QRCodeService] Unknown response format:",n),new Error("Não foi possível gerar QR Code. A instância pode não existir ou já estar conectada.");if(!r.base64)throw console.error("[QRCodeService] QR code data missing base64:",r),new Error("QR Code não contém imagem base64");return console.log("[QRCodeService] QR code successfully parsed"),r}catch(n){throw console.error("[QRCodeService] Error connecting:",n),n}}async getConnectionState(e){try{this.validateInstanceName(e);const n=await j.get(G.CONNECTION_STATE(e));if(!n||!("instance"in n))throw new Error("Erro ao verificar estado da conexão");return n}catch(n){throw console.error("[QRCodeService] Error getting connection state:",n),n}}async logout(e){try{this.validateInstanceName(e),await j.delete(G.LOGOUT(e))}catch(n){throw console.error("[QRCodeService] Error logging out:",n),n}}async restart(e){try{this.validateInstanceName(e),await j.post(G.RESTART(e),{})}catch(n){throw console.error("[QRCodeService] Error restarting:",n),n}}async fetchInstanceInfo(e){try{this.validateInstanceName(e);const n=await j.get(G.FETCH_INSTANCES);return Array.isArray(n)&&n.find(o=>o.instanceName===e)||null}catch(n){return console.error("[QRCodeService] Error fetching instance info:",n),null}}async updateProfileName(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_NAME,e)}catch(n){throw console.error("[QRCodeService] Error updating profile name:",n),n}}async updateProfileStatus(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_STATUS,e)}catch(n){throw console.error("[QRCodeService] Error updating profile status:",n),n}}async updateProfilePicture(e){try{this.validateInstanceName(e.instanceName),await j.post(G.UPDATE_PROFILE_PICTURE,e)}catch(n){throw console.error("[QRCodeService] Error updating profile picture:",n),n}}validateInstanceName(e){if(!e||typeof e!="string")throw new Error("Nome da instância é obrigatório");if(e.length<3||e.length>50)throw new Error("Nome da instância deve ter entre 3 e 50 caracteres");if(!/^[a-zA-Z0-9\-_]+$/.test(e))throw new Error("Nome da instância contém caracteres inválidos")}}const X=new Br,z=H({isAuthenticated:!1,sessionToken:null,apiKey:null});function $r(){const t=async()=>{try{const i=await X.checkApiKey();if(i.configured&&i.sessionToken)return z.value.sessionToken=i.sessionToken,sessionStorage.setItem(J.SESSION_TOKEN,i.sessionToken),!0;throw new Error(W.ERROR.API_KEY_NOT_CONFIGURED)}catch(i){throw console.error("[useAuth] Error checking API key:",i),i}},e=async()=>{try{const i=z.value.sessionToken||sessionStorage.getItem(J.SESSION_TOKEN);if(!i)throw new Error("Session token não encontrado");const u=await X.exchangeToken(i);z.value.apiKey=u,z.value.isAuthenticated=!0,j.setApiKey(u),localStorage.setItem(J.API_KEY,u),z.value.sessionToken=null,sessionStorage.removeItem(J.SESSION_TOKEN)}catch(i){throw console.error("[useAuth] Error exchanging token:",i),i}},n=()=>{const i=localStorage.getItem(J.API_KEY);return i?(z.value.apiKey=i,z.value.isAuthenticated=!0,j.setApiKey(i),!0):!1},r=()=>{z.value.isAuthenticated=!1,z.value.sessionToken=null,z.value.apiKey=null,j.clearApiKey(),localStorage.removeItem(J.API_KEY),sessionStorage.removeItem(J.SESSION_TOKEN)},o=async()=>{n()||(await t(),await e())},s=N(()=>z.value.isAuthenticated),a=N(()=>!!z.value.sessionToken);return{isAuthenticated:s,hasSessionToken:a,checkApiKey:t,exchangeToken:e,restoreApiKey:n,clearAuth:r,initAuth:o}}const A=H({qrCodeData:null,isLoading:!1,error:null,countdown:30});let Te=null,fe=null;function qr(){const t=async p=>{try{A.value.isLoading=!0,A.value.error=null;const y=await X.connect(p);if(A.value.qrCodeData=y,A.value.isLoading=!1,y.isConnected){console.log("[useQRCode] Instance already connected, skipping countdown");return}n(),s(p)}catch(y){throw A.value.isLoading=!1,A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error generating QR code:",y),y}},e=async p=>{try{const y=await X.connect(p);A.value.qrCodeData=y,A.value.error=null,o(),s(p)}catch(y){A.value.error=y instanceof Error?y.message:W.ERROR.GENERIC,console.error("[useQRCode] Error refreshing QR code:",y)}},n=()=>{r(),A.value.countdown=30,Te=setInterval(()=>{A.value.countdown>0?A.value.countdown--:r()},1e3)},r=()=>{Te&&(clearInterval(Te),Te=null)},o=()=>{A.value.countdown=30},s=p=>{fe&&clearTimeout(fe),fe=setTimeout(()=>{e(p)},Gt.QR_REFRESH_INTERVAL)},a=()=>{A.value.qrCodeData=null,A.value.error=null,A.value.countdown=30,r(),fe&&(clearTimeout(fe),fe=null)};xt(()=>{a()});const i=N(()=>!!A.value.qrCodeData),u=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.base64)||""}),f=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.count)||0}),c=N(()=>{var p;return((p=A.value.qrCodeData)==null?void 0:p.isConnected)||!1});return{qrCodeData:N(()=>A.value.qrCodeData),isLoading:N(()=>A.value.isLoading),error:N(()=>A.value.error),countdown:N(()=>A.value.countdown),hasQRCode:i,qrCodeBase64:u,qrCodeCount:f,isConnected:c,generateQRCode:t,refreshQRCode:e,clearQRCode:a}}const R=H({state:"close",isConnected:!1,profileInfo:null,isPolling:!1});let ke=null;function jr(){const t=async g=>{try{const v=(await X.getConnectionState(g)).instance.state;return R.value.state=v,R.value.isConnected=v==="open",v==="open"&&(await e(g),r()),v}catch(m){throw console.error("[useConnection] Error checking connection state:",m),R.value.state="close",R.value.isConnected=!1,m}},e=async g=>{try{const m=await X.fetchInstanceInfo(g);R.value.profileInfo=m}catch(m){console.error("[useConnection] Error fetching profile info:",m)}},n=g=>{R.value.isPolling||(R.value.isPolling=!0,t(g),ke=setInterval(()=>{t(g)},Gt.CONNECTION_CHECK_INTERVAL))},r=()=>{ke&&(clearInterval(ke),ke=null),R.value.isPolling=!1},o=async g=>{try{await X.logout(g),R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()}catch(m){throw console.error("[useConnection] Error disconnecting:",m),m}},s=async g=>{try{await X.restart(g),R.value.state="connecting",R.value.isConnected=!1,R.value.profileInfo=null,n(g)}catch(m){throw console.error("[useConnection] Error restarting:",m),m}},a=async(g,m)=>{try{await X.updateProfileName({instanceName:g,name:m}),R.value.profileInfo&&(R.value.profileInfo.profileName=m)}catch(v){throw console.error("[useConnection] Error updating profile name:",v),v}},i=async(g,m)=>{try{await X.updateProfileStatus({instanceName:g,status:m})}catch(v){throw console.error("[useConnection] Error updating profile status:",v),v}},u=()=>{R.value.state="close",R.value.isConnected=!1,R.value.profileInfo=null,r()};xt(()=>{r()});const f=N(()=>R.value.state),c=N(()=>R.value.isConnected),p=N(()=>R.value.state==="connecting"),y=N(()=>R.value.profileInfo),O=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profileName)||""}),h=N(()=>{var g;return((g=R.value.profileInfo)==null?void 0:g.profilePicUrl)||""});return{connectionState:f,isConnected:c,isConnecting:p,profileInfo:y,profileName:O,profilePicUrl:h,isPolling:N(()=>R.value.isPolling),checkConnectionState:t,fetchProfileInfo:e,startPolling:n,stopPolling:r,disconnect:o,restart:s,updateProfileName:a,updateProfileStatus:i,resetConnection:u}}const Hr={class:"space-y-6"},zr=["pattern","disabled"],Kr={key:0,class:"mt-1 text-sm text-red-600 dark:text-red-400"},Qr={key:1,class:"mt-1 text-xs text-gray-500 dark:text-gray-400"},Vr=["disabled"],Gr={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wr={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jr=ie({__name:"ConnectionForm",props:{isLoading:{type:Boolean,default:!1},isConnected:{type:Boolean,default:!1},initialInstance:{default:""}},emits:["generate"],setup(t,{emit:e}){const n=t,r=e,o=H(n.initialInstance||""),s=H(""),a=re.INSTANCE_NAME.PATTERN.source,i=N(()=>{const c=o.value.trim();return c?c.lengthre.INSTANCE_NAME.MAX_LENGTH?(s.value=`Máximo de ${re.INSTANCE_NAME.MAX_LENGTH} caracteres`,!1):re.INSTANCE_NAME.PATTERN.test(c)?(s.value="",!0):(s.value=re.INSTANCE_NAME.ERROR_MESSAGE,!1):(s.value="",!1)}),u=N(()=>n.isLoading?"Gerando...":n.isConnected?"Conectado":"Gerar QR Code"),f=()=>{if(!i.value||n.isLoading||n.isConnected)return;const c=o.value.trim();localStorage.setItem(J.INSTANCE_NAME,c),r("generate",c)};return(c,p)=>(E(),x("div",Hr,[d("div",null,[p[1]||(p[1]=d("label",{for:"instance",class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),vt(d("input",{id:"instance","onUpdate:modelValue":p[0]||(p[0]=y=>o.value=y),type:"text",class:"w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white",placeholder:"minha-instancia-whatsapp",pattern:k(a),maxlength:50,disabled:t.isLoading||t.isConnected,onKeyup:Zt(f,["enter"])},null,40,zr),[[Yt,o.value]]),s.value?(E(),x("p",Kr,I(s.value),1)):(E(),x("p",Qr," Apenas letras, números, hífens e underscores são permitidos "))]),d("button",{disabled:!i.value||t.isLoading||t.isConnected,class:"w-full bg-primary-500 text-white font-medium py-3 px-4 rounded-lg hover:bg-primary-600 active:bg-primary-700 transition-all duration-200 transform hover:shadow-lg flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",onClick:f},[t.isLoading?(E(),x("svg",Gr,[...p[2]||(p[2]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wr,[...p[3]||(p[3]=[d("path",{"fill-rule":"evenodd",d:"M3 4a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm2 2V5h1v1H5zM3 13a1 1 0 011-1h3a1 1 0 011 1v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3zm2 2v-1h1v1H5zM13 3a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1V4a1 1 0 00-1-1h-3zm1 2v1h1V5h-1zM13 12a1 1 0 00-1 1v3a1 1 0 001 1h3a1 1 0 001-1v-3a1 1 0 00-1-1h-3zm1 2v1h1v-1h-1z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(u.value),1)],8,Vr)]))}}),Xr={class:"mt-8 text-center"},Yr={class:"bg-white dark:bg-gray-700 rounded-2xl shadow-lg overflow-hidden"},Zr={class:"p-6 space-y-4"},eo={class:"bg-white dark:bg-gray-800 w-64 h-64 mx-auto flex items-center justify-center rounded-xl shadow-inner"},to={key:0,class:"flex flex-col items-center gap-3"},no=["src"],ro={key:1,class:"flex flex-col items-center gap-3 p-4"},oo={class:"text-sm text-red-600 dark:text-red-400 text-center"},so={key:0,class:"flex items-center justify-center gap-2"},ao={class:"text-sm text-gray-600 dark:text-gray-400"},io={key:1,class:"text-sm text-gray-600 dark:text-gray-400"},lo=ie({__name:"QRCodeDisplay",props:{qrCodeBase64:{default:""},isLoading:{type:Boolean,default:!1},error:{default:null},countdown:{default:30}},setup(t){return(e,n)=>(E(),x("div",Xr,[d("div",Yr,[d("div",Zr,[d("div",eo,[t.isLoading?(E(),x("div",to,[...n[0]||(n[0]=[d("svg",{class:"animate-spin h-12 w-12 text-primary-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1),d("p",{class:"text-sm text-gray-600 dark:text-gray-400"},"Gerando QR Code...",-1)])])):U("",!0),vt(d("img",{src:t.qrCodeBase64,alt:"QR Code",class:"max-w-full max-h-full rounded-lg"},null,8,no),[[en,!t.isLoading&&t.qrCodeBase64]]),!t.isLoading&&t.error?(E(),x("div",ro,[n[1]||(n[1]=d("svg",{class:"w-12 h-12 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("p",oo,I(t.error),1)])):U("",!0)]),!t.isLoading&&t.qrCodeBase64?(E(),x("div",so,[n[2]||(n[2]=d("svg",{class:"w-5 h-5 text-gray-600 dark:text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("span",ao," Atualiza em "+I(t.countdown)+"s ",1)])):U("",!0),!t.isLoading&&t.qrCodeBase64?(E(),x("div",io,[...n[3]||(n[3]=[d("p",{class:"font-medium mb-2"},"Escaneie o QR Code com seu WhatsApp:",-1),d("ol",{class:"text-left space-y-1 list-decimal list-inside"},[d("li",null,"Abra o WhatsApp no celular"),d("li",null,[Ie("Vá em "),d("strong",null,"Configurações > Aparelhos conectados")]),d("li",null,[Ie("Toque em "),d("strong",null,"Parear dispositivo")]),d("li",null,"Aponte a câmera para o QR Code")],-1)])])):U("",!0)])])]))}}),co={key:0,class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg p-6"},uo={class:"flex items-center gap-4 mb-6"},fo={class:"flex-shrink-0"},po={key:0,class:"w-16 h-16 rounded-full overflow-hidden ring-2 ring-primary-500"},ho=["src","alt"],mo={key:1,class:"w-16 h-16 rounded-full bg-primary-500 flex items-center justify-center text-white text-2xl font-bold"},go={class:"flex-1 min-w-0"},yo={class:"text-lg font-medium text-gray-900 dark:text-white truncate"},wo={class:"text-sm text-gray-500 dark:text-gray-400"},Eo={key:0,class:"grid grid-cols-3 gap-4 mb-6"},xo={class:"text-center"},vo={class:"text-2xl font-bold text-primary-500"},bo={class:"text-center"},Co={class:"text-2xl font-bold text-primary-500"},Ro={class:"text-center"},So={class:"text-2xl font-bold text-primary-500"},Ao={class:"flex gap-3"},To={key:1,class:"mt-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-4 flex items-center gap-3"},ko=ie({__name:"StatusDisplay",props:{connectionState:{default:"close"},isConnected:{type:Boolean,default:!1},profileInfo:{default:null},instanceName:{default:""}},emits:["disconnect"],setup(t){const e=t,n=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profileName)||""}),r=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a.profilePicUrl)||""}),o=N(()=>{var a;return((a=e.profileInfo)==null?void 0:a._count)||null}),s=N(()=>(n.value||e.instanceName).charAt(0).toUpperCase());return(a,i)=>t.isConnected&&t.profileInfo?(E(),x("div",co,[i[5]||(i[5]=d("div",{class:"flex items-center justify-between mb-4"},[d("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white"},"Perfil Conectado"),d("span",{class:"px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},[d("span",{class:"inline-block w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"}),Ie(" Conectado ")])],-1)),d("div",uo,[d("div",fo,[r.value?(E(),x("div",po,[d("img",{src:r.value,alt:n.value,class:"w-full h-full object-cover"},null,8,ho)])):(E(),x("div",mo,I(s.value),1))]),d("div",go,[d("p",yo,I(n.value||"Sem nome"),1),d("p",wo,I(t.instanceName),1)])]),o.value?(E(),x("div",Eo,[d("div",xo,[d("p",vo,I(o.value.Chat||0),1),i[1]||(i[1]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",bo,[d("p",Co,I(o.value.Contact||0),1),i[2]||(i[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",Ro,[d("p",So,I(o.value.Message||0),1),i[3]||(i[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])):U("",!0),d("div",Ao,[d("button",{onClick:i[0]||(i[0]=u=>a.$emit("disconnect")),class:"flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"},[...i[4]||(i[4]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})],-1),Ie(" Desconectar ",-1)])])])])):t.connectionState==="connecting"?(E(),x("div",To,[...i[6]||(i[6]=[Pe('

Conectando...

Aguardando escaneamento do QR Code

',2)])])):U("",!0)}}),No={class:"space-y-6"},_o={class:"bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 border-2 border-green-500"},Oo={class:"mb-4"},Io={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Po={class:"text-gray-900 dark:text-white font-mono"},Lo={key:0,class:"space-y-3"},Do={key:0},Uo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"},Fo={class:"text-gray-900 dark:text-white"},Mo={key:1},Bo={class:"grid grid-cols-3 gap-3"},$o={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},qo={class:"text-2xl font-bold text-primary-500"},jo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ho={class:"text-2xl font-bold text-primary-500"},zo={class:"px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 text-center"},Ko={class:"text-2xl font-bold text-primary-500"},Qo={class:"grid grid-cols-2 gap-4"},Vo=["disabled"],Go={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Wo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Jo=["disabled"],Xo={key:0,class:"animate-spin h-5 w-5",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},Yo={key:1,xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor"},Zo=ie({__name:"ConnectedInstance",props:{instanceName:{},profileInfo:{}},emits:["restart","disconnect"],setup(t,{emit:e}){const n=e,r=H(!1),o=H(null),s=()=>{r.value||(r.value=!0,o.value="restart",n("restart"),setTimeout(()=>{r.value=!1,o.value=null},3e3))},a=()=>{r.value||confirm("Tem certeza que deseja desconectar? Será necessário escanear novo QR Code.")&&(r.value=!0,o.value="disconnect",n("disconnect"),setTimeout(()=>{r.value=!1,o.value=null},3e3))};return(i,u)=>(E(),x("div",No,[d("div",_o,[u[6]||(u[6]=Pe('

Instância Conectada

Online
',1)),d("div",Oo,[u[0]||(u[0]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome da Instância ",-1)),d("div",Io,[d("p",Po,I(t.instanceName),1)])]),t.profileInfo?(E(),x("div",Lo,[t.profileInfo.profileName?(E(),x("div",Do,[u[1]||(u[1]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Nome do Perfil ",-1)),d("div",Uo,[d("p",Fo,I(t.profileInfo.profileName),1)])])):U("",!0),t.profileInfo._count?(E(),x("div",Mo,[u[5]||(u[5]=d("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Estatísticas ",-1)),d("div",Bo,[d("div",$o,[d("p",qo,I(t.profileInfo._count.Chat),1),u[2]||(u[2]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Conversas",-1))]),d("div",jo,[d("p",Ho,I(t.profileInfo._count.Contact),1),u[3]||(u[3]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Contatos",-1))]),d("div",zo,[d("p",Ko,I(t.profileInfo._count.Message),1),u[4]||(u[4]=d("p",{class:"text-xs text-gray-600 dark:text-gray-400"},"Mensagens",-1))])])])):U("",!0)])):U("",!0)]),d("div",Qo,[d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 active:bg-blue-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:s},[r.value&&o.value==="restart"?(E(),x("svg",Go,[...u[7]||(u[7]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Wo,[...u[8]||(u[8]=[d("path",{"fill-rule":"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="restart"?"Reiniciando...":"Reiniciar"),1)],8,Vo),d("button",{disabled:r.value,class:"flex items-center justify-center gap-2 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 active:bg-red-700 transition-all duration-200 transform hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed",onClick:a},[r.value&&o.value==="disconnect"?(E(),x("svg",Xo,[...u[9]||(u[9]=[d("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"},null,-1),d("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"},null,-1)])])):(E(),x("svg",Yo,[...u[10]||(u[10]=[d("path",{"fill-rule":"evenodd",d:"M3 3a1 1 0 00-1 1v12a1 1 0 102 0V4a1 1 0 00-1-1zm10.293 9.293a1 1 0 001.414 1.414l3-3a1 1 0 000-1.414l-3-3a1 1 0 10-1.414 1.414L14.586 9H7a1 1 0 100 2h7.586l-1.293 1.293z","clip-rule":"evenodd"},null,-1)])])),d("span",null,I(r.value&&o.value==="disconnect"?"Desconectando...":"Desconectar"),1)],8,Jo)]),u[11]||(u[11]=Pe('

Atenção

Reiniciar: Reconecta a instância mantendo a sessão.
Desconectar: Remove a sessão completamente. Será necessário escanear novo QR Code.

',1))]))}}),es={class:"mt-6 bg-white dark:bg-gray-700 rounded-xl shadow-lg overflow-hidden"},ts={class:"px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-600"},ns={class:"flex items-center justify-between"},rs={class:"flex items-center gap-2"},os={class:"text-xs text-gray-500 dark:text-gray-400"},ss={key:0,class:"flex items-center justify-center h-full text-gray-400 dark:text-gray-500"},as={class:"flex-shrink-0 mt-0.5"},is={class:"flex-1 min-w-0"},ls={class:"break-words"},cs={class:"text-xs opacity-75 mt-0.5"},us=ie({__name:"LogViewer",props:{logs:{default:()=>[]}},emits:["clear"],setup(t,{emit:e}){const n=t,r=e,o=H(null);bt(()=>n.logs.length,async()=>{await tn(),o.value&&(o.value.scrollTop=o.value.scrollHeight)});const s=f=>{const c={info:"text-blue-600 dark:text-blue-400",success:"text-green-600 dark:text-green-400",error:"text-red-600 dark:text-red-400",warning:"text-yellow-600 dark:text-yellow-400"};return c[f]||c.info},a=f=>{const c={info:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})),success:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})),error:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})),warning:()=>ee("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ee("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))};return c[f]||c.info},i=f=>new Date(f).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),u=()=>{r("clear")};return(f,c)=>(E(),x("div",es,[d("div",ts,[d("div",ns,[c[0]||(c[0]=d("h3",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Logs do Sistema",-1)),d("div",rs,[d("span",os,I(t.logs.length)+" mensagens",1),t.logs.length>0?(E(),x("button",{key:0,onClick:u,class:"text-xs text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"}," Limpar ")):U("",!0)])])]),d("div",{ref_key:"logsContainer",ref:o,class:"h-48 overflow-y-auto p-4 space-y-2 bg-gray-50 dark:bg-gray-900"},[t.logs.length===0?(E(),x("div",ss,[...c[1]||(c[1]=[d("p",{class:"text-sm"},"Nenhum log ainda...",-1)])])):U("",!0),(E(!0),x(nn,null,rn(t.logs,p=>(E(),x("div",{key:p.id,class:on(["flex items-start gap-2 text-sm animate-fade-in",s(p.type)])},[d("div",as,[(E(),Ee(sn(a(p.type)),{class:"w-4 h-4"}))]),d("div",is,[d("p",ls,I(p.message),1),d("p",cs,I(i(p.timestamp)),1)])],2))),128))],512)]))}}),ds=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},fs=ds(us,[["__scopeId","data-v-ad0ecda8"]]),te=H(!1);function ps(){const t=()=>{te.value=!te.value,n(),r()},e=s=>{te.value=s===Ae.DARK,n(),r()},n=()=>{te.value?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},r=()=>{const s=te.value?Ae.DARK:Ae.LIGHT;localStorage.setItem(J.THEME,s)},o=()=>{const s=localStorage.getItem(J.THEME);s?te.value=s===Ae.DARK:te.value=!1,n()};return Ct(()=>{o()}),{isDark:te,toggleTheme:t,setTheme:e}}const hs=["aria-label"],ms={key:0,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},gs={key:1,class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},ys=ie({__name:"ThemeToggle",setup(t){const{isDark:e,toggleTheme:n}=ps();return(r,o)=>(E(),x("button",{onClick:o[0]||(o[0]=(...s)=>k(n)&&k(n)(...s)),class:"p-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-200","aria-label":k(e)?"Mudar para tema claro":"Mudar para tema escuro"},[k(e)?(E(),x("svg",ms,[...o[1]||(o[1]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},null,-1)])])):(E(),x("svg",gs,[...o[2]||(o[2]=[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"},null,-1)])]))],8,hs))}}),ws={class:"bg-gradient-to-br from-primary-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 min-h-screen flex items-center justify-center font-sans p-4 relative"},Es={class:"absolute top-4 right-4 z-10"},xs={class:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md p-8 transition-all duration-300 transform hover:shadow-primary-200/50"},vs={key:0,class:"mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"},bs={class:"flex items-start gap-3"},Cs={class:"flex-1"},Rs={class:"text-sm font-medium text-red-800 dark:text-red-200"},Ss=ie({__name:"App",setup(t){const{initAuth:e,isAuthenticated:n}=$r(),{isLoading:r,error:o,countdown:s,hasQRCode:a,qrCodeBase64:i,isConnected:u,generateQRCode:f,clearQRCode:c}=qr(),{connectionState:p,isConnected:y,profileInfo:O,startPolling:h,stopPolling:g,disconnect:m,restart:v,resetConnection:B,fetchProfileInfo:L}=jr(),T=H(""),_=H(""),K=H([]),M=H(""),S=(C,b)=>{K.value.push({id:Date.now().toString()+Math.random(),type:C,message:b,timestamp:new Date})},le=()=>{K.value=[]},ge=async C=>{try{_.value="",T.value=C,S("info",`Gerando QR Code para instância: ${C}`),n.value||(S("info","Autenticando..."),await e(),S("success","Autenticado com sucesso!")),await f(C),u.value?(S("info","Instância já conectada! Buscando informações..."),await L(C),S("success","Detalhes da instância carregados!")):(S("success",W.SUCCESS.QR_GENERATED),h(C),S("info",W.INFO.WAITING_SCAN))}catch(b){const D=b instanceof Error?b.message:W.ERROR.GENERIC;_.value=D,S("error",D),console.error("[App] Error generating QR code:",b)}},ye=async()=>{try{_.value="",S("info",`Desconectando instância: ${T.value}`),await m(T.value),S("success",W.SUCCESS.LOGOUT_SUCCESS),c(),B(),T.value=""}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error disconnecting:",C)}},ce=async()=>{try{_.value="",S("info",`Reiniciando instância: ${T.value}`),await v(T.value),S("success","Instância reiniciada com sucesso!"),c(),S("info","Aguardando reconexão...")}catch(C){const b=C instanceof Error?C.message:W.ERROR.GENERIC;_.value=b,S("error",b),console.error("[App] Error restarting:",C)}};bt(y,C=>{C&&(S("success",W.SUCCESS.CONNECTED),g())});const ne=()=>new URLSearchParams(window.location.search);return Ct(async()=>{S("info","Aplicação iniciada"),console.log("🚀 QR Code Vue Application Started"),console.log("📱 Ready to connect WhatsApp instances");const C=ne(),b=C.get("instance"),D=C.get("autoConnect")==="true"||C.get("auto")==="true";b&&(S("info",`Parâmetro de instância detectado: ${b}`),/^[a-zA-Z0-9\-_]+$/.test(b)&&b.length>=3&&b.length<=50?(M.value=b,D?(S("info","Gerando QR Code automaticamente..."),setTimeout(()=>{ge(b)},500)):S("info",'Instância preenchida. Clique em "Gerar QR Code" para conectar.')):(S("error","Nome de instância inválido no parâmetro da URL"),_.value="Nome de instância inválido no parâmetro da URL"))}),(C,b)=>(E(),x("div",ws,[d("div",Es,[rt(ys)]),d("div",xs,[b[3]||(b[3]=Pe('
SE7E Sistemas

Evolution API

QR Code Scanner

',1)),_.value?(E(),x("div",vs,[d("div",bs,[b[2]||(b[2]=d("svg",{class:"w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})],-1)),d("div",Cs,[d("p",Rs,I(_.value),1)]),d("button",{onClick:b[0]||(b[0]=D=>_.value=""),class:"text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"},[...b[1]||(b[1]=[d("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[d("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])])])):U("",!0),!k(y)&&!k(u)?(E(),Ee(Jr,{key:1,"is-loading":k(r),"is-connected":k(y),"initial-instance":M.value,onGenerate:ge},null,8,["is-loading","is-connected","initial-instance"])):U("",!0),k(u)||k(y)?(E(),Ee(Zo,{key:2,"instance-name":T.value,"profile-info":k(O),onRestart:ce,onDisconnect:ye},null,8,["instance-name","profile-info"])):U("",!0),k(a)&&!k(y)&&!k(u)?(E(),Ee(lo,{key:3,"qr-code-base64":k(i),"is-loading":k(r),error:k(o),countdown:k(s)},null,8,["qr-code-base64","is-loading","error","countdown"])):U("",!0),k(u)?U("",!0):(E(),Ee(ko,{key:4,"connection-state":k(p),"is-connected":k(y),"profile-info":k(O),"instance-name":T.value,onDisconnect:ye},null,8,["connection-state","is-connected","profile-info","instance-name"])),rt(fs,{logs:K.value,onClear:le},null,8,["logs"])])]))}}),Ze=an(Ss);Ze.config.errorHandler=(t,e,n)=>{console.error("[Vue Error]",t),console.error("[Component]",e),console.error("[Info]",n)};Ze.config.warnHandler=(t,e,n)=>{console.warn("[Vue Warning]",t),console.warn("[Component]",e),console.warn("[Trace]",n)};Ze.mount("#app");console.log("🚀 QR Code Vue Application Started");console.log("📱 Ready to connect WhatsApp instances"); diff --git a/dist_extensions/assets/qrcode-vendor-l0sNRNKZ.js b/dist_extensions/assets/qrcode-vendor-l0sNRNKZ.js new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/dist_extensions/assets/qrcode-vendor-l0sNRNKZ.js @@ -0,0 +1 @@ + diff --git a/dist_extensions/assets/vue-vendor-BwOErZoh.js b/dist_extensions/assets/vue-vendor-BwOErZoh.js new file mode 100644 index 000000000..bbb322e35 --- /dev/null +++ b/dist_extensions/assets/vue-vendor-BwOErZoh.js @@ -0,0 +1,17 @@ +/** +* @vue/shared v3.5.22 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function Ps(e){const t=Object.create(null);for(const s of e.split(","))t[s]=1;return s=>s in t}const $={},Ze=[],Se=()=>{},Rn=()=>!1,Yt=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Rs=e=>e.startsWith("onUpdate:"),Q=Object.assign,Is=(e,t)=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)},jr=Object.prototype.hasOwnProperty,H=(e,t)=>jr.call(e,t),M=Array.isArray,Qe=e=>zt(e)==="[object Map]",In=e=>zt(e)==="[object Set]",P=e=>typeof e=="function",G=e=>typeof e=="string",Le=e=>typeof e=="symbol",B=e=>e!==null&&typeof e=="object",Fn=e=>(B(e)||P(e))&&P(e.then)&&P(e.catch),Dn=Object.prototype.toString,zt=e=>Dn.call(e),$r=e=>zt(e).slice(8,-1),Nn=e=>zt(e)==="[object Object]",Fs=e=>G(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,at=Ps(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Xt=e=>{const t=Object.create(null);return s=>t[s]||(t[s]=e(s))},Lr=/-\w/g,de=Xt(e=>e.replace(Lr,t=>t.slice(1).toUpperCase())),Ur=/\B([A-Z])/g,Ue=Xt(e=>e.replace(Ur,"-$1").toLowerCase()),Zt=Xt(e=>e.charAt(0).toUpperCase()+e.slice(1)),ls=Xt(e=>e?`on${Zt(e)}`:""),He=(e,t)=>!Object.is(e,t),Ft=(e,...t)=>{for(let s=0;s{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:n,value:s})},bs=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let tn;const Qt=()=>tn||(tn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Ds(e){if(M(e)){const t={};for(let s=0;s{if(s){const n=s.split(Kr);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function Ns(e){let t="";if(G(e))t=e;else if(M(e))for(let s=0;s!!(e&&e.__v_isRef===!0),Jr=e=>G(e)?e:e==null?"":M(e)||B(e)&&(e.toString===Dn||!P(e.toString))?$n(e)?Jr(e.value):JSON.stringify(e,Ln,2):String(e),Ln=(e,t)=>$n(t)?Ln(e,t.value):Qe(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((s,[n,r],i)=>(s[fs(n,i)+" =>"]=r,s),{})}:In(t)?{[`Set(${t.size})`]:[...t.values()].map(s=>fs(s))}:Le(t)?fs(t):B(t)&&!M(t)&&!Nn(t)?String(t):t,fs=(e,t="")=>{var s;return Le(e)?`Symbol(${(s=e.description)!=null?s:t})`:e};/** +* @vue/reactivity v3.5.22 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/let ie;class Yr{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=ie,!t&&ie&&(this.index=(ie.scopes||(ie.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,s;if(this.scopes)for(t=0,s=this.scopes.length;t0&&--this._on===0&&(ie=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let s,n;for(s=0,n=this.effects.length;s0)return;if(ht){let t=ht;for(ht=void 0;t;){const s=t.next;t.next=void 0,t.flags&=-9,t=s}}let e;for(;dt;){let t=dt;for(dt=void 0;t;){const s=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(n){e||(e=n)}t=s}}if(e)throw e}function Bn(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Wn(e){let t,s=e.depsTail,n=s;for(;n;){const r=n.prevDep;n.version===-1?(n===s&&(s=r),$s(n),Xr(n)):t=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=r}e.deps=t,e.depsTail=s}function ys(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(qn(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function qn(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===bt)||(e.globalVersion=bt,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!ys(e))))return;e.flags|=2;const t=e.dep,s=V,n=he;V=e,he=!0;try{Bn(e);const r=e.fn(e._value);(t.version===0||He(r,e._value))&&(e.flags|=128,e._value=r,t.version++)}catch(r){throw t.version++,r}finally{V=s,he=n,Wn(e),e.flags&=-3}}function $s(e,t=!1){const{dep:s,prevSub:n,nextSub:r}=e;if(n&&(n.nextSub=r,e.prevSub=void 0),r&&(r.prevSub=n,e.nextSub=void 0),s.subs===e&&(s.subs=n,!n&&s.computed)){s.computed.flags&=-5;for(let i=s.computed.deps;i;i=i.nextDep)$s(i,!0)}!t&&!--s.sc&&s.map&&s.map.delete(s.key)}function Xr(e){const{prevDep:t,nextDep:s}=e;t&&(t.nextDep=s,e.prevDep=void 0),s&&(s.prevDep=t,e.nextDep=void 0)}let he=!0;const Gn=[];function Me(){Gn.push(he),he=!1}function Pe(){const e=Gn.pop();he=e===void 0?!0:e}function sn(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const s=V;V=void 0;try{t()}finally{V=s}}}let bt=0;class Zr{constructor(t,s){this.sub=t,this.dep=s,this.version=s.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class Ls{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!V||!he||V===this.computed)return;let s=this.activeLink;if(s===void 0||s.sub!==V)s=this.activeLink=new Zr(V,this),V.deps?(s.prevDep=V.depsTail,V.depsTail.nextDep=s,V.depsTail=s):V.deps=V.depsTail=s,Jn(s);else if(s.version===-1&&(s.version=this.version,s.nextDep)){const n=s.nextDep;n.prevDep=s.prevDep,s.prevDep&&(s.prevDep.nextDep=n),s.prevDep=V.depsTail,s.nextDep=void 0,V.depsTail.nextDep=s,V.depsTail=s,V.deps===s&&(V.deps=n)}return s}trigger(t){this.version++,bt++,this.notify(t)}notify(t){Hs();try{for(let s=this.subs;s;s=s.prevSub)s.sub.notify()&&s.sub.dep.notify()}finally{js()}}}function Jn(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let n=t.deps;n;n=n.nextDep)Jn(n)}const s=e.dep.subs;s!==e&&(e.prevSub=s,s&&(s.nextSub=e)),e.dep.subs=e}}const xs=new WeakMap,Je=Symbol(""),vs=Symbol(""),yt=Symbol("");function z(e,t,s){if(he&&V){let n=xs.get(e);n||xs.set(e,n=new Map);let r=n.get(s);r||(n.set(s,r=new Ls),r.map=n,r.key=s),r.track()}}function Ae(e,t,s,n,r,i){const o=xs.get(e);if(!o){bt++;return}const l=c=>{c&&c.trigger()};if(Hs(),t==="clear")o.forEach(l);else{const c=M(e),h=c&&Fs(s);if(c&&s==="length"){const a=Number(n);o.forEach((p,w)=>{(w==="length"||w===yt||!Le(w)&&w>=a)&&l(p)})}else switch((s!==void 0||o.has(void 0))&&l(o.get(s)),h&&l(o.get(yt)),t){case"add":c?h&&l(o.get("length")):(l(o.get(Je)),Qe(e)&&l(o.get(vs)));break;case"delete":c||(l(o.get(Je)),Qe(e)&&l(o.get(vs)));break;case"set":Qe(e)&&l(o.get(Je));break}}js()}function Ye(e){const t=N(e);return t===e?t:(z(t,"iterate",yt),ae(e)?t:t.map(Y))}function kt(e){return z(e=N(e),"iterate",yt),e}const Qr={__proto__:null,[Symbol.iterator](){return us(this,Symbol.iterator,Y)},concat(...e){return Ye(this).concat(...e.map(t=>M(t)?Ye(t):t))},entries(){return us(this,"entries",e=>(e[1]=Y(e[1]),e))},every(e,t){return Te(this,"every",e,t,void 0,arguments)},filter(e,t){return Te(this,"filter",e,t,s=>s.map(Y),arguments)},find(e,t){return Te(this,"find",e,t,Y,arguments)},findIndex(e,t){return Te(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return Te(this,"findLast",e,t,Y,arguments)},findLastIndex(e,t){return Te(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return Te(this,"forEach",e,t,void 0,arguments)},includes(...e){return as(this,"includes",e)},indexOf(...e){return as(this,"indexOf",e)},join(e){return Ye(this).join(e)},lastIndexOf(...e){return as(this,"lastIndexOf",e)},map(e,t){return Te(this,"map",e,t,void 0,arguments)},pop(){return lt(this,"pop")},push(...e){return lt(this,"push",e)},reduce(e,...t){return nn(this,"reduce",e,t)},reduceRight(e,...t){return nn(this,"reduceRight",e,t)},shift(){return lt(this,"shift")},some(e,t){return Te(this,"some",e,t,void 0,arguments)},splice(...e){return lt(this,"splice",e)},toReversed(){return Ye(this).toReversed()},toSorted(e){return Ye(this).toSorted(e)},toSpliced(...e){return Ye(this).toSpliced(...e)},unshift(...e){return lt(this,"unshift",e)},values(){return us(this,"values",Y)}};function us(e,t,s){const n=kt(e),r=n[t]();return n!==e&&!ae(e)&&(r._next=r.next,r.next=()=>{const i=r._next();return i.done||(i.value=s(i.value)),i}),r}const kr=Array.prototype;function Te(e,t,s,n,r,i){const o=kt(e),l=o!==e&&!ae(e),c=o[t];if(c!==kr[t]){const p=c.apply(e,i);return l?Y(p):p}let h=s;o!==e&&(l?h=function(p,w){return s.call(this,Y(p),w,e)}:s.length>2&&(h=function(p,w){return s.call(this,p,w,e)}));const a=c.call(o,h,n);return l&&r?r(a):a}function nn(e,t,s,n){const r=kt(e);let i=s;return r!==e&&(ae(e)?s.length>3&&(i=function(o,l,c){return s.call(this,o,l,c,e)}):i=function(o,l,c){return s.call(this,o,Y(l),c,e)}),r[t](i,...n)}function as(e,t,s){const n=N(e);z(n,"iterate",yt);const r=n[t](...s);return(r===-1||r===!1)&&Bs(s[0])?(s[0]=N(s[0]),n[t](...s)):r}function lt(e,t,s=[]){Me(),Hs();const n=N(e)[t].apply(e,s);return js(),Pe(),n}const ei=Ps("__proto__,__v_isRef,__isVue"),Yn=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(Le));function ti(e){Le(e)||(e=String(e));const t=N(this);return z(t,"has",e),t.hasOwnProperty(e)}class zn{constructor(t=!1,s=!1){this._isReadonly=t,this._isShallow=s}get(t,s,n){if(s==="__v_skip")return t.__v_skip;const r=this._isReadonly,i=this._isShallow;if(s==="__v_isReactive")return!r;if(s==="__v_isReadonly")return r;if(s==="__v_isShallow")return i;if(s==="__v_raw")return n===(r?i?ai:kn:i?Qn:Zn).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(n)?t:void 0;const o=M(t);if(!r){let c;if(o&&(c=Qr[s]))return c;if(s==="hasOwnProperty")return ti}const l=Reflect.get(t,s,Z(t)?t:n);if((Le(s)?Yn.has(s):ei(s))||(r||z(t,"get",s),i))return l;if(Z(l)){const c=o&&Fs(s)?l:l.value;return r&&B(c)?ws(c):c}return B(l)?r?ws(l):Vs(l):l}}class Xn extends zn{constructor(t=!1){super(!1,t)}set(t,s,n,r){let i=t[s];if(!this._isShallow){const c=je(i);if(!ae(n)&&!je(n)&&(i=N(i),n=N(n)),!M(t)&&Z(i)&&!Z(n))return c||(i.value=n),!0}const o=M(t)&&Fs(s)?Number(s)e,Pt=e=>Reflect.getPrototypeOf(e);function oi(e,t,s){return function(...n){const r=this.__v_raw,i=N(r),o=Qe(i),l=e==="entries"||e===Symbol.iterator&&o,c=e==="keys"&&o,h=r[e](...n),a=s?Ss:t?$t:Y;return!t&&z(i,"iterate",c?vs:Je),{next(){const{value:p,done:w}=h.next();return w?{value:p,done:w}:{value:l?[a(p[0]),a(p[1])]:a(p),done:w}},[Symbol.iterator](){return this}}}}function Rt(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function li(e,t){const s={get(r){const i=this.__v_raw,o=N(i),l=N(r);e||(He(r,l)&&z(o,"get",r),z(o,"get",l));const{has:c}=Pt(o),h=t?Ss:e?$t:Y;if(c.call(o,r))return h(i.get(r));if(c.call(o,l))return h(i.get(l));i!==o&&i.get(r)},get size(){const r=this.__v_raw;return!e&&z(N(r),"iterate",Je),r.size},has(r){const i=this.__v_raw,o=N(i),l=N(r);return e||(He(r,l)&&z(o,"has",r),z(o,"has",l)),r===l?i.has(r):i.has(r)||i.has(l)},forEach(r,i){const o=this,l=o.__v_raw,c=N(l),h=t?Ss:e?$t:Y;return!e&&z(c,"iterate",Je),l.forEach((a,p)=>r.call(i,h(a),h(p),o))}};return Q(s,e?{add:Rt("add"),set:Rt("set"),delete:Rt("delete"),clear:Rt("clear")}:{add(r){!t&&!ae(r)&&!je(r)&&(r=N(r));const i=N(this);return Pt(i).has.call(i,r)||(i.add(r),Ae(i,"add",r,r)),this},set(r,i){!t&&!ae(i)&&!je(i)&&(i=N(i));const o=N(this),{has:l,get:c}=Pt(o);let h=l.call(o,r);h||(r=N(r),h=l.call(o,r));const a=c.call(o,r);return o.set(r,i),h?He(i,a)&&Ae(o,"set",r,i):Ae(o,"add",r,i),this},delete(r){const i=N(this),{has:o,get:l}=Pt(i);let c=o.call(i,r);c||(r=N(r),c=o.call(i,r)),l&&l.call(i,r);const h=i.delete(r);return c&&Ae(i,"delete",r,void 0),h},clear(){const r=N(this),i=r.size!==0,o=r.clear();return i&&Ae(r,"clear",void 0,void 0),o}}),["keys","values","entries",Symbol.iterator].forEach(r=>{s[r]=oi(r,e,t)}),s}function Us(e,t){const s=li(e,t);return(n,r,i)=>r==="__v_isReactive"?!e:r==="__v_isReadonly"?e:r==="__v_raw"?n:Reflect.get(H(s,r)&&r in n?s:n,r,i)}const fi={get:Us(!1,!1)},ci={get:Us(!1,!0)},ui={get:Us(!0,!1)};const Zn=new WeakMap,Qn=new WeakMap,kn=new WeakMap,ai=new WeakMap;function di(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function hi(e){return e.__v_skip||!Object.isExtensible(e)?0:di($r(e))}function Vs(e){return je(e)?e:Ks(e,!1,ni,fi,Zn)}function pi(e){return Ks(e,!1,ii,ci,Qn)}function ws(e){return Ks(e,!0,ri,ui,kn)}function Ks(e,t,s,n,r){if(!B(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const i=hi(e);if(i===0)return e;const o=r.get(e);if(o)return o;const l=new Proxy(e,i===2?n:s);return r.set(e,l),l}function ke(e){return je(e)?ke(e.__v_raw):!!(e&&e.__v_isReactive)}function je(e){return!!(e&&e.__v_isReadonly)}function ae(e){return!!(e&&e.__v_isShallow)}function Bs(e){return e?!!e.__v_raw:!1}function N(e){const t=e&&e.__v_raw;return t?N(t):e}function gi(e){return!H(e,"__v_skip")&&Object.isExtensible(e)&&Hn(e,"__v_skip",!0),e}const Y=e=>B(e)?Vs(e):e,$t=e=>B(e)?ws(e):e;function Z(e){return e?e.__v_isRef===!0:!1}function hl(e){return _i(e,!1)}function _i(e,t){return Z(e)?e:new mi(e,t)}class mi{constructor(t,s){this.dep=new Ls,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=s?t:N(t),this._value=s?t:Y(t),this.__v_isShallow=s}get value(){return this.dep.track(),this._value}set value(t){const s=this._rawValue,n=this.__v_isShallow||ae(t)||je(t);t=n?t:N(t),He(t,s)&&(this._rawValue=t,this._value=n?t:Y(t),this.dep.trigger())}}function bi(e){return Z(e)?e.value:e}const yi={get:(e,t,s)=>t==="__v_raw"?e:bi(Reflect.get(e,t,s)),set:(e,t,s,n)=>{const r=e[t];return Z(r)&&!Z(s)?(r.value=s,!0):Reflect.set(e,t,s,n)}};function er(e){return ke(e)?e:new Proxy(e,yi)}class xi{constructor(t,s,n){this.fn=t,this.setter=s,this._value=void 0,this.dep=new Ls(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=bt-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!s,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&V!==this)return Kn(this,!0),!0}get value(){const t=this.dep.track();return qn(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function vi(e,t,s=!1){let n,r;return P(e)?n=e:(n=e.get,r=e.set),new xi(n,r,s)}const It={},Lt=new WeakMap;let Ge;function Si(e,t=!1,s=Ge){if(s){let n=Lt.get(s);n||Lt.set(s,n=[]),n.push(e)}}function wi(e,t,s=$){const{immediate:n,deep:r,once:i,scheduler:o,augmentJob:l,call:c}=s,h=A=>r?A:ae(A)||r===!1||r===0?Oe(A,1):Oe(A);let a,p,w,T,R=!1,F=!1;if(Z(e)?(p=()=>e.value,R=ae(e)):ke(e)?(p=()=>h(e),R=!0):M(e)?(F=!0,R=e.some(A=>ke(A)||ae(A)),p=()=>e.map(A=>{if(Z(A))return A.value;if(ke(A))return h(A);if(P(A))return c?c(A,2):A()})):P(e)?t?p=c?()=>c(e,2):e:p=()=>{if(w){Me();try{w()}finally{Pe()}}const A=Ge;Ge=a;try{return c?c(e,3,[T]):e(T)}finally{Ge=A}}:p=Se,t&&r){const A=p,J=r===!0?1/0:r;p=()=>Oe(A(),J)}const k=zr(),D=()=>{a.stop(),k&&k.active&&Is(k.effects,a)};if(i&&t){const A=t;t=(...J)=>{A(...J),D()}}let K=F?new Array(e.length).fill(It):It;const q=A=>{if(!(!(a.flags&1)||!a.dirty&&!A))if(t){const J=a.run();if(r||R||(F?J.some((Ie,pe)=>He(Ie,K[pe])):He(J,K))){w&&w();const Ie=Ge;Ge=a;try{const pe=[J,K===It?void 0:F&&K[0]===It?[]:K,T];K=J,c?c(t,3,pe):t(...pe)}finally{Ge=Ie}}}else a.run()};return l&&l(q),a=new Un(p),a.scheduler=o?()=>o(q,!1):q,T=A=>Si(A,!1,a),w=a.onStop=()=>{const A=Lt.get(a);if(A){if(c)c(A,4);else for(const J of A)J();Lt.delete(a)}},t?n?q(!0):K=a.run():o?o(q.bind(null,!0),!0):a.run(),D.pause=a.pause.bind(a),D.resume=a.resume.bind(a),D.stop=D,D}function Oe(e,t=1/0,s){if(t<=0||!B(e)||e.__v_skip||(s=s||new Map,(s.get(e)||0)>=t))return e;if(s.set(e,t),t--,Z(e))Oe(e.value,t,s);else if(M(e))for(let n=0;n{Oe(n,t,s)});else if(Nn(e)){for(const n in e)Oe(e[n],t,s);for(const n of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,n)&&Oe(e[n],t,s)}return e}/** +* @vue/runtime-core v3.5.22 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function wt(e,t,s,n){try{return n?e(...n):e()}catch(r){es(r,t,s)}}function we(e,t,s,n){if(P(e)){const r=wt(e,t,s,n);return r&&Fn(r)&&r.catch(i=>{es(i,t,s)}),r}if(M(e)){const r=[];for(let i=0;i>>1,r=se[n],i=xt(r);i=xt(s)?se.push(e):se.splice(Ei(t),0,e),e.flags|=1,sr()}}function sr(){Ut||(Ut=tr.then(rr))}function Ai(e){M(e)?et.push(...e):De&&e.id===-1?De.splice(ze+1,0,e):e.flags&1||(et.push(e),e.flags|=1),sr()}function rn(e,t,s=xe+1){for(;sxt(s)-xt(n));if(et.length=0,De){De.push(...t);return}for(De=t,ze=0;zee.id==null?e.flags&2?-1:1/0:e.id;function rr(e){try{for(xe=0;xe{n._d&&Wt(-1);const i=Vt(t);let o;try{o=e(...r)}finally{Vt(i),n._d&&Wt(1)}return o};return n._n=!0,n._c=!0,n._d=!0,n}function pl(e,t){if(ce===null)return e;const s=rs(ce),n=e.dirs||(e.dirs=[]);for(let r=0;re.__isTeleport,Ri=Symbol("_leaveCb");function qs(e,t){e.shapeFlag&6&&e.component?(e.transition=t,qs(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function gl(e,t){return P(e)?Q({name:e.name},t,{setup:e}):e}function or(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}const Kt=new WeakMap;function pt(e,t,s,n,r=!1){if(M(e)){e.forEach((R,F)=>pt(R,t&&(M(t)?t[F]:t),s,n,r));return}if(gt(n)&&!r){n.shapeFlag&512&&n.type.__asyncResolved&&n.component.subTree.component&&pt(e,t,s,n.component.subTree);return}const i=n.shapeFlag&4?rs(n.component):n.el,o=r?null:i,{i:l,r:c}=e,h=t&&t.r,a=l.refs===$?l.refs={}:l.refs,p=l.setupState,w=N(p),T=p===$?Rn:R=>H(w,R);if(h!=null&&h!==c){if(on(t),G(h))a[h]=null,T(h)&&(p[h]=null);else if(Z(h)){h.value=null;const R=t;R.k&&(a[R.k]=null)}}if(P(c))wt(c,l,12,[o,a]);else{const R=G(c),F=Z(c);if(R||F){const k=()=>{if(e.f){const D=R?T(c)?p[c]:a[c]:c.value;if(r)M(D)&&Is(D,i);else if(M(D))D.includes(i)||D.push(i);else if(R)a[c]=[i],T(c)&&(p[c]=a[c]);else{const K=[i];c.value=K,e.k&&(a[e.k]=K)}}else R?(a[c]=o,T(c)&&(p[c]=o)):F&&(c.value=o,e.k&&(a[e.k]=o))};if(o){const D=()=>{k(),Kt.delete(e)};D.id=-1,Kt.set(e,D),fe(D,s)}else on(e),k()}}}function on(e){const t=Kt.get(e);t&&(t.flags|=8,Kt.delete(e))}Qt().requestIdleCallback;Qt().cancelIdleCallback;const gt=e=>!!e.type.__asyncLoader,lr=e=>e.type.__isKeepAlive;function Ii(e,t){fr(e,"a",t)}function Fi(e,t){fr(e,"da",t)}function fr(e,t,s=X){const n=e.__wdc||(e.__wdc=()=>{let r=s;for(;r;){if(r.isDeactivated)return;r=r.parent}return e()});if(ts(t,n,s),s){let r=s.parent;for(;r&&r.parent;)lr(r.parent.vnode)&&Di(n,t,s,r),r=r.parent}}function Di(e,t,s,n){const r=ts(t,e,n,!0);cr(()=>{Is(n[t],r)},s)}function ts(e,t,s=X,n=!1){if(s){const r=s[e]||(s[e]=[]),i=t.__weh||(t.__weh=(...o)=>{Me();const l=Tt(s),c=we(t,s,e,o);return l(),Pe(),c});return n?r.unshift(i):r.push(i),i}}const Re=e=>(t,s=X)=>{(!St||e==="sp")&&ts(e,(...n)=>t(...n),s)},Ni=Re("bm"),Hi=Re("m"),ji=Re("bu"),$i=Re("u"),Li=Re("bum"),cr=Re("um"),Ui=Re("sp"),Vi=Re("rtg"),Ki=Re("rtc");function Bi(e,t=X){ts("ec",e,t)}const Wi="components",ur=Symbol.for("v-ndc");function _l(e){return G(e)?qi(Wi,e,!1)||e:e||ur}function qi(e,t,s=!0,n=!1){const r=ce||X;if(r){const i=r.type;{const l=$o(i,!1);if(l&&(l===t||l===de(t)||l===Zt(de(t))))return i}const o=ln(r[e]||i[e],t)||ln(r.appContext[e],t);return!o&&n?i:o}}function ln(e,t){return e&&(e[t]||e[de(t)]||e[Zt(de(t))])}function ml(e,t,s,n){let r;const i=s,o=M(e);if(o||G(e)){const l=o&&ke(e);let c=!1,h=!1;l&&(c=!ae(e),h=je(e),e=kt(e)),r=new Array(e.length);for(let a=0,p=e.length;at(l,c,void 0,i));else{const l=Object.keys(e);r=new Array(l.length);for(let c=0,h=l.length;ce?Rr(e)?rs(e):Ts(e.parent):null,_t=Q(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Ts(e.parent),$root:e=>Ts(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>dr(e),$forceUpdate:e=>e.f||(e.f=()=>{Ws(e.update)}),$nextTick:e=>e.n||(e.n=Ci.bind(e.proxy)),$watch:e=>po.bind(e)}),ds=(e,t)=>e!==$&&!e.__isScriptSetup&&H(e,t),Gi={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:s,setupState:n,data:r,props:i,accessCache:o,type:l,appContext:c}=e;let h;if(t[0]!=="$"){const T=o[t];if(T!==void 0)switch(T){case 1:return n[t];case 2:return r[t];case 4:return s[t];case 3:return i[t]}else{if(ds(n,t))return o[t]=1,n[t];if(r!==$&&H(r,t))return o[t]=2,r[t];if((h=e.propsOptions[0])&&H(h,t))return o[t]=3,i[t];if(s!==$&&H(s,t))return o[t]=4,s[t];Cs&&(o[t]=0)}}const a=_t[t];let p,w;if(a)return t==="$attrs"&&z(e.attrs,"get",""),a(e);if((p=l.__cssModules)&&(p=p[t]))return p;if(s!==$&&H(s,t))return o[t]=4,s[t];if(w=c.config.globalProperties,H(w,t))return w[t]},set({_:e},t,s){const{data:n,setupState:r,ctx:i}=e;return ds(r,t)?(r[t]=s,!0):n!==$&&H(n,t)?(n[t]=s,!0):H(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(i[t]=s,!0)},has({_:{data:e,setupState:t,accessCache:s,ctx:n,appContext:r,propsOptions:i,type:o}},l){let c,h;return!!(s[l]||e!==$&&l[0]!=="$"&&H(e,l)||ds(t,l)||(c=i[0])&&H(c,l)||H(n,l)||H(_t,l)||H(r.config.globalProperties,l)||(h=o.__cssModules)&&h[l])},defineProperty(e,t,s){return s.get!=null?e._.accessCache[t]=0:H(s,"value")&&this.set(e,t,s.value,null),Reflect.defineProperty(e,t,s)}};function fn(e){return M(e)?e.reduce((t,s)=>(t[s]=null,t),{}):e}let Cs=!0;function Ji(e){const t=dr(e),s=e.proxy,n=e.ctx;Cs=!1,t.beforeCreate&&cn(t.beforeCreate,e,"bc");const{data:r,computed:i,methods:o,watch:l,provide:c,inject:h,created:a,beforeMount:p,mounted:w,beforeUpdate:T,updated:R,activated:F,deactivated:k,beforeDestroy:D,beforeUnmount:K,destroyed:q,unmounted:A,render:J,renderTracked:Ie,renderTriggered:pe,errorCaptured:Fe,serverPrefetch:Ct,expose:Ve,inheritAttrs:nt,components:Et,directives:At,filters:is}=t;if(h&&Yi(h,n,null),o)for(const W in o){const L=o[W];P(L)&&(n[W]=L.bind(s))}if(r){const W=r.call(s,s);B(W)&&(e.data=Vs(W))}if(Cs=!0,i)for(const W in i){const L=i[W],Ke=P(L)?L.bind(s,s):P(L.get)?L.get.bind(s,s):Se,Ot=!P(L)&&P(L.set)?L.set.bind(s):Se,Be=Uo({get:Ke,set:Ot});Object.defineProperty(n,W,{enumerable:!0,configurable:!0,get:()=>Be.value,set:ge=>Be.value=ge})}if(l)for(const W in l)ar(l[W],n,s,W);if(c){const W=P(c)?c.call(s):c;Reflect.ownKeys(W).forEach(L=>{eo(L,W[L])})}a&&cn(a,e,"c");function ee(W,L){M(L)?L.forEach(Ke=>W(Ke.bind(s))):L&&W(L.bind(s))}if(ee(Ni,p),ee(Hi,w),ee(ji,T),ee($i,R),ee(Ii,F),ee(Fi,k),ee(Bi,Fe),ee(Ki,Ie),ee(Vi,pe),ee(Li,K),ee(cr,A),ee(Ui,Ct),M(Ve))if(Ve.length){const W=e.exposed||(e.exposed={});Ve.forEach(L=>{Object.defineProperty(W,L,{get:()=>s[L],set:Ke=>s[L]=Ke,enumerable:!0})})}else e.exposed||(e.exposed={});J&&e.render===Se&&(e.render=J),nt!=null&&(e.inheritAttrs=nt),Et&&(e.components=Et),At&&(e.directives=At),Ct&&or(e)}function Yi(e,t,s=Se){M(e)&&(e=Es(e));for(const n in e){const r=e[n];let i;B(r)?"default"in r?i=Dt(r.from||n,r.default,!0):i=Dt(r.from||n):i=Dt(r),Z(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:o=>i.value=o}):t[n]=i}}function cn(e,t,s){we(M(e)?e.map(n=>n.bind(t.proxy)):e.bind(t.proxy),t,s)}function ar(e,t,s,n){let r=n.includes(".")?Cr(s,n):()=>s[n];if(G(e)){const i=t[e];P(i)&&ps(r,i)}else if(P(e))ps(r,e.bind(s));else if(B(e))if(M(e))e.forEach(i=>ar(i,t,s,n));else{const i=P(e.handler)?e.handler.bind(s):t[e.handler];P(i)&&ps(r,i,e)}}function dr(e){const t=e.type,{mixins:s,extends:n}=t,{mixins:r,optionsCache:i,config:{optionMergeStrategies:o}}=e.appContext,l=i.get(t);let c;return l?c=l:!r.length&&!s&&!n?c=t:(c={},r.length&&r.forEach(h=>Bt(c,h,o,!0)),Bt(c,t,o)),B(t)&&i.set(t,c),c}function Bt(e,t,s,n=!1){const{mixins:r,extends:i}=t;i&&Bt(e,i,s,!0),r&&r.forEach(o=>Bt(e,o,s,!0));for(const o in t)if(!(n&&o==="expose")){const l=zi[o]||s&&s[o];e[o]=l?l(e[o],t[o]):t[o]}return e}const zi={data:un,props:an,emits:an,methods:ut,computed:ut,beforeCreate:te,created:te,beforeMount:te,mounted:te,beforeUpdate:te,updated:te,beforeDestroy:te,beforeUnmount:te,destroyed:te,unmounted:te,activated:te,deactivated:te,errorCaptured:te,serverPrefetch:te,components:ut,directives:ut,watch:Zi,provide:un,inject:Xi};function un(e,t){return t?e?function(){return Q(P(e)?e.call(this,this):e,P(t)?t.call(this,this):t)}:t:e}function Xi(e,t){return ut(Es(e),Es(t))}function Es(e){if(M(e)){const t={};for(let s=0;s1)return s&&P(t)?t.call(n&&n.proxy):t}}const pr={},gr=()=>Object.create(pr),_r=e=>Object.getPrototypeOf(e)===pr;function to(e,t,s,n=!1){const r={},i=gr();e.propsDefaults=Object.create(null),mr(e,t,r,i);for(const o in e.propsOptions[0])o in r||(r[o]=void 0);s?e.props=n?r:pi(r):e.type.props?e.props=r:e.props=i,e.attrs=i}function so(e,t,s,n){const{props:r,attrs:i,vnode:{patchFlag:o}}=e,l=N(r),[c]=e.propsOptions;let h=!1;if((n||o>0)&&!(o&16)){if(o&8){const a=e.vnode.dynamicProps;for(let p=0;p{c=!0;const[w,T]=br(p,t,!0);Q(o,w),T&&l.push(...T)};!s&&t.mixins.length&&t.mixins.forEach(a),e.extends&&a(e.extends),e.mixins&&e.mixins.forEach(a)}if(!i&&!c)return B(e)&&n.set(e,Ze),Ze;if(M(i))for(let a=0;ae==="_"||e==="_ctx"||e==="$stable",Js=e=>M(e)?e.map(ve):[ve(e)],ro=(e,t,s)=>{if(t._n)return t;const n=Oi((...r)=>Js(t(...r)),s);return n._c=!1,n},yr=(e,t,s)=>{const n=e._ctx;for(const r in e){if(Gs(r))continue;const i=e[r];if(P(i))t[r]=ro(r,i,n);else if(i!=null){const o=Js(i);t[r]=()=>o}}},xr=(e,t)=>{const s=Js(t);e.slots.default=()=>s},vr=(e,t,s)=>{for(const n in t)(s||!Gs(n))&&(e[n]=t[n])},io=(e,t,s)=>{const n=e.slots=gr();if(e.vnode.shapeFlag&32){const r=t._;r?(vr(n,t,s),s&&Hn(n,"_",r,!0)):yr(t,n)}else t&&xr(e,t)},oo=(e,t,s)=>{const{vnode:n,slots:r}=e;let i=!0,o=$;if(n.shapeFlag&32){const l=t._;l?s&&l===1?i=!1:vr(r,t,s):(i=!t.$stable,yr(t,r)),o=t}else t&&(xr(e,t),o={default:1});if(i)for(const l in r)!Gs(l)&&o[l]==null&&delete r[l]},fe=So;function lo(e){return fo(e)}function fo(e,t){const s=Qt();s.__VUE__=!0;const{insert:n,remove:r,patchProp:i,createElement:o,createText:l,createComment:c,setText:h,setElementText:a,parentNode:p,nextSibling:w,setScopeId:T=Se,insertStaticContent:R}=e,F=(f,u,d,m=null,g=null,_=null,v=void 0,x=null,y=!!u.dynamicChildren)=>{if(f===u)return;f&&!ft(f,u)&&(m=Mt(f),ge(f,g,_,!0),f=null),u.patchFlag===-2&&(y=!1,u.dynamicChildren=null);const{type:b,ref:E,shapeFlag:S}=u;switch(b){case ns:k(f,u,d,m);break;case $e:D(f,u,d,m);break;case Nt:f==null&&K(u,d,m,v);break;case Ee:Et(f,u,d,m,g,_,v,x,y);break;default:S&1?J(f,u,d,m,g,_,v,x,y):S&6?At(f,u,d,m,g,_,v,x,y):(S&64||S&128)&&b.process(f,u,d,m,g,_,v,x,y,it)}E!=null&&g?pt(E,f&&f.ref,_,u||f,!u):E==null&&f&&f.ref!=null&&pt(f.ref,null,_,f,!0)},k=(f,u,d,m)=>{if(f==null)n(u.el=l(u.children),d,m);else{const g=u.el=f.el;u.children!==f.children&&h(g,u.children)}},D=(f,u,d,m)=>{f==null?n(u.el=c(u.children||""),d,m):u.el=f.el},K=(f,u,d,m)=>{[f.el,f.anchor]=R(f.children,u,d,m,f.el,f.anchor)},q=({el:f,anchor:u},d,m)=>{let g;for(;f&&f!==u;)g=w(f),n(f,d,m),f=g;n(u,d,m)},A=({el:f,anchor:u})=>{let d;for(;f&&f!==u;)d=w(f),r(f),f=d;r(u)},J=(f,u,d,m,g,_,v,x,y)=>{u.type==="svg"?v="svg":u.type==="math"&&(v="mathml"),f==null?Ie(u,d,m,g,_,v,x,y):Ct(f,u,g,_,v,x,y)},Ie=(f,u,d,m,g,_,v,x)=>{let y,b;const{props:E,shapeFlag:S,transition:C,dirs:O}=f;if(y=f.el=o(f.type,_,E&&E.is,E),S&8?a(y,f.children):S&16&&Fe(f.children,y,null,m,g,hs(f,_),v,x),O&&We(f,null,m,"created"),pe(y,f,f.scopeId,v,m),E){for(const U in E)U!=="value"&&!at(U)&&i(y,U,null,E[U],_,m);"value"in E&&i(y,"value",null,E.value,_),(b=E.onVnodeBeforeMount)&&ye(b,m,f)}O&&We(f,null,m,"beforeMount");const I=co(g,C);I&&C.beforeEnter(y),n(y,u,d),((b=E&&E.onVnodeMounted)||I||O)&&fe(()=>{b&&ye(b,m,f),I&&C.enter(y),O&&We(f,null,m,"mounted")},g)},pe=(f,u,d,m,g)=>{if(d&&T(f,d),m)for(let _=0;_{for(let b=y;b{const x=u.el=f.el;let{patchFlag:y,dynamicChildren:b,dirs:E}=u;y|=f.patchFlag&16;const S=f.props||$,C=u.props||$;let O;if(d&&qe(d,!1),(O=C.onVnodeBeforeUpdate)&&ye(O,d,u,f),E&&We(u,f,d,"beforeUpdate"),d&&qe(d,!0),(S.innerHTML&&C.innerHTML==null||S.textContent&&C.textContent==null)&&a(x,""),b?Ve(f.dynamicChildren,b,x,d,m,hs(u,g),_):v||L(f,u,x,null,d,m,hs(u,g),_,!1),y>0){if(y&16)nt(x,S,C,d,g);else if(y&2&&S.class!==C.class&&i(x,"class",null,C.class,g),y&4&&i(x,"style",S.style,C.style,g),y&8){const I=u.dynamicProps;for(let U=0;U{O&&ye(O,d,u,f),E&&We(u,f,d,"updated")},m)},Ve=(f,u,d,m,g,_,v)=>{for(let x=0;x{if(u!==d){if(u!==$)for(const _ in u)!at(_)&&!(_ in d)&&i(f,_,u[_],null,g,m);for(const _ in d){if(at(_))continue;const v=d[_],x=u[_];v!==x&&_!=="value"&&i(f,_,x,v,g,m)}"value"in d&&i(f,"value",u.value,d.value,g)}},Et=(f,u,d,m,g,_,v,x,y)=>{const b=u.el=f?f.el:l(""),E=u.anchor=f?f.anchor:l("");let{patchFlag:S,dynamicChildren:C,slotScopeIds:O}=u;O&&(x=x?x.concat(O):O),f==null?(n(b,d,m),n(E,d,m),Fe(u.children||[],d,E,g,_,v,x,y)):S>0&&S&64&&C&&f.dynamicChildren?(Ve(f.dynamicChildren,C,d,g,_,v,x),(u.key!=null||g&&u===g.subTree)&&Sr(f,u,!0)):L(f,u,d,E,g,_,v,x,y)},At=(f,u,d,m,g,_,v,x,y)=>{u.slotScopeIds=x,f==null?u.shapeFlag&512?g.ctx.activate(u,d,m,v,y):is(u,d,m,g,_,v,y):zs(f,u,y)},is=(f,u,d,m,g,_,v)=>{const x=f.component=Io(f,m,g);if(lr(f)&&(x.ctx.renderer=it),Do(x,!1,v),x.asyncDep){if(g&&g.registerDep(x,ee,v),!f.el){const y=x.subTree=oe($e);D(null,y,u,d),f.placeholder=y.el}}else ee(x,f,u,d,g,_,v)},zs=(f,u,d)=>{const m=u.component=f.component;if(xo(f,u,d))if(m.asyncDep&&!m.asyncResolved){W(m,u,d);return}else m.next=u,m.update();else u.el=f.el,m.vnode=u},ee=(f,u,d,m,g,_,v)=>{const x=()=>{if(f.isMounted){let{next:S,bu:C,u:O,parent:I,vnode:U}=f;{const me=wr(f);if(me){S&&(S.el=U.el,W(f,S,v)),me.asyncDep.then(()=>{f.isUnmounted||x()});return}}let j=S,ne;qe(f,!1),S?(S.el=U.el,W(f,S,v)):S=U,C&&Ft(C),(ne=S.props&&S.props.onVnodeBeforeUpdate)&&ye(ne,I,S,U),qe(f,!0);const re=pn(f),_e=f.subTree;f.subTree=re,F(_e,re,p(_e.el),Mt(_e),f,g,_),S.el=re.el,j===null&&vo(f,re.el),O&&fe(O,g),(ne=S.props&&S.props.onVnodeUpdated)&&fe(()=>ye(ne,I,S,U),g)}else{let S;const{el:C,props:O}=u,{bm:I,m:U,parent:j,root:ne,type:re}=f,_e=gt(u);qe(f,!1),I&&Ft(I),!_e&&(S=O&&O.onVnodeBeforeMount)&&ye(S,j,u),qe(f,!0);{ne.ce&&ne.ce._def.shadowRoot!==!1&&ne.ce._injectChildStyle(re);const me=f.subTree=pn(f);F(null,me,d,m,f,g,_),u.el=me.el}if(U&&fe(U,g),!_e&&(S=O&&O.onVnodeMounted)){const me=u;fe(()=>ye(S,j,me),g)}(u.shapeFlag&256||j&>(j.vnode)&&j.vnode.shapeFlag&256)&&f.a&&fe(f.a,g),f.isMounted=!0,u=d=m=null}};f.scope.on();const y=f.effect=new Un(x);f.scope.off();const b=f.update=y.run.bind(y),E=f.job=y.runIfDirty.bind(y);E.i=f,E.id=f.uid,y.scheduler=()=>Ws(E),qe(f,!0),b()},W=(f,u,d)=>{u.component=f;const m=f.vnode.props;f.vnode=u,f.next=null,so(f,u.props,m,d),oo(f,u.children,d),Me(),rn(f),Pe()},L=(f,u,d,m,g,_,v,x,y=!1)=>{const b=f&&f.children,E=f?f.shapeFlag:0,S=u.children,{patchFlag:C,shapeFlag:O}=u;if(C>0){if(C&128){Ot(b,S,d,m,g,_,v,x,y);return}else if(C&256){Ke(b,S,d,m,g,_,v,x,y);return}}O&8?(E&16&&rt(b,g,_),S!==b&&a(d,S)):E&16?O&16?Ot(b,S,d,m,g,_,v,x,y):rt(b,g,_,!0):(E&8&&a(d,""),O&16&&Fe(S,d,m,g,_,v,x,y))},Ke=(f,u,d,m,g,_,v,x,y)=>{f=f||Ze,u=u||Ze;const b=f.length,E=u.length,S=Math.min(b,E);let C;for(C=0;CE?rt(f,g,_,!0,!1,S):Fe(u,d,m,g,_,v,x,y,S)},Ot=(f,u,d,m,g,_,v,x,y)=>{let b=0;const E=u.length;let S=f.length-1,C=E-1;for(;b<=S&&b<=C;){const O=f[b],I=u[b]=y?Ne(u[b]):ve(u[b]);if(ft(O,I))F(O,I,d,null,g,_,v,x,y);else break;b++}for(;b<=S&&b<=C;){const O=f[S],I=u[C]=y?Ne(u[C]):ve(u[C]);if(ft(O,I))F(O,I,d,null,g,_,v,x,y);else break;S--,C--}if(b>S){if(b<=C){const O=C+1,I=OC)for(;b<=S;)ge(f[b],g,_,!0),b++;else{const O=b,I=b,U=new Map;for(b=I;b<=C;b++){const le=u[b]=y?Ne(u[b]):ve(u[b]);le.key!=null&&U.set(le.key,b)}let j,ne=0;const re=C-I+1;let _e=!1,me=0;const ot=new Array(re);for(b=0;b=re){ge(le,g,_,!0);continue}let be;if(le.key!=null)be=U.get(le.key);else for(j=I;j<=C;j++)if(ot[j-I]===0&&ft(le,u[j])){be=j;break}be===void 0?ge(le,g,_,!0):(ot[be-I]=b+1,be>=me?me=be:_e=!0,F(le,u[be],d,null,g,_,v,x,y),ne++)}const Qs=_e?uo(ot):Ze;for(j=Qs.length-1,b=re-1;b>=0;b--){const le=I+b,be=u[le],ks=u[le+1],en=le+1{const{el:_,type:v,transition:x,children:y,shapeFlag:b}=f;if(b&6){Be(f.component.subTree,u,d,m);return}if(b&128){f.suspense.move(u,d,m);return}if(b&64){v.move(f,u,d,it);return}if(v===Ee){n(_,u,d);for(let S=0;Sx.enter(_),g);else{const{leave:S,delayLeave:C,afterLeave:O}=x,I=()=>{f.ctx.isUnmounted?r(_):n(_,u,d)},U=()=>{_._isLeaving&&_[Ri](!0),S(_,()=>{I(),O&&O()})};C?C(_,I,U):U()}else n(_,u,d)},ge=(f,u,d,m=!1,g=!1)=>{const{type:_,props:v,ref:x,children:y,dynamicChildren:b,shapeFlag:E,patchFlag:S,dirs:C,cacheIndex:O}=f;if(S===-2&&(g=!1),x!=null&&(Me(),pt(x,null,d,f,!0),Pe()),O!=null&&(u.renderCache[O]=void 0),E&256){u.ctx.deactivate(f);return}const I=E&1&&C,U=!gt(f);let j;if(U&&(j=v&&v.onVnodeBeforeUnmount)&&ye(j,u,f),E&6)Hr(f.component,d,m);else{if(E&128){f.suspense.unmount(d,m);return}I&&We(f,null,u,"beforeUnmount"),E&64?f.type.remove(f,u,d,it,m):b&&!b.hasOnce&&(_!==Ee||S>0&&S&64)?rt(b,u,d,!1,!0):(_===Ee&&S&384||!g&&E&16)&&rt(y,u,d),m&&Xs(f)}(U&&(j=v&&v.onVnodeUnmounted)||I)&&fe(()=>{j&&ye(j,u,f),I&&We(f,null,u,"unmounted")},d)},Xs=f=>{const{type:u,el:d,anchor:m,transition:g}=f;if(u===Ee){Nr(d,m);return}if(u===Nt){A(f);return}const _=()=>{r(d),g&&!g.persisted&&g.afterLeave&&g.afterLeave()};if(f.shapeFlag&1&&g&&!g.persisted){const{leave:v,delayLeave:x}=g,y=()=>v(d,_);x?x(f.el,_,y):y()}else _()},Nr=(f,u)=>{let d;for(;f!==u;)d=w(f),r(f),f=d;r(u)},Hr=(f,u,d)=>{const{bum:m,scope:g,job:_,subTree:v,um:x,m:y,a:b}=f;hn(y),hn(b),m&&Ft(m),g.stop(),_&&(_.flags|=8,ge(v,f,u,d)),x&&fe(x,u),fe(()=>{f.isUnmounted=!0},u)},rt=(f,u,d,m=!1,g=!1,_=0)=>{for(let v=_;v{if(f.shapeFlag&6)return Mt(f.component.subTree);if(f.shapeFlag&128)return f.suspense.next();const u=w(f.anchor||f.el),d=u&&u[Mi];return d?w(d):u};let os=!1;const Zs=(f,u,d)=>{f==null?u._vnode&&ge(u._vnode,null,null,!0):F(u._vnode||null,f,u,null,null,null,d),u._vnode=f,os||(os=!0,rn(),nr(),os=!1)},it={p:F,um:ge,m:Be,r:Xs,mt:is,mc:Fe,pc:L,pbc:Ve,n:Mt,o:e};return{render:Zs,hydrate:void 0,createApp:ki(Zs)}}function hs({type:e,props:t},s){return s==="svg"&&e==="foreignObject"||s==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:s}function qe({effect:e,job:t},s){s?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function co(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Sr(e,t,s=!1){const n=e.children,r=t.children;if(M(n)&&M(r))for(let i=0;i>1,e[s[l]]0&&(t[n]=s[i-1]),s[i]=n)}}for(i=s.length,o=s[i-1];i-- >0;)s[i]=o,o=t[o];return s}function wr(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:wr(t)}function hn(e){if(e)for(let t=0;tDt(ao);function ps(e,t,s){return Tr(e,t,s)}function Tr(e,t,s=$){const{immediate:n,deep:r,flush:i,once:o}=s,l=Q({},s),c=t&&n||!t&&i!=="post";let h;if(St){if(i==="sync"){const T=ho();h=T.__watcherHandles||(T.__watcherHandles=[])}else if(!c){const T=()=>{};return T.stop=Se,T.resume=Se,T.pause=Se,T}}const a=X;l.call=(T,R,F)=>we(T,a,R,F);let p=!1;i==="post"?l.scheduler=T=>{fe(T,a&&a.suspense)}:i!=="sync"&&(p=!0,l.scheduler=(T,R)=>{R?T():Ws(T)}),l.augmentJob=T=>{t&&(T.flags|=4),p&&(T.flags|=2,a&&(T.id=a.uid,T.i=a))};const w=wi(e,t,l);return St&&(h?h.push(w):c&&w()),w}function po(e,t,s){const n=this.proxy,r=G(e)?e.includes(".")?Cr(n,e):()=>n[e]:e.bind(n,n);let i;P(t)?i=t:(i=t.handler,s=t);const o=Tt(this),l=Tr(r,i.bind(n),s);return o(),l}function Cr(e,t){const s=t.split(".");return()=>{let n=e;for(let r=0;rt==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${de(t)}Modifiers`]||e[`${Ue(t)}Modifiers`];function _o(e,t,...s){if(e.isUnmounted)return;const n=e.vnode.props||$;let r=s;const i=t.startsWith("update:"),o=i&&go(n,t.slice(7));o&&(o.trim&&(r=s.map(a=>G(a)?a.trim():a)),o.number&&(r=s.map(bs)));let l,c=n[l=ls(t)]||n[l=ls(de(t))];!c&&i&&(c=n[l=ls(Ue(t))]),c&&we(c,e,6,r);const h=n[l+"Once"];if(h){if(!e.emitted)e.emitted={};else if(e.emitted[l])return;e.emitted[l]=!0,we(h,e,6,r)}}const mo=new WeakMap;function Er(e,t,s=!1){const n=s?mo:t.emitsCache,r=n.get(e);if(r!==void 0)return r;const i=e.emits;let o={},l=!1;if(!P(e)){const c=h=>{const a=Er(h,t,!0);a&&(l=!0,Q(o,a))};!s&&t.mixins.length&&t.mixins.forEach(c),e.extends&&c(e.extends),e.mixins&&e.mixins.forEach(c)}return!i&&!l?(B(e)&&n.set(e,null),null):(M(i)?i.forEach(c=>o[c]=null):Q(o,i),B(e)&&n.set(e,o),o)}function ss(e,t){return!e||!Yt(t)?!1:(t=t.slice(2).replace(/Once$/,""),H(e,t[0].toLowerCase()+t.slice(1))||H(e,Ue(t))||H(e,t))}function pn(e){const{type:t,vnode:s,proxy:n,withProxy:r,propsOptions:[i],slots:o,attrs:l,emit:c,render:h,renderCache:a,props:p,data:w,setupState:T,ctx:R,inheritAttrs:F}=e,k=Vt(e);let D,K;try{if(s.shapeFlag&4){const A=r||n,J=A;D=ve(h.call(J,A,a,p,T,w,R)),K=l}else{const A=t;D=ve(A.length>1?A(p,{attrs:l,slots:o,emit:c}):A(p,null)),K=t.props?l:bo(l)}}catch(A){mt.length=0,es(A,e,1),D=oe($e)}let q=D;if(K&&F!==!1){const A=Object.keys(K),{shapeFlag:J}=q;A.length&&J&7&&(i&&A.some(Rs)&&(K=yo(K,i)),q=st(q,K,!1,!0))}return s.dirs&&(q=st(q,null,!1,!0),q.dirs=q.dirs?q.dirs.concat(s.dirs):s.dirs),s.transition&&qs(q,s.transition),D=q,Vt(k),D}const bo=e=>{let t;for(const s in e)(s==="class"||s==="style"||Yt(s))&&((t||(t={}))[s]=e[s]);return t},yo=(e,t)=>{const s={};for(const n in e)(!Rs(n)||!(n.slice(9)in t))&&(s[n]=e[n]);return s};function xo(e,t,s){const{props:n,children:r,component:i}=e,{props:o,children:l,patchFlag:c}=t,h=i.emitsOptions;if(t.dirs||t.transition)return!0;if(s&&c>=0){if(c&1024)return!0;if(c&16)return n?gn(n,o,h):!!o;if(c&8){const a=t.dynamicProps;for(let p=0;pe.__isSuspense;function So(e,t){t&&t.pendingBranch?M(e)?t.effects.push(...e):t.effects.push(e):Ai(e)}const Ee=Symbol.for("v-fgt"),ns=Symbol.for("v-txt"),$e=Symbol.for("v-cmt"),Nt=Symbol.for("v-stc"),mt=[];let ue=null;function wo(e=!1){mt.push(ue=e?null:[])}function To(){mt.pop(),ue=mt[mt.length-1]||null}let vt=1;function Wt(e,t=!1){vt+=e,e<0&&ue&&t&&(ue.hasOnce=!0)}function Or(e){return e.dynamicChildren=vt>0?ue||Ze:null,To(),vt>0&&ue&&ue.push(e),e}function bl(e,t,s,n,r,i){return Or(Pr(e,t,s,n,r,i,!0))}function Co(e,t,s,n,r){return Or(oe(e,t,s,n,r,!0))}function qt(e){return e?e.__v_isVNode===!0:!1}function ft(e,t){return e.type===t.type&&e.key===t.key}const Mr=({key:e})=>e??null,Ht=({ref:e,ref_key:t,ref_for:s})=>(typeof e=="number"&&(e=""+e),e!=null?G(e)||Z(e)||P(e)?{i:ce,r:e,k:t,f:!!s}:e:null);function Pr(e,t=null,s=null,n=0,r=null,i=e===Ee?0:1,o=!1,l=!1){const c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Mr(t),ref:t&&Ht(t),scopeId:ir,slotScopeIds:null,children:s,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:i,patchFlag:n,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:ce};return l?(Ys(c,s),i&128&&e.normalize(c)):s&&(c.shapeFlag|=G(s)?8:16),vt>0&&!o&&ue&&(c.patchFlag>0||i&6)&&c.patchFlag!==32&&ue.push(c),c}const oe=Eo;function Eo(e,t=null,s=null,n=0,r=null,i=!1){if((!e||e===ur)&&(e=$e),qt(e)){const l=st(e,t,!0);return s&&Ys(l,s),vt>0&&!i&&ue&&(l.shapeFlag&6?ue[ue.indexOf(e)]=l:ue.push(l)),l.patchFlag=-2,l}if(Lo(e)&&(e=e.__vccOpts),t){t=Ao(t);let{class:l,style:c}=t;l&&!G(l)&&(t.class=Ns(l)),B(c)&&(Bs(c)&&!M(c)&&(c=Q({},c)),t.style=Ds(c))}const o=G(e)?1:Ar(e)?128:Pi(e)?64:B(e)?4:P(e)?2:0;return Pr(e,t,s,n,r,o,i,!0)}function Ao(e){return e?Bs(e)||_r(e)?Q({},e):e:null}function st(e,t,s=!1,n=!1){const{props:r,ref:i,patchFlag:o,children:l,transition:c}=e,h=t?Mo(r||{},t):r,a={__v_isVNode:!0,__v_skip:!0,type:e.type,props:h,key:h&&Mr(h),ref:t&&t.ref?s&&i?M(i)?i.concat(Ht(t)):[i,Ht(t)]:Ht(t):i,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:l,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Ee?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&st(e.ssContent),ssFallback:e.ssFallback&&st(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return c&&n&&qs(a,c.clone(a)),a}function Oo(e=" ",t=0){return oe(ns,null,e,t)}function yl(e,t){const s=oe(Nt,null,e);return s.staticCount=t,s}function xl(e="",t=!1){return t?(wo(),Co($e,null,e)):oe($e,null,e)}function ve(e){return e==null||typeof e=="boolean"?oe($e):M(e)?oe(Ee,null,e.slice()):qt(e)?Ne(e):oe(ns,null,String(e))}function Ne(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:st(e)}function Ys(e,t){let s=0;const{shapeFlag:n}=e;if(t==null)t=null;else if(M(t))s=16;else if(typeof t=="object")if(n&65){const r=t.default;r&&(r._c&&(r._d=!1),Ys(e,r()),r._c&&(r._d=!0));return}else{s=32;const r=t._;!r&&!_r(t)?t._ctx=ce:r===3&&ce&&(ce.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else P(t)?(t={default:t,_ctx:ce},s=32):(t=String(t),n&64?(s=16,t=[Oo(t)]):s=8);e.children=t,e.shapeFlag|=s}function Mo(...e){const t={};for(let s=0;sX||ce;let Gt,Os;{const e=Qt(),t=(s,n)=>{let r;return(r=e[s])||(r=e[s]=[]),r.push(n),i=>{r.length>1?r.forEach(o=>o(i)):r[0](i)}};Gt=t("__VUE_INSTANCE_SETTERS__",s=>X=s),Os=t("__VUE_SSR_SETTERS__",s=>St=s)}const Tt=e=>{const t=X;return Gt(e),e.scope.on(),()=>{e.scope.off(),Gt(t)}},_n=()=>{X&&X.scope.off(),Gt(null)};function Rr(e){return e.vnode.shapeFlag&4}let St=!1;function Do(e,t=!1,s=!1){t&&Os(t);const{props:n,children:r}=e.vnode,i=Rr(e);to(e,n,i,t),io(e,r,s||t);const o=i?No(e,t):void 0;return t&&Os(!1),o}function No(e,t){const s=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,Gi);const{setup:n}=s;if(n){Me();const r=e.setupContext=n.length>1?jo(e):null,i=Tt(e),o=wt(n,e,0,[e.props,r]),l=Fn(o);if(Pe(),i(),(l||e.sp)&&!gt(e)&&or(e),l){if(o.then(_n,_n),t)return o.then(c=>{mn(e,c)}).catch(c=>{es(c,e,0)});e.asyncDep=o}else mn(e,o)}else Ir(e)}function mn(e,t,s){P(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:B(t)&&(e.setupState=er(t)),Ir(e)}function Ir(e,t,s){const n=e.type;e.render||(e.render=n.render||Se);{const r=Tt(e);Me();try{Ji(e)}finally{Pe(),r()}}}const Ho={get(e,t){return z(e,"get",""),e[t]}};function jo(e){const t=s=>{e.exposed=s||{}};return{attrs:new Proxy(e.attrs,Ho),slots:e.slots,emit:e.emit,expose:t}}function rs(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(er(gi(e.exposed)),{get(t,s){if(s in t)return t[s];if(s in _t)return _t[s](e)},has(t,s){return s in t||s in _t}})):e.proxy}function $o(e,t=!0){return P(e)?e.displayName||e.name:e.name||t&&e.__name}function Lo(e){return P(e)&&"__vccOpts"in e}const Uo=(e,t)=>vi(e,t,St);function vl(e,t,s){try{Wt(-1);const n=arguments.length;return n===2?B(t)&&!M(t)?qt(t)?oe(e,null,[t]):oe(e,t):oe(e,null,t):(n>3?s=Array.prototype.slice.call(arguments,2):n===3&&qt(s)&&(s=[s]),oe(e,t,s))}finally{Wt(1)}}const Vo="3.5.22";/** +* @vue/runtime-dom v3.5.22 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/let Ms;const bn=typeof window<"u"&&window.trustedTypes;if(bn)try{Ms=bn.createPolicy("vue",{createHTML:e=>e})}catch{}const Fr=Ms?e=>Ms.createHTML(e):e=>e,Ko="http://www.w3.org/2000/svg",Bo="http://www.w3.org/1998/Math/MathML",Ce=typeof document<"u"?document:null,yn=Ce&&Ce.createElement("template"),Wo={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const r=t==="svg"?Ce.createElementNS(Ko,e):t==="mathml"?Ce.createElementNS(Bo,e):s?Ce.createElement(e,{is:s}):Ce.createElement(e);return e==="select"&&n&&n.multiple!=null&&r.setAttribute("multiple",n.multiple),r},createText:e=>Ce.createTextNode(e),createComment:e=>Ce.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Ce.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,r,i){const o=s?s.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),s),!(r===i||!(r=r.nextSibling)););else{yn.innerHTML=Fr(n==="svg"?`${e}`:n==="mathml"?`${e}`:e);const l=yn.content;if(n==="svg"||n==="mathml"){const c=l.firstChild;for(;c.firstChild;)l.appendChild(c.firstChild);l.removeChild(c)}t.insertBefore(l,s)}return[o?o.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},qo=Symbol("_vtc");function Go(e,t,s){const n=e[qo];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const Jt=Symbol("_vod"),Dr=Symbol("_vsh"),Sl={name:"show",beforeMount(e,{value:t},{transition:s}){e[Jt]=e.style.display==="none"?"":e.style.display,s&&t?s.beforeEnter(e):ct(e,t)},mounted(e,{value:t},{transition:s}){s&&t&&s.enter(e)},updated(e,{value:t,oldValue:s},{transition:n}){!t!=!s&&(n?t?(n.beforeEnter(e),ct(e,!0),n.enter(e)):n.leave(e,()=>{ct(e,!1)}):ct(e,t))},beforeUnmount(e,{value:t}){ct(e,t)}};function ct(e,t){e.style.display=t?e[Jt]:"none",e[Dr]=!t}const Jo=Symbol(""),Yo=/(?:^|;)\s*display\s*:/;function zo(e,t,s){const n=e.style,r=G(s);let i=!1;if(s&&!r){if(t)if(G(t))for(const o of t.split(";")){const l=o.slice(0,o.indexOf(":")).trim();s[l]==null&&jt(n,l,"")}else for(const o in t)s[o]==null&&jt(n,o,"");for(const o in s)o==="display"&&(i=!0),jt(n,o,s[o])}else if(r){if(t!==s){const o=n[Jo];o&&(s+=";"+o),n.cssText=s,i=Yo.test(s)}}else t&&e.removeAttribute("style");Jt in e&&(e[Jt]=i?n.display:"",e[Dr]&&(n.display="none"))}const xn=/\s*!important$/;function jt(e,t,s){if(M(s))s.forEach(n=>jt(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=Xo(e,t);xn.test(s)?e.setProperty(Ue(n),s.replace(xn,""),"important"):e[n]=s}}const vn=["Webkit","Moz","ms"],gs={};function Xo(e,t){const s=gs[t];if(s)return s;let n=de(t);if(n!=="filter"&&n in e)return gs[t]=n;n=Zt(n);for(let r=0;r_s||(el.then(()=>_s=0),_s=Date.now());function sl(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;we(nl(n,s.value),t,5,[n])};return s.value=e,s.attached=tl(),s}function nl(e,t){if(M(t)){const s=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{s.call(e),e._stopped=!0},t.map(n=>r=>!r._stopped&&n&&n(r))}else return t}const An=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,rl=(e,t,s,n,r,i)=>{const o=r==="svg";t==="class"?Go(e,n,o):t==="style"?zo(e,s,n):Yt(t)?Rs(t)||Qo(e,t,s,n,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):il(e,t,n,o))?(Tn(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&wn(e,t,n,o,i,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!G(n))?Tn(e,de(t),n,i,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._falseValue=n),wn(e,t,n,o))};function il(e,t,s,n){if(n)return!!(t==="innerHTML"||t==="textContent"||t in e&&An(t)&&P(s));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return An(t)&&G(s)?!1:t in e}const On=e=>{const t=e.props["onUpdate:modelValue"]||!1;return M(t)?s=>Ft(t,s):t};function ol(e){e.target.composing=!0}function Mn(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const ms=Symbol("_assign"),wl={created(e,{modifiers:{lazy:t,trim:s,number:n}},r){e[ms]=On(r);const i=n||r.props&&r.props.type==="number";Xe(e,t?"change":"input",o=>{if(o.target.composing)return;let l=e.value;s&&(l=l.trim()),i&&(l=bs(l)),e[ms](l)}),s&&Xe(e,"change",()=>{e.value=e.value.trim()}),t||(Xe(e,"compositionstart",ol),Xe(e,"compositionend",Mn),Xe(e,"change",Mn))},mounted(e,{value:t}){e.value=t??""},beforeUpdate(e,{value:t,oldValue:s,modifiers:{lazy:n,trim:r,number:i}},o){if(e[ms]=On(o),e.composing)return;const l=(i||e.type==="number")&&!/^0\d/.test(e.value)?bs(e.value):e.value,c=t??"";l!==c&&(document.activeElement===e&&e.type!=="range"&&(n&&t===s||r&&e.value.trim()===c)||(e.value=c))}},ll={esc:"escape",space:" ",up:"arrow-up",left:"arrow-left",right:"arrow-right",down:"arrow-down",delete:"backspace"},Tl=(e,t)=>{const s=e._withKeys||(e._withKeys={}),n=t.join(".");return s[n]||(s[n]=r=>{if(!("key"in r))return;const i=Ue(r.key);if(t.some(o=>o===i||ll[o]===i))return e(r)})},fl=Q({patchProp:rl},Wo);let Pn;function cl(){return Pn||(Pn=lo(fl))}const Cl=(...e)=>{const t=cl().createApp(...e),{mount:s}=t;return t.mount=n=>{const r=al(n);if(!r)return;const i=t._component;!P(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const o=s(r,!1,ul(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),o},t};function ul(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function al(e){return G(e)?document.querySelector(e):e}export{Ee as F,bl as a,wo as b,Uo as c,gl as d,Pr as e,Tl as f,xl as g,Sl as h,Oo as i,yl as j,ps as k,ml as l,Ns as m,Ci as n,cr as o,Co as p,_l as q,hl as r,vl as s,Jr as t,bi as u,wl as v,pl as w,Hi as x,oe as y,Cl as z}; diff --git a/dist_extensions/images/backgrund SE7E dark.png b/dist_extensions/images/backgrund SE7E dark.png new file mode 100644 index 000000000..0d87f7c26 Binary files /dev/null and b/dist_extensions/images/backgrund SE7E dark.png differ diff --git a/dist_extensions/images/backgrund light SE7E.png b/dist_extensions/images/backgrund light SE7E.png new file mode 100644 index 000000000..f8406448f Binary files /dev/null and b/dist_extensions/images/backgrund light SE7E.png differ diff --git a/dist_extensions/images/favicon.png b/dist_extensions/images/favicon.png new file mode 100644 index 000000000..2af246e62 Binary files /dev/null and b/dist_extensions/images/favicon.png differ diff --git a/dist_extensions/images/logo-se7e-dark.png b/dist_extensions/images/logo-se7e-dark.png new file mode 100644 index 000000000..9520b6b14 Binary files /dev/null and b/dist_extensions/images/logo-se7e-dark.png differ diff --git a/dist_extensions/images/logo-se7e-light.png b/dist_extensions/images/logo-se7e-light.png new file mode 100644 index 000000000..5699ea6a0 Binary files /dev/null and b/dist_extensions/images/logo-se7e-light.png differ diff --git a/dist_extensions/index.html b/dist_extensions/index.html new file mode 100644 index 000000000..d9f4c4ba9 --- /dev/null +++ b/dist_extensions/index.html @@ -0,0 +1,43 @@ + + + + + + + + + QR Code Scanner - WhatsApp Connection + + + + + + + + + + + + + + + + + +
+ + + + + + + + diff --git a/docs/editMessage/EXAMPLES.md b/docs/editMessage/EXAMPLES.md new file mode 100644 index 000000000..9f7687f32 --- /dev/null +++ b/docs/editMessage/EXAMPLES.md @@ -0,0 +1,454 @@ +# 📝 Exemplos Práticos - Edição de Mensagens + +## 🎯 Cenários de Uso + +### 1. Corrigir Erro de Digitação + +```bash +# Situação: Enviou "Oláa" por engano e quer corrigir para "Olá" + +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "Olá" + }' +``` + +### 2. Adicionar Informação em Mensagem Anterior + +```bash +# Situação: Enviou preço de produto e precisa adicionar detalhes + +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "Produto: R$ 100,00\nTamanho: P, M, G\nCor: Preto, Branco" + }' +``` + +### 3. Corrigir Caption de Produto + +```bash +# Situação: Enviou imagem de produto com caption errado + +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "🎯 Promoção Especial!\n\nCamiseta: R$ 49,90\nFrete Grátis!" + }' +``` + +### 4. Atualizar Status de Pedido + +```bash +# Situação: Status do pedido mudou e precisa atualizar mensagem + +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "✅ Pedido #12345\n📦 Status: Enviado\n🚚 Previsão: 2-3 dias úteis" + }' +``` + +## 💻 Exemplos por Linguagem + +### Node.js/JavaScript + +```javascript +const axios = require('axios'); + +async function editMessage(apikey, instanceName, messageData) { + try { + const response = await axios.post( + `http://localhost:8080/chat/updateMessage`, + { + number: messageData.number, + key: { + id: messageData.keyId, + remoteJid: messageData.remoteJid, + fromMe: true + }, + text: messageData.newText + }, + { + headers: { + 'apikey': apikey, + 'Content-Type': 'application/json' + } + } + ); + + console.log('✅ Mensagem editada com sucesso!', response.data); + return response.data; + } catch (error) { + console.error('❌ Erro ao editar mensagem:', error.response?.data || error.message); + throw error; + } +} + +// Exemplo de uso +editMessage('SUA_CHAVE_API', 'minha-instancia', { + number: '5511999999999', + keyId: 'BAE5xxxxxxxxxxx', + remoteJid: '5511999999999@s.whatsapp.net', + newText: 'Mensagem editada!' +}); +``` + +### Python + +```python +import requests +from typing import Dict + +def edit_message(apikey: str, instance_name: str, data: Dict) -> Dict: + """ + Edita uma mensagem no WhatsApp. + + Args: + apikey: Chave de API do Evolution + instance_name: Nome da instância + data: Dados da mensagem + + Returns: + Dict com resposta da API + """ + url = f"http://localhost:8080/chat/updateMessage" + headers = { + "apikey": apikey, + "Content-Type": "application/json" + } + + payload = { + "number": data["number"], + "key": { + "id": data["key"]["id"], + "remoteJid": data["key"]["remoteJid"], + "fromMe": True + }, + "text": data["text"] + } + + try: + response = requests.post(url, json=payload, headers=headers) + response.raise_for_status() + print("✅ Mensagem editada com sucesso!") + return response.json() + except requests.exceptions.RequestException as e: + print(f"❌ Erro ao editar mensagem: {e}") + raise + +# Exemplo de uso +result = edit_message( + apikey='SUA_CHAVE_API', + instance_name='minha-instancia', + data={ + 'number': '5511999999999', + 'key': { + 'id': 'BAE5xxxxxxxxxxx', + 'remoteJid': '5511999999999@s.whatsapp.net' + }, + 'text': 'Mensagem editada com sucesso!' + } +) + +print(result) +``` + +### PHP + +```php +baseUrl = $baseUrl; + $this->apikey = $apikey; + } + + /** + * Edita uma mensagem no WhatsApp + */ + public function editMessage(array $data): array { + $url = $this->baseUrl . '/chat/updateMessage'; + + $payload = [ + 'number' => $data['number'], + 'key' => [ + 'id' => $data['key']['id'], + 'remoteJid' => $data['key']['remoteJid'], + 'fromMe' => true + ], + 'text' => $data['text'] + ]; + + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'apikey: ' . $this->apikey, + 'Content-Type: application/json', + ]); + + $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + + if ($httpCode !== 200) { + throw new Exception("Erro ao editar mensagem: HTTP $httpCode"); + } + + return json_decode($response, true); + } +} + +// Exemplo de uso +$editor = new MessageEditor('http://localhost:8080', 'SUA_CHAVE_API'); + +try { + $result = $editor->editMessage([ + 'number' => '5511999999999', + 'key' => [ + 'id' => 'BAE5xxxxxxxxxxx', + 'remoteJid' => '5511999999999@s.whatsapp.net' + ], + 'text' => 'Mensagem editada com sucesso!' + ]); + + echo "✅ Mensagem editada com sucesso!\n"; + print_r($result); +} catch (Exception $e) { + echo "❌ Erro: " . $e->getMessage() . "\n"; +} +?> +``` + +### cURL + +```bash +#!/bin/bash + +# Configurações +APIKEY="SUA_CHAVE_API" +BASE_URL="http://localhost:8080" +NUMBER="5511999999999" +KEY_ID="BAE5xxxxxxxxxxx" +REMOTE_JID="5511999999999@s.whatsapp.net" +NEW_TEXT="Mensagem editada com sucesso!" + +# Função para editar mensagem +edit_message() { + curl -X POST "${BASE_URL}/chat/updateMessage" \ + -H "apikey: ${APIKEY}" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "'"${NUMBER}"'", + "key": { + "id": "'"${KEY_ID}"'", + "remoteJid": "'"${REMOTE_JID}"'", + "fromMe": true + }, + "text": "'"${NEW_TEXT}"'" + }' +} + +# Executar +echo "📝 Editando mensagem..." +RESPONSE=$(edit_message) +echo "Resposta: ${RESPONSE}" +``` + +## 🔄 Fluxo Completo + +### Buscar → Editar → Verificar + +```javascript +// 1. Buscar mensagens recentes +const findMessages = async (apikey, number) => { + const response = await axios.post( + 'http://localhost:8080/chat/findMessages', + { + where: { + fromMe: true, + remoteJid: `${number}@s.whatsapp.net` + }, + limit: 1 + }, + { headers: { apikey } } + ); + + return response.data.messages[0]; +}; + +// 2. Editar mensagem +const editMessage = async (apikey, number, keyId, newText) => { + const response = await axios.post( + 'http://localhost:8080/chat/updateMessage', + { + number, + key: { + id: keyId, + remoteJid: `${number}@s.whatsapp.net`, + fromMe: true + }, + text: newText + }, + { headers: { apikey } } + ); + + return response.data; +}; + +// 3. Fluxo completo +(async () => { + try { + const apikey = 'SUA_CHAVE_API'; + const number = '5511999999999'; + + console.log('1️⃣ Buscando mensagem...'); + const message = await findMessages(apikey, number); + + console.log('2️⃣ Editando mensagem...'); + const result = await editMessage( + apikey, + number, + message.key.id, + 'Mensagem editada!' + ); + + console.log('✅ Sucesso!', result); + } catch (error) { + console.error('❌ Erro:', error.message); + } +})(); +``` + +## 🚨 Tratamento de Erros + +```javascript +const editWithErrorHandling = async (data) => { + try { + // Validar dados + if (!data.number || !data.key || !data.text) { + throw new Error('Dados incompletos'); + } + + // Verificar timestamp (15 minutos) + const messageAge = Date.now() - (data.messageTimestamp * 1000); + if (messageAge > 15 * 60 * 1000) { + throw new Error('Mensagem muito antiga (limite: 15 minutos)'); + } + + // Tentar editar + const response = await editMessage(data); + return response; + + } catch (error) { + // Tratar erros específicos + if (error.response?.status === 404) { + console.error('❌ Mensagem não encontrada'); + } else if (error.response?.status === 400) { + console.error('❌ Dados inválidos:', error.response.data); + } else if (error.message.includes('15 minutos')) { + console.error('⏰ Mensagem muito antiga para editar'); + } else { + console.error('❌ Erro desconhecido:', error.message); + } + throw error; + } +}; +``` + +## 📊 Monitoramento + +```javascript +const editWithMonitoring = async (data) => { + const startTime = Date.now(); + + try { + console.log('📝 Iniciando edição...'); + const result = await editMessage(data); + + const duration = Date.now() - startTime; + console.log(`✅ Editada em ${duration}ms`); + + // Log para análise + console.log({ + timestamp: new Date().toISOString(), + duration, + success: true, + messageId: result.key?.id + }); + + return result; + } catch (error) { + console.log({ + timestamp: new Date().toISOString(), + duration: Date.now() - startTime, + success: false, + error: error.message + }); + throw error; + } +}; +``` + +## 🎯 Integração com Webhook + +```javascript +// Listener para eventos de edição +app.post('/webhook', (req, res) => { + const { event, data } = req.body; + + if (event === 'send.message.update') { + console.log('📝 Mensagem editada:', { + messageId: data.key.id, + newContent: data.editedMessage.conversation, + timestamp: new Date() + }); + + // Atualizar base de dados + // Notificar cliente + // Registrar auditoria + } + + res.status(200).send('OK'); +}); +``` + +--- + +**Veja também:** +- [📖 README Completo](./README.md) +- [🔧 Troubleshooting](./TROUBLESHOOTING.md) diff --git a/docs/editMessage/README.md b/docs/editMessage/README.md new file mode 100644 index 000000000..f253c0c4f --- /dev/null +++ b/docs/editMessage/README.md @@ -0,0 +1,463 @@ +# 📝 Edição de Mensagens - Evolution API + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Requisitos](#requisitos) +- [Funcionalidades](#funcionalidades) +- [Como Usar](#como-usar) +- [Exemplos Práticos](#exemplos-práticos) +- [Limitações](#limitações) +- [Integração com Chatwoot](#integração-com-chatwoot) +- [Troubleshooting](#troubleshooting) + +## Visão Geral + +O Evolution API permite **editar mensagens** enviadas através do WhatsApp, incluindo texto, captions de imagens e vídeos. + +### ✅ Tipos de Mensagens Suportadas + +- ✅ **Texto simples** (`conversation`) +- ✅ **Texto estendido** (`extendedTextMessage`) +- ✅ **Imagens** (mantém mídia, edita caption) +- ✅ **Vídeos** (mantém mídia, edita caption) + +### ❌ Não Suportado + +- ❌ Mensagens de áudio/voz +- ❌ Mensagens de documentos +- ❌ Mensagens de contato +- ❌ Mensagens de localização +- ❌ Mensagens de outros usuários (apenas suas próprias) + +## Requisitos + +### Ambiente + +- ✅ **Canal:** WhatsApp Baileys (único canal suportado) +- ✅ **Node.js:** 18+ (para ESM) +- ✅ **Banco de dados:** Configurado e rodando +- ✅ **Instância:** Conectada e ativa + +### Configurações + +```env +# .env - Configurações necessárias +DATABASE_SAVE_DATA_NEW_MESSAGE=true +DATABASE_SAVE_DATA_MESSAGE_UPDATE=true +CHATWOOT_ENABLED=true # Opcional, para integração +``` + +### Autenticação + +```bash +# Header obrigatório em todas as requisições +apikey: SUA_CHAVE_API +``` + +## Funcionalidades + +### 1. Editar Mensagem de Texto + +Edita mensagens de texto simples ou texto estendido. + +```bash +POST /chat/updateMessage +``` + +### 2. Editar Caption de Mídia + +Edita o caption (legenda) de imagens e vídeos, mantendo a mídia original. + +```bash +POST /chat/updateMessage +``` + +### 3. Validações Automáticas + +- ✅ Verifica se a mensagem existe no banco +- ✅ Valida se é sua própria mensagem (`fromMe: true`) +- ✅ Verifica limite de tempo (15 minutos após envio) +- ✅ Valida formato da chave da mensagem +- ✅ Impede edição de mensagens deletadas + +### 4. Webhooks + +Dispara evento `SEND_MESSAGE_UPDATE` quando mensagem é editada. + +### 5. Histórico + +Salva histórico de edições na tabela `MessageUpdate` com status "EDITED". + +## Como Usar + +### Passo 1: Buscar Mensagens + +```bash +curl -X POST "http://localhost:8080/chat/findMessages" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "where": { + "fromMe": true, + "remoteJid": "5511999999999@s.whatsapp.net" + }, + "limit": 10 + }' +``` + +### Passo 2: Editar Mensagem + +```bash +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "Nova mensagem editada" + }' +``` + +## Exemplos Práticos + +### Exemplo 1: Editar Mensagem de Texto + +```bash +# 1. Buscar mensagem para editar +curl -X POST "http://localhost:8080/chat/findMessages" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "where": { + "fromMe": true, + "messageType": "conversation" + }, + "limit": 1 + }' + +# Resposta: +# { +# "messages": [{ +# "key": { +# "id": "BAE5xxxxxxxxxxx", +# "remoteJid": "5511999999999@s.whatsapp.net", +# "fromMe": true +# }, +# "message": { +# "conversation": "Mensagem original" +# } +# }] +# } + +# 2. Editar mensagem +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "Mensagem editada com sucesso" + }' +``` + +### Exemplo 2: Editar Caption de Imagem + +```bash +# 1. Buscar imagem enviada +curl -X POST "http://localhost:8080/chat/findMessages" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "where": { + "fromMe": true, + "messageType": "imageMessage" + }, + "limit": 1 + }' + +# 2. Editar caption da imagem +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "Nova legenda da imagem!" + }' +``` + +### Exemplo 3: Editar Caption de Vídeo + +```bash +curl -X POST "http://localhost:8080/chat/updateMessage" \ + -H "apikey: SUA_CHAVE_API" \ + -H "Content-Type: application/json" \ + -d '{ + "number": "5511999999999", + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "text": "Nova legenda do vídeo!" + }' +``` + +## Limitações + +### Limite de Tempo + +⚠️ **15 minutos:** Mensagens só podem ser editadas até 15 minutos após o envio original. + +### Permissões + +- ✅ Só pode editar suas próprias mensagens +- ❌ Não pode editar mensagens de outros usuários +- ❌ Não pode editar mensagens deletadas + +### Canais Suportados + +- ✅ **WhatsApp Baileys** - Totalmente suportado +- ❌ **WhatsApp Business API** - Não suportado +- ❌ **Evolution Channel** - Não suportado + +### Tipos de Mídia + +- ✅ Texto (qualquer tipo) +- ✅ Imagem (caption) +- ✅ Vídeo (caption) +- ❌ Áudio/Voz +- ❌ Documentos +- ❌ Localização +- ❌ Contatos + +## Integração com Chatwoot + +### Evento Disparado + +```json +{ + "event": "send.message.update", + "instanceName": "minha-instancia", + "instanceId": "inst_123", + "data": { + "key": { + "id": "BAE5xxxxxxxxxxx", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true + }, + "editedMessage": { + "conversation": "Nova mensagem editada" + } + } +} +``` + +### Comportamento no Chatwoot + +Quando uma mensagem é editada, o Chatwoot recebe: + +1. **Notificação automática** com o novo conteúdo +2. **Indicador visual** de mensagem editada +3. **Texto formatado:** + ``` + Mensagem editada: + + [Novo conteúdo da mensagem] + ``` + +### Configuração + +```env +# .env +CHATWOOT_ENABLED=true +CHATWOOT_URL=https://seu-chatwoot.com +CHATWOOT_ACCOUNT_ID=1 +CHATWOOT_TOKEN=seu_token_aqui +``` + +## Troubleshooting + +### Erro: "Message not found" + +**Causa:** Mensagem não existe no banco de dados ou não foi enviada por você. + +**Solução:** +- Verificar se `DATABASE_SAVE_DATA_NEW_MESSAGE=true` +- Confirmar que `key.fromMe: true` +- Verificar se a mensagem existe no banco + +### Erro: "Message is older than 15 minutes" + +**Causa:** Tentativa de editar mensagem enviada há mais de 15 minutos. + +**Solução:** +- ⏰ Editar apenas mensagens recentes (últimos 15 minutos) +- Verificar timestamp da mensagem antes de editar + +### Erro: "Message not compatible" + +**Causa:** Tipo de mensagem não suportado para edição. + +**Solução:** +- ✅ Usar apenas: texto, imagem ou vídeo +- ❌ Não tentar editar: áudio, documento, localização + +### Erro: "RemoteJid does not match" + +**Causa:** `key.remoteJid` não corresponde ao `number` informado. + +**Solução:** +- Verificar se `remoteJid` está correto +- Usar formato JID completo: `5511999999999@s.whatsapp.net` + +### Erro: "You cannot edit others messages" + +**Causa:** Tentativa de editar mensagem de outro usuário. + +**Solução:** +- Verificar se `key.fromMe: true` +- Editar apenas suas próprias mensagens + +## Exemplos de Código + +### JavaScript/TypeScript + +```typescript +async function editMessage(apikey: string, instanceName: string, data: { + number: string; + key: { + id: string; + remoteJid: string; + fromMe: boolean; + }; + text: string; +}) { + const response = await fetch(`http://localhost:8080/chat/updateMessage`, { + method: 'POST', + headers: { + 'apikey': apikey, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(data), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + return await response.json(); +} + +// Uso +await editMessage('SUA_CHAVE_API', 'minha-instancia', { + number: '5511999999999', + key: { + id: 'BAE5xxxxxxxxxxx', + remoteJid: '5511999999999@s.whatsapp.net', + fromMe: true, + }, + text: 'Mensagem editada com sucesso!', +}); +``` + +### Python + +```python +import requests + +def edit_message(apikey: str, data: dict) -> dict: + url = "http://localhost:8080/chat/updateMessage" + headers = { + "apikey": apikey, + "Content-Type": "application/json" + } + + response = requests.post(url, json=data, headers=headers) + response.raise_for_status() + return response.json() + +# Uso +result = edit_message('SUA_CHAVE_API', { + 'number': '5511999999999', + 'key': { + 'id': 'BAE5xxxxxxxxxxx', + 'remoteJid': '5511999999999@s.whatsapp.net', + 'fromMe': True, + }, + 'text': 'Mensagem editada com sucesso!', +}) + +print(result) +``` + +### PHP + +```php + '5511999999999', + 'key' => [ + 'id' => 'BAE5xxxxxxxxxxx', + 'remoteJid' => '5511999999999@s.whatsapp.net', + 'fromMe' => true, + ], + 'text' => 'Mensagem editada com sucesso!', +]); + +var_dump($result); +?> +``` + +## Documentação Relacionada + +- [📄 Análise Completa](../ANALISE_EDICAO_MENSAGENS.md) +- [🔗 API de Chat](../api-reference.md) +- [🤖 Integração Chatwoot](../chatwoot-integration.md) +- [📊 Webhooks](../webhooks.md) + +## Suporte + +Para mais informações ou suporte: + +- 📧 Email: contato@evolution-api.com +- 💬 Discord: [Evolution API Community](https://discord.gg/evolution-api) +- 📚 Documentação: https://doc.evolution-api.com + +--- + +**Versão:** 2.3.6 +**Última Atualização:** Outubro 2025 +**Autor:** Evolution API Team diff --git a/docs/nginx/README-nginx.md b/docs/nginx/README-nginx.md new file mode 100644 index 000000000..e3f5fb8f2 --- /dev/null +++ b/docs/nginx/README-nginx.md @@ -0,0 +1,129 @@ +# Documentação Nginx para Evolution API + +Este diretório contém toda a documentação e arquivos necessários para configurar o Nginx como proxy reverso para a Evolution API no domínio `evo.se7esistemassinop.com.br`. + +## Arquivos Criados + +### 📚 `nginx-setup.md` +Manual completo e detalhado com instruções passo a passo para: +- Instalação do Nginx +- Configuração de proxy reverso para a Evolution API (porta 8080) +- Configuração de SSL com Let's Encrypt +- Implementação de cabeçalhos de segurança +- Resolução de problemas +- Comandos de manutenção + +### ⚙️ `nginx-config-example.conf` +Arquivo de configuração pronta para uso com: +- Redirecionamento HTTP → HTTPS +- Proxy reverso para porta 8080 +- Configurações SSL modernas +- Cabeçalhos de segurança +- Suporte a WebSocket +- Cache para arquivos estáticos + +### 🚀 `install-nginx.sh` +Script automatizado que executa: +- Instalação do Nginx +- Configuração do firewall +- Criação da configuração do site +- Instalação do Certbot +- Obtenção de certificados SSL +- Configuração de renovação automática + +## Como Usar + +### Opção 1: Instalação Automatizada (Recomendada) + +1. **Edite o script primeiro:** + ```bash + nano docs/install-nginx.sh + # Altere a variável EMAIL para seu email real + ``` + +2. **Execute o script:** + ```bash + sudo ./docs/install-nginx.sh + ``` + +### Opção 2: Instalação Manual + +Siga o manual completo em `nginx-setup.md`. + +### Opção 3: Usar Configuração Pronta + +```bash +# Copiar configuração +sudo cp docs/nginx-config-example.conf /etc/nginx/sites-available/evo.se7esistemassinop.com.br + +# Ativar site +sudo ln -s /etc/nginx/sites-available/evo.se7esistemassinop.com.br /etc/nginx/sites-enabled/ + +# Testar e recarregar +sudo nginx -t && sudo systemctl reload nginx +``` + +## Informações do Domínio Atual + +- **Domínio:** `evo.se7esistemassinop.com.br` +- **IP atual:** Verificar com `dig +short evo.se7esistemassinop.com.br` +- **Evolution API:** Porta 8080 (local) +- **Manager:** `/manager` +- **Documentação:** `/docs` +- **Versão:** 2.3.1 + +## Estrutura da Configuração + +``` +Nginx (443/80) → Evolution API (127.0.0.1:8080) + ↓ + Docker Container +``` + +## Verificações Pós-Instalação + +1. **Nginx funcionando:** + ```bash + sudo systemctl status nginx + ``` + +2. **Evolution API respondendo:** + ```bash + curl -I http://127.0.0.1:8080 + ``` + +3. **HTTPS funcionando:** + ```bash + curl -I https://evo.se7esistemassinop.com.br + ``` + +4. **Certificados válidos:** + ```bash + sudo certbot certificates + ``` + +## Migração para Novo Servidor + +Para migrar para um novo servidor: + +1. **Apontar DNS** para o novo servidor +2. **Instalar Docker** e Evolution API +3. **Executar script** de instalação do Nginx +4. **Restaurar dados** da Evolution API (diretório `instances`) + +## Logs e Monitoramento + +- **Logs Nginx:** `/var/log/nginx/evolution-api-*.log` +- **Logs Evolution API:** `docker logs evolution_api` +- **Status SSL:** `curl -I https://evo.se7esistemassinop.com.br` + +## Suporte + +- **Documentação oficial:** https://doc.evolution-api.com +- **GitHub:** https://github.com/EvolutionAPI/evolution-api + +--- + +**Criado em:** $(date) +**Para domínio:** evo.se7esistemassinop.com.br +**Evolution API versão:** 2.3.1 diff --git a/docs/nginx/install-nginx.sh b/docs/nginx/install-nginx.sh new file mode 100644 index 000000000..27da33b44 --- /dev/null +++ b/docs/nginx/install-nginx.sh @@ -0,0 +1,243 @@ +#!/bin/bash + +# Script de instalação e configuração do Nginx para Evolution API +# Domínio: evo.se7esistemassinop.com.br +# Versão: 1.0 + +set -e + +# Cores para output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Variáveis +DOMAIN="evo.se7esistemassinop.com.br" +WWW_DOMAIN="www.evo.se7esistemassinop.com.br" +EMAIL="your-email@example.com" # ALTERE ESTE EMAIL + +echo -e "${GREEN}🚀 Iniciando instalação do Nginx para Evolution API${NC}" + +# Verificar se está rodando como root +if [[ $EUID -ne 0 ]]; then + echo -e "${RED}❌ Este script deve ser executado como root${NC}" + exit 1 +fi + +# Função para imprimir status +print_status() { + echo -e "${GREEN}✅ $1${NC}" +} + +print_warning() { + echo -e "${YELLOW}⚠️ $1${NC}" +} + +print_error() { + echo -e "${RED}❌ $1${NC}" +} + +# Verificar se o domínio aponta para este servidor +echo -e "${YELLOW}📋 Verificando se o domínio aponta para este servidor...${NC}" +SERVER_IP=$(curl -s http://checkip.amazonaws.com/) +DOMAIN_IP=$(dig +short $DOMAIN | tail -n1) + +if [ "$SERVER_IP" != "$DOMAIN_IP" ]; then + print_warning "O domínio $DOMAIN não aponta para este servidor ($SERVER_IP vs $DOMAIN_IP)" + print_warning "Certifique-se de que o DNS esteja configurado corretamente antes de continuar" + read -p "Deseja continuar mesmo assim? (y/N): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi +fi + +# 1. Atualizar sistema +echo -e "${YELLOW}📦 Atualizando sistema...${NC}" +apt update && apt upgrade -y +print_status "Sistema atualizado" + +# 2. Instalar Nginx +echo -e "${YELLOW}🌐 Instalando Nginx...${NC}" +apt install nginx -y +systemctl enable nginx +systemctl start nginx +print_status "Nginx instalado e iniciado" + +# 3. Configurar firewall +echo -e "${YELLOW}🔥 Configurando firewall...${NC}" +ufw allow 'Nginx Full' +ufw allow ssh +print_status "Firewall configurado" + +# 4. Criar arquivo de configuração do Nginx +echo -e "${YELLOW}⚙️ Criando configuração do Nginx...${NC}" +cat > /etc/nginx/sites-available/$DOMAIN << EOF +# Redirecionar HTTP para HTTPS +server { + listen 80; + listen [::]:80; + server_name $DOMAIN $WWW_DOMAIN; + return 301 https://\$server_name\$request_uri; +} + +# Configuração HTTPS principal +server { + listen 443 ssl http2; + listen [::]:443 ssl http2; + server_name $DOMAIN $WWW_DOMAIN; + + # Certificados SSL (serão configurados pelo Certbot) + ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem; + + # Configurações SSL modernas + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384; + ssl_prefer_server_ciphers on; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 10m; + + # Configurações de upload e timeout + client_max_body_size 100M; + proxy_read_timeout 300; + proxy_connect_timeout 300; + proxy_send_timeout 300; + + # Logs + access_log /var/log/nginx/evolution-api-access.log; + error_log /var/log/nginx/evolution-api-error.log; + + # Cabeçalhos de segurança + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # Proxy principal para Evolution API (porta 8080) + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade \$http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host \$host; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_cache_bypass \$http_upgrade; + + # CORS headers para Evolution API + add_header 'Access-Control-Allow-Origin' '*' always; + add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; + add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization,apikey' always; + add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; + } + + # WebSocket support + location /ws { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade \$http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host \$host; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto \$scheme; + } + + # Cache para arquivos estáticos + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)\$ { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host \$host; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto \$scheme; + expires 1y; + add_header Cache-Control "public, immutable"; + } +} +EOF + +# 5. Ativar o site +echo -e "${YELLOW}🔗 Ativando configuração do site...${NC}" +ln -sf /etc/nginx/sites-available/$DOMAIN /etc/nginx/sites-enabled/ +rm -f /etc/nginx/sites-enabled/default + +# Testar configuração +nginx -t +if [ $? -eq 0 ]; then + print_status "Configuração do Nginx válida" +else + print_error "Erro na configuração do Nginx" + exit 1 +fi + +# 6. Instalar Certbot +echo -e "${YELLOW}🔒 Instalando Certbot...${NC}" +apt install certbot python3-certbot-nginx -y +print_status "Certbot instalado" + +# 7. Recarregar Nginx +systemctl reload nginx +print_status "Nginx recarregado" + +# 8. Obter certificados SSL +echo -e "${YELLOW}🔐 Obtendo certificados SSL...${NC}" +print_warning "IMPORTANTE: Altere o email no script para um email válido antes de executar o Certbot" + +if [ "$EMAIL" == "your-email@example.com" ]; then + print_error "Por favor, altere a variável EMAIL no início do script para um email válido" + print_warning "Execute manualmente: certbot --nginx -d $DOMAIN -d $WWW_DOMAIN" +else + certbot --nginx -d $DOMAIN -d $WWW_DOMAIN --non-interactive --agree-tos --email $EMAIL + if [ $? -eq 0 ]; then + print_status "Certificados SSL configurados" + else + print_error "Erro ao configurar certificados SSL" + print_warning "Execute manualmente: certbot --nginx -d $DOMAIN -d $WWW_DOMAIN" + fi +fi + +# 9. Configurar renovação automática +echo -e "${YELLOW}🔄 Configurando renovação automática...${NC}" +(crontab -l 2>/dev/null; echo "0 3 * * * /usr/bin/certbot renew --quiet --post-hook 'systemctl reload nginx'") | crontab - +print_status "Renovação automática configurada" + +# 10. Verificar se Evolution API está rodando +echo -e "${YELLOW}🔍 Verificando Evolution API...${NC}" +if docker ps | grep -q evolution_api; then + print_status "Evolution API está rodando" +else + print_warning "Evolution API não está rodando. Inicie com: docker-compose up -d" +fi + +# 11. Testar conectividade +echo -e "${YELLOW}🧪 Testando conectividade...${NC}" +if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8080 | grep -q "200\|404"; then + print_status "Evolution API respondendo na porta 8080" +else + print_warning "Evolution API não está respondendo na porta 8080" +fi + +echo +echo -e "${GREEN}🎉 Instalação concluída!${NC}" +echo +echo -e "${YELLOW}📋 Próximos passos:${NC}" +echo "1. Verifique se o Evolution API está rodando: docker ps" +echo "2. Acesse: https://$DOMAIN" +echo "3. Manager: https://$DOMAIN/manager" +echo "4. Documentação: https://$DOMAIN/docs" +echo +echo -e "${YELLOW}📁 Arquivos importantes:${NC}" +echo "- Configuração Nginx: /etc/nginx/sites-available/$DOMAIN" +echo "- Logs Nginx: /var/log/nginx/evolution-api-*.log" +echo "- Certificados SSL: /etc/letsencrypt/live/$DOMAIN/" +echo +echo -e "${YELLOW}🔧 Comandos úteis:${NC}" +echo "- Reiniciar Nginx: systemctl restart nginx" +echo "- Ver logs: tail -f /var/log/nginx/evolution-api-access.log" +echo "- Testar SSL: curl -I https://$DOMAIN" +echo +print_status "Configuração do Nginx para Evolution API concluída com sucesso!" diff --git a/docs/nginx/nginx-config-example.conf b/docs/nginx/nginx-config-example.conf new file mode 100644 index 000000000..eb4481f1a --- /dev/null +++ b/docs/nginx/nginx-config-example.conf @@ -0,0 +1,87 @@ +# Arquivo de configuração nginx para Evolution API +# Local: /etc/nginx/sites-available/evo.se7esistemassinop.com.br + +# Redirecionar HTTP para HTTPS +server { + listen 80; + listen [::]:80; + server_name evo.se7esistemassinop.com.br www.evo.se7esistemassinop.com.br; + return 301 https://$server_name$request_uri; +} + +# Configuração HTTPS principal +server { + listen 443 ssl http2; + listen [::]:443 ssl http2; + server_name evo.se7esistemassinop.com.br www.evo.se7esistemassinop.com.br; + + # Certificados SSL (configurados pelo Certbot) + ssl_certificate /etc/letsencrypt/live/evo.se7esistemassinop.com.br/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/evo.se7esistemassinop.com.br/privkey.pem; + + # Configurações SSL modernas + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384; + ssl_prefer_server_ciphers on; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 10m; + + # Configurações de upload e timeout + client_max_body_size 100M; + proxy_read_timeout 300; + proxy_connect_timeout 300; + proxy_send_timeout 300; + + # Logs + access_log /var/log/nginx/evolution-api-access.log; + error_log /var/log/nginx/evolution-api-error.log; + + # Cabeçalhos de segurança + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # Proxy principal para Evolution API (porta 8080) + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + + # CORS headers para Evolution API + add_header 'Access-Control-Allow-Origin' '*' always; + add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; + add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization,apikey' always; + add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; + } + + # WebSocket support + location /ws { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # Cache para arquivos estáticos + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + expires 1y; + add_header Cache-Control "public, immutable"; + } +} diff --git a/docs/nginx/nginx-setup.md b/docs/nginx/nginx-setup.md new file mode 100644 index 000000000..29fe885a4 --- /dev/null +++ b/docs/nginx/nginx-setup.md @@ -0,0 +1,364 @@ +# Manual de Configuração do Nginx para Evolution API + +## Visão Geral + +Este manual fornece instruções passo a passo para configurar o Nginx como proxy reverso para a Evolution API no domínio `evo.se7esistemassinop.com.br`. Este guia permitirá que você reconfigure o servidor em caso de migração. + +## Informações do Projeto + +- **Domínio:** `evo.se7esistemassinop.com.br` +- **API Evolution:** Porta 8080 (Docker) +- **Versão atual:** 2.3.1 +- **Manager:** Disponível em `/manager` +- **Documentação:** Disponível em `/docs` + +## Pré-requisitos + +- Servidor Ubuntu/Debian com Docker instalado +- Domínio apontando para o IP do servidor +- Docker e Docker Compose funcionando +- Acesso root ou sudo + +## 1. Instalação do Nginx + +```bash +# Atualizar repositórios +sudo apt update + +# Instalar Nginx +sudo apt install nginx -y + +# Verificar status +sudo systemctl status nginx + +# Habilitar inicialização automática +sudo systemctl enable nginx +``` + +## 2. Configuração do Evolution API (Docker) + +Certifique-se de que o docker-compose.yaml está configurado corretamente: + +```yaml +services: + api: + container_name: evolution_api + image: evoapicloud/evolution-api:latest + restart: always + ports: + - "127.0.0.1:8080:8080" # Bind apenas no localhost + # ... outras configurações +``` + +**Importante:** Modifique o `docker-compose.yaml` para que a porta 8080 seja acessível apenas pelo localhost (`127.0.0.1:8080:8080`) por segurança. + +## 3. Configuração do Nginx + +### 3.1 Criar o arquivo de configuração + +```bash +sudo nano /etc/nginx/sites-available/evo.se7esistemassinop.com.br +``` + +### 3.2 Configuração completa do site + +```nginx +# Redirecionar HTTP para HTTPS +server { + listen 80; + listen [::]:80; + server_name evo.se7esistemassinop.com.br www.evo.se7esistemassinop.com.br; + + # Redirecionar para HTTPS + return 301 https://$server_name$request_uri; +} + +# Configuração HTTPS +server { + listen 443 ssl http2; + listen [::]:443 ssl http2; + server_name evo.se7esistemassinop.com.br www.evo.se7esistemassinop.com.br; + + # Configurações SSL (serão preenchidas pelo Certbot) + ssl_certificate /etc/letsencrypt/live/evo.se7esistemassinop.com.br/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/evo.se7esistemassinop.com.br/privkey.pem; + + # Configurações SSL modernas + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384; + ssl_prefer_server_ciphers on; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 10m; + + # Configurações de upload e timeout + client_max_body_size 100M; + proxy_read_timeout 300; + proxy_connect_timeout 300; + proxy_send_timeout 300; + + # Logs + access_log /var/log/nginx/evolution-api-access.log; + error_log /var/log/nginx/evolution-api-error.log; + + # Cabeçalhos de segurança + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # Proxy para Evolution API + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + + # CORS headers + add_header 'Access-Control-Allow-Origin' '*' always; + add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; + add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization,apikey' always; + add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; + } + + # Configuração específica para WebSocket (se necessário) + location /ws { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # Cache para arquivos estáticos + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + expires 1y; + add_header Cache-Control "public, immutable"; + } +} +``` + +### 3.3 Ativar a configuração + +```bash +# Habilitar o site +sudo ln -s /etc/nginx/sites-available/evo.se7esistemassinop.com.br /etc/nginx/sites-enabled/ + +# Remover configuração padrão (opcional) +sudo rm /etc/nginx/sites-enabled/default + +# Testar configuração +sudo nginx -t + +# Recarregar Nginx +sudo systemctl reload nginx +``` + +## 4. Instalação e Configuração do SSL (Let's Encrypt) + +### 4.1 Instalar Certbot + +```bash +sudo apt install certbot python3-certbot-nginx -y +``` + +### 4.2 Obter certificados SSL + +```bash +sudo certbot --nginx -d evo.se7esistemassinop.com.br -d www.evo.se7esistemassinop.com.br +``` + +**Responda às perguntas:** +- Email: Insira um email válido +- Termos: Aceite (Y) +- Compartilhar email: Opção sua (Y/N) + +### 4.3 Configurar renovação automática + +```bash +# Testar renovação +sudo certbot renew --dry-run + +# Configurar cron para renovação automática +sudo crontab -e + +# Adicionar linha (verificar renovação diariamente às 3h da manhã): +0 3 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx" +``` + +## 5. Configuração de Firewall + +```bash +# Permitir tráfego HTTP e HTTPS +sudo ufw allow 'Nginx Full' + +# Verificar status +sudo ufw status +``` + +## 6. Configurações da Evolution API (.env) + +No arquivo `.env` da Evolution API, certifique-se de ter: + +```env +# Configurações do servidor +SERVER_TYPE=http +SERVER_PORT=8080 +SERVER_URL=https://evo.se7esistemassinop.com.br + +# SSL (não necessário se usando nginx como proxy) +# SSL_CONF_PRIVKEY= +# SSL_CONF_FULLCHAIN= + +# CORS +CORS_ORIGIN=https://evo.se7esistemassinop.com.br,https://www.evo.se7esistemassinop.com.br +CORS_METHODS=POST,GET,PUT,DELETE +CORS_CREDENTIALS=true +``` + +## 7. Comandos Úteis de Manutenção + +### Verificar status dos serviços + +```bash +# Status do Nginx +sudo systemctl status nginx + +# Status do Docker +sudo docker ps + +# Status da Evolution API +sudo docker logs evolution_api +``` + +### Reiniciar serviços + +```bash +# Reiniciar Nginx +sudo systemctl restart nginx + +# Reiniciar Evolution API +sudo docker-compose restart + +# Recarregar configuração Nginx (sem interrupção) +sudo nginx -s reload +``` + +### Logs e Monitoramento + +```bash +# Ver logs do Nginx +sudo tail -f /var/log/nginx/evolution-api-access.log +sudo tail -f /var/log/nginx/evolution-api-error.log + +# Ver logs da Evolution API +sudo docker logs -f evolution_api +``` + +## 8. Backup da Configuração + +Sempre faça backup das configurações importantes: + +```bash +# Criar diretório de backup +sudo mkdir -p /root/backup/nginx + +# Backup da configuração do Nginx +sudo cp /etc/nginx/sites-available/evo.se7esistemassinop.com.br /root/backup/nginx/ + +# Backup do docker-compose +cp docker-compose.yaml /root/backup/ + +# Backup do .env (cuidado com dados sensíveis) +cp .env /root/backup/env.backup +``` + +## 9. Resolução de Problemas + +### Erro 502 Bad Gateway + +```bash +# Verificar se Evolution API está rodando +sudo docker ps + +# Verificar logs +sudo docker logs evolution_api + +# Reiniciar container +sudo docker-compose restart +``` + +### Erro de SSL + +```bash +# Testar certificados +sudo certbot certificates + +# Forçar renovação +sudo certbot renew --force-renewal +``` + +### Verificar conectividade + +```bash +# Testar conexão local +curl -I http://127.0.0.1:8080 + +# Testar HTTPS +curl -I https://evo.se7esistemassinop.com.br +``` + +## 10. Segurança Adicional + +### Limitar acesso por IP (opcional) + +Adicione no bloco `server` do Nginx: + +```nginx +# Permitir apenas IPs específicos +allow 192.168.1.0/24; +deny all; +``` + +### Rate Limiting + +Adicione na configuração do Nginx: + +```nginx +# No bloco http +http { + limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; + + # No bloco server + server { + limit_req zone=api burst=20 nodelay; + } +} +``` + +## Contatos e Suporte + +- **Site oficial:** https://doc.evolution-api.com +- **Repositório:** https://github.com/EvolutionAPI/evolution-api +- **Domínio atual:** https://evo.se7esistemassinop.com.br + +--- + +**Nota:** Este manual foi criado especificamente para o domínio `evo.se7esistemassinop.com.br`. Adapte os nomes de domínio conforme necessário para sua instalação. + +**Versão do manual:** 1.0 +**Data:** $(date) +**Evolution API versão:** 2.3.1 diff --git a/docs/scan_qrcode/CONFIGURATION.md b/docs/scan_qrcode/CONFIGURATION.md new file mode 100644 index 000000000..8d70572b8 --- /dev/null +++ b/docs/scan_qrcode/CONFIGURATION.md @@ -0,0 +1,850 @@ +# QR Code Scanning - Configuração Completa + +Este documento detalha todas as configurações disponíveis para o sistema de QR Code scanning do Evolution API. + +## 📋 Sumário + +1. [Variáveis de Ambiente](#variáveis-de-ambiente) +2. [Configurações do Banco de Dados](#configurações-do-banco-de-dados) +3. [Configurações de Autenticação](#configurações-de-autenticação) +4. [Configurações do QR Code](#configurações-do-qr-code) +5. [Configurações de Cache](#configurações-de-cache) +6. [Configurações de Webhook](#configurações-de-webhook) +7. [Configurações de Rate Limiting](#configurações-de-rate-limiting) +8. [Configurações de Interface](#configurações-de-interface) +9. [Configurações Avançadas](#configurações-avançadas) +10. [Validação de Configurações](#validação-de-configurações) + +## 🌍 Variáveis de Ambiente + +### **Configurações Principais** + +```env +# ======================================== +# CONFIGURAÇÕES GERAIS DO SISTEMA +# ======================================== + +# URL do servidor (importante para webhooks) +SERVER_URL=http://localhost:8080 + +# Porta do servidor +SERVER_PORT=8080 + +# Ambiente (development, production, test) +NODE_ENV=development + +# Recarregar automaticamente (development) +AUTO_RELOAD=false + +# ======================================== +# AUTENTICAÇÃO E SEGURANÇA +# ======================================== + +# API Key principal para autenticação +AUTHENTICATION_API_KEY=BQYHJGJHJ1234567890ABCDEF + +# Tipo de autenticação (apikey ou jwt) +AUTHENTICATION_TYPE=apikey + +# Tempo de expiração do token (em segundos) +AUTHENTICATION_TOKEN_EXPIRY=3600 + +# ======================================== +# CONFIGURAÇÕES DO QR CODE +# ======================================== + +# Número máximo de QR codes por instância +QRCODE_LIMIT=30 + +# Cor do QR code (formato hexadecimal) +QRCODE_COLOR=#22c55e + +# Timeout para geração de QR code (em milissegundos) +QRCODE_TIMEOUT=45000 + +# Intervalo de atualização do QR code (em segundos) +QRCODE_REFRESH_INTERVAL=30 + +# ======================================== +# CONFIGURAÇÕES DA SESSÃO WHATSAPP +# ======================================== + +# Nome do cliente para identificação no WhatsApp +CONFIG_SESSION_PHONE_CLIENT=Evolution API + +# Nome do navegador para simulação +CONFIG_SESSION_PHONE_NAME=Chrome + +# ======================================== +# CONFIGURAÇÕES DE LOGGING +# ======================================== + +# Nível de log (error, warn, info, debug, trace) +LOG_LEVEL=info + +# Logs específicos do Baileys +LOG_BAILEYS=error + +# Salvar logs no arquivo +LOG_SAVE=true + +# Diretório dos logs +LOG_DIR=logs + +# ======================================== +# CONFIGURAÇÕES DE CORS +# ======================================== + +# Origens permitidas (separadas por vírgula) +CORS_ORIGIN=* + +# Métodos HTTP permitidos +CORS_METHODS=GET,POST,PUT,DELETE,OPTIONS + +# Headers permitidos +CORS_ALLOWED_HEADERS=Content-Type,Authorization,apikey +``` + +### **Configurações de Database** + +```env +# ======================================== +# CONFIGURAÇÕES DO BANCO DE DADOS +# ======================================== + +# Provedor do banco (postgresql ou mysql) +DATABASE_PROVIDER=postgresql + +# PostgreSQL +DATABASE_CONNECTION_HOST=localhost +DATABASE_CONNECTION_PORT=5432 +DATABASE_CONNECTION_DATABASE=evolution_api +DATABASE_CONNECTION_USERNAME=postgres +DATABASE_CONNECTION_PASSWORD=password +DATABASE_CONNECTION_SSL=false +DATABASE_CONNECTION_SSL_KEY= +DATABASE_CONNECTION_SSL_CERT= +DATABASE_CONNECTION_SSL_CA= + +# MySQL (alternativa) +# DATABASE_CONNECTION_HOST=localhost +# DATABASE_CONNECTION_PORT=3306 +# DATABASE_CONNECTION_DATABASE=evolution_api +# DATABASE_CONNECTION_USERNAME=root +# DATABASE_CONNECTION_PASSWORD=password + +# Pool de conexões +DATABASE_CONNECTION_POOL_MIN=2 +DATABASE_CONNECTION_POOL_MAX=10 +DATABASE_CONNECTION_POOL_IDLE=30000 +DATABASE_CONNECTION_POOL_ACQUIRE=60000 + +# Salvar dados no banco +DATABASE_SAVE_DATA_INSTANCE=true +DATABASE_SAVE_DATA_NEW_MESSAGE=true +DATABASE_SAVE_DATA_MESSAGE_UPDATE=true +DATABASE_SAVE_DATA_CONTACTS=true +DATABASE_SAVE_DATA_CHATS=true +``` + +### **Configurações de Cache** + +```env +# ======================================== +# CONFIGURAÇÕES DE CACHE +# ======================================== + +# Redis (recomendado para produção) +CACHE_REDIS_ENABLED=false +CACHE_REDIS_HOST=localhost +CACHE_REDIS_PORT=6379 +CACHE_REDIS_PASSWORD= +CACHE_REDIS_DB=0 +CACHE_REDIS_SAVE_INSTANCES=true + +# Cache local (fallback) +CACHE_LOCAL_ENABLED=true +CACHE_LOCAL_TTL=3600 + +# Configurações específicas +CACHE_MESSAGE_TTL=300 +CACHE_CONTACT_TTL=3600 +CACHE_CHAT_TTL=1800 +CACHE_QRCODE_TTL=60 +``` + +### **Configurações de Webhook** + +```env +# ======================================== +# CONFIGURAÇÕES DE WEBHOOK +# ======================================== + +# Webhook global +WEBHOOK_GLOBAL_ENABLED=false +WEBHOOK_GLOBAL_URL=https://your-webhook-url.com/webhook +WEBHOOK_GLOBAL_WEBHOOK_HEADERS={"Authorization": "Bearer your-token"} + +# Eventos de webhook +WEBHOOK_EVENTS_APPLICATION_STARTUP=true +WEBHOOK_EVENTS_INSTANCE_CREATE=true +WEBHOOK_EVENTS_INSTANCE_DELETE=true +WEBHOOK_EVENTS_QRCODE_UPDATED=true +WEBHOOK_EVENTS_CONNECTION_UPDATE=true +WEBHOOK_EVENTS_MESSAGES_SET=true +WEBHOOK_EVENTS_MESSAGES_UPSERT=true +WEBHOOK_EVENTS_MESSAGES_EDITED=true +WEBHOOK_EVENTS_MESSAGES_UPDATE=true +WEBHOOK_EVENTS_MESSAGES_DELETE=true +WEBHOOK_EVENTS_SEND_MESSAGE=true +WEBHOOK_EVENTS_CONTACTS_SET=true +WEBHOOK_EVENTS_CONTACTS_UPSERT=true +WEBHOOK_EVENTS_PRESENCE_UPDATE=true +WEBHOOK_EVENTS_CHATS_SET=true +WEBHOOK_EVENTS_CHATS_UPSERT=true +WEBHOOK_EVENTS_CHATS_UPDATE=true +WEBHOOK_EVENTS_CHATS_DELETE=true +WEBHOOK_EVENTS_GROUPS_UPSERT=true +WEBHOOK_EVENTS_GROUPS_UPDATE=true +WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true + +# Configurações avançadas +WEBHOOK_WEBHOOK_BY_EVENTS=false +WEBHOOK_WEBHOOK_BASE64=false +``` + +## 🗄️ Configurações do Banco de Dados + +### **PostgreSQL Schema** + +```sql +-- Configurações específicas para PostgreSQL +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +-- Tabela de instâncias +CREATE TABLE "Instance" ( + "id" UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + "name" VARCHAR(255) UNIQUE NOT NULL, + "integration" VARCHAR(50), + "token" VARCHAR(255), + "connectionStatus" VARCHAR(50) DEFAULT 'close', + "ownerJid" VARCHAR(255), + "profileName" VARCHAR(255), + "profilePicUrl" TEXT, + "number" VARCHAR(50), + "businessId" VARCHAR(255), + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Índices para performance +CREATE INDEX idx_instance_name ON "Instance"(name); +CREATE INDEX idx_instance_connection_status ON "Instance"(connectionStatus); +``` + +### **MySQL Schema** + +```sql +-- Configurações específicas para MySQL +CREATE TABLE `Instance` ( + `id` VARCHAR(36) PRIMARY KEY DEFAULT (UUID()), + `name` VARCHAR(255) UNIQUE NOT NULL, + `integration` VARCHAR(50), + `token` VARCHAR(255), + `connectionStatus` VARCHAR(50) DEFAULT 'close', + `ownerJid` VARCHAR(255), + `profileName` VARCHAR(255), + `profilePicUrl` TEXT, + `number` VARCHAR(50), + `businessId` VARCHAR(255), + `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +); + +-- Índices para performance +CREATE INDEX idx_instance_name ON `Instance`(name); +CREATE INDEX idx_instance_connection_status ON `Instance`(connectionStatus); +``` + +## 🔐 Configurações de Autenticação + +### **API Key Configuration** + +```typescript +// Configuração no arquivo .env +AUTHENTICATION_API_KEY=your-secure-api-key-here + +// Validação da API key +const validateApiKey = (providedKey: string): boolean => { + const validKey = process.env.AUTHENTICATION_API_KEY; + return providedKey === validKey && validKey !== 'BQYHJGJHJ'; +}; +``` + +### **Token de Sessão (Segurança Extra)** + +```typescript +// Configurações de token temporário +const TOKEN_CONFIG = { + expiry: 3600 * 1000, // 1 hora em milissegundos + algorithm: 'HS256', // Algoritmo para assinatura + secret: process.env.TOKEN_SECRET || 'fallback-secret' +}; + +// Geração de token seguro +const generateSessionToken = (): string => { + return crypto.randomBytes(32).toString('hex'); +}; +``` + +## 📱 Configurações do QR Code + +### **Configurações de Geração** + +```typescript +// Configurações do QR Code +export const QRCODE_CONFIG = { + // Limite de QR codes por instância + LIMIT: parseInt(process.env.QRCODE_LIMIT) || 30, + + // Cor do QR code + COLOR: process.env.QRCODE_COLOR || '#22c55e', + + // Configurações de geração + OPTIONS: { + margin: 3, + scale: 4, + errorCorrectionLevel: 'H', // Alto nível de correção + color: { + light: '#ffffff', // Cor de fundo + dark: process.env.QRCODE_COLOR || '#22c55e' // Cor do QR code + } + }, + + // Timeouts + TIMEOUT: parseInt(process.env.QRCODE_TIMEOUT) || 45000, + REFRESH_INTERVAL: parseInt(process.env.QRCODE_REFRESH_INTERVAL) || 30, +}; +``` + +### **Configurações de Display** + +```css +/* CSS para o container do QR code */ +.qr-code-container { + width: 256px; /* 256x256 pixels */ + height: 256px; + margin: 0 auto; + border: 2px solid #e5e7eb; + border-radius: 12px; + background: white; + display: flex; + align-items: center; + justify-content: center; +} + +/* Loading spinner */ +.qr-loading { + width: 48px; + height: 48px; + border: 4px solid #f3f4f6; + border-top: 4px solid #22c55e; + border-radius: 50%; + animation: spin 1s linear infinite; +} + +@keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } +} +``` + +## 💾 Configurações de Cache + +### **Redis Configuration** + +```env +# Redis para cache distribuído +CACHE_REDIS_ENABLED=true +CACHE_REDIS_HOST=localhost +CACHE_REDIS_PORT=6379 +CACHE_REDIS_PASSWORD=your-redis-password +CACHE_REDIS_DB=0 +CACHE_REDIS_SAVE_INSTANCES=true + +# TTL específico para QR codes +CACHE_QRCODE_TTL=60 +``` + +### **Cache Keys Pattern** + +```javascript +// Padrão de chaves de cache +const CACHE_KEYS = { + INSTANCE: 'instance:{instanceName}', + QRCODE: 'qrcode:{instanceName}', + CONNECTION_STATE: 'connection:{instanceName}', + PROFILE: 'profile:{instanceName}', + WEBHOOK: 'webhook:{instanceName}' +}; + +// Função para gerar chave +const getCacheKey = (pattern, params) => { + return pattern.replace(/{(\w+)}/g, (match, key) => params[key]); +}; +``` + +## 🔗 Configurações de Webhook + +### **Webhook Events para QR Code** + +```typescript +// Eventos específicos de QR code +const QRCODE_EVENTS = { + QRCODE_UPDATED: 'qrcode.updated', + CONNECTION_UPDATE: 'connection.update', + INSTANCE_CREATE: 'instance.create', + INSTANCE_DELETE: 'instance.delete' +}; + +// Payload do webhook +const webhookPayload = { + event: 'qrcode.updated', + instanceName: 'minha-instancia', + timestamp: new Date().toISOString(), + data: { + qrcode: { + code: '2@ABC123...', + base64: 'data:image/png;base64,...', + count: 1 + }, + connectionStatus: 'connecting' + } +}; +``` + +### **Configuração de Headers** + +```env +# Headers personalizados para webhook +WEBHOOK_GLOBAL_WEBHOOK_HEADERS={ + "Authorization": "Bearer your-webhook-token", + "Content-Type": "application/json", + "User-Agent": "Evolution-API/2.0" +} +``` + +## ⏱️ Configurações de Rate Limiting + +### **Rate Limiting para QR Code** + +```typescript +// Configuração de rate limiting +const RATE_LIMIT_CONFIG = { + windowMs: 60 * 1000, // 1 minuto + max: 10, // 10 tentativas por minuto + message: { + error: 'Too many requests', + message: 'Rate limit exceeded. Try again later.', + retryAfter: 60 + }, + standardHeaders: true, + legacyHeaders: false, +}; + +// Aplicar rate limiting por endpoint +const createRateLimit = (maxRequests = 10) => { + return rateLimit({ + windowMs: RATE_LIMIT_CONFIG.windowMs, + max: maxRequests, + message: RATE_LIMIT_CONFIG.message, + standardHeaders: RATE_LIMIT_CONFIG.standardHeaders, + legacyHeaders: RATE_LIMIT_CONFIG.legacyHeaders, + }); +}; +``` + +### **Rate Limiting por IP** + +```javascript +// Middleware de rate limiting por IP +const rateLimitByIP = (req, res, next) => { + const clientIP = req.ip || req.connection.remoteAddress; + const now = Date.now(); + const windowStart = now - RATE_LIMIT_CONFIG.windowMs; + + // Limpar IPs antigos + rateLimitMap = rateLimitMap.filter(entry => entry.resetTime > windowStart); + + // Verificar limite do IP atual + let ipEntry = rateLimitMap.find(entry => entry.ip === clientIP); + + if (!ipEntry) { + ipEntry = { ip: clientIP, count: 0, resetTime: now + RATE_LIMIT_CONFIG.windowMs }; + rateLimitMap.push(ipEntry); + } + + if (ipEntry.count >= RATE_LIMIT_CONFIG.max) { + return res.status(429).json(RATE_LIMIT_CONFIG.message); + } + + ipEntry.count++; + next(); +}; +``` + +## 🎨 Configurações de Interface + +### **Configurações de Tema** + +```javascript +// Configuração de tema +const THEME_CONFIG = { + default: 'light', // Tema padrão + colors: { + primary: { + light: '#22c55e', // Verde Evolution + dark: '#16a34a' // Verde mais escuro + }, + success: '#10b981', + error: '#ef4444', + warning: '#f59e0b', + info: '#3b82f6' + }, + fonts: { + title: ['Lato', 'system-ui', 'sans-serif'], + body: ['Open Sans', 'system-ui', 'sans-serif'] + } +}; +``` + +### **Configurações de Responsividade** + +```css +/* Breakpoints para responsividade */ +.mobile-first { + /* Mobile (default) */ + max-width: 767px; +} + +.tablet { + /* Tablet */ + min-width: 768px; + max-width: 1023px; +} + +.desktop { + /* Desktop */ + min-width: 1024px; +} + +/* Container responsivo */ +.qr-container { + width: 100%; + max-width: 400px; + margin: 0 auto; + padding: 1rem; +} + +@media (min-width: 768px) { + .qr-container { + max-width: 500px; + padding: 2rem; + } +} +``` + +## ⚙️ Configurações Avançadas + +### **Configurações de Proxy** + +```env +# Proxy para conexões WhatsApp +PROXY_ENABLED=false +PROXY_HOST=your-proxy-host.com +PROXY_PORT=3128 +PROXY_PROTOCOL=http +PROXY_USERNAME=your-username +PROXY_PASSWORD=your-password + +# Lista de proxies (para rotação) +PROXY_LIST_URL=https://your-proxy-list-url.com/proxies.txt +``` + +### **Configurações de SSL/HTTPS** + +```env +# Configurações SSL +SSL_ENABLED=false +SSL_KEY_PATH=/path/to/private-key.pem +SSL_CERT_PATH=/path/to/certificate.pem +SSL_CA_PATH=/path/to/ca-certificate.pem + +# Configurações HSTS +HSTS_ENABLED=true +HSTS_MAX_AGE=31536000 +``` + +### **Configurações de Performance** + +```env +# Configurações de performance +PERFORMANCE_MAX_INSTANCES=100 +PERFORMANCE_MAX_CONNECTIONS_PER_INSTANCE=10 +PERFORMANCE_CLEANUP_INTERVAL=300000 + +# Configurações de garbage collection +GC_INTERVAL=30000 +GC_THRESHOLD=100 +``` + +## ✅ Validação de Configurações + +### **Script de Validação** + +```bash +#!/bin/bash +# validate-config.sh - Valida configurações do sistema + +echo "=== Validação de Configurações ===" + +# 1. Verificar API Key +echo -n "1. API Key: " +if [ -n "$AUTHENTICATION_API_KEY" ] && [ "$AUTHENTICATION_API_KEY" != "BQYHJGJHJ" ]; then + echo "✅ OK" +else + echo "❌ NÃO CONFIGURADA" +fi + +# 2. Verificar Banco de Dados +echo -n "2. Database: " +if [ "$DATABASE_PROVIDER" = "postgresql" ]; then + if pg_isready -h "$DATABASE_CONNECTION_HOST" -p "$DATABASE_CONNECTION_PORT" 2>/dev/null; then + echo "✅ PostgreSQL OK" + else + echo "❌ PostgreSQL OFFLINE" + fi +elif [ "$DATABASE_PROVIDER" = "mysql" ]; then + if mysqladmin ping -h "$DATABASE_CONNECTION_HOST" -u "$DATABASE_CONNECTION_USERNAME" -p"$DATABASE_CONNECTION_PASSWORD" --silent; then + echo "✅ MySQL OK" + else + echo "❌ MySQL OFFLINE" + fi +else + echo "❌ Provider inválido: $DATABASE_PROVIDER" +fi + +# 3. Verificar Redis (se habilitado) +if [ "$CACHE_REDIS_ENABLED" = "true" ]; then + echo -n "3. Redis: " + if redis-cli -h "$CACHE_REDIS_HOST" -p "$CACHE_REDIS_PORT" ping >/dev/null 2>&1; then + echo "✅ OK" + else + echo "❌ OFFLINE" + fi +else + echo "3. Redis: ❌ DESABILITADO" +fi + +# 4. Verificar Porta +echo -n "4. Porta $SERVER_PORT: " +if netstat -tln | grep ":$SERVER_PORT " >/dev/null 2>&1; then + echo "❌ OCUPADA" +else + echo "✅ LIVRE" +fi + +# 5. Verificar Permissões +echo -n "5. Permissões: " +if [ -w "public/qrcode" ]; then + echo "✅ OK" +else + echo "❌ SEM PERMISSÃO" +fi + +echo "=== Validação Concluída ===" +``` + +### **Validação Programática** + +```typescript +// Validação de configurações no código +export class ConfigValidator { + static validate(): { valid: boolean; errors: string[] } { + const errors: string[] = []; + + // Validar API Key + if (!process.env.AUTHENTICATION_API_KEY || + process.env.AUTHENTICATION_API_KEY === 'BQYHJGJHJ') { + errors.push('AUTHENTICATION_API_KEY deve ser configurada com um valor seguro'); + } + + // Validar Database + if (!['postgresql', 'mysql'].includes(process.env.DATABASE_PROVIDER)) { + errors.push('DATABASE_PROVIDER deve ser postgresql ou mysql'); + } + + // Validar Porta + const port = parseInt(process.env.SERVER_PORT); + if (isNaN(port) || port < 1 || port > 65535) { + errors.push('SERVER_PORT deve ser um número entre 1 e 65535'); + } + + // Validar URL + if (!process.env.SERVER_URL || !this.isValidUrl(process.env.SERVER_URL)) { + errors.push('SERVER_URL deve ser uma URL válida'); + } + + return { + valid: errors.length === 0, + errors + }; + } + + private static isValidUrl(url: string): boolean { + try { + new URL(url); + return true; + } catch { + return false; + } + } +} +``` + +## 🚀 Configurações de Produção + +### **Configuração para Produção** + +```env +# ======================================== +# CONFIGURAÇÕES DE PRODUÇÃO +# ======================================== + +# Ambiente +NODE_ENV=production + +# Servidor +SERVER_URL=https://your-domain.com +SERVER_PORT=8080 + +# SSL +SSL_ENABLED=true +SSL_KEY_PATH=/etc/ssl/private/your-key.pem +SSL_CERT_PATH=/etc/ssl/certs/your-cert.pem + +# Database (PostgreSQL recomendado) +DATABASE_PROVIDER=postgresql +DATABASE_CONNECTION_HOST=localhost +DATABASE_CONNECTION_PORT=5432 +DATABASE_CONNECTION_DATABASE=evolution_prod +DATABASE_CONNECTION_USERNAME=evolution_user +DATABASE_CONNECTION_PASSWORD=strong_password_here +DATABASE_CONNECTION_SSL=true + +# Cache Redis +CACHE_REDIS_ENABLED=true +CACHE_REDIS_HOST=localhost +CACHE_REDIS_PORT=6379 +CACHE_REDIS_PASSWORD=redis_password_here + +# Logs +LOG_LEVEL=warn +LOG_SAVE=true +LOG_DIR=/var/log/evolution + +# Rate Limiting mais restritivo +QRCODE_LIMIT=10 + +# CORS restritivo +CORS_ORIGIN=https://your-frontend-domain.com + +# Webhook +WEBHOOK_GLOBAL_ENABLED=true +WEBHOOK_GLOBAL_URL=https://your-app.com/webhook + +# Performance +PERFORMANCE_MAX_INSTANCES=1000 +``` + +### **Configuração para Desenvolvimento** + +```env +# ======================================== +# CONFIGURAÇÕES DE DESENVOLVIMENTO +# ======================================== + +# Ambiente +NODE_ENV=development +AUTO_RELOAD=true + +# Servidor +SERVER_URL=http://localhost:8080 +SERVER_PORT=8080 + +# Database +DATABASE_PROVIDER=postgresql +DATABASE_CONNECTION_HOST=localhost +DATABASE_CONNECTION_PORT=5432 +DATABASE_CONNECTION_DATABASE=evolution_dev +DATABASE_CONNECTION_USERNAME=postgres +DATABASE_CONNECTION_PASSWORD=password + +# Cache (desabilitado para desenvolvimento) +CACHE_REDIS_ENABLED=false +CACHE_LOCAL_ENABLED=true + +# Logs detalhados +LOG_LEVEL=debug +LOG_BAILEYS=debug + +# Rate Limiting mais permissivo +QRCODE_LIMIT=100 + +# CORS permissivo +CORS_ORIGIN=* + +# Sem SSL +SSL_ENABLED=false +``` + +## 📊 Monitoramento de Configurações + +### **Endpoint de Status** + +```typescript +// Endpoint para verificar configurações +app.get('/config/status', (req, res) => { + const configStatus = { + timestamp: new Date().toISOString(), + environment: process.env.NODE_ENV, + database: { + provider: process.env.DATABASE_PROVIDER, + connected: checkDatabaseConnection(), + instances: getInstanceCount() + }, + cache: { + redis: process.env.CACHE_REDIS_ENABLED === 'true' ? 'enabled' : 'disabled', + connected: checkRedisConnection() + }, + qrcode: { + limit: process.env.QRCODE_LIMIT, + color: process.env.QRCODE_COLOR, + generated: getQRCodesGenerated() + }, + performance: { + uptime: process.uptime(), + memory: process.memoryUsage(), + instances: getActiveInstances() + } + }; + + res.json(configStatus); +}); +``` + +--- + +**Evolution API** - QR Code Configuration +Versão: 2.0.0 +Data: 2025 diff --git a/docs/scan_qrcode/IMPLEMENTACAO-FORK.md b/docs/scan_qrcode/IMPLEMENTACAO-FORK.md new file mode 100644 index 000000000..7dbade8c6 --- /dev/null +++ b/docs/scan_qrcode/IMPLEMENTACAO-FORK.md @@ -0,0 +1,379 @@ +# Implementação para Forks - Guia Prático + +Este documento fornece um guia passo-a-passo para implementar o sistema de QR Code scanning do Evolution API em outros projetos/forks. + +## 🎯 Objetivo + +O objetivo desta documentação é permitir que qualquer desenvolvedor implemente uma interface de QR Code similar ao Evolution API em seu próprio projeto, com: + +- ✅ Interface web responsiva +- ✅ Sistema de autenticação seguro +- ✅ Integração com WhatsApp via Baileys +- ✅ Logs em tempo real +- ✅ Gestão de perfil +- ✅ Sistema de rate limiting + +## 📁 Arquivos Necessários + +### **Frontend (Interface Web)** +``` +/public/qrcode/index.html # Interface principal +/public/qrcode/ # Assets estáticos (CSS, JS, imagens) +``` + +### **Backend (API)** +``` +/src/api/routes/qrcode.router.ts # Rotas da API +/src/api/controllers/instance.controller.ts # Controller de instâncias +/src/api/services/monitor.service.ts # Monitor de conexões +``` + +### **Configurações** +``` +/src/config/env.config.ts # Configurações do sistema +/.env # Variáveis de ambiente +``` + +## 🚀 Implementação Passo-a-Passo + +### **Passo 1: Configurar Frontend** + +```html + +mkdir -p public/qrcode + + +cp /path/to/evolution-api/public/qrcode/index.html public/qrcode/ + + +npm install qrcode tailwindcss express +``` + +### **Passo 2: Configurar Backend** + +```typescript +// 1. Criar arquivo de rotas +// src/routes/qrcode.router.ts +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { ConfigService } from '@config/env.config'; + +export class QrcodeRouter extends RouterBroker { + constructor( + readonly configService: ConfigService, + ...guards: RequestHandler[] + ) { + super(); + + // Rota principal - serve interface HTML + this.router.get('/', (req, res) => { + const qrcodeHtmlPath = path.join(process.cwd(), 'public', 'qrcode', 'index.html'); + res.sendFile(qrcodeHtmlPath); + }); + + // Conectar WhatsApp + this.router.get('/connect/:instanceName', ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: null, + ClassRef: InstanceDto, + execute: () => instanceController.connectToWhatsapp({ + instanceName: req.params.instanceName + }), + }); + res.json(response); + }); + } +} +``` + +### **Passo 3: Configurar Serviço WhatsApp** + +```typescript +// Implementar métodos necessários +export class WhatsAppService { + async connectToWhatsapp(instanceName: string) { + // 1. Verificar se instância existe + const instance = this.getInstance(instanceName); + if (!instance) { + throw new Error('Instância não encontrada'); + } + + // 2. Iniciar conexão Baileys + const client = new Client({ + authStrategy: new LocalAuth({ clientId: instanceName }), + puppeteer: { headless: true } + }); + + // 3. Gerar QR code + client.on('qr', (qr) => { + // Converter QR para base64 + qrcode.toDataURL(qr, (err, url) => { + instance.qrCode = { + code: qr, + base64: url, + count: (instance.qrCode?.count || 0) + 1 + }; + }); + }); + + // 4. Monitorar conexão + client.on('ready', () => { + instance.connectionStatus = 'open'; + }); + + await client.initialize(); + + return instance.qrCode; + } + + async getConnectionState(instanceName: string) { + const instance = this.getInstance(instanceName); + return { + instance: { + instanceName, + state: instance?.connectionStatus || 'close' + } + }; + } +} +``` + +### **Passo 4: Configurar Autenticação** + +```typescript +// Sistema de autenticação seguro +class AuthService { + async validateApiKey(providedKey: string): Promise { + const validKey = process.env.AUTHENTICATION_API_KEY; + return providedKey === validKey && validKey !== 'BQYHJGJHJ'; + } + + generateSessionToken(): string { + return crypto.randomBytes(32).toString('hex'); + } +} + +// Middleware de autenticação +const authMiddleware = async (req, res, next) => { + const apiKey = req.headers.apikey; + + if (!apiKey || !await authService.validateApiKey(apiKey)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + next(); +}; +``` + +### **Passo 5: Configurar Rate Limiting** + +```typescript +// Rate limiting por IP +const rateLimitMap = new Map(); +const RATE_LIMIT_WINDOW = 60000; // 1 minuto +const RATE_LIMIT_MAX = 10; // 10 tentativas + +const rateLimitMiddleware = (req, res, next) => { + const clientIP = req.ip || req.connection.remoteAddress; + const now = Date.now(); + + let clientData = rateLimitMap.get(clientIP); + + if (!clientData || now > clientData.resetTime) { + rateLimitMap.set(clientIP, { + count: 1, + resetTime: now + RATE_LIMIT_WINDOW + }); + return next(); + } + + if (clientData.count >= RATE_LIMIT_MAX) { + return res.status(429).json({ + error: 'Rate limit exceeded', + retryAfter: Math.ceil((clientData.resetTime - now) / 1000) + }); + } + + clientData.count++; + next(); +}; +``` + +### **Passo 6: Configurar Banco de Dados** + +```sql +-- PostgreSQL +CREATE TABLE instances ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) UNIQUE NOT NULL, + connection_status VARCHAR(50) DEFAULT 'close', + profile_name VARCHAR(255), + profile_pic_url TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- MySQL +CREATE TABLE instances ( + id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()), + name VARCHAR(255) UNIQUE NOT NULL, + connection_status VARCHAR(50) DEFAULT 'close', + profile_name VARCHAR(255), + profile_pic_url TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +### **Passo 7: Configurar Variáveis de Ambiente** + +```env +# API +AUTHENTICATION_API_KEY=your-secure-api-key-here +SERVER_URL=http://localhost:8080 + +# Database +DATABASE_PROVIDER=postgresql +DATABASE_CONNECTION_HOST=localhost +DATABASE_CONNECTION_PORT=5432 +DATABASE_CONNECTION_DATABASE=evolution_api +DATABASE_CONNECTION_USERNAME=postgres +DATABASE_CONNECTION_PASSWORD=password + +# QR Code +QRCODE_LIMIT=30 +QRCODE_COLOR=#22c55e + +# WhatsApp +CONFIG_SESSION_PHONE_CLIENT=MyApp +CONFIG_SESSION_PHONE_NAME=Chrome +``` + +## 🎨 Personalização da Interface + +### **Alterar Cores** +```css +:root { + --primary-color: #your-brand-color; + --success-color: #10b981; + --error-color: #ef4444; +} +``` + +### **Alterar Logo** +```html + + +``` + +### **Alterar Textos** +```javascript +// Personalizar mensagens +const MESSAGES = { + title: "Conectar WhatsApp", + subtitle: "Escaneie o QR Code", + button: "Gerar QR Code", + connected: "Conectado!", + error: "Erro na conexão" +}; +``` + +## 🔧 Testando a Implementação + +### **1. Testar API** +```bash +# Verificar API key +curl http://localhost:8080/qrcode/api-key + +# Testar conexão +curl -H "apikey: your-api-key" \ + http://localhost:8080/qrcode/connect/test-instance +``` + +### **2. Testar Interface** +```bash +# Abrir no navegador +open http://localhost:8080/qrcode/ + +# Verificar logs +tail -f logs/app.log | grep -i qrcode +``` + +### **3. Testar WhatsApp** +```bash +# Verificar status +curl -H "apikey: your-api-key" \ + http://localhost:8080/qrcode/connectionState/test-instance + +# Fazer logout +curl -X DELETE -H "apikey: your-api-key" \ + http://localhost:8080/qrcode/logout/test-instance +``` + +## 🚨 Problemas Comuns + +### **1. QR Code não aparece** +- Verificar se JavaScript carregou +- Checar console do navegador +- Verificar se qrcode.min.js está acessível + +### **2. API Key inválida** +- Verificar variável AUTHENTICATION_API_KEY +- Checar se valor não é padrão "BQYHJGJHJ" +- Verificar headers da requisição + +### **3. Instância não encontrada** +- Criar instância antes de conectar +- Verificar nome da instância +- Checar banco de dados + +### **4. Rate limit** +- Aguardar 1 minuto entre tentativas +- Verificar configuração RATE_LIMIT_MAX +- Implementar retry com backoff + +## 📊 Monitoramento + +### **Logs Importantes** +```bash +# Logs de QR code +tail -f logs/app.log | grep -E "(qrcode|QR|connecting|open|close)" + +# Logs de erro +tail -f logs/app.log | grep -i error + +# Logs de performance +tail -f logs/app.log | grep -E "(memory|cpu|response)" +``` + +### **Métricas** +```typescript +// Endpoint de métricas +app.get('/metrics', (req, res) => { + res.json({ + uptime: process.uptime(), + instances: getInstanceCount(), + qrcodes: getQRCodesGenerated(), + errors: getErrorCount() + }); +}); +``` + +## 🎯 Próximos Passos + +1. **Testar em produção** com SSL e domínio +2. **Implementar WebSocket** para updates em tempo real +3. **Adicionar cache Redis** para performance +4. **Configurar monitoring** e alertas +5. **Documentar APIs específicas** do projeto + +## 📚 Referências + +- [Documentação Completa](README.md) +- [Configurações](CONFIGURATION.md) +- [Troubleshooting](TROUBLESHOOTING.md) +- [Casos de Uso](USE_CASES.md) + +--- + +**Implementação para Forks** - Evolution API QR Code System +Data: 2025 diff --git a/docs/scan_qrcode/README.md b/docs/scan_qrcode/README.md new file mode 100644 index 000000000..ee07677b1 --- /dev/null +++ b/docs/scan_qrcode/README.md @@ -0,0 +1,539 @@ +# QR Code Scanning - Evolution API + +Esta documentação detalha a implementação completa do sistema de QR Code scanning do Evolution API, incluindo frontend, backend, configurações e guias de implementação para forks. + +## 📋 Sumário + +1. [Visão Geral](#visão-geral) +2. [Arquitetura](#arquitetura) +3. [Frontend - Interface do Usuário](#frontend---interface-do-usuário) +4. [Backend - API Endpoints](#backend---api-endpoints) +5. [Serviço WhatsApp Baileys](#serviço-whatsapp-baileys) +6. [Configurações](#configurações) +7. [Fluxo de Conexão](#fluxo-de-conexão) +8. [Casos de Uso](#casos-de-uso) +9. [Troubleshooting](#troubleshooting) +10. [Implementação para Forks](#implementação-para-forks) + +## 🎯 Visão Geral + +O sistema de QR Code scanning do Evolution API permite que usuários conectem suas instâncias WhatsApp de forma simples e segura através de uma interface web responsiva. O sistema suporta: + +- ✅ Geração automática de QR codes +- ✅ Atualização em tempo real do status de conexão +- ✅ Interface responsiva com tema dark/light +- ✅ Sistema de logs em tempo real +- ✅ Gestão de perfil (nome, status, foto) +- ✅ Suporte a múltiplas instâncias +- ✅ Rate limiting de segurança +- ✅ Tutorial interativo para novos usuários + +## 🏗️ Arquitetura + +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ Frontend │ │ Backend │ │ WhatsApp API │ +│ (HTML/JS) │◄──►│ (Node.js) │◄──►│ (Baileys) │ +│ │ │ │ │ │ +│ - Interface Web │ │ - API Routes │ │ - QR Generation │ +│ - Real-time UI │ │ - Auth System │ │ - Connection │ +│ - Theme Toggle │ │ - Rate Limiting │ │ - Event System │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ +``` + +## 🎨 Frontend - Interface do Usuário + +### Localização dos Arquivos + +``` +/public/qrcode/index.html # Interface principal +/public/qrcode/ # Assets estáticos +/src/api/routes/qrcode.router.ts # Routes do backend +``` + +### Funcionalidades da Interface + +#### 1. **Formulário de Conexão** +- Campo para nome da instância +- Validação de caracteres (apenas letras, números, hífens e underscores) +- Botão "Gerar QR Code" com indicador visual + +#### 2. **Display do QR Code** +- Canvas HTML5 para renderização do QR code +- Spinner de carregamento animado +- Contador regressivo (30s) para atualização automática +- Status de conexão em tempo real + +#### 3. **Sistema de Logs** +- Logs em tempo real das operações +- Diferentes cores por tipo (info, success, error, warning) +- Contador de mensagens +- Scroll automático + +#### 4. **Gestão de Perfil** +- Visualização das informações do WhatsApp conectado +- Edição de nome e status +- Upload de foto de perfil +- Botões para reiniciar/desconectar + +#### 5. **Interface Adaptativa** +- Suporte a tema dark/light com toggle +- Design responsivo para mobile e desktop +- Tutorial interativo para novos usuários + +### Tecnologias Utilizadas + +```html + + + +``` + +## 🔧 Backend - API Endpoints + +### Routes Principais + +#### **GET /qrcode/** +Serve a interface HTML principal com headers de segurança. + +```typescript +// Headers de segurança implementados +res.setHeader('Content-Type', 'text/html; charset=utf-8'); +res.setHeader('X-Content-Type-Options', 'nosniff'); +res.setHeader('X-Frame-Options', 'DENY'); +res.setHeader('X-XSS-Protection', '1; mode=block'); +res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); +``` + +#### **GET /qrcode/api-key** +Verifica se a API key está configurada de forma segura (sem expor a chave). + +**Response:** +```json +{ + "configured": true, + "sessionToken": "abc123...", + "expiresIn": 3600 +} +``` + +#### **POST /qrcode/exchange-token** +Troca um token de sessão pela API key real (rate limited). + +**Request:** +```json +{ + "sessionToken": "abc123..." +} +``` + +**Response:** +```json +{ + "apiKey": "BQYHJGJHJ..." +} +``` + +#### **GET /qrcode/connect/:instanceName** +Inicia a conexão WhatsApp e gera o QR code. + +**Response:** +```json +{ + "code": "2@ABC123...", + "pairingCode": null, + "base64": "data:image/png;base64,iVBOR...", + "count": 1 +} +``` + +#### **GET /qrcode/connectionState/:instanceName** +Verifica o estado atual da conexão. + +**Response:** +```json +{ + "instance": { + "instanceName": "minha-instancia", + "state": "connecting" // connecting | open | close + } +} +``` + +#### **DELETE /qrcode/logout/:instanceName** +Desconecta a instância WhatsApp. + +#### **GET /qrcode/fetchInstances** +Busca informações da instância (perfil, estatísticas). + +#### **POST /qrcode/updateProfileName** +Atualiza o nome do perfil. + +#### **POST /qrcode/updateProfileStatus** +Atualiza o status do perfil. + +#### **POST /qrcode/updateProfilePicture** +Atualiza a foto do perfil. + +### Rate Limiting + +O sistema implementa rate limiting para proteger contra abuso: + +```typescript +const RATE_LIMIT_WINDOW = 60000; // 1 minuto +const RATE_LIMIT_MAX_REQUESTS = 10; // 10 requests por minuto +``` + +### Sistema de Autenticação + +O sistema usa um mecanismo de dois passos para autenticação: + +1. **Verificação segura**: `/api-key` retorna apenas se está configurado +2. **Troca de tokens**: Token temporário é trocado pela API key real +3. **Rate limiting**: Proteção contra força bruta + +## 📱 Serviço WhatsApp Baileys + +### Configuração do QR Code + +```typescript +// Configurações do QR Code (src/config/env.config.ts) +export type QrCode = { + LIMIT: number; // Máximo de QR codes por instância (padrão: 30) + COLOR: string; // Cor do QR code (padrão: '#198754') +}; + +// Opções de geração do QR Code +const optsQrcode: QRCodeToDataURLOptions = { + margin: 3, + scale: 4, + errorCorrectionLevel: 'H', + color: { + light: '#ffffff', + dark: color // Cor configurável + } +}; +``` + +### Fluxo de Conexão + +1. **Inicialização da Instância** + ```typescript + // Cria nova instância + const instance = channelController.init(instanceData, options); + ``` + +2. **Conexão WhatsApp** + ```typescript + // Conecta ao WhatsApp + await instance.connectToWhatsapp(number); + ``` + +3. **Geração do QR Code** + ```typescript + // Quando QR code é recebido + if (qr) { + this.instance.qrcode.count++; + qrcode.toDataURL(qr, optsQrcode, (error, base64) => { + this.instance.qrcode.base64 = base64; + this.instance.qrcode.code = qr; + }); + } + ``` + +4. **Monitoramento de Status** + ```typescript + // Estados possíveis + enum ConnectionState { + connecting = 'connecting', + open = 'open', + close = 'close' + } + ``` + +### Eventos Emitidos + +O sistema emite eventos através do EventEmitter2: + +```typescript +// Evento de QR code atualizado +this.sendDataWebhook(Events.QRCODE_UPDATED, { + qrcode: { + instance: this.instance.name, + pairingCode: this.instance.qrcode.pairingCode, + code: qr, + base64: base64 + } +}); +``` + +## ⚙️ Configurações + +### Variáveis de Ambiente + +```bash +# QR Code +QRCODE_LIMIT=30 # Máximo de QR codes por instância +QRCODE_COLOR=#198754 # Cor do QR code + +# Autenticação +AUTHENTICATION_API_KEY=BQYHJGJHJ # API Key para autenticação + +# Configurações de sessão +CONFIG_SESSION_PHONE_CLIENT=Evolution API +CONFIG_SESSION_PHONE_NAME=Chrome +``` + +### Configurações do Database + +O sistema suporta PostgreSQL e MySQL: + +```prisma +// Para PostgreSQL +model Instance { + id String @id @default(uuid()) + name String @unique + integration String? + token String? + connectionStatus String @default("close") + // ... outros campos +} + +// Para MySQL (adaptações necessárias) +model Instance { + id String @id @default(uuid()) + name String @unique + integration String? + token String? + connectionStatus String @default("close") + // ... outros campos +} +``` + +## 🔄 Fluxo de Conexão + +```mermaid +sequenceDiagram + participant U as Usuário + participant F as Frontend + participant B as Backend + participant W as WhatsApp + + U->>F: Digita nome da instância + U->>F: Clica "Gerar QR Code" + F->>B: GET /qrcode/connect/{instance} + B->>W: Inicia conexão Baileys + W->>B: QR Code gerado + B->>F: Retorna QR Code (base64) + F->>U: Exibe QR Code + U->>W: Escaneia QR Code no WhatsApp + W->>B: Confirma conexão + B->>F: Atualiza status (connecting -> open) + F->>U: Mostra perfil conectado +``` + +## 🎯 Casos de Uso + +### 1. **Primeira Conexão** +- Usuário cria nova instância +- Sistema gera QR code +- Usuário escaneia com WhatsApp +- Conexão estabelecida automaticamente + +### 2. **Reconexão** +- Instância desconectada +- Sistema detecta mudança de status +- QR code é regenerado automaticamente +- Usuário pode reconectar + +### 3. **Gestão de Múltiplas Instâncias** +- Interface permite alternar entre instâncias +- Cada instância tem QR code independente +- Logs separados por instância + +### 4. **Recuperação de Erro** +- Sistema detecta falhas de conexão +- QR code é regenerado automaticamente +- Rate limiting previne abuso + +## 🔍 Troubleshooting + +### Problemas Comuns + +#### **1. QR Code não é gerado** +```bash +# Verificar logs do backend +tail -f logs/evolution-api.log | grep -i qrcode + +# Verificar se a instância existe +curl -H "apikey: YOUR_API_KEY" http://localhost:8080/instance/fetchInstances +``` + +#### **2. API Key não configurada** +```bash +# Verificar variável de ambiente +echo $AUTHENTICATION_API_KEY + +# Configurar no .env +AUTHENTICATION_API_KEY=your_secure_api_key_here +``` + +#### **3. Rate limit atingido** +```bash +# Aguardar reset do rate limit (1 minuto) +# Ou verificar configuração no código +grep "RATE_LIMIT_MAX_REQUESTS" src/api/routes/qrcode.router.ts +``` + +#### **4. WhatsApp já conectado** +```bash +# Verificar status da conexão +curl -H "apikey: YOUR_API_KEY" http://localhost:8080/qrcode/connectionState/instance-name + +# Se conectado, fazer logout primeiro +curl -X DELETE -H "apikey: YOUR_API_KEY" http://localhost:8080/qrcode/logout/instance-name +``` + +### Logs de Debug + +```javascript +// Ativar logs detalhados +process.env.LOG_LEVEL=debug + +// Verificar logs específicos +grep "qrcode\|QR\|connection" logs/evolution-api.log +``` + +## 🚀 Implementação para Forks + +### 1. **Clonagem da Interface** + +```bash +# Copiar arquivos do frontend +cp -r public/qrcode/ your-project/public/ +cp src/api/routes/qrcode.router.ts your-project/src/api/routes/ +``` + +### 2. **Configuração do Backend** + +```typescript +// Adicionar rotas ao router principal +import { QrcodeRouter } from './routes/qrcode.router'; + +const qrcodeRouter = new QrcodeRouter(configService, ...guards); +app.use('/qrcode', qrcodeRouter.router); +``` + +### 3. **Configuração do WhatsApp Service** + +```typescript +// Implementar método connectToWhatsapp +export class YourWhatsAppService { + async connectToWhatsapp(instanceName: string) { + // Sua implementação aqui + return { + code: qrCodeString, + base64: base64Image, + count: 1 + }; + } + + async getConnectionState(instanceName: string) { + // Retornar estado da conexão + return { + instance: { + instanceName, + state: 'connecting' // connecting | open | close + } + }; + } +} +``` + +### 4. **Configuração de Segurança** + +```typescript +// Implementar rate limiting +const rateLimit = (req: Request, res: Response, next: NextFunction) => { + const clientIp = req.ip; + const now = Date.now(); + const windowMs = 60000; // 1 minute + const maxRequests = 10; + + // Sua lógica de rate limiting aqui +}; +``` + +### 5. **Template HTML Personalizável** + +```html + +:root { + --primary-color: #22c55e; /* Verde Evolution */ + --primary-hover: #16a34a; + --success-color: #10b981; + --error-color: #ef4444; +} + + + +``` + +### 6. **Integração com WebSocket (Opcional)** + +```typescript +// Para updates em tempo real +import { WebSocket } from 'ws'; + +export class QRCodeWebSocket { + private wss: WebSocket.Server; + + constructor(server: any) { + this.wss = new WebSocket.Server({ server }); + + this.wss.on('connection', (ws) => { + ws.on('message', (message) => { + // Handle WebSocket messages + }); + + // Emitir updates de QR code + this.emitQRCodeUpdate(ws, qrData); + }); + } +} +``` + +## 📝 Checklist de Implementação + +- [ ] Clonar arquivos do frontend (`public/qrcode/`) +- [ ] Configurar rotas do backend (`qrcode.router.ts`) +- [ ] Implementar serviço WhatsApp com QR code +- [ ] Configurar autenticação e rate limiting +- [ ] Personalizar interface (cores, logo, textos) +- [ ] Configurar variáveis de ambiente +- [ ] Testar fluxo completo de conexão +- [ ] Documentar endpoints específicos +- [ ] Implementar logs e monitoramento +- [ ] Configurar SSL/HTTPS para produção + +## 🔐 Considerações de Segurança + +1. **Rate Limiting**: Implementar para todos os endpoints +2. **CORS**: Configurar adequadamente para produção +3. **HTTPS**: Usar SSL em produção +4. **API Keys**: Nunca expor chaves no frontend +5. **Input Validation**: Validar todos os inputs +6. **Headers de Segurança**: Implementar headers HTTP de segurança + +## 📚 Referências Técnicas + +- [Baileys WhatsApp Web](https://github.com/WhiskeySockets/Baileys) +- [QRCode.js Library](https://github.com/soldair/node-qrcode) +- [Tailwind CSS](https://tailwindcss.com/) +- [Express.js Security](https://expressjs.com/en/advanced/best-practice-security.html) + +--- + +**Evolution API** - Sistema de QR Code Scanning +Versão: 2.0.0 +Data: 2025 diff --git a/docs/scan_qrcode/TROUBLESHOOTING.md b/docs/scan_qrcode/TROUBLESHOOTING.md new file mode 100644 index 000000000..3ac73d948 --- /dev/null +++ b/docs/scan_qrcode/TROUBLESHOOTING.md @@ -0,0 +1,679 @@ +# QR Code Scanning - Troubleshooting + +Este documento fornece soluções para problemas comuns encontrados na implementação do sistema de QR Code scanning do Evolution API. + +## 📋 Sumário + +1. [Problemas de Conexão](#problemas-de-conexão) +2. [QR Code não é Gerado](#qr-code-não-é-gerado) +3. [Problemas de Autenticação](#problemas-de-autenticação) +4. [Rate Limiting](#rate-limiting) +5. [Problemas de Interface](#problemas-de-interface) +6. [WhatsApp Connection Issues](#whatsapp-connection-issues) +7. [Database Problems](#database-problems) +8. [Logs e Debug](#logs-e-debug) +9. [Performance Issues](#performance-issues) +10. [Common Error Codes](#common-error-codes) + +## 🚨 Problemas de Conexão + +### **Erro: "Instance does not exist"** + +**Sintoma:** Ao tentar conectar, recebe erro de instância não encontrada. + +**Causas possíveis:** +- Nome da instância incorreto +- Instância ainda não foi criada +- Problema no banco de dados + +**Soluções:** + +1. **Verificar nome da instância:** + ```bash + # Listar instâncias existentes + curl -H "apikey: YOUR_API_KEY" http://localhost:8080/instance/fetchInstances + ``` + +2. **Criar instância se necessário:** + ```bash + curl -X POST http://localhost:8080/instance/create \ + -H "apikey: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "instanceName": "minha-instancia", + "integration": "WHATSAPP-BAILEYS" + }' + ``` + +3. **Verificar banco de dados:** + ```sql + -- PostgreSQL + SELECT * FROM "Instance" WHERE name = 'minha-instancia'; + + -- MySQL + SELECT * FROM `Instance` WHERE name = 'minha-instancia'; + ``` + +### **Erro: "Connection timeout"** + +**Sintoma:** QR code é gerado mas expira sem conexão. + +**Causas possíveis:** +- Problemas de rede +- Firewall bloqueando conexão +- WhatsApp Web detectou atividade suspeita + +**Soluções:** + +1. **Verificar conectividade:** + ```bash + # Testar conexão com WhatsApp servers + ping web.whatsapp.com + curl -I https://web.whatsapp.com/ + ``` + +2. **Ajustar timeout:** + ```typescript + // Em whatsapp.baileys.service.ts + connectTimeoutMs: 60_000, // Aumentar para 60s + qrTimeout: 60_000, // Aumentar para 60s + ``` + +3. **Verificar proxy (se usando):** + ```bash + # Testar proxy + curl -x http://your-proxy:port https://web.whatsapp.com/ + ``` + +## 📱 QR Code não é Gerado + +### **Erro: "QR Code not available"** + +**Sintoma:** Interface mostra "QR Code não disponível no momento". + +**Causas possíveis:** +- Instância em estado incorreto +- Problema na geração do QR code +- Limite de QR codes excedido + +**Soluções:** + +1. **Verificar estado da instância:** + ```bash + curl -H "apikey: YOUR_API_KEY" \ + http://localhost:8080/qrcode/connectionState/minha-instancia + ``` + +2. **Reiniciar instância:** + ```bash + # Fazer logout primeiro + curl -X DELETE -H "apikey: YOUR_API_KEY" \ + http://localhost:8080/qrcode/logout/minha-instancia + + # Tentar conectar novamente + curl -H "apikey: YOUR_API_KEY" \ + http://localhost:8080/qrcode/connect/minha-instancia + ``` + +3. **Verificar limite de QR codes:** + ```typescript + // Verificar configuração + QRCODE_LIMIT: 30 // Padrão + + // Resetar contador se necessário + instance.qrcode.count = 0; + ``` + +### **Erro: "Invalid QR code generated"** + +**Sintoma:** QR code gerado mas inválido. + +**Causas possíveis:** +- Problema na biblioteca qrcode +- Configurações incorretas do QR code + +**Soluções:** + +1. **Verificar instalação do qrcode:** + ```bash + npm list qrcode + # Deve mostrar versão 1.5.1 ou superior + ``` + +2. **Verificar configurações do QR code:** + ```typescript + const optsQrcode = { + margin: 3, + scale: 4, + errorCorrectionLevel: 'H', // Nível alto de correção + color: { + light: '#ffffff', + dark: '#198754' // Cor configurável + } + }; + ``` + +## 🔐 Problemas de Autenticação + +### **Erro: "API Key not configured"** + +**Sintoma:** Interface mostra erro de API key não configurada. + +**Causas possíveis:** +- Variável de ambiente não definida +- API key com valor padrão incorreto + +**Soluções:** + +1. **Verificar variável de ambiente:** + ```bash + # Verificar se está definida + echo $AUTHENTICATION_API_KEY + + # Configurar se necessário + export AUTHENTICATION_API_KEY="your-secure-api-key" + ``` + +2. **Atualizar arquivo .env:** + ```env + AUTHENTICATION_API_KEY=your-secure-api-key-here + AUTHENTICATION_TYPE=apikey + ``` + +3. **Verificar valor padrão incorreto:** + ```typescript + // Não usar valor padrão inseguro + API_KEY: process.env.AUTHENTICATION_API_KEY || 'BQYHJGJHJ' + ``` + +### **Erro: "Rate limit exceeded"** + +**Sintoma:** Muitas tentativas resultam em bloqueio temporário. + +**Causas possíveis:** +- Muitas tentativas de conexão +- Rate limiting muito restritivo + +**Soluções:** + +1. **Aguardar reset do rate limit:** + ```bash + # Aguardar 1 minuto (padrão) + sleep 60 + ``` + +2. **Ajustar rate limiting:** + ```typescript + const RATE_LIMIT_WINDOW = 60000; // 1 minuto + const RATE_LIMIT_MAX_REQUESTS = 10; // 10 tentativas + ``` + +3. **Implementar exponential backoff:** + ```javascript + function exponentialBackoff(attempt) { + const delay = Math.min(1000 * Math.pow(2, attempt), 30000); + return new Promise(resolve => setTimeout(resolve, delay)); + } + ``` + +## 🎨 Problemas de Interface + +### **Erro: "Error loading QR code page"** + +**Sintoma:** Página não carrega ou mostra erro 500. + +**Causas possíveis:** +- Arquivo HTML não encontrado +- Problemas de permissões +- Headers de segurança incorretos + +**Soluções:** + +1. **Verificar se arquivo existe:** + ```bash + ls -la public/qrcode/index.html + ``` + +2. **Verificar permissões:** + ```bash + chmod 644 public/qrcode/index.html + chown www-data:www-data public/qrcode/index.html # Se usando Apache + ``` + +3. **Verificar headers de segurança:** + ```typescript + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'DENY'); + ``` + +### **Erro: "QR Code not displaying"** + +**Sintoma:** Container do QR code aparece mas não mostra a imagem. + +**Causas possíveis:** +- JavaScript não carregou +- Problema na geração do canvas +- CSS ocultando o elemento + +**Soluções:** + +1. **Verificar se bibliotecas carregaram:** + ```html + + + ``` + +2. **Verificar CSS do canvas:** + ```css + #qrcodeCanvas { + display: block !important; + max-width: 100%; + height: auto; + } + ``` + +3. **Debug JavaScript:** + ```javascript + console.log('QRCode library loaded:', typeof QRCode); + console.log('Canvas element:', document.getElementById('qrcodeCanvas')); + ``` + +## 📶 WhatsApp Connection Issues + +### **Erro: "QR code expired"** + +**Sintoma:** QR code expira antes da leitura. + +**Causas possíveis:** +- Conexão lenta +- QR code muito complexo +- Problemas no WhatsApp Web + +**Soluções:** + +1. **Aumentar timeout:** + ```typescript + qrTimeout: 60_000, // 60 segundos + ``` + +2. **Simplificar QR code:** + ```typescript + const optsQrcode = { + margin: 2, // Reduzir margem + scale: 3, // Reduzir escala + errorCorrectionLevel: 'M' // Nível médio (ao invés de H) + }; + ``` + +3. **Verificar conectividade:** + ```bash + # Testar latência para WhatsApp + curl -w "@curl-format.txt" -o /dev/null -s "https://web.whatsapp.com/" + ``` + +### **Erro: "Phone number already connected"** + +**Sintoma:** WhatsApp já está conectado em outro lugar. + +**Causas possíveis:** +- Múltiplas sessões ativas +- WhatsApp Web aberto em outro navegador + +**Soluções:** + +1. **Logout de outras sessões:** + - Abrir WhatsApp no celular + - Configurações > Aparelhos conectados + - Desconectar outras sessões + +2. **Limpar cache local:** + ```bash + # Limpar cache do Baileys + rm -rf .wwebjs_cache/ + rm -rf .wwebjs_auth/ + ``` + +3. **Forçar nova autenticação:** + ```javascript + // No código + await instance.logoutInstance(); + await instance.connectToWhatsapp(); + ``` + +## 💾 Database Problems + +### **Erro: "Database connection failed"** + +**Sintoma:** Erro ao conectar com banco de dados. + +**Causas possíveis:** +- Configurações incorretas +- Banco não disponível +- Problemas de autenticação + +**Soluções:** + +1. **Verificar configurações:** + ```env + # PostgreSQL + DATABASE_PROVIDER=postgresql + DATABASE_CONNECTION_HOST=localhost + DATABASE_CONNECTION_PORT=5432 + DATABASE_CONNECTION_DATABASE=evolution_api + DATABASE_CONNECTION_USERNAME=postgres + DATABASE_CONNECTION_PASSWORD=password + + # MySQL + DATABASE_PROVIDER=mysql + DATABASE_CONNECTION_HOST=localhost + DATABASE_CONNECTION_PORT=3306 + DATABASE_CONNECTION_DATABASE=evolution_api + DATABASE_CONNECTION_USERNAME=root + DATABASE_CONNECTION_PASSWORD=password + ``` + +2. **Testar conexão:** + ```bash + # PostgreSQL + psql -h localhost -U postgres -d evolution_api + + # MySQL + mysql -h localhost -u root -p evolution_api + ``` + +3. **Verificar se banco está rodando:** + ```bash + # Docker + docker ps | grep postgres + docker ps | grep mysql + + # Sistema + systemctl status postgresql + systemctl status mysql + ``` + +### **Erro: "Migration failed"** + +**Sintoma:** Falha ao executar migrações. + +**Soluções:** + +1. **Resetar migrações:** + ```bash + # PostgreSQL + npm run db:migrate:reset:postgresql + + # MySQL + npm run db:migrate:reset:mysql + ``` + +2. **Limpar dados de teste:** + ```sql + -- PostgreSQL + TRUNCATE TABLE "Instance" CASCADE; + + -- MySQL + TRUNCATE TABLE `Instance`; + ``` + +## 📝 Logs e Debug + +### **Como habilitar logs detalhados:** + +1. **Configurar nível de log:** + ```env + LOG_LEVEL=debug + LOG_BAILEYS=debug + ``` + +2. **Verificar logs do sistema:** + ```bash + # Logs da aplicação + tail -f logs/evolution-api.log + + # Logs específicos de QR code + tail -f logs/evolution-api.log | grep -i qrcode + + # Logs do sistema + journalctl -u evolution-api -f + ``` + +3. **Logs específicos do Baileys:** + ```bash + # Logs de conexão WhatsApp + tail -f logs/evolution-api.log | grep -E "(connecting|open|close|qr)" + ``` + +### **Debug JavaScript:** + +```javascript +// Adicionar logs de debug +console.log('QR Code data:', qrCodeData); +console.log('Canvas element:', canvas); +console.log('QRCode library version:', QRCode.version); + +// Debug de API calls +const originalFetch = window.fetch; +window.fetch = function(...args) { + console.log('API Call:', args[0], args[1]); + return originalFetch.apply(this, args); +}; +``` + +## ⚡ Performance Issues + +### **QR Code lento para gerar:** + +1. **Otimizar configurações:** + ```typescript + const optsQrcode = { + margin: 2, // Reduzir de 3 para 2 + scale: 3, // Reduzir de 4 para 3 + errorCorrectionLevel: 'M' // Médio ao invés de Alto + }; + ``` + +2. **Usar cache:** + ```javascript + // Cache para QR codes + const qrCache = new Map(); + + function getCachedQRCode(data) { + if (qrCache.has(data)) { + return qrCache.get(data); + } + // Gerar e armazenar + } + ``` + +### **Interface travando:** + +1. **Otimizar JavaScript:** + ```javascript + // Usar requestAnimationFrame para updates + function updateQRCode() { + requestAnimationFrame(() => { + // Atualizar interface + }); + } + + // Debounce para inputs + const debounce = (func, wait) => { + let timeout; + return function executedFunction(...args) { + const later = () => { + clearTimeout(timeout); + func(...args); + }; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + }; + }; + ``` + +## 📊 Common Error Codes + +### **HTTP Status Codes:** + +- **400 Bad Request:** Dados inválidos ou instância incorreta +- **401 Unauthorized:** API key inválida ou token expirado +- **404 Not Found:** Instância não existe ou endpoint errado +- **429 Too Many Requests:** Rate limit excedido +- **500 Internal Server Error:** Erro interno do servidor + +### **Códigos de erro específicos:** + +```typescript +// Códigos do WhatsApp Baileys +enum DisconnectReason { + connectionClosed = 428, + connectionLost = 408, + connectionReplaced = 440, + loggedOut = 401, + badSession = 500, + forbidden = 403, + unreachable = 408, +} + +// Tratamento de códigos +switch (disconnectCode) { + case DisconnectReason.loggedOut: + console.log('Usuário fez logout'); + break; + case DisconnectReason.forbidden: + console.log('Número banido pelo WhatsApp'); + break; + default: + console.log('Código de desconexão:', disconnectCode); +} +``` + +## 🔧 Scripts de Troubleshooting + +### **Script de diagnóstico:** + +```bash +#!/bin/bash +# diagnostic.sh - Script de diagnóstico do QR Code + +echo "=== Diagnóstico QR Code System ===" + +# 1. Verificar API Key +echo -n "1. API Key configurada: " +if [ -n "$AUTHENTICATION_API_KEY" ] && [ "$AUTHENTICATION_API_KEY" != "BQYHJGJHJ" ]; then + echo "✅ OK" +else + echo "❌ NÃO CONFIGURADA" +fi + +# 2. Verificar instância +echo -n "2. Instância existe: " +INSTANCE_COUNT=$(curl -s -H "apikey: $AUTHENTICATION_API_KEY" http://localhost:8080/instance/fetchInstances | jq '. | length') +echo "$INSTANCE_COUNT instâncias" + +# 3. Verificar conexão +echo -n "3. Status da conexão: " +STATUS=$(curl -s -H "apikey: $AUTHENTICATION_API_KEY" http://localhost:8080/qrcode/connectionState/minha-instancia | jq -r '.instance.state') +echo "$STATUS" + +# 4. Verificar banco +echo -n "4. Banco de dados: " +if pg_isready -h localhost -p 5432 2>/dev/null; then + echo "✅ PostgreSQL OK" +elif mysqladmin ping -h localhost --silent; then + echo "✅ MySQL OK" +else + echo "❌ OFFLINE" +fi + +# 5. Verificar logs +echo "5. Últimos logs de erro:" +tail -n 10 logs/evolution-api.log | grep -i error || echo "Nenhum erro recente" + +echo "=== Fim do diagnóstico ===" +``` + +### **Script de reset:** + +```bash +#!/bin/bash +# reset-qr.sh - Reset do sistema QR Code + +echo "=== Reset QR Code System ===" + +# 1. Parar serviço +echo "1. Parando serviço..." +sudo systemctl stop evolution-api + +# 2. Limpar cache +echo "2. Limpando cache..." +rm -rf .wwebjs_cache/ +rm -rf .wwebjs_auth/ +rm -rf cache/ + +# 3. Resetar banco (opcional) +read -p "3. Resetar banco de dados? (y/N): " -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]]; then + npm run db:migrate:reset +fi + +# 4. Reiniciar serviço +echo "4. Reiniciando serviço..." +sudo systemctl start evolution-api + +# 5. Verificar status +echo "5. Verificando status..." +sleep 5 +curl -H "apikey: $AUTHENTICATION_API_KEY" http://localhost:8080/qrcode/api-key + +echo "=== Reset concluído ===" +``` + +## 📞 Suporte e Ajuda + +### **Como reportar bugs:** + +1. **Informações necessárias:** + - Versão do Evolution API + - Versão do Node.js + - Sistema operacional + - Logs completos do erro + - Passos para reproduzir + +2. **Template de bug report:** + ```markdown + ## Descrição do Problema + [Descreva o problema] + + ## Passos para Reproduzir + 1. [Passo 1] + 2. [Passo 2] + + ## Comportamento Esperado + [O que deveria acontecer] + + ## Comportamento Atual + [O que está acontecendo] + + ## Logs + [Logs relevantes] + + ## Configuração + - OS: [Sistema] + - Node.js: [Versão] + - Evolution API: [Versão] + ``` + +### **Comunidade:** + +- **GitHub Issues:** [Link para issues] +- **Discord:** [Link do Discord] +- **Documentação:** [Link da documentação] + +--- + +**Evolution API** - QR Code Troubleshooting +Versão: 2.0.0 +Data: 2025 diff --git a/docs/scan_qrcode/USE_CASES.md b/docs/scan_qrcode/USE_CASES.md new file mode 100644 index 000000000..1727814f3 --- /dev/null +++ b/docs/scan_qrcode/USE_CASES.md @@ -0,0 +1,784 @@ +# QR Code Scanning - Casos de Uso + +Este documento apresenta os principais casos de uso e cenários de implementação do sistema de QR Code scanning do Evolution API. + +## 📋 Sumário + +1. [Primeira Conexão](#1-primeira-conexão) +2. [Reconexão Automática](#2-reconexão-automática) +3. [Gestão de Múltiplas Instâncias](#3-gestão-de-múltiplas-instâncias) +4. [Integração com Chatbots](#4-integração-com-chatbots) +5. [Sistema de Monitoramento](#5-sistema-de-monitoramento) +6. [Recuperação de Falhas](#6-recuperação-de-falhas) +7. [Interface Personalizada](#7-interface-personalizada) +8. [Webhooks e Eventos](#8-webhooks-e-eventos) +9. [API para Desenvolvedores](#9-api-para-desenvolvedores) +10. [Cenários Avançados](#10-cenários-avançados) + +## 🎯 1. Primeira Conexão + +### **Cenário:** Usuário conecta WhatsApp pela primeira vez + +**Fluxo:** +1. Usuário acessa interface web +2. Digita nome da instância (ex: "minha-loja") +3. Clica em "Gerar QR Code" +4. Sistema cria nova instância no banco +5. Baileys inicia conexão WhatsApp +6. QR code é gerado e exibido +7. Usuário escaneia com celular +8. Conexão é estabelecida automaticamente + +**Código de exemplo:** +```javascript +// Frontend +document.getElementById('generate-qr').addEventListener('click', async () => { + const instanceName = document.getElementById('instance').value; + + try { + const response = await fetch(`/qrcode/connect/${instanceName}`, { + headers: { 'apikey': API_KEY } + }); + + const data = await response.json(); + + if (data.code) { + // Gerar QR code visual + QRCode.toCanvas(document.getElementById('qrcodeCanvas'), data.code); + } + } catch (error) { + console.error('Erro na conexão:', error); + } +}); +``` + +**Configuração típica:** +```env +# Configurações para primeira conexão +QRCODE_LIMIT=30 +QRCODE_COLOR=#22c55e +AUTHENTICATION_API_KEY=sua-chave-segura +``` + +## 🔄 2. Reconexão Automática + +### **Cenário:** Dispositivo desconectado precisa reconectar + +**Fluxo:** +1. Sistema detecta desconexão +2. Interface mostra status "Desconectado" +3. QR code é regenerado automaticamente +4. Usuário pode escanear novamente +5. Conexão é restabelecida + +**Implementação:** +```typescript +// Monitoramento de status +async function checkConnectionStatus() { + const response = await fetch(`/qrcode/connectionState/${instanceName}`, { + headers: { 'apikey': API_KEY } + }); + + const data = await response.json(); + + if (data.instance.state === 'close') { + // Regenerar QR code automaticamente + await generateQRCode(); + startCountdown(); // Reiniciar contador + } +} +``` + +**Configuração:** +```javascript +// Configuração do contador +const COUNTDOWN_INTERVAL = 30; // segundos +const MAX_RETRY_ATTEMPTS = 5; +``` + +## 🏢 3. Gestão de Múltiplas Instâncias + +### **Cenário:** Empresa gerencia várias contas WhatsApp + +**Fluxo:** +1. Interface permite alternar entre instâncias +2. Cada instância tem QR code independente +3. Logs separados por instância +4. Status individual por conexão + +**Implementação:** +```html + + +``` + +**Backend:** +```typescript +// Endpoint para listar todas as instâncias +app.get('/qrcode/instances', async (req, res) => { + const instances = await prisma.instance.findMany({ + select: { + name: true, + connectionStatus: true, + profileName: true + } + }); + + res.json(instances); +}); +``` + +## 🤖 4. Integração com Chatbots + +### **Cenário:** Sistema conectado a chatbot para atendimento + +**Fluxo:** +1. QR code conecta WhatsApp +2. Sistema de chatbot é ativado +3. Mensagens são processadas automaticamente +4. Interface mostra status do chatbot + +**Integração com Typebot:** +```typescript +// Configuração Typebot +const typebotConfig = { + enabled: true, + apiVersion: 'old', + sendMediaBase64: true +}; + +// Webhook para chatbot +app.post('/webhook/typebot', async (req, res) => { + const { instanceName, message } = req.body; + + // Processar mensagem no Typebot + const response = await typebotService.processMessage(message); + + // Enviar resposta via WhatsApp + await whatsappService.sendMessage(instanceName, response); +}); +``` + +**Interface com status do chatbot:** +```html +
+ 🤖 Chatbot: Ativo + 📊 Mensagens processadas: 1,234 +
+``` + +## 📊 5. Sistema de Monitoramento + +### **Cenário:** Dashboard para monitoramento de conexões + +**Fluxo:** +1. Painel mostra todas as instâncias +2. Status em tempo real (online/offline) +3. Métricas de uso e performance +4. Alertas automáticos + +**Dashboard JSON:** +```json +{ + "instances": [ + { + "name": "principal", + "status": "open", + "profileName": "Minha Empresa", + "profilePicture": "https://...", + "uptime": "99.8%", + "messagesToday": 150, + "lastActivity": "2025-01-15T10:30:00Z" + } + ] +} +``` + +**Métricas em tempo real:** +```javascript +// WebSocket para updates em tempo real +const wss = new WebSocket.Server({ port: 8081 }); + +wss.on('connection', (ws) => { + // Enviar métricas a cada 5 segundos + setInterval(() => { + const metrics = getInstanceMetrics(); + ws.send(JSON.stringify(metrics)); + }, 5000); +}); +``` + +## 🛠️ 6. Recuperação de Falhas + +### **Cenário:** Sistema detecta e recupera falhas automaticamente + +**Fluxo:** +1. Sistema monitora conexões continuamente +2. Falhas são detectadas automaticamente +3. Tentativas de reconexão são feitas +4. Logs detalhados são gerados + +**Sistema de retry:** +```javascript +class RetryManager { + constructor(maxAttempts = 5, baseDelay = 1000) { + this.maxAttempts = maxAttempts; + this.baseDelay = baseDelay; + } + + async executeWithRetry(operation, instanceName) { + for (let attempt = 1; attempt <= this.maxAttempts; attempt++) { + try { + return await operation(); + } catch (error) { + if (attempt === this.maxAttempts) { + throw new Error(`Falha após ${this.maxAttempts} tentativas`); + } + + const delay = this.baseDelay * Math.pow(2, attempt - 1); + console.log(`Tentativa ${attempt} falhou, retrying em ${delay}ms`); + + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + } +} +``` + +**Monitoramento de saúde:** +```typescript +// Health check endpoint +app.get('/health/qrcode', async (req, res) => { + const health = { + status: 'healthy', + timestamp: new Date().toISOString(), + instances: {}, + uptime: process.uptime() + }; + + // Verificar cada instância + for (const instanceName of activeInstances) { + try { + const state = await getConnectionState(instanceName); + health.instances[instanceName] = { + status: state.instance.state, + healthy: state.instance.state === 'open' + }; + } catch (error) { + health.instances[instanceName] = { + status: 'error', + healthy: false + }; + } + } + + res.json(health); +}); +``` + +## 🎨 7. Interface Personalizada + +### **Cenário:** Interface adaptada para diferentes negócios + +**Exemplo 1: E-commerce** +```html + +
+
+ Logo da Loja +

Conectar WhatsApp da Loja

+

Automatize atendimento de pedidos

+
+ +
+
📦 Consultar pedidos
+
💳 Status de pagamento
+
🚚 Rastreio de entrega
+
+
+``` + +**Exemplo 2: Clínica médica** +```html + +
+
+

WhatsApp da Clínica

+

Agendamento e confirmações

+
+ +
+
📅 Agendar consultas
+
⏰ Lembretes
+
📋 Resultados
+
+
+``` + +**Personalização de cores:** +```css +:root { + --primary-color: #22c55e; /* Verde Evolution */ + --secondary-color: #3b82f6; /* Azul para e-commerce */ + --accent-color: #10b981; /* Verde para sucesso */ + --danger-color: #ef4444; /* Vermelho para erro */ +} +``` + +## 🔗 8. Webhooks e Eventos + +### **Cenário:** Sistema reage a eventos do WhatsApp + +**Eventos suportados:** +```typescript +enum WhatsAppEvents { + QRCODE_UPDATED = 'qrcode.updated', + CONNECTION_UPDATE = 'connection.update', + MESSAGES_UPSERT = 'messages.upsert', + CONTACTS_SET = 'contacts.set' +} +``` + +**Webhook de exemplo:** +```javascript +// Webhook para QR code atualizado +app.post('/webhook/qrcode-updated', (req, res) => { + const { instanceName, qrcode } = req.body; + + console.log(`QR Code atualizado para ${instanceName}`); + + // Notificar frontend via WebSocket + wss.clients.forEach(client => { + if (client.instanceName === instanceName) { + client.send(JSON.stringify({ + type: 'qrcode_updated', + data: qrcode + })); + } + }); + + res.json({ status: 'received' }); +}); +``` + +**Sistema de eventos interno:** +```typescript +// EventEmitter2 para comunicação interna +const eventManager = new EventEmitter2(); + +eventManager.on('qrcode.updated', (data) => { + // Atualizar cache + cache.set(`qrcode_${data.instanceName}`, data.qrcode); + + // Emitir para WebSocket + emitToWebSocket('qrcode_updated', data); +}); +``` + +## 💻 9. API para Desenvolvedores + +### **Cenário:** Integração via API REST + +**Criar instância via API:** +```bash +curl -X POST http://localhost:8080/instance/create \ + -H "apikey: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "instanceName": "api-integration", + "integration": "WHATSAPP-BAILEYS", + "webhook": { + "enabled": true, + "url": "https://your-app.com/webhook" + } + }' +``` + +**Conectar via API:** +```bash +curl -H "apikey: YOUR_API_KEY" \ + http://localhost:8080/qrcode/connect/api-integration +``` + +**Monitorar status via API:** +```bash +# Verificar status +curl -H "apikey: YOUR_API_KEY" \ + http://localhost:8080/qrcode/connectionState/api-integration + +# Buscar informações +curl -H "apikey: YOUR_API_KEY" \ + http://localhost:8080/qrcode/fetchInstances?instanceName=api-integration +``` + +**SDK JavaScript:** +```javascript +class EvolutionAPI { + constructor(apiKey, baseUrl = 'http://localhost:8080') { + this.apiKey = apiKey; + this.baseUrl = baseUrl; + } + + async connect(instanceName) { + const response = await fetch(`${this.baseUrl}/qrcode/connect/${instanceName}`, { + headers: { 'apikey': this.apiKey } + }); + + return await response.json(); + } + + async getStatus(instanceName) { + const response = await fetch(`${this.baseUrl}/qrcode/connectionState/${instanceName}`, { + headers: { 'apikey': this.apiKey } + }); + + return await response.json(); + } + + async sendMessage(instanceName, number, message) { + const response = await fetch(`${this.baseUrl}/message/sendText/${instanceName}`, { + method: 'POST', + headers: { + 'apikey': this.apiKey, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ number, text: message }) + }); + + return await response.json(); + } +} +``` + +## 🚀 10. Cenários Avançados + +### **Cenário A: Load Balancer com Múltiplas Instâncias** + +**Arquitetura:** +``` +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ Load │ │ Instance │ │ Instance │ +│ Balancer │───►│ A │ │ B │ +│ (Nginx) │ │ (Port 8080)│ │ (Port 8081)│ +└─────────────┘ └─────────────┘ └─────────────┘ +``` + +**Configuração:** +```nginx +# Nginx load balancer +upstream evolution_api { + server localhost:8080; + server localhost:8081; + server localhost:8082; +} + +server { + location /qrcode/ { + proxy_pass http://evolution_api; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } +} +``` + +### **Cenário B: Cluster Kubernetes** + +**YAML de exemplo:** +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: evolution-api-qrcode +spec: + replicas: 3 + selector: + matchLabels: + app: evolution-api-qrcode + template: + metadata: + labels: + app: evolution-api-qrcode + spec: + containers: + - name: api + image: evolution-api:latest + ports: + - containerPort: 8080 + env: + - name: AUTHENTICATION_API_KEY + valueFrom: + secretKeyRef: + name: api-secrets + key: api-key + volumeMounts: + - name: qrcode-storage + mountPath: /app/public/qrcode + volumes: + - name: qrcode-storage + persistentVolumeClaim: + claimName: qrcode-pvc +``` + +### **Cenário C: Multi-tenant SaaS** + +**Estrutura de dados:** +```sql +-- Tabela de tenants +CREATE TABLE tenants ( + id UUID PRIMARY KEY, + name VARCHAR(255), + api_key VARCHAR(255) UNIQUE, + qrcode_limit INTEGER DEFAULT 30, + created_at TIMESTAMP +); + +-- Tabela de instâncias por tenant +CREATE TABLE instances ( + id UUID PRIMARY KEY, + tenant_id UUID REFERENCES tenants(id), + name VARCHAR(255), + connection_status VARCHAR(50), + UNIQUE(tenant_id, name) +); +``` + +**Middleware de tenant:** +```typescript +// Middleware para identificar tenant +const tenantMiddleware = async (req, res, next) => { + const apiKey = req.headers.apikey; + + if (!apiKey) { + return res.status(401).json({ error: 'API key required' }); + } + + const tenant = await prisma.tenant.findUnique({ + where: { api_key: apiKey } + }); + + if (!tenant) { + return res.status(401).json({ error: 'Invalid API key' }); + } + + req.tenant = tenant; + next(); +}; +``` + +## 📈 Métricas e Analytics + +### **Dashboard de métricas:** + +**Endpoint de métricas:** +```javascript +app.get('/metrics/qrcode', async (req, res) => { + const metrics = { + totalInstances: await getTotalInstances(), + activeInstances: await getActiveInstances(), + qrCodesGenerated: await getQRCodesGenerated(), + connectionSuccessRate: await getConnectionSuccessRate(), + averageConnectionTime: await getAverageConnectionTime(), + errorsByType: await getErrorsByType() + }; + + res.json(metrics); +}); +``` + +**Métricas em tempo real:** +```json +{ + "timestamp": "2025-01-15T10:30:00Z", + "instances": { + "total": 150, + "active": 142, + "inactive": 8 + }, + "qrcode": { + "generated_today": 25, + "success_rate": "96.2%", + "average_scan_time": "12.5s" + }, + "errors": { + "connection_timeout": 3, + "invalid_qr": 1, + "rate_limited": 0 + } +} +``` + +## 🔄 Fluxos de Integração + +### **Fluxo com CRM:** + +```mermaid +graph LR + A[Cliente envia mensagem] --> B[WhatsApp via QR Code] + B --> C[Evolution API] + C --> D[Webhook para CRM] + D --> E[CRM processa] + E --> F[Resposta via API] + F --> G[Evolution API] + G --> H[WhatsApp responde] +``` + +### **Fluxo com E-commerce:** + +```mermaid +graph LR + A[Cliente faz pedido] --> B[Sistema E-commerce] + B --> C[API Evolution] + C --> D[QR Code WhatsApp] + D --> E[Cliente escaneia] + E --> F[Confirmação automática] + F --> G[Status do pedido] +``` + +## 📚 Exemplos Práticos + +### **Exemplo 1: Integração com React** + +```jsx +import React, { useState, useEffect } from 'react'; +import QRCode from 'qrcode.react'; + +function WhatsAppQRCode({ instanceName, apiKey }) { + const [qrCode, setQrCode] = useState(null); + const [status, setStatus] = useState('disconnected'); + const [logs, setLogs] = useState([]); + + useEffect(() => { + connectToWhatsApp(); + const interval = setInterval(checkStatus, 3000); + return () => clearInterval(interval); + }, []); + + const connectToWhatsApp = async () => { + try { + const response = await fetch(`/qrcode/connect/${instanceName}`, { + headers: { 'apikey': apiKey } + }); + + const data = await response.json(); + setQrCode(data.code); + + addLog('info', 'QR Code gerado com sucesso'); + } catch (error) { + addLog('error', `Erro: ${error.message}`); + } + }; + + const checkStatus = async () => { + try { + const response = await fetch(`/qrcode/connectionState/${instanceName}`, { + headers: { 'apikey': apiKey } + }); + + const data = await response.json(); + setStatus(data.instance.state); + + if (data.instance.state === 'open') { + addLog('success', 'WhatsApp conectado!'); + } + } catch (error) { + addLog('error', `Erro ao verificar status: ${error.message}`); + } + }; + + const addLog = (type, message) => { + setLogs(prev => [...prev, { type, message, timestamp: new Date() }]); + }; + + return ( +
+

Conectar WhatsApp

+ + {status === 'connecting' && qrCode && ( +
+ +

Escaneie o QR Code com seu WhatsApp

+
+ )} + + {status === 'open' && ( +
+
+

WhatsApp Conectado!

+
+ )} + +
+

Logs

+
+ {logs.map((log, index) => ( +
+ [{log.timestamp.toLocaleTimeString()}] {log.message} +
+ ))} +
+
+
+ ); +} +``` + +### **Exemplo 2: Bot de Notificação** + +```javascript +// Bot que notifica sobre status do QR Code +class QRCodeNotificationBot { + constructor(webhookUrl) { + this.webhookUrl = webhookUrl; + } + + async notifyQRCodeGenerated(instanceName, qrCode) { + await this.sendNotification({ + type: 'qrcode_generated', + instanceName, + qrCode, + message: `Novo QR Code gerado para ${instanceName}`, + timestamp: new Date().toISOString() + }); + } + + async notifyConnected(instanceName) { + await this.sendNotification({ + type: 'connected', + instanceName, + message: `✅ WhatsApp conectado com sucesso: ${instanceName}`, + timestamp: new Date().toISOString() + }); + } + + async notifyDisconnected(instanceName) { + await this.sendNotification({ + type: 'disconnected', + instanceName, + message: `❌ WhatsApp desconectado: ${instanceName}`, + timestamp: new Date().toISOString() + }); + } + + async sendNotification(payload) { + try { + await fetch(this.webhookUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + } catch (error) { + console.error('Erro ao enviar notificação:', error); + } + } +} +``` + +--- + +**Evolution API** - QR Code Use Cases +Versão: 2.0.0 +Data: 2025 diff --git a/docs/scan_qrcode/example-implementation.js b/docs/scan_qrcode/example-implementation.js new file mode 100644 index 000000000..5d3aa531a --- /dev/null +++ b/docs/scan_qrcode/example-implementation.js @@ -0,0 +1,329 @@ +/** + * QR Code Scanning - Exemplo de Implementação para Forks + * + * Este arquivo demonstra como implementar o sistema de QR Code scanning + * do Evolution API em outros projetos/forks. + */ + +const express = require('express'); +const qrcode = require('qrcode'); +const path = require('path'); +const crypto = require('crypto'); + +// Classe principal do QR Code Router +class QrCodeRouter { + constructor(configService, ...guards) { + this.configService = configService; + this.guards = guards; + this.router = express.Router(); + this.tokenCache = new Map(); + this.setupRoutes(); + } + + setupRoutes() { + // Rate limiting em memória + const rateLimitMap = new Map(); + const RATE_LIMIT_WINDOW = 60000; // 1 minuto + const RATE_LIMIT_MAX_REQUESTS = 10; // 10 requests por minuto + + const rateLimit = (req, res, next) => { + const clientIp = req.ip || req.connection.remoteAddress || 'unknown'; + const now = Date.now(); + + let clientData = rateLimitMap.get(clientIp); + + if (!clientData || now > clientData.resetTime) { + rateLimitMap.set(clientIp, { count: 1, resetTime: now + RATE_LIMIT_WINDOW }); + return next(); + } + + if (clientData.count >= RATE_LIMIT_MAX_REQUESTS) { + return res.status(429).json({ + error: 'Too many requests', + message: 'Rate limit exceeded. Try again later.', + retryAfter: Math.ceil((clientData.resetTime - now) / 1000), + }); + } + + clientData.count++; + next(); + }; + + // Endpoint para verificar API key de forma segura + this.router.get('/api-key', async (req, res) => { + try { + const auth = this.configService.get('AUTHENTICATION'); + let isConfigured = false; + let sessionToken = ''; + + if (auth && auth.API_KEY && typeof auth.API_KEY.KEY === 'string') { + const apiKey = auth.API_KEY.KEY; + isConfigured = !!apiKey && apiKey !== 'BQYHJGJHJ'; + + if (isConfigured) { + sessionToken = crypto.randomBytes(32).toString('hex'); + this.storeTemporaryToken(sessionToken, apiKey); + } + } + + res.json({ + configured: isConfigured, + sessionToken: sessionToken, + expiresIn: 3600, // 1 hora + }); + } catch (error) { + console.error(`Error checking API key status: ${error.message}`); + res.status(500).json({ configured: false, error: 'Internal server error' }); + } + }); + + // Endpoint para trocar token por API key + this.router.post('/exchange-token', rateLimit, async (req, res) => { + try { + const { sessionToken } = req.body; + + if (!sessionToken) { + return res.status(400).json({ error: 'Session token required' }); + } + + const apiKey = this.getApiKeyFromToken(sessionToken); + + if (!apiKey) { + return res.status(401).json({ error: 'Invalid or expired session token' }); + } + + res.json({ apiKey }); + } catch (error) { + console.error(`Error exchanging token: ${error.message}`); + res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Serve a interface HTML + this.router.get('/', (req, res) => { + const qrcodeHtmlPath = path.join(__dirname, '..', 'public', 'qrcode', 'index.html'); + + // Headers de segurança + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'DENY'); + res.setHeader('X-XSS-Protection', '1; mode=block'); + res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + + res.sendFile(qrcodeHtmlPath, (err) => { + if (err) { + console.error(`Error serving QR code page: ${err.message}`); + res.status(500).json({ error: 'Error loading QR code page' }); + } + }); + }); + + // Conectar ao WhatsApp + this.router.get('/connect/:instanceName', ...this.guards, async (req, res) => { + try { + const { instanceName } = req.params; + + // Sua lógica de conexão WhatsApp aqui + const result = await this.connectToWhatsapp(instanceName); + + res.json(result); + } catch (error) { + console.error(`Error connecting to WhatsApp: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + + // Verificar estado da conexão + this.router.get('/connectionState/:instanceName', ...this.guards, async (req, res) => { + try { + const { instanceName } = req.params; + + // Sua lógica para verificar estado da conexão + const result = await this.getConnectionState(instanceName); + + res.json(result); + } catch (error) { + console.error(`Error getting connection state: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + + // Logout da instância + this.router.delete('/logout/:instanceName', ...this.guards, async (req, res) => { + try { + const { instanceName } = req.params; + + // Sua lógica de logout aqui + const result = await this.logoutInstance(instanceName); + + res.json(result); + } catch (error) { + console.error(`Error logging out: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + + // Buscar informações da instância + this.router.get('/fetchInstances', ...this.guards, async (req, res) => { + try { + const { instanceName } = req.query; + + // Sua lógica para buscar informações da instância + const result = await this.fetchInstanceInfo(instanceName); + + res.json(result); + } catch (error) { + console.error(`Error fetching instance info: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + + // Atualizar nome do perfil + this.router.post('/updateProfileName', ...this.guards, async (req, res) => { + try { + const { instanceName, name } = req.body; + + // Sua lógica para atualizar nome do perfil + const result = await this.updateProfileName(instanceName, name); + + res.json(result); + } catch (error) { + console.error(`Error updating profile name: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + + // Atualizar status do perfil + this.router.post('/updateProfileStatus', ...this.guards, async (req, res) => { + try { + const { instanceName, status } = req.body; + + // Sua lógica para atualizar status do perfil + const result = await this.updateProfileStatus(instanceName, status); + + res.json(result); + } catch (error) { + console.error(`Error updating profile status: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + + // Atualizar foto do perfil + this.router.post('/updateProfilePicture', ...this.guards, async (req, res) => { + try { + const { instanceName, image } = req.body; + + // Sua lógica para atualizar foto do perfil + const result = await this.updateProfilePicture(instanceName, image); + + res.json(result); + } catch (error) { + console.error(`Error updating profile picture: ${error.message}`); + res.status(500).json({ error: error.message }); + } + }); + } + + // Métodos auxiliares para cache de tokens + storeTemporaryToken(sessionToken, apiKey) { + const expiresAt = Date.now() + 3600 * 1000; // 1 hora + this.tokenCache.set(sessionToken, { apiKey, expiresAt }); + + // Limpa token após expiração + setTimeout(() => { + this.tokenCache.delete(sessionToken); + }, 3600 * 1000); + } + + getApiKeyFromToken(sessionToken) { + const tokenData = this.tokenCache.get(sessionToken); + + if (!tokenData || Date.now() > tokenData.expiresAt) { + this.tokenCache.delete(sessionToken); + return null; + } + + return tokenData.apiKey; + } + + // Implementar estes métodos conforme sua lógica WhatsApp + async connectToWhatsapp(instanceName) { + // TODO: Implementar lógica de conexão WhatsApp + // Retornar objeto com QR code + return { + code: '2@ABC123...', // QR code string + pairingCode: null, + base64: 'data:image/png;base64,...', // QR code em base64 + count: 1, + }; + } + + async getConnectionState(instanceName) { + // TODO: Implementar verificação de estado da conexão + return { + instance: { + instanceName: instanceName, + state: 'connecting', // connecting | open | close + }, + }; + } + + async logoutInstance(instanceName) { + // TODO: Implementar lógica de logout + return { + status: 'SUCCESS', + error: false, + response: { message: 'Instance logged out' }, + }; + } + + async fetchInstanceInfo(instanceName) { + // TODO: Implementar busca de informações da instância + return { + instanceName: instanceName, + profileName: 'Nome do Perfil', + profilePicUrl: 'https://...', + connectionStatus: 'open', + _count: { + Chat: 10, + Contact: 50, + Message: 100, + }, + }; + } + + async updateProfileName(instanceName, name) { + // TODO: Implementar atualização de nome do perfil + return { + status: 'SUCCESS', + error: false, + response: { message: 'Profile name updated' }, + }; + } + + async updateProfileStatus(instanceName, status) { + // TODO: Implementar atualização de status do perfil + return { + status: 'SUCCESS', + error: false, + response: { message: 'Profile status updated' }, + }; + } + + async updateProfilePicture(instanceName, image) { + // TODO: Implementar atualização de foto do perfil + return { + status: 'SUCCESS', + error: false, + response: { message: 'Profile picture updated' }, + }; + } +} + +// Exemplo de uso +module.exports = QrCodeRouter; + +// Para usar em seu projeto: +const QrCodeRouter = require('./path/to/qrcode-router'); +const qrcodeRouter = new QrCodeRouter(configService, ...yourGuards); +app.use('/qrcode', qrcodeRouter.router); diff --git a/docs/scan_qrcode/index.md b/docs/scan_qrcode/index.md new file mode 100644 index 000000000..1fd364d96 --- /dev/null +++ b/docs/scan_qrcode/index.md @@ -0,0 +1,192 @@ +# QR Code Scanning - Documentação Completa + +Bem-vindo à documentação completa do sistema de QR Code scanning do Evolution API. Esta pasta contém toda a implementação, configurações e guias necessários para entender e implementar o sistema de QR Code em outros projetos. + +## 📚 Documentação Disponível + +### 🎯 **Documentação Principal** +- **[README.md](README.md)** - Visão geral completa do sistema de QR Code +- **[CONFIGURATION.md](CONFIGURATION.md)** - Todas as configurações disponíveis +- **[USE_CASES.md](USE_CASES.md)** - Casos de uso e cenários de implementação +- **[TROUBLESHOOTING.md](TROUBLESHOOTING.md)** - Solução de problemas e debug + +### 💻 **Implementação** +- **[example-implementation.js](example-implementation.js)** - Exemplo completo de implementação +- **[interface-example.html](interface-example.html)** - Interface HTML completa +- **[config-example.env](config-example.env)** - Arquivo de configuração de exemplo + +## 🚀 Início Rápido + +### 1. **Clonar Interface** +```bash +# Copiar arquivos do frontend +cp -r /path/to/evolution-api/public/qrcode/ your-project/public/ +``` + +### 2. **Configurar Backend** +```typescript +// Adicionar ao seu Express app +import { QrCodeRouter } from './routes/qrcode.router'; + +const qrcodeRouter = new QrCodeRouter(configService, ...guards); +app.use('/qrcode', qrcodeRouter.router); +``` + +### 3. **Configurar Ambiente** +```bash +# Copiar configuração de exemplo +cp config-example.env .env + +# Editar configurações +nano .env +``` + +### 4. **Testar Conexão** +```bash +# Verificar se está funcionando +curl http://localhost:8080/qrcode/api-key +``` + +## 📋 Checklist de Implementação + +- [ ] ✅ Clonar arquivos do frontend +- [ ] ✅ Configurar rotas do backend +- [ ] ✅ Implementar serviço WhatsApp +- [ ] ✅ Configurar autenticação +- [ ] ✅ Personalizar interface +- [ ] ✅ Configurar variáveis de ambiente +- [ ] ✅ Testar fluxo completo +- [ ] ✅ Documentar endpoints específicos +- [ ] ✅ Implementar logs +- [ ] ✅ Configurar produção + +## 🎨 Personalização + +### **Cores e Branding** +```css +:root { + --primary-color: #22c55e; /* Verde Evolution */ + --success-color: #10b981; + --error-color: #ef4444; +} +``` + +### **Textos e Idiomas** +```javascript +// Personalizar textos +const MESSAGES = { + title: "Conectar WhatsApp", + subtitle: "Escaneie o QR Code com seu celular", + button: "Gerar QR Code", + connected: "WhatsApp conectado!", + error: "Erro na conexão" +}; +``` + +## 🔧 Principais Endpoints + +### **Autenticação** +```bash +GET /qrcode/api-key # Verificar API key +POST /qrcode/exchange-token # Trocar token por API key +``` + +### **WhatsApp** +```bash +GET /qrcode/connect/{instance} # Conectar WhatsApp +GET /qrcode/connectionState/{instance} # Status da conexão +DELETE /qrcode/logout/{instance} # Desconectar +``` + +### **Perfil** +```bash +GET /qrcode/fetchInstances # Informações da instância +POST /qrcode/updateProfileName # Atualizar nome +POST /qrcode/updateProfileStatus # Atualizar status +POST /qrcode/updateProfilePicture # Atualizar foto +``` + +## ⚙️ Configurações Essenciais + +### **Variáveis Obrigatórias** +```env +AUTHENTICATION_API_KEY=your-secure-api-key +SERVER_URL=http://localhost:8080 +DATABASE_PROVIDER=postgresql +``` + +### **Configurações Recomendadas** +```env +QRCODE_LIMIT=30 +QRCODE_COLOR=#22c55e +LOG_LEVEL=info +CACHE_REDIS_ENABLED=true +``` + +## 🔍 Troubleshooting Rápido + +### **Problemas Comuns** +1. **QR Code não aparece**: Verificar se JavaScript carregou +2. **API Key não configurada**: Verificar variável de ambiente +3. **Instância não existe**: Criar instância primeiro +4. **Rate limit**: Aguardar 1 minuto entre tentativas + +### **Logs Importantes** +```bash +# Logs da aplicação +tail -f logs/evolution-api.log | grep -i qrcode + +# Logs do sistema +journalctl -u evolution-api -f +``` + +## 📞 Suporte + +### **Comunidade** +- GitHub Issues: [Link para issues] +- Documentação: [Link da documentação] +- Discord: [Link do Discord] + +### **Reportar Bugs** +```markdown +## Descrição +[Problema encontrado] + +## Passos +1. [Passo para reproduzir] +2. [Passo para reproduzir] + +## Configuração +- OS: [Sistema] +- Node.js: [Versão] +- Evolution API: [Versão] + +## Logs +[Logs relevantes] +``` + +## 📈 Próximos Passos + +1. **Testar implementação** em ambiente de desenvolvimento +2. **Personalizar interface** com cores e logo da empresa +3. **Configurar produção** com SSL e cache Redis +4. **Implementar monitoring** e alertas +5. **Documentar APIs específicas** do seu projeto + +## 🎯 Recursos Avançados + +- **WebSocket** para updates em tempo real +- **Load Balancer** para múltiplas instâncias +- **Kubernetes** para deploy em cluster +- **Multi-tenant** para SaaS +- **Webhooks** para integrações + +--- + +## 📄 Licença + +Esta documentação é parte do Evolution API e segue a mesma licença do projeto. + +**Evolution API** - QR Code Scanning System +Versão: 2.0.0 +Data: 2025 diff --git a/docs/scan_qrcode/interface-example.html b/docs/scan_qrcode/interface-example.html new file mode 100644 index 000000000..e3437f42b --- /dev/null +++ b/docs/scan_qrcode/interface-example.html @@ -0,0 +1,297 @@ + + + + + + Se7e Sistemas - Conector WhatsApp + + + + + + + + + + +
+ +
+
+

+ + + + Como Conectar seu WhatsApp +

+

+ Siga os passos abaixo para conectar seu WhatsApp a este painel +

+
+
+
1
+

Clique no botão "Gerar QR Code" para gerar o QR Code.

+
+
+
2
+

Abra o WhatsApp no seu celular e vá em Configurações > Aparelhos conectados.

+
+
+
3
+

Toque em "Parear dispositivo" e aponte a câmera para o QR Code mostrado.

+
+
+
4
+

Aguarde alguns segundos até o status mudar para "Conectado".

+
+
+ +
+
+ +
+ + + +
+
+
+ Se7e Sistemas Logo + +
+

Se7e Sistemas

+

Conecte seu WhatsApp aos nossos serviços

+
+
+ +
+
+ + +
+ +
+ + + + + + + + + +
+ + +
+ + + + +
+

Integração Segura com API WhatsApp

+
+ + + Status: Pronto + +
+
+
+
+
+ + + + + + diff --git a/evolution-api-esm-migration.patch b/evolution-api-esm-migration.patch new file mode 100644 index 000000000..e2da7f504 --- /dev/null +++ b/evolution-api-esm-migration.patch @@ -0,0 +1,820 @@ +From 5434c81657209d535ca6f9e1bfbd40a02b20bd70 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:26:59 +0000 +Subject: [PATCH 01/13] build: migrate config files to CommonJS for ESM + compatibility + +--- + .eslintrc.cjs | 39 +++++++++++++++++++++++++++++++++++++++ + .prettierrc.cjs | 12 ++++++++++++ + commitlint.config.cjs | 34 ++++++++++++++++++++++++++++++++++ + 3 files changed, 85 insertions(+) + create mode 100644 .eslintrc.cjs + create mode 100644 .prettierrc.cjs + create mode 100644 commitlint.config.cjs + +diff --git a/.eslintrc.cjs b/.eslintrc.cjs +new file mode 100644 +index 00000000..8f54a776 +--- /dev/null ++++ b/.eslintrc.cjs +@@ -0,0 +1,39 @@ ++module.exports = { ++ parser: '@typescript-eslint/parser', ++ parserOptions: { ++ project: 'tsconfig.json', ++ tsconfigRootDir: __dirname, ++ sourceType: 'module', ++ warnOnUnsupportedTypeScriptVersion: false, ++ EXPERIMENTAL_useSourceOfProjectReferenceRedirect: true, ++ }, ++ plugins: ['@typescript-eslint', 'simple-import-sort', 'import'], ++ extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'], ++ globals: { ++ Atomics: 'readonly', ++ SharedArrayBuffer: 'readonly', ++ }, ++ root: true, ++ env: { ++ node: true, ++ jest: true, ++ }, ++ ignorePatterns: ['.eslintrc.js'], ++ rules: { ++ '@typescript-eslint/interface-name-prefix': 'off', ++ '@typescript-eslint/explicit-function-return-type': 'off', ++ '@typescript-eslint/explicit-module-boundary-types': 'off', ++ '@typescript-eslint/no-explicit-any': 'off', ++ '@typescript-eslint/no-empty-function': 'off', ++ '@typescript-eslint/no-non-null-assertion': 'off', ++ '@typescript-eslint/no-unused-vars': 'error', ++ 'import/first': 'error', ++ 'import/no-duplicates': 'error', ++ 'simple-import-sort/imports': 'error', ++ 'simple-import-sort/exports': 'error', ++ '@typescript-eslint/no-empty-object-type': 'off', ++ '@typescript-eslint/no-wrapper-object-types': 'off', ++ '@typescript-eslint/no-unused-expressions': 'off', ++ 'prettier/prettier': ['error', { endOfLine: 'auto' }], ++ }, ++}; +diff --git a/.prettierrc.cjs b/.prettierrc.cjs +new file mode 100644 +index 00000000..f55f3f06 +--- /dev/null ++++ b/.prettierrc.cjs +@@ -0,0 +1,12 @@ ++module.exports = { ++ semi: true, ++ trailingComma: 'all', ++ singleQuote: true, ++ printWidth: 120, ++ arrowParens: 'always', ++ tabWidth: 2, ++ useTabs: false, ++ bracketSameLine: false, ++ bracketSpacing: true, ++ parser: 'typescript' ++} +\ No newline at end of file +diff --git a/commitlint.config.cjs b/commitlint.config.cjs +new file mode 100644 +index 00000000..9beb860b +--- /dev/null ++++ b/commitlint.config.cjs +@@ -0,0 +1,34 @@ ++module.exports = { ++ extends: ['@commitlint/config-conventional'], ++ rules: { ++ 'type-enum': [ ++ 2, ++ 'always', ++ [ ++ 'feat', // New feature ++ 'fix', // Bug fix ++ 'docs', // Documentation changes ++ 'style', // Code style changes (formatting, etc) ++ 'refactor', // Code refactoring ++ 'perf', // Performance improvements ++ 'test', // Adding or updating tests ++ 'chore', // Maintenance tasks ++ 'ci', // CI/CD changes ++ 'build', // Build system changes ++ 'revert', // Reverting changes ++ 'security', // Security fixes ++ ], ++ ], ++ 'type-case': [2, 'always', 'lower-case'], ++ 'type-empty': [2, 'never'], ++ 'scope-case': [2, 'always', 'lower-case'], ++ 'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']], ++ 'subject-empty': [2, 'never'], ++ 'subject-full-stop': [2, 'never', '.'], ++ 'header-max-length': [2, 'always', 100], ++ 'body-leading-blank': [1, 'always'], ++ 'body-max-line-length': [0, 'always', 150], ++ 'footer-leading-blank': [1, 'always'], ++ 'footer-max-line-length': [0, 'always', 150], ++ }, ++}; +-- +2.43.0 + + +From a486398b249a271fe774f98f18dacdbb0c2fb521 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:27:03 +0000 +Subject: [PATCH 02/13] build: remove old CommonJS config files + +--- + .eslintrc.js | 39 --------------------------------------- + .prettierrc.js | 12 ------------ + commitlint.config.js | 34 ---------------------------------- + 3 files changed, 85 deletions(-) + delete mode 100644 .eslintrc.js + delete mode 100644 .prettierrc.js + delete mode 100644 commitlint.config.js + +diff --git a/.eslintrc.js b/.eslintrc.js +deleted file mode 100644 +index 8f54a776..00000000 +--- a/.eslintrc.js ++++ /dev/null +@@ -1,39 +0,0 @@ +-module.exports = { +- parser: '@typescript-eslint/parser', +- parserOptions: { +- project: 'tsconfig.json', +- tsconfigRootDir: __dirname, +- sourceType: 'module', +- warnOnUnsupportedTypeScriptVersion: false, +- EXPERIMENTAL_useSourceOfProjectReferenceRedirect: true, +- }, +- plugins: ['@typescript-eslint', 'simple-import-sort', 'import'], +- extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'], +- globals: { +- Atomics: 'readonly', +- SharedArrayBuffer: 'readonly', +- }, +- root: true, +- env: { +- node: true, +- jest: true, +- }, +- ignorePatterns: ['.eslintrc.js'], +- rules: { +- '@typescript-eslint/interface-name-prefix': 'off', +- '@typescript-eslint/explicit-function-return-type': 'off', +- '@typescript-eslint/explicit-module-boundary-types': 'off', +- '@typescript-eslint/no-explicit-any': 'off', +- '@typescript-eslint/no-empty-function': 'off', +- '@typescript-eslint/no-non-null-assertion': 'off', +- '@typescript-eslint/no-unused-vars': 'error', +- 'import/first': 'error', +- 'import/no-duplicates': 'error', +- 'simple-import-sort/imports': 'error', +- 'simple-import-sort/exports': 'error', +- '@typescript-eslint/no-empty-object-type': 'off', +- '@typescript-eslint/no-wrapper-object-types': 'off', +- '@typescript-eslint/no-unused-expressions': 'off', +- 'prettier/prettier': ['error', { endOfLine: 'auto' }], +- }, +-}; +diff --git a/.prettierrc.js b/.prettierrc.js +deleted file mode 100644 +index f55f3f06..00000000 +--- a/.prettierrc.js ++++ /dev/null +@@ -1,12 +0,0 @@ +-module.exports = { +- semi: true, +- trailingComma: 'all', +- singleQuote: true, +- printWidth: 120, +- arrowParens: 'always', +- tabWidth: 2, +- useTabs: false, +- bracketSameLine: false, +- bracketSpacing: true, +- parser: 'typescript' +-} +\ No newline at end of file +diff --git a/commitlint.config.js b/commitlint.config.js +deleted file mode 100644 +index 9beb860b..00000000 +--- a/commitlint.config.js ++++ /dev/null +@@ -1,34 +0,0 @@ +-module.exports = { +- extends: ['@commitlint/config-conventional'], +- rules: { +- 'type-enum': [ +- 2, +- 'always', +- [ +- 'feat', // New feature +- 'fix', // Bug fix +- 'docs', // Documentation changes +- 'style', // Code style changes (formatting, etc) +- 'refactor', // Code refactoring +- 'perf', // Performance improvements +- 'test', // Adding or updating tests +- 'chore', // Maintenance tasks +- 'ci', // CI/CD changes +- 'build', // Build system changes +- 'revert', // Reverting changes +- 'security', // Security fixes +- ], +- ], +- 'type-case': [2, 'always', 'lower-case'], +- 'type-empty': [2, 'never'], +- 'scope-case': [2, 'always', 'lower-case'], +- 'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']], +- 'subject-empty': [2, 'never'], +- 'subject-full-stop': [2, 'never', '.'], +- 'header-max-length': [2, 'always', 100], +- 'body-leading-blank': [1, 'always'], +- 'body-max-line-length': [0, 'always', 150], +- 'footer-leading-blank': [1, 'always'], +- 'footer-max-line-length': [0, 'always', 150], +- }, +-}; +-- +2.43.0 + + +From 23d5323fa47afff0b17a1e564cebad5d570b2b41 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:27:07 +0000 +Subject: [PATCH 03/13] feat: migrate project to ES Modules (ESM) + +--- + package.json | 6 +++--- + tsconfig.json | 5 +++-- + tsup.config.ts | 4 +++- + 3 files changed, 9 insertions(+), 6 deletions(-) + +diff --git a/package.json b/package.json +index 009782b7..bcf2ecba 100644 +--- a/package.json ++++ b/package.json +@@ -3,7 +3,7 @@ + "version": "2.3.6", + "description": "Rest api for communication with WhatsApp", + "main": "./dist/main.js", +- "type": "commonjs", ++ "type": "module", + "scripts": { + "build": "tsc --noEmit && tsup", + "start": "tsx ./src/main.ts", +@@ -77,7 +77,7 @@ + "amqplib": "^0.10.5", + "audio-decode": "^2.2.3", + "axios": "^1.7.9", +- "baileys": "7.0.0-rc.6", ++ "baileys": "^7.0.0-rc.6", + "class-validator": "^0.14.1", + "compression": "^1.7.5", + "cors": "^2.8.5", +@@ -152,4 +152,4 @@ + "tsx": "^4.20.5", + "typescript": "^5.7.2" + } +-} ++} +\ No newline at end of file +diff --git a/tsconfig.json b/tsconfig.json +index af814134..bc49928a 100644 +--- a/tsconfig.json ++++ b/tsconfig.json +@@ -4,7 +4,7 @@ + "emitDecoratorMetadata": true, + "declaration": true, + "target": "es2020", +- "module": "CommonJS", ++ "module": "ES2020", + "rootDir": "./", + "resolveJsonModule": true, + "removeComments": true, +@@ -32,6 +32,7 @@ + "exclude": ["node_modules", "./test", "./dist", "./prisma"], + "include": [ + "src/**/*", +- "src/**/*.json" ++ "src/**/*.json", ++ "tsup.config.ts" + ] + } +\ No newline at end of file +diff --git a/tsup.config.ts b/tsup.config.ts +index f09ecd87..1cd22919 100644 +--- a/tsup.config.ts ++++ b/tsup.config.ts +@@ -9,7 +9,9 @@ export default defineConfig({ + sourcemap: true, + clean: true, + minify: true, +- format: ['cjs', 'esm'], ++ format: ['esm'], ++ target: 'es2020', ++ platform: 'node', + onSuccess: async () => { + cpSync('src/utils/translations', 'dist/translations', { recursive: true }); + }, +-- +2.43.0 + + +From 48b6a9d8cf02c48bf8cafa1e8d0b5fed1409e1d4 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:27:11 +0000 +Subject: [PATCH 04/13] fix: add ESM support for __dirname in i18n utility + +--- + src/utils/i18n.ts | 6 +++++- + 1 file changed, 5 insertions(+), 1 deletion(-) + +diff --git a/src/utils/i18n.ts b/src/utils/i18n.ts +index 1e2f8a1b..d7bdc6f6 100644 +--- a/src/utils/i18n.ts ++++ b/src/utils/i18n.ts +@@ -1,7 +1,11 @@ + import { ConfigService, Language } from '@config/env.config'; + import fs from 'fs'; + import i18next from 'i18next'; +-import path from 'path'; ++import path, { dirname } from 'path'; ++import { fileURLToPath } from 'url'; ++ ++const __filename = fileURLToPath(import.meta.url); ++const __dirname = dirname(__filename); + + const languages = ['en', 'pt-BR', 'es']; + const translationsPath = path.join(__dirname, 'translations'); +-- +2.43.0 + + +From 5332241141cf7d50cb88d89587a74dc0c8b8184c Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:27:23 +0000 +Subject: [PATCH 05/13] fix: resolve ChatwootClient constructor issue in ESM + environment + +--- + .../chatwoot/services/chatwoot.service.ts | 32 +++++++++++++++---- + 1 file changed, 25 insertions(+), 7 deletions(-) + +diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +index cc2bd9e4..04ff1f74 100644 +--- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts ++++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +@@ -9,7 +9,7 @@ import { WAMonitoringService } from '@api/services/monitor.service'; + import { Events } from '@api/types/wa.types'; + import { Chatwoot, ConfigService, Database, HttpServer } from '@config/env.config'; + import { Logger } from '@config/logger.config'; +-import ChatwootClient, { ++import { + ChatwootAPIConfig, + contact, + contact_inboxes, +@@ -18,7 +18,7 @@ import ChatwootClient, { + generic_id, + inbox, + } from '@figuro/chatwoot-sdk'; +-import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request'; ++import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request.js'; + import { Chatwoot as ChatwootModel, Contact as ContactModel, Message as MessageModel } from '@prisma/client'; + import i18next from '@utils/i18n'; + import { sendTelemetry } from '@utils/sendTelemetry'; +@@ -29,9 +29,13 @@ import FormData from 'form-data'; + import { Jimp, JimpMime } from 'jimp'; + import Long from 'long'; + import mimeTypes from 'mime-types'; ++import { createRequire } from 'module'; + import path from 'path'; + import { Readable } from 'stream'; + ++const require = createRequire(import.meta.url); ++const ChatwootClient = require('@figuro/chatwoot-sdk').default || require('@figuro/chatwoot-sdk'); ++ + interface ChatwootMessage { + messageId?: number; + inboxId?: number; +@@ -110,7 +114,14 @@ export class ChatwootService { + } + + public async create(instance: InstanceDto, data: ChatwootDto) { +- await this.waMonitor.waInstances[instance.instanceName].setChatwoot(data); ++ const waInstance = this.waMonitor.waInstances[instance.instanceName]; ++ ++ if (!waInstance) { ++ this.logger.error(`Instance ${instance.instanceName} not found`); ++ throw new Error(`Instance ${instance.instanceName} not found`); ++ } ++ ++ await waInstance.setChatwoot(data); + + if (data.autoCreate) { + this.logger.log('Auto create chatwoot instance'); +@@ -131,9 +142,16 @@ export class ChatwootService { + + public async find(instance: InstanceDto): Promise { + try { +- return await this.waMonitor.waInstances[instance.instanceName].findChatwoot(); +- } catch { +- this.logger.error('chatwoot not found'); ++ const waInstance = this.waMonitor.waInstances[instance.instanceName]; ++ ++ if (!waInstance) { ++ this.logger.error(`Instance ${instance.instanceName} not found`); ++ return { enabled: null, url: '' }; ++ } ++ ++ return await waInstance.findChatwoot(); ++ } catch (error) { ++ this.logger.error(`chatwoot not found: ${error?.toString()}`); + return { enabled: null, url: '' }; + } + } +@@ -1256,7 +1274,7 @@ export class ChatwootService { + + public async receiveWebhook(instance: InstanceDto, body: any) { + try { +- await new Promise((resolve) => setTimeout(resolve, 500)); ++ // Removed fixed 500ms delay to improve response time + + const client = await this.clientCw(instance); + +-- +2.43.0 + + +From ebc723e705c98482d1632ab2cb14dc7350e573bb Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:27:36 +0000 +Subject: [PATCH 06/13] fix: add .js extension to amqplib import for ESM + compatibility + +--- + src/api/integrations/event/rabbitmq/rabbitmq.controller.ts | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts +index 3295b12d..9de38dbf 100644 +--- a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts ++++ b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts +@@ -2,7 +2,7 @@ import { PrismaRepository } from '@api/repository/repository.service'; + import { WAMonitoringService } from '@api/services/monitor.service'; + import { configService, Log, Rabbitmq } from '@config/env.config'; + import { Logger } from '@config/logger.config'; +-import * as amqp from 'amqplib/callback_api'; ++import * as amqp from 'amqplib/callback_api.js'; + + import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +-- +2.43.0 + + +From 1cc861dfba753fe2c440c000a456cb0656a09e25 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:27:46 +0000 +Subject: [PATCH 07/13] fix: add improved error handling for instance + validation + +--- + src/api/abstract/abstract.router.ts | 7 ++- + .../whatsapp/whatsapp.baileys.service.ts | 4 +- + .../controllers/chatwoot.controller.ts | 61 ++++++++++--------- + 3 files changed, 41 insertions(+), 31 deletions(-) + +diff --git a/src/api/abstract/abstract.router.ts b/src/api/abstract/abstract.router.ts +index e8449a8c..bdffb3eb 100644 +--- a/src/api/abstract/abstract.router.ts ++++ b/src/api/abstract/abstract.router.ts +@@ -59,7 +59,12 @@ export abstract class RouterBroker { + throw new BadRequestException(message); + } + +- return await execute(instance, ref); ++ try { ++ return await execute(instance, ref); ++ } catch (error) { ++ logger.error(`Error executing route: ${error?.message || error}`); ++ throw error; ++ } + } + + public async groupNoValidate(args: DataValidate) { +diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +index 1e3bdcf1..8ecd09b0 100644 +--- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts ++++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +@@ -3398,7 +3398,7 @@ export class BaileysStartupService extends ChannelStartupService { + + if (normalNumbersNotInCache.length > 0) { + this.logger.verbose(`Checking ${normalNumbersNotInCache.length} numbers via Baileys (not found in cache)`); +- verify = await this.client.onWhatsApp(...normalNumbersNotInCache); ++ verify = (await this.client.onWhatsApp(...normalNumbersNotInCache)) as any; + } + + const verifiedUsers = await Promise.all( +@@ -4709,7 +4709,7 @@ export class BaileysStartupService extends ChannelStartupService { + public async baileysGenerateMessageTag() { + const response = await this.client.generateMessageTag(); + +- return response; ++ return response || ''; + } + + public async baileysSignalRepositoryDecryptMessage(jid: string, type: 'pkmsg' | 'msg', ciphertext: string) { +diff --git a/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts +index 17cdce01..4877fdb3 100644 +--- a/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts ++++ b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts +@@ -17,41 +17,46 @@ export class ChatwootController { + ) {} + + public async createChatwoot(instance: InstanceDto, data: ChatwootDto) { +- if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); +- +- if (data?.enabled) { +- if (!isURL(data.url, { require_tld: false })) { +- throw new BadRequestException('url is not valid'); ++ try { ++ if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); ++ ++ if (data?.enabled) { ++ if (!isURL(data.url, { require_tld: false })) { ++ throw new BadRequestException('url is not valid'); ++ } ++ ++ if (!data.accountId) { ++ throw new BadRequestException('accountId is required'); ++ } ++ ++ if (!data.token) { ++ throw new BadRequestException('token is required'); ++ } ++ ++ if (data.signMsg !== true && data.signMsg !== false) { ++ throw new BadRequestException('signMsg is required'); ++ } ++ if (data.signMsg === false) data.signDelimiter = null; + } + +- if (!data.accountId) { +- throw new BadRequestException('accountId is required'); ++ if (!data.nameInbox || data.nameInbox === '') { ++ data.nameInbox = instance.instanceName; + } + +- if (!data.token) { +- throw new BadRequestException('token is required'); +- } ++ const result = await this.chatwootService.create(instance, data); + +- if (data.signMsg !== true && data.signMsg !== false) { +- throw new BadRequestException('signMsg is required'); +- } +- if (data.signMsg === false) data.signDelimiter = null; +- } ++ const urlServer = this.configService.get('SERVER').URL; + +- if (!data.nameInbox || data.nameInbox === '') { +- data.nameInbox = instance.instanceName; +- } +- +- const result = await this.chatwootService.create(instance, data); +- +- const urlServer = this.configService.get('SERVER').URL; +- +- const response = { +- ...result, +- webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`, +- }; ++ const response = { ++ ...result, ++ webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`, ++ }; + +- return response; ++ return response; ++ } catch (error) { ++ console.error('Error in createChatwoot:', error); ++ throw error; ++ } + } + + public async findChatwoot(instance: InstanceDto): Promise { +-- +2.43.0 + + +From 973114bede128ac26c7bf3800cc748b86d44c506 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:28:03 +0000 +Subject: [PATCH 08/13] perf: reduce retry delay from 1000ms to 200ms for + faster message processing + +--- + .../integrations/channel/whatsapp/baileysMessage.processor.ts | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts +index c2c5931e..2ad1b28b 100644 +--- a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts ++++ b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts +@@ -29,7 +29,7 @@ export class BaileysMessageProcessor { + retryWhen((errors) => + errors.pipe( + tap((error) => this.processorLogs.warn(`Retrying message batch due to error: ${error.message}`)), +- delay(1000), // 1 segundo de delay ++ delay(200), // Reduzido para 200ms de delay + take(3), // Máximo 3 tentativas + ), + ), +-- +2.43.0 + + +From ff7fd02f332d7f6642abe6da0f38fdd032faa2b6 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:28:12 +0000 +Subject: [PATCH 09/13] perf: optimize message delay timing (min: 500ms, max: + 8s) + +--- + src/api/integrations/chatbot/base-chatbot.service.ts | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/src/api/integrations/chatbot/base-chatbot.service.ts b/src/api/integrations/chatbot/base-chatbot.service.ts +index 11f71b17..e84a0069 100644 +--- a/src/api/integrations/chatbot/base-chatbot.service.ts ++++ b/src/api/integrations/chatbot/base-chatbot.service.ts +@@ -275,8 +275,8 @@ export abstract class BaseChatbotService { + linkPreview: boolean = true, + ): Promise { + const timePerChar = settings?.timePerChar ?? 0; +- const minDelay = 1000; +- const maxDelay = 20000; ++ const minDelay = 500; // Reduzido de 1000ms para 500ms ++ const maxDelay = 8000; // Reduzido de 20000ms para 8000ms + const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); + + this.logger.debug(`[BaseChatbot] Sending single message with linkPreview: ${linkPreview}`); +-- +2.43.0 + + +From 5cb478f88db4be96f3156abc1f849d3d8f174f0a Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:28:21 +0000 +Subject: [PATCH 10/13] chore: update package-lock.json for ESM migration + +--- + package-lock.json | 6 +----- + 1 file changed, 1 insertion(+), 5 deletions(-) + +diff --git a/package-lock.json b/package-lock.json +index c9c50513..ccd25f4b 100644 +--- a/package-lock.json ++++ b/package-lock.json +@@ -21,7 +21,7 @@ + "amqplib": "^0.10.5", + "audio-decode": "^2.2.3", + "axios": "^1.7.9", +- "baileys": "7.0.0-rc.6", ++ "baileys": "^7.0.0-rc.6", + "class-validator": "^0.14.1", + "compression": "^1.7.5", + "cors": "^2.8.5", +@@ -5860,7 +5860,6 @@ + "resolved": "https://registry.npmjs.org/baileys/-/baileys-7.0.0-rc.6.tgz", + "integrity": "sha512-Unt58dy39rFQ3dRgTUxT38/AXWInNLYx9zijU7PpHDeoNdJfvgyROnHLtmh9hAglLKA1t374v1JLnfI5Tk/TSQ==", + "hasInstallScript": true, +- "license": "MIT", + "dependencies": { + "@cacheable/node-cache": "^1.4.0", + "@hapi/boom": "^9.1.3", +@@ -11289,7 +11288,6 @@ + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz", + "integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==", +- "license": "ISC", + "engines": { + "node": "20 || >=22" + } +@@ -12456,7 +12454,6 @@ + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.0.0.tgz", + "integrity": "sha512-KO1RyxstL9g1mK76530TExamZC/S2Glm080Nx8PE5sTd7nlduDQsAfEl4uXX+qZjLiwvDauvzXavufy3+rJ9zQ==", +- "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.1", + "p-timeout": "^7.0.0" +@@ -12472,7 +12469,6 @@ + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz", + "integrity": "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==", +- "license": "MIT", + "engines": { + "node": ">=20" + }, +-- +2.43.0 + + +From 2257b566cf0b714edd6ac96bf76496f68e2e404d Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:33:33 +0000 +Subject: [PATCH 11/13] fix: correct broadcast check to use remoteJid for + Chatwoot integration + +--- + .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +index 8ecd09b0..2bbc2482 100644 +--- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts ++++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +@@ -1207,7 +1207,7 @@ export class BaileysStartupService extends ChannelStartupService { + if ( + this.configService.get('CHATWOOT').ENABLED && + this.localChatwoot?.enabled && +- !received.key.id.includes('@broadcast') ++ received.key.remoteJid !== 'status@broadcast' + ) { + const chatwootSentMessage = await this.chatwootService.eventWhatsapp( + Events.MESSAGES_UPSERT, +-- +2.43.0 + + +From 15bab7f14a07af4bd4fa0c90abfc8b491dba4941 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:38:57 +0000 +Subject: [PATCH 12/13] perf: add error handling for Chatwoot database check to + prevent delays + +--- + .../chatbot/chatwoot/services/chatwoot.service.ts | 9 ++++++--- + 1 file changed, 6 insertions(+), 3 deletions(-) + +diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +index 04ff1f74..078ac92b 100644 +--- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts ++++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +@@ -1027,12 +1027,15 @@ export class ChatwootService { + quotedMsg?: MessageModel, + ) { + if (sourceId && this.isImportHistoryAvailable()) { +- const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); +- if (messageAlreadySaved) { +- if (messageAlreadySaved.size > 0) { ++ try { ++ const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); ++ if (messageAlreadySaved && messageAlreadySaved.size > 0) { + this.logger.warn('Message already saved on chatwoot'); + return null; + } ++ } catch (error) { ++ // Ignore database connection errors and continue sending message ++ this.logger.verbose(`Could not check duplicate message (database unavailable): ${error?.message || error}`); + } + } + const data = new FormData(); +-- +2.43.0 + + +From e62ef3e063ab96192ef3d1b1e24ed805fe0c4b54 Mon Sep 17 00:00:00 2001 +From: Seu Nome +Date: Sat, 25 Oct 2025 17:45:36 +0000 +Subject: [PATCH 13/13] perf: reduce keepAliveIntervalMs to prevent WebSocket + connection timeout + +--- + .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +index 2bbc2482..ee18903d 100644 +--- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts ++++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +@@ -635,8 +635,8 @@ export class BaileysStartupService extends ChannelStartupService { + retryRequestDelayMs: 350, + maxMsgRetryCount: 4, + fireInitQueries: true, +- connectTimeoutMs: 30_000, +- keepAliveIntervalMs: 30_000, ++ connectTimeoutMs: 60_000, ++ keepAliveIntervalMs: 10_000, + qrTimeout: 45_000, + emitOwnEvents: false, + shouldIgnoreJid: (jid) => { +-- +2.43.0 + diff --git a/package-lock.json b/package-lock.json index c9c50513a..ccd25f4bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,7 @@ "amqplib": "^0.10.5", "audio-decode": "^2.2.3", "axios": "^1.7.9", - "baileys": "7.0.0-rc.6", + "baileys": "^7.0.0-rc.6", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", @@ -5860,7 +5860,6 @@ "resolved": "https://registry.npmjs.org/baileys/-/baileys-7.0.0-rc.6.tgz", "integrity": "sha512-Unt58dy39rFQ3dRgTUxT38/AXWInNLYx9zijU7PpHDeoNdJfvgyROnHLtmh9hAglLKA1t374v1JLnfI5Tk/TSQ==", "hasInstallScript": true, - "license": "MIT", "dependencies": { "@cacheable/node-cache": "^1.4.0", "@hapi/boom": "^9.1.3", @@ -11289,7 +11288,6 @@ "version": "11.2.2", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz", "integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==", - "license": "ISC", "engines": { "node": "20 || >=22" } @@ -12456,7 +12454,6 @@ "version": "9.0.0", "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.0.0.tgz", "integrity": "sha512-KO1RyxstL9g1mK76530TExamZC/S2Glm080Nx8PE5sTd7nlduDQsAfEl4uXX+qZjLiwvDauvzXavufy3+rJ9zQ==", - "license": "MIT", "dependencies": { "eventemitter3": "^5.0.1", "p-timeout": "^7.0.0" @@ -12472,7 +12469,6 @@ "version": "7.0.1", "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz", "integrity": "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==", - "license": "MIT", "engines": { "node": ">=20" }, diff --git a/package.json b/package.json index 009782b7c..bcf2ecbab 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "2.3.6", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", - "type": "commonjs", + "type": "module", "scripts": { "build": "tsc --noEmit && tsup", "start": "tsx ./src/main.ts", @@ -77,7 +77,7 @@ "amqplib": "^0.10.5", "audio-decode": "^2.2.3", "axios": "^1.7.9", - "baileys": "7.0.0-rc.6", + "baileys": "^7.0.0-rc.6", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", @@ -152,4 +152,4 @@ "tsx": "^4.20.5", "typescript": "^5.7.2" } -} +} \ No newline at end of file diff --git a/src/api/abstract/abstract.router.ts b/src/api/abstract/abstract.router.ts index e8449a8c8..bdffb3eb3 100644 --- a/src/api/abstract/abstract.router.ts +++ b/src/api/abstract/abstract.router.ts @@ -59,7 +59,12 @@ export abstract class RouterBroker { throw new BadRequestException(message); } - return await execute(instance, ref); + try { + return await execute(instance, ref); + } catch (error) { + logger.error(`Error executing route: ${error?.message || error}`); + throw error; + } } public async groupNoValidate(args: DataValidate) { diff --git a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts index c2c5931ef..cca949c5d 100644 --- a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts +++ b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts @@ -1,6 +1,6 @@ import { Logger } from '@config/logger.config'; import { BaileysEventMap, MessageUpsertType, WAMessage } from 'baileys'; -import { catchError, concatMap, delay, EMPTY, from, retryWhen, Subject, Subscription, take, tap } from 'rxjs'; +import { catchError, delay, EMPTY, from, mergeMap, retryWhen, Subject, Subscription, take, tap } from 'rxjs'; type MessageUpsertPayload = BaileysEventMap['messages.upsert']; type MountProps = { @@ -22,18 +22,29 @@ export class BaileysMessageProcessor { this.subscription = this.messageSubject .pipe( tap(({ messages }) => { - this.processorLogs.log(`Processing batch of ${messages.length} messages`); + const timestamp = new Date().toISOString(); + this.processorLogs.log(`[${timestamp}] Processing batch of ${messages.length} messages`); }), - concatMap(({ messages, type, requestId, settings }) => - from(onMessageReceive({ messages, type, requestId }, settings)).pipe( - retryWhen((errors) => - errors.pipe( - tap((error) => this.processorLogs.warn(`Retrying message batch due to error: ${error.message}`)), - delay(1000), // 1 segundo de delay - take(3), // Máximo 3 tentativas + // Changed from concatMap to mergeMap with concurrency limit of 3 + // This allows processing up to 3 messages in parallel instead of sequentially + mergeMap( + ({ messages, type, requestId, settings }) => { + const startTime = Date.now(); + return from(onMessageReceive({ messages, type, requestId }, settings)).pipe( + tap(() => { + const duration = Date.now() - startTime; + this.processorLogs.log(`Batch processed in ${duration}ms`); + }), + retryWhen((errors) => + errors.pipe( + tap((error) => this.processorLogs.warn(`Retrying message batch due to error: ${error.message}`)), + delay(200), // Reduzido para 200ms de delay + take(3), // Máximo 3 tentativas + ), ), - ), - ), + ); + }, + 3, // Process up to 3 messages concurrently ), catchError((error) => { this.processorLogs.error(`Error processing message batch: ${error}`); @@ -49,6 +60,8 @@ export class BaileysMessageProcessor { processMessage(payload: MessageUpsertPayload, settings: any) { const { messages, type, requestId } = payload; + const timestamp = new Date().toISOString(); + this.processorLogs.log(`[${timestamp}] Message added to queue: ${messages.length} message(s)`); this.messageSubject.next({ messages, type, requestId, settings }); } diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 1e3bdcf13..fe78e1a83 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -635,8 +635,8 @@ export class BaileysStartupService extends ChannelStartupService { retryRequestDelayMs: 350, maxMsgRetryCount: 4, fireInitQueries: true, - connectTimeoutMs: 30_000, - keepAliveIntervalMs: 30_000, + connectTimeoutMs: 60_000, + keepAliveIntervalMs: 5_000, // Reduced to 5s to prevent WebSocket timeout in production qrTimeout: 45_000, emitOwnEvents: false, shouldIgnoreJid: (jid) => { @@ -1207,7 +1207,7 @@ export class BaileysStartupService extends ChannelStartupService { if ( this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && - !received.key.id.includes('@broadcast') + received.key.remoteJid !== 'status@broadcast' ) { const chatwootSentMessage = await this.chatwootService.eventWhatsapp( Events.MESSAGES_UPSERT, @@ -1759,6 +1759,11 @@ export class BaileysStartupService extends ChannelStartupService { if (events['messages.upsert']) { const payload = events['messages.upsert']; + // Log timestamp to diagnose message batching issues + this.logger.verbose( + `Received ${payload.messages.length} message(s) from WebSocket at ${new Date().toISOString()}`, + ); + this.messageProcessor.processMessage(payload, settings); // this.messageHandle['messages.upsert'](payload, settings); } @@ -3398,7 +3403,7 @@ export class BaileysStartupService extends ChannelStartupService { if (normalNumbersNotInCache.length > 0) { this.logger.verbose(`Checking ${normalNumbersNotInCache.length} numbers via Baileys (not found in cache)`); - verify = await this.client.onWhatsApp(...normalNumbersNotInCache); + verify = (await this.client.onWhatsApp(...normalNumbersNotInCache)) as any; } const verifiedUsers = await Promise.all( @@ -4709,7 +4714,7 @@ export class BaileysStartupService extends ChannelStartupService { public async baileysGenerateMessageTag() { const response = await this.client.generateMessageTag(); - return response; + return response || ''; } public async baileysSignalRepositoryDecryptMessage(jid: string, type: 'pkmsg' | 'msg', ciphertext: string) { diff --git a/src/api/integrations/chatbot/base-chatbot.service.ts b/src/api/integrations/chatbot/base-chatbot.service.ts index 11f71b17e..e84a0069b 100644 --- a/src/api/integrations/chatbot/base-chatbot.service.ts +++ b/src/api/integrations/chatbot/base-chatbot.service.ts @@ -275,8 +275,8 @@ export abstract class BaseChatbotService { linkPreview: boolean = true, ): Promise { const timePerChar = settings?.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; + const minDelay = 500; // Reduzido de 1000ms para 500ms + const maxDelay = 8000; // Reduzido de 20000ms para 8000ms const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); this.logger.debug(`[BaseChatbot] Sending single message with linkPreview: ${linkPreview}`); diff --git a/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts index 17cdce01d..fb02472ca 100644 --- a/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts +++ b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts @@ -17,41 +17,44 @@ export class ChatwootController { ) {} public async createChatwoot(instance: InstanceDto, data: ChatwootDto) { - if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); - - if (data?.enabled) { - if (!isURL(data.url, { require_tld: false })) { - throw new BadRequestException('url is not valid'); + try { + if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); + + if (data?.enabled) { + if (!isURL(data.url, { require_tld: false })) { + throw new BadRequestException('url is not valid'); + } + + if (!data.accountId) { + throw new BadRequestException('accountId is required'); + } + + if (!data.token) { + throw new BadRequestException('token is required'); + } + + if (data.signMsg !== true && data.signMsg !== false) { + throw new BadRequestException('signMsg is required'); + } + if (data.signMsg === false) data.signDelimiter = null; } - if (!data.accountId) { - throw new BadRequestException('accountId is required'); + if (!data.nameInbox || data.nameInbox === '') { + data.nameInbox = instance.instanceName; } - if (!data.token) { - throw new BadRequestException('token is required'); - } + const result = await this.chatwootService.create(instance, data); - if (data.signMsg !== true && data.signMsg !== false) { - throw new BadRequestException('signMsg is required'); - } - if (data.signMsg === false) data.signDelimiter = null; - } + const urlServer = this.configService.get('SERVER').URL; - if (!data.nameInbox || data.nameInbox === '') { - data.nameInbox = instance.instanceName; + return { + ...result, + webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`, + }; + } catch (error) { + console.error('Error in createChatwoot:', error); + throw error; } - - const result = await this.chatwootService.create(instance, data); - - const urlServer = this.configService.get('SERVER').URL; - - const response = { - ...result, - webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`, - }; - - return response; } public async findChatwoot(instance: InstanceDto): Promise { @@ -73,12 +76,10 @@ export class ChatwootController { }; } - const response = { + return { ...result, webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`, }; - - return response; } public async receiveWebhook(instance: InstanceDto, data: any) { diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index cc2bd9e4d..9c99ae56d 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -9,7 +9,7 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { Events } from '@api/types/wa.types'; import { Chatwoot, ConfigService, Database, HttpServer } from '@config/env.config'; import { Logger } from '@config/logger.config'; -import ChatwootClient, { +import { ChatwootAPIConfig, contact, contact_inboxes, @@ -18,7 +18,7 @@ import ChatwootClient, { generic_id, inbox, } from '@figuro/chatwoot-sdk'; -import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request'; +import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request.js'; import { Chatwoot as ChatwootModel, Contact as ContactModel, Message as MessageModel } from '@prisma/client'; import i18next from '@utils/i18n'; import { sendTelemetry } from '@utils/sendTelemetry'; @@ -29,9 +29,13 @@ import FormData from 'form-data'; import { Jimp, JimpMime } from 'jimp'; import Long from 'long'; import mimeTypes from 'mime-types'; +import { createRequire } from 'module'; import path from 'path'; import { Readable } from 'stream'; +const require = createRequire(import.meta.url); +const ChatwootClient = require('@figuro/chatwoot-sdk').default || require('@figuro/chatwoot-sdk'); + interface ChatwootMessage { messageId?: number; inboxId?: number; @@ -110,7 +114,14 @@ export class ChatwootService { } public async create(instance: InstanceDto, data: ChatwootDto) { - await this.waMonitor.waInstances[instance.instanceName].setChatwoot(data); + const waInstance = this.waMonitor.waInstances[instance.instanceName]; + + if (!waInstance) { + this.logger.error(`Instance ${instance.instanceName} not found`); + throw new Error(`Instance ${instance.instanceName} not found`); + } + + await waInstance.setChatwoot(data); if (data.autoCreate) { this.logger.log('Auto create chatwoot instance'); @@ -131,9 +142,16 @@ export class ChatwootService { public async find(instance: InstanceDto): Promise { try { - return await this.waMonitor.waInstances[instance.instanceName].findChatwoot(); - } catch { - this.logger.error('chatwoot not found'); + const waInstance = this.waMonitor.waInstances[instance.instanceName]; + + if (!waInstance) { + this.logger.error(`Instance ${instance.instanceName} not found`); + return { enabled: null, url: '' }; + } + + return await waInstance.findChatwoot(); + } catch (error) { + this.logger.error(`chatwoot not found: ${error?.toString()}`); return { enabled: null, url: '' }; } } @@ -1009,12 +1027,15 @@ export class ChatwootService { quotedMsg?: MessageModel, ) { if (sourceId && this.isImportHistoryAvailable()) { - const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); - if (messageAlreadySaved) { - if (messageAlreadySaved.size > 0) { + try { + const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); + if (messageAlreadySaved && messageAlreadySaved.size > 0) { this.logger.warn('Message already saved on chatwoot'); return null; } + } catch (error) { + // Ignore database connection errors and continue sending message + this.logger.verbose(`Could not check duplicate message (database unavailable): ${error?.message || error}`); } } const data = new FormData(); @@ -1256,7 +1277,7 @@ export class ChatwootService { public async receiveWebhook(instance: InstanceDto, body: any) { try { - await new Promise((resolve) => setTimeout(resolve, 500)); + // Removed fixed 500ms delay to improve response time const client = await this.clientCw(instance); @@ -2275,7 +2296,9 @@ export class ChatwootService { const message = await this.getMessageByKeyId(instance, body?.key?.id); if (!message) { - this.logger.warn('Message not found for edit event'); + this.logger.verbose( + `Message not found for edit event (keyId: ${body?.key?.id}) - message may not have been saved to database`, + ); return; } diff --git a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts index a4fd01df4..cefa39b90 100644 --- a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -201,7 +201,8 @@ class ChatwootImport { return existingSourceIdsSet; } catch (error) { - this.logger.error(`Error on getExistingSourceIds: ${error.toString()}`); + // Log as verbose instead of error when Chatwoot PostgreSQL database is not configured + this.logger.verbose(`Could not query Chatwoot database (database may not be configured): ${error.toString()}`); return new Set(); } } diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts index 3295b12de..9de38dbf8 100644 --- a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts +++ b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts @@ -2,7 +2,7 @@ import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { configService, Log, Rabbitmq } from '@config/env.config'; import { Logger } from '@config/logger.config'; -import * as amqp from 'amqplib/callback_api'; +import * as amqp from 'amqplib/callback_api.js'; import { EmitData, EventController, EventControllerInterface } from '../event.controller'; diff --git a/src/main.ts b/src/main.ts index 44a6187b6..494a4c998 100644 --- a/src/main.ts +++ b/src/main.ts @@ -70,6 +70,9 @@ async function bootstrap() { app.use('/store', express.static(join(ROOT_DIR, 'store'))); + // Serve QR Code Vue.js extension + app.use('/qrcode', express.static(join(ROOT_DIR, 'dist_extensions'))); + app.use('/', router); app.use( diff --git a/src/utils/i18n.ts b/src/utils/i18n.ts index 1e2f8a1bd..d7bdc6f6b 100644 --- a/src/utils/i18n.ts +++ b/src/utils/i18n.ts @@ -1,7 +1,11 @@ import { ConfigService, Language } from '@config/env.config'; import fs from 'fs'; import i18next from 'i18next'; -import path from 'path'; +import path, { dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const languages = ['en', 'pt-BR', 'es']; const translationsPath = path.join(__dirname, 'translations'); diff --git a/tsconfig.json b/tsconfig.json index af814134a..bc49928ab 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,7 @@ "emitDecoratorMetadata": true, "declaration": true, "target": "es2020", - "module": "CommonJS", + "module": "ES2020", "rootDir": "./", "resolveJsonModule": true, "removeComments": true, @@ -32,6 +32,7 @@ "exclude": ["node_modules", "./test", "./dist", "./prisma"], "include": [ "src/**/*", - "src/**/*.json" + "src/**/*.json", + "tsup.config.ts" ] } \ No newline at end of file diff --git a/tsup.config.ts b/tsup.config.ts index f09ecd877..1cd229190 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -9,7 +9,9 @@ export default defineConfig({ sourcemap: true, clean: true, minify: true, - format: ['cjs', 'esm'], + format: ['esm'], + target: 'es2020', + platform: 'node', onSuccess: async () => { cpSync('src/utils/translations', 'dist/translations', { recursive: true }); },