diff --git a/.dockerignore b/.dockerignore index 0d406464..eb211532 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,7 @@ .git *Dockerfile* *docker-compose* +package-lock.json +.env node_modules dist \ No newline at end of file diff --git a/.env.example b/.env.example index 637a3d7e..c0cefda6 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,9 @@ SERVER_PORT=8080 # Server URL - Set your application url SERVER_URL=http://localhost:8080 +SSL_CONF_PRIVKEY=/path/to/cert.key +SSL_CONF_FULLCHAIN=/path/to/cert.crt + SENTRY_DSN= # Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com' @@ -47,6 +50,7 @@ DATABASE_DELETE_MESSAGE=true RABBITMQ_ENABLED=false RABBITMQ_URI=amqp://localhost RABBITMQ_EXCHANGE_NAME=evolution +RABBITMQ_FRAME_MAX=8192 # Global events - By enabling this variable, events from all instances are sent in the same event queue. RABBITMQ_GLOBAL_ENABLED=false # Prefix key to queue name @@ -62,6 +66,7 @@ RABBITMQ_EVENTS_MESSAGES_EDITED=false RABBITMQ_EVENTS_MESSAGES_UPDATE=false RABBITMQ_EVENTS_MESSAGES_DELETE=false RABBITMQ_EVENTS_SEND_MESSAGE=false +RABBITMQ_EVENTS_SEND_MESSAGE_UPDATE=false RABBITMQ_EVENTS_CONTACTS_SET=false RABBITMQ_EVENTS_CONTACTS_UPSERT=false RABBITMQ_EVENTS_CONTACTS_UPDATE=false @@ -108,6 +113,7 @@ PUSHER_EVENTS_MESSAGES_EDITED=true PUSHER_EVENTS_MESSAGES_UPDATE=true PUSHER_EVENTS_MESSAGES_DELETE=true PUSHER_EVENTS_SEND_MESSAGE=true +PUSHER_EVENTS_SEND_MESSAGE_UPDATE=true PUSHER_EVENTS_CONTACTS_SET=true PUSHER_EVENTS_CONTACTS_UPSERT=true PUSHER_EVENTS_CONTACTS_UPDATE=true @@ -149,6 +155,7 @@ WEBHOOK_EVENTS_MESSAGES_EDITED=true WEBHOOK_EVENTS_MESSAGES_UPDATE=true WEBHOOK_EVENTS_MESSAGES_DELETE=true WEBHOOK_EVENTS_SEND_MESSAGE=true +WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE=true WEBHOOK_EVENTS_CONTACTS_SET=true WEBHOOK_EVENTS_CONTACTS_UPSERT=true WEBHOOK_EVENTS_CONTACTS_UPDATE=true @@ -173,6 +180,15 @@ WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=false WEBHOOK_EVENTS_ERRORS=false WEBHOOK_EVENTS_ERRORS_WEBHOOK= +WEBHOOK_REQUEST_TIMEOUT_MS=60000 +WEBHOOK_RETRY_MAX_ATTEMPTS=10 +WEBHOOK_RETRY_INITIAL_DELAY_SECONDS=5 +WEBHOOK_RETRY_USE_EXPONENTIAL_BACKOFF=true +WEBHOOK_RETRY_MAX_DELAY_SECONDS=300 +WEBHOOK_RETRY_JITTER_FACTOR=0.2 +# Comma separated list of HTTP status codes that should not trigger retries +WEBHOOK_RETRY_NON_RETRYABLE_STATUS_CODES=400,401,403,404,422 + # Name that will be displayed on smartphone connection CONFIG_SESSION_PHONE_CLIENT=Evolution API # Browser Name = Chrome | Firefox | Edge | Opera | Safari @@ -210,6 +226,12 @@ OPENAI_ENABLED=false # Dify - Environment variables DIFY_ENABLED=false +# n8n - Environment variables +N8N_ENABLED=false + +# EvoAI - Environment variables +EVOAI_ENABLED=false + # Cache - Environment variables # Redis Cache enabled CACHE_REDIS_ENABLED=true @@ -266,4 +288,4 @@ LANGUAGE=en # PROXY_PORT=80 # PROXY_PROTOCOL=http # PROXY_USERNAME= -# PROXY_PASSWORD= \ No newline at end of file +# PROXY_PASSWORD= diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml index 68a08a31..09d09390 100644 --- a/.github/workflows/publish_docker_image.yml +++ b/.github/workflows/publish_docker_image.yml @@ -20,7 +20,7 @@ jobs: id: meta uses: docker/metadata-action@v5 with: - images: atendai/evolution-api + images: evoapicloud/evolution-api tags: type=semver,pattern=v{{version}} - name: Set up QEMU diff --git a/.github/workflows/publish_docker_image_homolog.yml b/.github/workflows/publish_docker_image_homolog.yml index 77032dc9..b97a5e25 100644 --- a/.github/workflows/publish_docker_image_homolog.yml +++ b/.github/workflows/publish_docker_image_homolog.yml @@ -20,7 +20,7 @@ jobs: id: meta uses: docker/metadata-action@v5 with: - images: atendai/evolution-api + images: evoapicloud/evolution-api tags: homolog - name: Set up QEMU diff --git a/.github/workflows/publish_docker_image_latest.yml b/.github/workflows/publish_docker_image_latest.yml index 641dc5e0..cffdab01 100644 --- a/.github/workflows/publish_docker_image_latest.yml +++ b/.github/workflows/publish_docker_image_latest.yml @@ -20,7 +20,7 @@ jobs: id: meta uses: docker/metadata-action@v5 with: - images: atendai/evolution-api + images: evoapicloud/evolution-api tags: latest - name: Set up QEMU diff --git a/.gitignore b/.gitignore index a8226ede..1cecfa98 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ /dist /node_modules +.cursor* + /Docker/.env .vscode diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d316041..38211249 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,32 @@ +# 2.3.0 (develop) + +### Feature + +* Add support to get Catalogs and Collections with new routes: '{{baseUrl}}/chat/fetchCatalogs' and '{{baseUrl}}/chat/fetchCollections' +* Add NATS integration support to the event system +* Add message location support meta +* Add S3_SKIP_POLICY env variable to disable setBucketPolicy for incompatible providers +* Add EvoAI integration with models, services, and routes +* Add N8n integration with models, services, and routes + +### Fixed + +* Shell injection vulnerability +* Update Baileys Version v6.7.17 +* Audio send duplicate from chatwoot +* Chatwoot csat creating new conversation in another language +* Refactor SQS controller to correct bug in sqs events by instance +* Adjustin cloud api send audio and video +* Preserve animation in GIF and WebP stickers +* Preventing use conversation from other inbox for the same user +* Ensure full WhatsApp compatibility for audio conversion (libopus, 48kHz, mono) +* Enhance message fetching and processing logic + +### Security + +* Change execSync to execFileSync +* Enhance WebSocket authentication and connection handling + # 2.2.3 (2025-02-03 11:52) ### Fixed diff --git a/Docker/swarm/evolution_api_v2.yaml b/Docker/swarm/evolution_api_v2.yaml index 894f1f80..db06823b 100644 --- a/Docker/swarm/evolution_api_v2.yaml +++ b/Docker/swarm/evolution_api_v2.yaml @@ -2,7 +2,7 @@ version: "3.7" services: evolution_v2: - image: atendai/evolution-api:v2.2.3 + image: atendai/evolution-api:v2.2.3 volumes: - evolution_instances:/evolution/instances networks: @@ -34,6 +34,7 @@ services: - RABBITMQ_EVENTS_MESSAGES_UPDATE=false - RABBITMQ_EVENTS_MESSAGES_DELETE=false - RABBITMQ_EVENTS_SEND_MESSAGE=false + - RABBITMQ_EVENTS_SEND_MESSAGE_UPDATE=false - RABBITMQ_EVENTS_CONTACTS_SET=false - RABBITMQ_EVENTS_CONTACTS_UPSERT=false - RABBITMQ_EVENTS_CONTACTS_UPDATE=false @@ -71,6 +72,7 @@ services: - WEBHOOK_EVENTS_MESSAGES_UPDATE=true - WEBHOOK_EVENTS_MESSAGES_DELETE=true - WEBHOOK_EVENTS_SEND_MESSAGE=true + - WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE=true - WEBHOOK_EVENTS_CONTACTS_SET=true - WEBHOOK_EVENTS_CONTACTS_UPSERT=true - WEBHOOK_EVENTS_CONTACTS_UPDATE=true diff --git a/Dockerfile b/Dockerfile index ca61b39a..fc535aa2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ FROM node:20-alpine AS builder RUN apk update && \ - apk add git ffmpeg wget curl bash openssl + apk add --no-cache git ffmpeg wget curl bash openssl -LABEL version="2.2.3" description="Api to control whatsapp features through http requests." +LABEL version="2.3.0" description="Api to control whatsapp features through http requests." LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes" -LABEL contact="contato@atendai.com" +LABEL contact="contato@evolution-api.com" WORKDIR /evolution diff --git a/LICENSE b/LICENSE index da01e779..ad430f14 100644 --- a/LICENSE +++ b/LICENSE @@ -8,7 +8,7 @@ a. LOGO and copyright information: In the process of using Evolution API's front b. Usage Notification Requirement: If Evolution API is used as part of any project, including closed-source systems (e.g., proprietary software), the user is required to display a clear notification within the system that Evolution API is being utilized. This notification should be visible to system administrators and accessible from the system's documentation or settings page. Failure to comply with this requirement may result in the necessity for a commercial license, as determined by the producer. -Please contact contato@atendai.com to inquire about licensing matters. +Please contact contato@evolution-api.com to inquire about licensing matters. 2. As a contributor, you should agree that: diff --git a/README.md b/README.md index 93197499..6e40ce74 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@
+[![Docker Image (https://img.shields.io/badge/Docker-Image-blue)](https://hub.docker.com/r/evoapicloud/evolution-api)] [![Whatsapp Group](https://img.shields.io/badge/Group-WhatsApp-%2322BC18)](https://evolution-api.com/whatsapp) [![Discord Community](https://img.shields.io/badge/Discord-Community-blue)](https://evolution-api.com/discord) [![Postman Collection](https://img.shields.io/badge/Postman-Collection-orange)](https://evolution-api.com/postman) @@ -87,6 +88,7 @@ https://github.com/sponsors/EvolutionAPI We are proud to collaborate with the following content creators who have contributed valuable insights and tutorials about Evolution API: - [Promovaweb](https://www.youtube.com/@promovaweb) +- [Sandeco](https://www.youtube.com/@canalsandeco) - [Comunidade ZDG](https://www.youtube.com/@ComunidadeZDG) - [Francis MNO](https://www.youtube.com/@FrancisMNO) - [Pablo Cabral](https://youtube.com/@pablocabral) @@ -111,7 +113,7 @@ Evolution API is licensed under the Apache License 2.0, with the following addit 2. **Usage Notification Requirement**: If Evolution API is used as part of any project, including closed-source systems (e.g., proprietary software), the user is required to display a clear notification within the system that Evolution API is being utilized. This notification should be visible to system administrators and accessible from the system's documentation or settings page. Failure to comply with this requirement may result in the necessity for a commercial license, as determined by the producer. -Please contact contato@atendai.com to inquire about licensing matters. +Please contact contato@evolution-api.com to inquire about licensing matters. Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0). diff --git a/docker-compose.yaml b/docker-compose.yaml index 9a60a9a9..33918c38 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,7 +1,7 @@ services: api: container_name: evolution_api - image: atendai/evolution-api:homolog + image: evoapicloud/evolution-api:latest restart: always depends_on: - redis diff --git a/manager/dist/assets/index-CFAZX6IV.js b/manager/dist/assets/index-CFAZX6IV.js deleted file mode 100644 index ffa565ff..00000000 --- a/manager/dist/assets/index-CFAZX6IV.js +++ /dev/null @@ -1,381 +0,0 @@ -var Ww=e=>{throw TypeError(e)};var qI=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var sm=(e,t,n)=>t.has(e)||Ww("Cannot "+n);var R=(e,t,n)=>(sm(e,t,"read from private field"),n?n.call(e):t.get(e)),Ie=(e,t,n)=>t.has(e)?Ww("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),xe=(e,t,n,r)=>(sm(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Je=(e,t,n)=>(sm(e,t,"access private method"),n);var uf=(e,t,n,r)=>({set _(s){xe(e,t,s,n)},get _(){return R(e,t,r)}});var kse=qI((ao,io)=>{function jE(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();function jb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var RE={exports:{}},Oh={},PE={exports:{}},ot={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Dd=Symbol.for("react.element"),WI=Symbol.for("react.portal"),GI=Symbol.for("react.fragment"),JI=Symbol.for("react.strict_mode"),QI=Symbol.for("react.profiler"),ZI=Symbol.for("react.provider"),YI=Symbol.for("react.context"),XI=Symbol.for("react.forward_ref"),eD=Symbol.for("react.suspense"),tD=Symbol.for("react.memo"),nD=Symbol.for("react.lazy"),Gw=Symbol.iterator;function rD(e){return e===null||typeof e!="object"?null:(e=Gw&&e[Gw]||e["@@iterator"],typeof e=="function"?e:null)}var ME={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},OE=Object.assign,NE={};function iu(e,t,n){this.props=e,this.context=t,this.refs=NE,this.updater=n||ME}iu.prototype.isReactComponent={};iu.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};iu.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function IE(){}IE.prototype=iu.prototype;function Rb(e,t,n){this.props=e,this.context=t,this.refs=NE,this.updater=n||ME}var Pb=Rb.prototype=new IE;Pb.constructor=Rb;OE(Pb,iu.prototype);Pb.isPureReactComponent=!0;var Jw=Array.isArray,DE=Object.prototype.hasOwnProperty,Mb={current:null},AE={key:!0,ref:!0,__self:!0,__source:!0};function FE(e,t,n){var r,s={},o=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(o=""+t.key),t)DE.call(t,r)&&!AE.hasOwnProperty(r)&&(s[r]=t[r]);var l=arguments.length-2;if(l===1)s.children=n;else if(1{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Kl=typeof window>"u"||"Deno"in globalThis;function Or(){}function hD(e,t){return typeof e=="function"?e(t):e}function Tv(e){return typeof e=="number"&&e>=0&&e!==1/0}function BE(e,t){return Math.max(e+(t||0)-Date.now(),0)}function bl(e,t){return typeof e=="function"?e(t):e}function Qr(e,t){return typeof e=="function"?e(t):e}function Zw(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:a,stale:l}=e;if(a){if(r){if(t.queryHash!==Nb(a,t.options))return!1}else if(!Dc(t.queryKey,a))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||s&&s!==t.state.fetchStatus||o&&!o(t))}function Yw(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(gi(t.options.mutationKey)!==gi(o))return!1}else if(!Dc(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Nb(e,t){return((t==null?void 0:t.queryKeyHashFn)||gi)(e)}function gi(e){return JSON.stringify(e,(t,n)=>kv(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Dc(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Dc(e[n],t[n])):!1}function zE(e,t){if(e===t)return e;const n=Xw(e)&&Xw(t);if(n||kv(e)&&kv(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),a=o.length,l=n?[]:{};let c=0;for(let i=0;i{setTimeout(t,e)})}function _v(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?zE(e,t):t}function mD(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function vD(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var UE=Symbol();function VE(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===UE?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var ei,Ko,Ol,yE,yD=(yE=class extends lu{constructor(){super();Ie(this,ei);Ie(this,Ko);Ie(this,Ol);xe(this,Ol,t=>{if(!Kl&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,Ko)||this.setEventListener(R(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,Ko))==null||t.call(this),xe(this,Ko,void 0))}setEventListener(t){var n;xe(this,Ol,t),(n=R(this,Ko))==null||n.call(this),xe(this,Ko,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,ei)!==t&&(xe(this,ei,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,ei)=="boolean"?R(this,ei):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ei=new WeakMap,Ko=new WeakMap,Ol=new WeakMap,yE),Ib=new yD,Nl,qo,Il,bE,bD=(bE=class extends lu{constructor(){super();Ie(this,Nl,!0);Ie(this,qo);Ie(this,Il);xe(this,Il,t=>{if(!Kl&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){R(this,qo)||this.setEventListener(R(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,qo))==null||t.call(this),xe(this,qo,void 0))}setEventListener(t){var n;xe(this,Il,t),(n=R(this,qo))==null||n.call(this),xe(this,qo,t(this.setOnline.bind(this)))}setOnline(t){R(this,Nl)!==t&&(xe(this,Nl,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,Nl)}},Nl=new WeakMap,qo=new WeakMap,Il=new WeakMap,bE),kp=new bD;function xD(e){return Math.min(1e3*2**e,3e4)}function HE(e){return(e??"online")==="online"?kp.isOnline():!0}var KE=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function am(e){return e instanceof KE}function qE(e){let t=!1,n=0,r=!1,s,o,a;const l=new Promise((b,y)=>{o=b,a=y}),c=b=>{var y;r||(g(new KE(b)),(y=e.abort)==null||y.call(e))},i=()=>{t=!0},d=()=>{t=!1},p=()=>Ib.isFocused()&&(e.networkMode==="always"||kp.isOnline())&&e.canRun(),f=()=>HE(e.networkMode)&&e.canRun(),h=b=>{var y;r||(r=!0,(y=e.onSuccess)==null||y.call(e,b),s==null||s(),o(b))},g=b=>{var y;r||(r=!0,(y=e.onError)==null||y.call(e,b),s==null||s(),a(b))},m=()=>new Promise(b=>{var y;s=w=>{(r||p())&&b(w)},(y=e.onPause)==null||y.call(e)}).then(()=>{var b;s=void 0,r||(b=e.onContinue)==null||b.call(e)}),x=()=>{if(r)return;let b;const y=n===0?e.initialPromise:void 0;try{b=y??e.fn()}catch(w){b=Promise.reject(w)}Promise.resolve(b).then(h).catch(w=>{var T;if(r)return;const S=e.retry??(Kl?0:3),E=e.retryDelay??xD,C=typeof E=="function"?E(n,w):E,k=S===!0||typeof S=="number"&&np()?void 0:m()).then(()=>{t?g(w):x()})})};return{promise:l,cancel:c,continue:()=>(s==null||s(),l),cancelRetry:i,continueRetry:d,canStart:f,start:()=>(f()?x():m().then(x),l)}}function wD(){let e=[],t=0,n=f=>{f()},r=f=>{f()},s=f=>setTimeout(f,0);const o=f=>{s=f},a=f=>{let h;t++;try{h=f()}finally{t--,t||i()}return h},l=f=>{t?e.push(f):s(()=>{n(f)})},c=f=>(...h)=>{l(()=>{f(...h)})},i=()=>{const f=e;e=[],f.length&&s(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:a,batchCalls:c,schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:o}}var cn=wD(),ti,xE,WE=(xE=class{constructor(){Ie(this,ti)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Tv(this.gcTime)&&xe(this,ti,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Kl?1/0:5*60*1e3))}clearGcTimeout(){R(this,ti)&&(clearTimeout(R(this,ti)),xe(this,ti,void 0))}},ti=new WeakMap,xE),Dl,Al,Mr,On,Md,ni,Wr,Js,wE,SD=(wE=class extends WE{constructor(t){super();Ie(this,Wr);Ie(this,Dl);Ie(this,Al);Ie(this,Mr);Ie(this,On);Ie(this,Md);Ie(this,ni);xe(this,ni,!1),xe(this,Md,t.defaultOptions),this.setOptions(t.options),this.observers=[],xe(this,Mr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,xe(this,Dl,CD(this.options)),this.state=t.state??R(this,Dl),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=R(this,On))==null?void 0:t.promise}setOptions(t){this.options={...R(this,Md),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,Mr).remove(this)}setData(t,n){const r=_v(this.state.data,t,this.options);return Je(this,Wr,Js).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Je(this,Wr,Js).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=R(this,On))==null?void 0:r.promise;return(s=R(this,On))==null||s.cancel(t),n?n.then(Or).catch(Or):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(R(this,Dl))}isActive(){return this.observers.some(t=>Qr(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!BE(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,On))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,On))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),R(this,Mr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(R(this,On)&&(R(this,ni)?R(this,On).cancel({revert:!0}):R(this,On).cancelRetry()),this.scheduleGc()),R(this,Mr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Je(this,Wr,Js).call(this,{type:"invalidate"})}fetch(t,n){var c,i,d;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(R(this,On))return R(this,On).continueRetry(),R(this,On).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,s=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(xe(this,ni,!0),r.signal)})},o=()=>{const p=VE(this.options,n),f={queryKey:this.queryKey,meta:this.meta};return s(f),xe(this,ni,!1),this.options.persister?this.options.persister(p,f,this):p(f)},a={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:o};s(a),(c=this.options.behavior)==null||c.onFetch(a,this),xe(this,Al,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((i=a.fetchOptions)==null?void 0:i.meta))&&Je(this,Wr,Js).call(this,{type:"fetch",meta:(d=a.fetchOptions)==null?void 0:d.meta});const l=p=>{var f,h,g,m;am(p)&&p.silent||Je(this,Wr,Js).call(this,{type:"error",error:p}),am(p)||((h=(f=R(this,Mr).config).onError)==null||h.call(f,p,this),(m=(g=R(this,Mr).config).onSettled)==null||m.call(g,this.state.data,p,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return xe(this,On,qE({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,h,g,m;if(p===void 0){l(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(x){l(x);return}(h=(f=R(this,Mr).config).onSuccess)==null||h.call(f,p,this),(m=(g=R(this,Mr).config).onSettled)==null||m.call(g,p,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:l,onFail:(p,f)=>{Je(this,Wr,Js).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Je(this,Wr,Js).call(this,{type:"pause"})},onContinue:()=>{Je(this,Wr,Js).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),R(this,On).start()}},Dl=new WeakMap,Al=new WeakMap,Mr=new WeakMap,On=new WeakMap,Md=new WeakMap,ni=new WeakMap,Wr=new WeakSet,Js=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...GE(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=t.error;return am(s)&&s.revert&&R(this,Al)?{...R(this,Al),fetchStatus:"idle"}:{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),cn.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),R(this,Mr).notify({query:this,type:"updated",action:t})})},wE);function GE(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:HE(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function CD(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ss,SE,ED=(SE=class extends lu{constructor(t={}){super();Ie(this,Ss);this.config=t,xe(this,Ss,new Map)}build(t,n,r){const s=n.queryKey,o=n.queryHash??Nb(s,n);let a=this.get(o);return a||(a=new SD({cache:this,queryKey:s,queryHash:o,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){R(this,Ss).has(t.queryHash)||(R(this,Ss).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Ss).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Ss).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){cn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Ss).get(t)}getAll(){return[...R(this,Ss).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Zw(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Zw(t,r)):n}notify(t){cn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){cn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){cn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ss=new WeakMap,SE),Cs,Ln,ri,Es,Ao,CE,TD=(CE=class extends WE{constructor(t){super();Ie(this,Es);Ie(this,Cs);Ie(this,Ln);Ie(this,ri);this.mutationId=t.mutationId,xe(this,Ln,t.mutationCache),xe(this,Cs,[]),this.state=t.state||JE(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){R(this,Cs).includes(t)||(R(this,Cs).push(t),this.clearGcTimeout(),R(this,Ln).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){xe(this,Cs,R(this,Cs).filter(n=>n!==t)),this.scheduleGc(),R(this,Ln).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Cs).length||(this.state.status==="pending"?this.scheduleGc():R(this,Ln).remove(this))}continue(){var t;return((t=R(this,ri))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,a,l,c,i,d,p,f,h,g,m,x,b,y,w,S,E,C,k;xe(this,ri,qE({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,P)=>{Je(this,Es,Ao).call(this,{type:"failed",failureCount:T,error:P})},onPause:()=>{Je(this,Es,Ao).call(this,{type:"pause"})},onContinue:()=>{Je(this,Es,Ao).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>R(this,Ln).canRun(this)}));const n=this.state.status==="pending",r=!R(this,ri).canStart();try{if(!n){Je(this,Es,Ao).call(this,{type:"pending",variables:t,isPaused:r}),await((o=(s=R(this,Ln).config).onMutate)==null?void 0:o.call(s,t,this));const P=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,t));P!==this.state.context&&Je(this,Es,Ao).call(this,{type:"pending",context:P,variables:t,isPaused:r})}const T=await R(this,ri).start();return await((i=(c=R(this,Ln).config).onSuccess)==null?void 0:i.call(c,T,t,this.state.context,this)),await((p=(d=this.options).onSuccess)==null?void 0:p.call(d,T,t,this.state.context)),await((h=(f=R(this,Ln).config).onSettled)==null?void 0:h.call(f,T,null,this.state.variables,this.state.context,this)),await((m=(g=this.options).onSettled)==null?void 0:m.call(g,T,null,t,this.state.context)),Je(this,Es,Ao).call(this,{type:"success",data:T}),T}catch(T){try{throw await((b=(x=R(this,Ln).config).onError)==null?void 0:b.call(x,T,t,this.state.context,this)),await((w=(y=this.options).onError)==null?void 0:w.call(y,T,t,this.state.context)),await((E=(S=R(this,Ln).config).onSettled)==null?void 0:E.call(S,void 0,T,this.state.variables,this.state.context,this)),await((k=(C=this.options).onSettled)==null?void 0:k.call(C,void 0,T,t,this.state.context)),T}finally{Je(this,Es,Ao).call(this,{type:"error",error:T})}}finally{R(this,Ln).runNext(this)}}},Cs=new WeakMap,Ln=new WeakMap,ri=new WeakMap,Es=new WeakSet,Ao=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),cn.batch(()=>{R(this,Cs).forEach(r=>{r.onMutationUpdate(t)}),R(this,Ln).notify({mutation:this,type:"updated",action:t})})},CE);function JE(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var lr,Od,EE,kD=(EE=class extends lu{constructor(t={}){super();Ie(this,lr);Ie(this,Od);this.config=t,xe(this,lr,new Map),xe(this,Od,Date.now())}build(t,n,r){const s=new TD({mutationCache:this,mutationId:++uf(this,Od)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){const n=df(t),r=R(this,lr).get(n)??[];r.push(t),R(this,lr).set(n,r),this.notify({type:"added",mutation:t})}remove(t){var r;const n=df(t);if(R(this,lr).has(n)){const s=(r=R(this,lr).get(n))==null?void 0:r.filter(o=>o!==t);s&&(s.length===0?R(this,lr).delete(n):R(this,lr).set(n,s))}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=(r=R(this,lr).get(df(t)))==null?void 0:r.find(s=>s.state.status==="pending");return!n||n===t}runNext(t){var r;const n=(r=R(this,lr).get(df(t)))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}clear(){cn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}getAll(){return[...R(this,lr).values()].flat()}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Yw(n,r))}findAll(t={}){return this.getAll().filter(n=>Yw(t,n))}notify(t){cn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return cn.batch(()=>Promise.all(t.map(n=>n.continue().catch(Or))))}},lr=new WeakMap,Od=new WeakMap,EE);function df(e){var t;return((t=e.options.scope)==null?void 0:t.id)??String(e.mutationId)}function _D(e){return{onFetch:(t,n)=>{const r=async()=>{var g,m,x,b,y;const s=t.options,o=(x=(m=(g=t.fetchOptions)==null?void 0:g.meta)==null?void 0:m.fetchMore)==null?void 0:x.direction,a=((b=t.state.data)==null?void 0:b.pages)||[],l=((y=t.state.data)==null?void 0:y.pageParams)||[],c={pages:[],pageParams:[]};let i=!1;const d=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?i=!0:t.signal.addEventListener("abort",()=>{i=!0}),t.signal)})},p=VE(t.options,t.fetchOptions),f=async(w,S,E)=>{if(i)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const C={queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};d(C);const k=await p(C),{maxPages:T}=t.options,P=E?vD:mD;return{pages:P(w.pages,k,T),pageParams:P(w.pageParams,S,T)}};let h;if(o&&a.length){const w=o==="backward",S=w?jD:tS,E={pages:a,pageParams:l},C=S(s,E);h=await f(E,C,w)}else{h=await f(c,l[0]??s.initialPageParam);const w=e??a.length;for(let S=1;S{var s,o;return(o=(s=t.options).persister)==null?void 0:o.call(s,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tS(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function jD(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Ht,Wo,Go,Fl,Ll,Jo,$l,Bl,TE,RD=(TE=class{constructor(e={}){Ie(this,Ht);Ie(this,Wo);Ie(this,Go);Ie(this,Fl);Ie(this,Ll);Ie(this,Jo);Ie(this,$l);Ie(this,Bl);xe(this,Ht,e.queryCache||new ED),xe(this,Wo,e.mutationCache||new kD),xe(this,Go,e.defaultOptions||{}),xe(this,Fl,new Map),xe(this,Ll,new Map),xe(this,Jo,0)}mount(){uf(this,Jo)._++,R(this,Jo)===1&&(xe(this,$l,Ib.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ht).onFocus())})),xe(this,Bl,kp.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ht).onOnline())})))}unmount(){var e,t;uf(this,Jo)._--,R(this,Jo)===0&&((e=R(this,$l))==null||e.call(this),xe(this,$l,void 0),(t=R(this,Bl))==null||t.call(this),xe(this,Bl,void 0))}isFetching(e){return R(this,Ht).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,Wo).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ht).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);if(t===void 0)return this.fetchQuery(e);{const n=this.defaultQueryOptions(e),r=R(this,Ht).build(this,n);return e.revalidateIfStale&&r.isStaleByTime(bl(n.staleTime,r))&&this.prefetchQuery(n),Promise.resolve(t)}}getQueriesData(e){return R(this,Ht).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=R(this,Ht).get(r.queryHash),o=s==null?void 0:s.state.data,a=hD(t,o);if(a!==void 0)return R(this,Ht).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return cn.batch(()=>R(this,Ht).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ht).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,Ht);cn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,Ht),r={type:"active",...e};return cn.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=cn.batch(()=>R(this,Ht).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Or).catch(Or)}invalidateQueries(e={},t={}){return cn.batch(()=>{if(R(this,Ht).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=cn.batch(()=>R(this,Ht).findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Or)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Or)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=R(this,Ht).build(this,t);return n.isStaleByTime(bl(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Or).catch(Or)}fetchInfiniteQuery(e){return e.behavior=_D(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Or).catch(Or)}resumePausedMutations(){return kp.isOnline()?R(this,Wo).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Ht)}getMutationCache(){return R(this,Wo)}getDefaultOptions(){return R(this,Go)}setDefaultOptions(e){xe(this,Go,e)}setQueryDefaults(e,t){R(this,Fl).set(gi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,Fl).values()];let n={};return t.forEach(r=>{Dc(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){R(this,Ll).set(gi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,Ll).values()];let n={};return t.forEach(r=>{Dc(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,Go).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Nb(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.enabled!==!0&&t.queryFn===UE&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,Go).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Ht).clear(),R(this,Wo).clear()}},Ht=new WeakMap,Wo=new WeakMap,Go=new WeakMap,Fl=new WeakMap,Ll=new WeakMap,Jo=new WeakMap,$l=new WeakMap,Bl=new WeakMap,TE),Qn,at,Nd,$n,si,zl,Ts,Id,Ul,Vl,oi,ai,Qo,Hl,gt,oc,jv,Rv,Pv,Mv,Ov,Nv,Iv,QE,kE,PD=(kE=class extends lu{constructor(t,n){super();Ie(this,gt);Ie(this,Qn);Ie(this,at);Ie(this,Nd);Ie(this,$n);Ie(this,si);Ie(this,zl);Ie(this,Ts);Ie(this,Id);Ie(this,Ul);Ie(this,Vl);Ie(this,oi);Ie(this,ai);Ie(this,Qo);Ie(this,Hl,new Set);this.options=n,xe(this,Qn,t),xe(this,Ts,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,at).addObserver(this),nS(R(this,at),this.options)?Je(this,gt,oc).call(this):this.updateResult(),Je(this,gt,Mv).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dv(R(this,at),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dv(R(this,at),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Je(this,gt,Ov).call(this),Je(this,gt,Nv).call(this),R(this,at).removeObserver(this)}setOptions(t,n){const r=this.options,s=R(this,at);if(this.options=R(this,Qn).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Qr(this.options.enabled,R(this,at))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Je(this,gt,Iv).call(this),R(this,at).setOptions(this.options),r._defaulted&&!Tp(this.options,r)&&R(this,Qn).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,at),observer:this});const o=this.hasListeners();o&&rS(R(this,at),s,this.options,r)&&Je(this,gt,oc).call(this),this.updateResult(n),o&&(R(this,at)!==s||Qr(this.options.enabled,R(this,at))!==Qr(r.enabled,R(this,at))||bl(this.options.staleTime,R(this,at))!==bl(r.staleTime,R(this,at)))&&Je(this,gt,jv).call(this);const a=Je(this,gt,Rv).call(this);o&&(R(this,at)!==s||Qr(this.options.enabled,R(this,at))!==Qr(r.enabled,R(this,at))||a!==R(this,Qo))&&Je(this,gt,Pv).call(this,a)}getOptimisticResult(t){const n=R(this,Qn).getQueryCache().build(R(this,Qn),t),r=this.createResult(n,t);return OD(this,r)&&(xe(this,$n,r),xe(this,zl,this.options),xe(this,si,R(this,at).state)),r}getCurrentResult(){return R(this,$n)}trackResult(t,n){const r={};return Object.keys(t).forEach(s=>{Object.defineProperty(r,s,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(s),n==null||n(s),t[s])})}),r}trackProp(t){R(this,Hl).add(t)}getCurrentQuery(){return R(this,at)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=R(this,Qn).defaultQueryOptions(t),r=R(this,Qn).getQueryCache().build(R(this,Qn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Je(this,gt,oc).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,$n)))}createResult(t,n){var k;const r=R(this,at),s=this.options,o=R(this,$n),a=R(this,si),l=R(this,zl),i=t!==r?t.state:R(this,Nd),{state:d}=t;let p={...d},f=!1,h;if(n._optimisticResults){const T=this.hasListeners(),P=!T&&nS(t,n),N=T&&rS(t,r,n,s);(P||N)&&(p={...p,...GE(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:g,errorUpdatedAt:m,status:x}=p;if(n.select&&p.data!==void 0)if(o&&p.data===(a==null?void 0:a.data)&&n.select===R(this,Id))h=R(this,Ul);else try{xe(this,Id,n.select),h=n.select(p.data),h=_v(o==null?void 0:o.data,h,n),xe(this,Ul,h),xe(this,Ts,null)}catch(T){xe(this,Ts,T)}else h=p.data;if(n.placeholderData!==void 0&&h===void 0&&x==="pending"){let T;if(o!=null&&o.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))T=o.data;else if(T=typeof n.placeholderData=="function"?n.placeholderData((k=R(this,Vl))==null?void 0:k.state.data,R(this,Vl)):n.placeholderData,n.select&&T!==void 0)try{T=n.select(T),xe(this,Ts,null)}catch(P){xe(this,Ts,P)}T!==void 0&&(x="success",h=_v(o==null?void 0:o.data,T,n),f=!0)}R(this,Ts)&&(g=R(this,Ts),h=R(this,Ul),m=Date.now(),x="error");const b=p.fetchStatus==="fetching",y=x==="pending",w=x==="error",S=y&&b,E=h!==void 0;return{status:x,fetchStatus:p.fetchStatus,isPending:y,isSuccess:x==="success",isError:w,isInitialLoading:S,isLoading:S,data:h,dataUpdatedAt:p.dataUpdatedAt,error:g,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>i.dataUpdateCount||p.errorUpdateCount>i.errorUpdateCount,isFetching:b,isRefetching:b&&!y,isLoadingError:w&&!E,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:w&&E,isStale:Db(t,n),refetch:this.refetch}}updateResult(t){const n=R(this,$n),r=this.createResult(R(this,at),this.options);if(xe(this,si,R(this,at).state),xe(this,zl,this.options),R(this,si).data!==void 0&&xe(this,Vl,R(this,at)),Tp(r,n))return;xe(this,$n,r);const s={},o=()=>{if(!n)return!0;const{notifyOnChangeProps:a}=this.options,l=typeof a=="function"?a():a;if(l==="all"||!l&&!R(this,Hl).size)return!0;const c=new Set(l??R(this,Hl));return this.options.throwOnError&&c.add("error"),Object.keys(R(this,$n)).some(i=>{const d=i;return R(this,$n)[d]!==n[d]&&c.has(d)})};(t==null?void 0:t.listeners)!==!1&&o()&&(s.listeners=!0),Je(this,gt,QE).call(this,{...s,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Je(this,gt,Mv).call(this)}},Qn=new WeakMap,at=new WeakMap,Nd=new WeakMap,$n=new WeakMap,si=new WeakMap,zl=new WeakMap,Ts=new WeakMap,Id=new WeakMap,Ul=new WeakMap,Vl=new WeakMap,oi=new WeakMap,ai=new WeakMap,Qo=new WeakMap,Hl=new WeakMap,gt=new WeakSet,oc=function(t){Je(this,gt,Iv).call(this);let n=R(this,at).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Or)),n},jv=function(){Je(this,gt,Ov).call(this);const t=bl(this.options.staleTime,R(this,at));if(Kl||R(this,$n).isStale||!Tv(t))return;const r=BE(R(this,$n).dataUpdatedAt,t)+1;xe(this,oi,setTimeout(()=>{R(this,$n).isStale||this.updateResult()},r))},Rv=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,at)):this.options.refetchInterval)??!1},Pv=function(t){Je(this,gt,Nv).call(this),xe(this,Qo,t),!(Kl||Qr(this.options.enabled,R(this,at))===!1||!Tv(R(this,Qo))||R(this,Qo)===0)&&xe(this,ai,setInterval(()=>{(this.options.refetchIntervalInBackground||Ib.isFocused())&&Je(this,gt,oc).call(this)},R(this,Qo)))},Mv=function(){Je(this,gt,jv).call(this),Je(this,gt,Pv).call(this,Je(this,gt,Rv).call(this))},Ov=function(){R(this,oi)&&(clearTimeout(R(this,oi)),xe(this,oi,void 0))},Nv=function(){R(this,ai)&&(clearInterval(R(this,ai)),xe(this,ai,void 0))},Iv=function(){const t=R(this,Qn).getQueryCache().build(R(this,Qn),this.options);if(t===R(this,at))return;const n=R(this,at);xe(this,at,t),xe(this,Nd,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},QE=function(t){cn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(R(this,$n))}),R(this,Qn).getQueryCache().notify({query:R(this,at),type:"observerResultsUpdated"})})},kE);function MD(e,t){return Qr(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nS(e,t){return MD(e,t)||e.state.data!==void 0&&Dv(e,t,t.refetchOnMount)}function Dv(e,t,n){if(Qr(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Db(e,t)}return!1}function rS(e,t,n,r){return(e!==t||Qr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Db(e,n)}function Db(e,t){return Qr(t.enabled,e)!==!1&&e.isStaleByTime(bl(t.staleTime,e))}function OD(e,t){return!Tp(e.getCurrentResult(),t)}var Zo,Yo,Zn,to,co,Xf,Av,_E,ND=(_E=class extends lu{constructor(n,r){super();Ie(this,co);Ie(this,Zo);Ie(this,Yo);Ie(this,Zn);Ie(this,to);xe(this,Zo,n),this.setOptions(r),this.bindMethods(),Je(this,co,Xf).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var s;const r=this.options;this.options=R(this,Zo).defaultMutationOptions(n),Tp(this.options,r)||R(this,Zo).getMutationCache().notify({type:"observerOptionsUpdated",mutation:R(this,Zn),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&gi(r.mutationKey)!==gi(this.options.mutationKey)?this.reset():((s=R(this,Zn))==null?void 0:s.state.status)==="pending"&&R(this,Zn).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=R(this,Zn))==null||n.removeObserver(this)}onMutationUpdate(n){Je(this,co,Xf).call(this),Je(this,co,Av).call(this,n)}getCurrentResult(){return R(this,Yo)}reset(){var n;(n=R(this,Zn))==null||n.removeObserver(this),xe(this,Zn,void 0),Je(this,co,Xf).call(this),Je(this,co,Av).call(this)}mutate(n,r){var s;return xe(this,to,r),(s=R(this,Zn))==null||s.removeObserver(this),xe(this,Zn,R(this,Zo).getMutationCache().build(R(this,Zo),this.options)),R(this,Zn).addObserver(this),R(this,Zn).execute(n)}},Zo=new WeakMap,Yo=new WeakMap,Zn=new WeakMap,to=new WeakMap,co=new WeakSet,Xf=function(){var r;const n=((r=R(this,Zn))==null?void 0:r.state)??JE();xe(this,Yo,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Av=function(n){cn.batch(()=>{var r,s,o,a,l,c,i,d;if(R(this,to)&&this.hasListeners()){const p=R(this,Yo).variables,f=R(this,Yo).context;(n==null?void 0:n.type)==="success"?((s=(r=R(this,to)).onSuccess)==null||s.call(r,n.data,p,f),(a=(o=R(this,to)).onSettled)==null||a.call(o,n.data,null,p,f)):(n==null?void 0:n.type)==="error"&&((c=(l=R(this,to)).onError)==null||c.call(l,n.error,p,f),(d=(i=R(this,to)).onSettled)==null||d.call(i,void 0,n.error,p,f))}this.listeners.forEach(p=>{p(R(this,Yo))})})},_E),ZE=v.createContext(void 0),Ab=e=>{const t=v.useContext(ZE);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ID=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),u.jsx(ZE.Provider,{value:e,children:t})),YE=v.createContext(!1),DD=()=>v.useContext(YE);YE.Provider;function AD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var FD=v.createContext(AD()),LD=()=>v.useContext(FD);function XE(e,t){return typeof e=="function"?e(...t):!!e}function $D(){}var BD=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},zD=e=>{v.useEffect(()=>{e.clearReset()},[e])},UD=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&XE(n,[e.error,r]),VD=e=>{e.suspense&&(typeof e.staleTime!="number"&&(e.staleTime=1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},HD=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,KD=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function qD(e,t,n){var i,d,p,f;const r=Ab(),s=DD(),o=LD(),a=r.defaultQueryOptions(e);(d=(i=r.getDefaultOptions().queries)==null?void 0:i._experimental_beforeQuery)==null||d.call(i,a),a._optimisticResults=s?"isRestoring":"optimistic",VD(a),BD(a,o),zD(o);const[l]=v.useState(()=>new t(r,a)),c=l.getOptimisticResult(a);if(v.useSyncExternalStore(v.useCallback(h=>{const g=s?()=>{}:l.subscribe(cn.batchCalls(h));return l.updateResult(),g},[l,s]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(a,{listeners:!1})},[a,l]),HD(a,c))throw KD(a,l,o);if(UD({result:c,errorResetBoundary:o,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash)}))throw c.error;return(f=(p=r.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,a,c),a.notifyOnChangeProps?c:l.trackResult(c)}function lt(e,t){return qD(e,PD)}function WD(e,t){const n=Ab(),[r]=v.useState(()=>new ND(n,e));v.useEffect(()=>{r.setOptions(e)},[r,e]);const s=v.useSyncExternalStore(v.useCallback(a=>r.subscribe(cn.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=v.useCallback((a,l)=>{r.mutate(a,l).catch($D)},[r]);if(s.error&&XE(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:o,mutateAsync:s.mutate}}var Fv={},eT={exports:{}},Cr={},tT={exports:{}},nT={};/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(e){function t(F,A){var Y=F.length;F.push(A);e:for(;0>>1,z=F[de];if(0>>1;des(ie,Y))oes(J,ie)?(F[de]=J,F[oe]=Y,de=oe):(F[de]=ie,F[ne]=Y,de=ne);else if(oes(J,Y))F[de]=J,F[oe]=Y,de=oe;else break e}}return A}function s(F,A){var Y=F.sortIndex-A.sortIndex;return Y!==0?Y:F.id-A.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,l=a.now();e.unstable_now=function(){return a.now()-l}}var c=[],i=[],d=1,p=null,f=3,h=!1,g=!1,m=!1,x=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(F){for(var A=n(i);A!==null;){if(A.callback===null)r(i);else if(A.startTime<=F)r(i),A.sortIndex=A.expirationTime,t(c,A);else break;A=n(i)}}function S(F){if(m=!1,w(F),!g)if(n(c)!==null)g=!0,ee(E);else{var A=n(i);A!==null&&W(S,A.startTime-F)}}function E(F,A){g=!1,m&&(m=!1,b(T),T=-1),h=!0;var Y=f;try{for(w(A),p=n(c);p!==null&&(!(p.expirationTime>A)||F&&!U());){var de=p.callback;if(typeof de=="function"){p.callback=null,f=p.priorityLevel;var z=de(p.expirationTime<=A);A=e.unstable_now(),typeof z=="function"?p.callback=z:p===n(c)&&r(c),w(A)}else r(c);p=n(c)}if(p!==null)var se=!0;else{var ne=n(i);ne!==null&&W(S,ne.startTime-A),se=!1}return se}finally{p=null,f=Y,h=!1}}var C=!1,k=null,T=-1,P=5,N=-1;function U(){return!(e.unstable_now()-NF||125de?(F.sortIndex=Y,t(i,F),n(c)===null&&F===n(i)&&(m?(b(T),T=-1):m=!0,W(S,Y-de))):(F.sortIndex=z,t(c,F),g||h||(g=!0,ee(E))),F},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(F){var A=f;return function(){var Y=f;f=A;try{return F.apply(this,arguments)}finally{f=Y}}}})(nT);tT.exports=nT;var GD=tT.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var JD=v,br=GD;function te(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Lv=Object.prototype.hasOwnProperty,QD=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,sS={},oS={};function ZD(e){return Lv.call(oS,e)?!0:Lv.call(sS,e)?!1:QD.test(e)?oS[e]=!0:(sS[e]=!0,!1)}function YD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function XD(e,t,n,r){if(t===null||typeof t>"u"||YD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Wn(e,t,n,r,s,o,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=a}var Tn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Tn[e]=new Wn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Tn[t]=new Wn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Tn[e]=new Wn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Tn[e]=new Wn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Tn[e]=new Wn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Tn[e]=new Wn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Tn[e]=new Wn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Tn[e]=new Wn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Tn[e]=new Wn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Fb=/[\-:]([a-z])/g;function Lb(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Tn[e]=new Wn(e,1,!1,e.toLowerCase(),null,!1,!1)});Tn.xlinkHref=new Wn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Tn[e]=new Wn(e,1,!1,e.toLowerCase(),null,!0,!0)});function $b(e,t,n,r){var s=Tn.hasOwnProperty(t)?Tn[t]:null;(s!==null?s.type!==0:r||!(2l||s[a]!==o[l]){var c=` -`+s[a].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=a&&0<=l);break}}}finally{lm=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ac(e):""}function eA(e){switch(e.tag){case 5:return ac(e.type);case 16:return ac("Lazy");case 13:return ac("Suspense");case 19:return ac("SuspenseList");case 0:case 2:case 15:return e=um(e.type,!1),e;case 11:return e=um(e.type.render,!1),e;case 1:return e=um(e.type,!0),e;default:return""}}function Uv(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case sl:return"Fragment";case rl:return"Portal";case $v:return"Profiler";case Bb:return"StrictMode";case Bv:return"Suspense";case zv:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case oT:return(e.displayName||"Context")+".Consumer";case sT:return(e._context.displayName||"Context")+".Provider";case zb:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ub:return t=e.displayName||null,t!==null?t:Uv(e.type)||"Memo";case $o:t=e._payload,e=e._init;try{return Uv(e(t))}catch{}}return null}function tA(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Uv(t);case 8:return t===Bb?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function da(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function iT(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nA(e){var t=iT(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function pf(e){e._valueTracker||(e._valueTracker=nA(e))}function lT(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=iT(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _p(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Vv(e,t){var n=t.checked;return Bt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function iS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=da(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function uT(e,t){t=t.checked,t!=null&&$b(e,"checked",t,!1)}function Hv(e,t){uT(e,t);var n=da(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Kv(e,t.type,n):t.hasOwnProperty("defaultValue")&&Kv(e,t.type,da(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function lS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Kv(e,t,n){(t!=="number"||_p(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ic=Array.isArray;function xl(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=hf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fc(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},rA=["Webkit","ms","Moz","O"];Object.keys(yc).forEach(function(e){rA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yc[t]=yc[e]})});function pT(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yc.hasOwnProperty(e)&&yc[e]?(""+t).trim():t+"px"}function hT(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=pT(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var sA=Bt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Gv(e,t){if(t){if(sA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(te(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(te(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(te(61))}if(t.style!=null&&typeof t.style!="object")throw Error(te(62))}}function Jv(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Qv=null;function Vb(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Zv=null,wl=null,Sl=null;function dS(e){if(e=Ld(e)){if(typeof Zv!="function")throw Error(te(280));var t=e.stateNode;t&&(t=Lh(t),Zv(e.stateNode,e.type,t))}}function gT(e){wl?Sl?Sl.push(e):Sl=[e]:wl=e}function mT(){if(wl){var e=wl,t=Sl;if(Sl=wl=null,dS(e),t)for(e=0;e>>=0,e===0?32:31-(gA(e)/mA|0)|0}var gf=64,mf=4194304;function lc(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Mp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,a=n&268435455;if(a!==0){var l=a&~s;l!==0?r=lc(l):(o&=a,o!==0&&(r=lc(o)))}else a=n&~s,a!==0?r=lc(a):o!==0&&(r=lc(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,o=t&-t,s>=o||s===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ad(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ts(t),e[t]=n}function xA(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=xc),xS=" ",wS=!1;function AT(e,t){switch(e){case"keyup":return GA.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function FT(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ol=!1;function QA(e,t){switch(e){case"compositionend":return FT(t);case"keypress":return t.which!==32?null:(wS=!0,xS);case"textInput":return e=t.data,e===xS&&wS?null:e;default:return null}}function ZA(e,t){if(ol)return e==="compositionend"||!Zb&&AT(e,t)?(e=IT(),tp=Gb=Xo=null,ol=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=TS(n)}}function zT(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?zT(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function UT(){for(var e=window,t=_p();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_p(e.document)}return t}function Yb(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function aF(e){var t=UT(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&zT(n.ownerDocument.documentElement,n)){if(r!==null&&Yb(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=kS(n,o);var a=kS(n,r);s&&a&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,al=null,ry=null,Sc=null,sy=!1;function _S(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;sy||al==null||al!==_p(r)||(r=al,"selectionStart"in r&&Yb(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Sc&&Vc(Sc,r)||(Sc=r,r=Ip(ry,"onSelect"),0ul||(e.current=cy[ul],cy[ul]=null,ul--)}function Et(e,t){ul++,cy[ul]=e.current,e.current=t}var fa={},In=Ea(fa),tr=Ea(!1),mi=fa;function Wl(e,t){var n=e.type.contextTypes;if(!n)return fa;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in n)s[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function nr(e){return e=e.childContextTypes,e!=null}function Ap(){Pt(tr),Pt(In)}function IS(e,t,n){if(In.current!==fa)throw Error(te(168));Et(In,t),Et(tr,n)}function ZT(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(te(108,tA(e)||"Unknown",s));return Bt({},n,r)}function Fp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||fa,mi=In.current,Et(In,e),Et(tr,tr.current),!0}function DS(e,t,n){var r=e.stateNode;if(!r)throw Error(te(169));n?(e=ZT(e,t,mi),r.__reactInternalMemoizedMergedChildContext=e,Pt(tr),Pt(In),Et(In,e)):Pt(tr),Et(tr,n)}var eo=null,$h=!1,Cm=!1;function YT(e){eo===null?eo=[e]:eo.push(e)}function yF(e){$h=!0,YT(e)}function Ta(){if(!Cm&&eo!==null){Cm=!0;var e=0,t=vt;try{var n=eo;for(vt=1;e>=a,s-=a,ro=1<<32-ts(t)+s|n<T?(P=k,k=null):P=k.sibling;var N=f(b,k,w[T],S);if(N===null){k===null&&(k=P);break}e&&k&&N.alternate===null&&t(b,k),y=o(N,y,T),C===null?E=N:C.sibling=N,C=N,k=P}if(T===w.length)return n(b,k),Ot&&$a(b,T),E;if(k===null){for(;TT?(P=k,k=null):P=k.sibling;var U=f(b,k,N.value,S);if(U===null){k===null&&(k=P);break}e&&k&&U.alternate===null&&t(b,k),y=o(U,y,T),C===null?E=U:C.sibling=U,C=U,k=P}if(N.done)return n(b,k),Ot&&$a(b,T),E;if(k===null){for(;!N.done;T++,N=w.next())N=p(b,N.value,S),N!==null&&(y=o(N,y,T),C===null?E=N:C.sibling=N,C=N);return Ot&&$a(b,T),E}for(k=r(b,k);!N.done;T++,N=w.next())N=h(k,b,T,N.value,S),N!==null&&(e&&N.alternate!==null&&k.delete(N.key===null?T:N.key),y=o(N,y,T),C===null?E=N:C.sibling=N,C=N);return e&&k.forEach(function(I){return t(b,I)}),Ot&&$a(b,T),E}function x(b,y,w,S){if(typeof w=="object"&&w!==null&&w.type===sl&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case ff:e:{for(var E=w.key,C=y;C!==null;){if(C.key===E){if(E=w.type,E===sl){if(C.tag===7){n(b,C.sibling),y=s(C,w.props.children),y.return=b,b=y;break e}}else if(C.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===$o&&LS(E)===C.type){n(b,C.sibling),y=s(C,w.props),y.ref=Uu(b,C,w),y.return=b,b=y;break e}n(b,C);break}else t(b,C);C=C.sibling}w.type===sl?(y=li(w.props.children,b.mode,S,w.key),y.return=b,b=y):(S=up(w.type,w.key,w.props,null,b.mode,S),S.ref=Uu(b,y,w),S.return=b,b=S)}return a(b);case rl:e:{for(C=w.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){n(b,y.sibling),y=s(y,w.children||[]),y.return=b,b=y;break e}else{n(b,y);break}else t(b,y);y=y.sibling}y=Mm(w,b.mode,S),y.return=b,b=y}return a(b);case $o:return C=w._init,x(b,y,C(w._payload),S)}if(ic(w))return g(b,y,w,S);if(Fu(w))return m(b,y,w,S);Cf(b,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(n(b,y.sibling),y=s(y,w),y.return=b,b=y):(n(b,y),y=Pm(w,b.mode,S),y.return=b,b=y),a(b)):n(b,y)}return x}var Jl=nk(!0),rk=nk(!1),Bp=Ea(null),zp=null,fl=null,nx=null;function rx(){nx=fl=zp=null}function sx(e){var t=Bp.current;Pt(Bp),e._currentValue=t}function py(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function El(e,t){zp=e,nx=fl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(er=!0),e.firstContext=null)}function Br(e){var t=e._currentValue;if(nx!==e)if(e={context:e,memoizedValue:t,next:null},fl===null){if(zp===null)throw Error(te(308));fl=e,zp.dependencies={lanes:0,firstContext:e}}else fl=fl.next=e;return t}var Ha=null;function ox(e){Ha===null?Ha=[e]:Ha.push(e)}function sk(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ox(t)):(n.next=s.next,s.next=n),t.interleaved=n,ho(e,r)}function ho(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Bo=!1;function ax(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ok(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lo(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ia(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ct&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,ho(e,n)}return s=r.interleaved,s===null?(t.next=t,ox(r)):(t.next=s.next,s.next=t),r.interleaved=t,ho(e,n)}function rp(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Kb(e,n)}}function $S(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?s=o=a:o=o.next=a,n=n.next}while(n!==null);o===null?s=o=t:o=o.next=t}else s=o=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Up(e,t,n,r){var s=e.updateQueue;Bo=!1;var o=s.firstBaseUpdate,a=s.lastBaseUpdate,l=s.shared.pending;if(l!==null){s.shared.pending=null;var c=l,i=c.next;c.next=null,a===null?o=i:a.next=i,a=c;var d=e.alternate;d!==null&&(d=d.updateQueue,l=d.lastBaseUpdate,l!==a&&(l===null?d.firstBaseUpdate=i:l.next=i,d.lastBaseUpdate=c))}if(o!==null){var p=s.baseState;a=0,d=i=c=null,l=o;do{var f=l.lane,h=l.eventTime;if((r&f)===f){d!==null&&(d=d.next={eventTime:h,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var g=e,m=l;switch(f=t,h=n,m.tag){case 1:if(g=m.payload,typeof g=="function"){p=g.call(h,p,f);break e}p=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=m.payload,f=typeof g=="function"?g.call(h,p,f):g,f==null)break e;p=Bt({},p,f);break e;case 2:Bo=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[l]:f.push(l))}else h={eventTime:h,lane:f,tag:l.tag,payload:l.payload,callback:l.callback,next:null},d===null?(i=d=h,c=p):d=d.next=h,a|=f;if(l=l.next,l===null){if(l=s.shared.pending,l===null)break;f=l,l=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(d===null&&(c=p),s.baseState=c,s.firstBaseUpdate=i,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do a|=s.lane,s=s.next;while(s!==t)}else o===null&&(s.shared.lanes=0);bi|=a,e.lanes=a,e.memoizedState=p}}function BS(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Tm.transition;Tm.transition={};try{e(!1),t()}finally{vt=n,Tm.transition=r}}function Sk(){return zr().memoizedState}function SF(e,t,n){var r=ua(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ck(e))Ek(t,n);else if(n=sk(e,t,n,r),n!==null){var s=Hn();ns(n,e,r,s),Tk(n,t,r)}}function CF(e,t,n){var r=ua(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ck(e))Ek(t,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var a=t.lastRenderedState,l=o(a,n);if(s.hasEagerState=!0,s.eagerState=l,us(l,a)){var c=t.interleaved;c===null?(s.next=s,ox(t)):(s.next=c.next,c.next=s),t.interleaved=s;return}}catch{}finally{}n=sk(e,t,s,r),n!==null&&(s=Hn(),ns(n,e,r,s),Tk(n,t,r))}}function Ck(e){var t=e.alternate;return e===Lt||t!==null&&t===Lt}function Ek(e,t){Cc=Hp=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Kb(e,n)}}var Kp={readContext:Br,useCallback:jn,useContext:jn,useEffect:jn,useImperativeHandle:jn,useInsertionEffect:jn,useLayoutEffect:jn,useMemo:jn,useReducer:jn,useRef:jn,useState:jn,useDebugValue:jn,useDeferredValue:jn,useTransition:jn,useMutableSource:jn,useSyncExternalStore:jn,useId:jn,unstable_isNewReconciler:!1},EF={readContext:Br,useCallback:function(e,t){return ws().memoizedState=[e,t===void 0?null:t],e},useContext:Br,useEffect:US,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,op(4194308,4,vk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return op(4194308,4,e,t)},useInsertionEffect:function(e,t){return op(4,2,e,t)},useMemo:function(e,t){var n=ws();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ws();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SF.bind(null,Lt,e),[r.memoizedState,e]},useRef:function(e){var t=ws();return e={current:e},t.memoizedState=e},useState:zS,useDebugValue:hx,useDeferredValue:function(e){return ws().memoizedState=e},useTransition:function(){var e=zS(!1),t=e[0];return e=wF.bind(null,e[1]),ws().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Lt,s=ws();if(Ot){if(n===void 0)throw Error(te(407));n=n()}else{if(n=t(),vn===null)throw Error(te(349));yi&30||uk(r,t,n)}s.memoizedState=n;var o={value:n,getSnapshot:t};return s.queue=o,US(dk.bind(null,r,o,e),[e]),r.flags|=2048,Zc(9,ck.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=ws(),t=vn.identifierPrefix;if(Ot){var n=so,r=ro;n=(r&~(1<<32-ts(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Jc++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[ks]=t,e[qc]=r,Dk(e,t,!1,!1),t.stateNode=e;e:{switch(a=Jv(n,r),n){case"dialog":jt("cancel",e),jt("close",e),s=r;break;case"iframe":case"object":case"embed":jt("load",e),s=r;break;case"video":case"audio":for(s=0;sYl&&(t.flags|=128,r=!0,Vu(o,!1),t.lanes=4194304)}else{if(!r)if(e=Vp(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Vu(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Ot)return Rn(t),null}else 2*Jt()-o.renderingStartTime>Yl&&n!==1073741824&&(t.flags|=128,r=!0,Vu(o,!1),t.lanes=4194304);o.isBackwards?(a.sibling=t.child,t.child=a):(n=o.last,n!==null?n.sibling=a:t.child=a,o.last=a)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Jt(),t.sibling=null,n=Ft.current,Et(Ft,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return xx(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?cr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(te(156,t.tag))}function OF(e,t){switch(ex(t),t.tag){case 1:return nr(t.type)&&Ap(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ql(),Pt(tr),Pt(In),ux(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return lx(t),null;case 13:if(Pt(Ft),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(te(340));Gl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Pt(Ft),null;case 4:return Ql(),null;case 10:return sx(t.type._context),null;case 22:case 23:return xx(),null;case 24:return null;default:return null}}var Tf=!1,Nn=!1,NF=typeof WeakSet=="function"?WeakSet:Set,we=null;function pl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Kt(e,t,r)}else n.current=null}function Sy(e,t,n){try{n()}catch(r){Kt(e,t,r)}}var XS=!1;function IF(e,t){if(oy=Op,e=UT(),Yb(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var a=0,l=-1,c=-1,i=0,d=0,p=e,f=null;t:for(;;){for(var h;p!==n||s!==0&&p.nodeType!==3||(l=a+s),p!==o||r!==0&&p.nodeType!==3||(c=a+r),p.nodeType===3&&(a+=p.nodeValue.length),(h=p.firstChild)!==null;)f=p,p=h;for(;;){if(p===e)break t;if(f===n&&++i===s&&(l=a),f===o&&++d===r&&(c=a),(h=p.nextSibling)!==null)break;p=f,f=p.parentNode}p=h}n=l===-1||c===-1?null:{start:l,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(ay={focusedElem:e,selectionRange:n},Op=!1,we=t;we!==null;)if(t=we,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,we=e;else for(;we!==null;){t=we;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var m=g.memoizedProps,x=g.memoizedState,b=t.stateNode,y=b.getSnapshotBeforeUpdate(t.elementType===t.type?m:qr(t.type,m),x);b.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(te(163))}}catch(S){Kt(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,we=e;break}we=t.return}return g=XS,XS=!1,g}function Ec(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&Sy(t,n,o)}s=s.next}while(s!==r)}}function Uh(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Cy(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Lk(e){var t=e.alternate;t!==null&&(e.alternate=null,Lk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ks],delete t[qc],delete t[uy],delete t[mF],delete t[vF])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function $k(e){return e.tag===5||e.tag===3||e.tag===4}function e0(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||$k(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ey(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Dp));else if(r!==4&&(e=e.child,e!==null))for(Ey(e,t,n),e=e.sibling;e!==null;)Ey(e,t,n),e=e.sibling}function Ty(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ty(e,t,n),e=e.sibling;e!==null;)Ty(e,t,n),e=e.sibling}var Sn=null,Gr=!1;function Mo(e,t,n){for(n=n.child;n!==null;)Bk(e,t,n),n=n.sibling}function Bk(e,t,n){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(Ih,n)}catch{}switch(n.tag){case 5:Nn||pl(n,t);case 6:var r=Sn,s=Gr;Sn=null,Mo(e,t,n),Sn=r,Gr=s,Sn!==null&&(Gr?(e=Sn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Sn.removeChild(n.stateNode));break;case 18:Sn!==null&&(Gr?(e=Sn,n=n.stateNode,e.nodeType===8?Sm(e.parentNode,n):e.nodeType===1&&Sm(e,n),zc(e)):Sm(Sn,n.stateNode));break;case 4:r=Sn,s=Gr,Sn=n.stateNode.containerInfo,Gr=!0,Mo(e,t,n),Sn=r,Gr=s;break;case 0:case 11:case 14:case 15:if(!Nn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&Sy(n,t,a),s=s.next}while(s!==r)}Mo(e,t,n);break;case 1:if(!Nn&&(pl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Kt(n,t,l)}Mo(e,t,n);break;case 21:Mo(e,t,n);break;case 22:n.mode&1?(Nn=(r=Nn)||n.memoizedState!==null,Mo(e,t,n),Nn=r):Mo(e,t,n);break;default:Mo(e,t,n)}}function t0(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new NF),t.forEach(function(r){var s=VF.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Kr(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=a),r&=~o}if(r=s,r=Jt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*AF(r/1960))-r,10e?16:e,ea===null)var r=!1;else{if(e=ea,ea=null,Gp=0,ct&6)throw Error(te(331));var s=ct;for(ct|=4,we=e.current;we!==null;){var o=we,a=o.child;if(we.flags&16){var l=o.deletions;if(l!==null){for(var c=0;cJt()-yx?ii(e,0):vx|=n),rr(e,t)}function Gk(e,t){t===0&&(e.mode&1?(t=mf,mf<<=1,!(mf&130023424)&&(mf=4194304)):t=1);var n=Hn();e=ho(e,t),e!==null&&(Ad(e,t,n),rr(e,n))}function UF(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Gk(e,n)}function VF(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(te(314))}r!==null&&r.delete(t),Gk(e,n)}var Jk;Jk=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||tr.current)er=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return er=!1,PF(e,t,n);er=!!(e.flags&131072)}else er=!1,Ot&&t.flags&1048576&&XT(t,$p,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ap(e,t),e=t.pendingProps;var s=Wl(t,In.current);El(t,n),s=dx(null,t,r,e,s,n);var o=fx();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,nr(r)?(o=!0,Fp(t)):o=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ax(t),s.updater=zh,t.stateNode=s,s._reactInternals=t,gy(t,r,e,n),t=yy(null,t,r,!0,o,n)):(t.tag=0,Ot&&o&&Xb(t),zn(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ap(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=KF(r),e=qr(r,e),s){case 0:t=vy(null,t,r,e,n);break e;case 1:t=QS(null,t,r,e,n);break e;case 11:t=GS(null,t,r,e,n);break e;case 14:t=JS(null,t,r,qr(r.type,e),n);break e}throw Error(te(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),vy(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),QS(e,t,r,s,n);case 3:e:{if(Ok(t),e===null)throw Error(te(387));r=t.pendingProps,o=t.memoizedState,s=o.element,ok(e,t),Up(t,r,null,n);var a=t.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){s=Zl(Error(te(423)),t),t=ZS(e,t,r,n,s);break e}else if(r!==s){s=Zl(Error(te(424)),t),t=ZS(e,t,r,n,s);break e}else for(hr=aa(t.stateNode.containerInfo.firstChild),mr=t,Ot=!0,Zr=null,n=rk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Gl(),r===s){t=go(e,t,n);break e}zn(e,t,r,n)}t=t.child}return t;case 5:return ak(t),e===null&&fy(t),r=t.type,s=t.pendingProps,o=e!==null?e.memoizedProps:null,a=s.children,iy(r,s)?a=null:o!==null&&iy(r,o)&&(t.flags|=32),Mk(e,t),zn(e,t,a,n),t.child;case 6:return e===null&&fy(t),null;case 13:return Nk(e,t,n);case 4:return ix(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Jl(t,null,r,n):zn(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),GS(e,t,r,s,n);case 7:return zn(e,t,t.pendingProps,n),t.child;case 8:return zn(e,t,t.pendingProps.children,n),t.child;case 12:return zn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,o=t.memoizedProps,a=s.value,Et(Bp,r._currentValue),r._currentValue=a,o!==null)if(us(o.value,a)){if(o.children===s.children&&!tr.current){t=go(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var l=o.dependencies;if(l!==null){a=o.child;for(var c=l.firstContext;c!==null;){if(c.context===r){if(o.tag===1){c=lo(-1,n&-n),c.tag=2;var i=o.updateQueue;if(i!==null){i=i.shared;var d=i.pending;d===null?c.next=c:(c.next=d.next,d.next=c),i.pending=c}}o.lanes|=n,c=o.alternate,c!==null&&(c.lanes|=n),py(o.return,n,t),l.lanes|=n;break}c=c.next}}else if(o.tag===10)a=o.type===t.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(te(341));a.lanes|=n,l=a.alternate,l!==null&&(l.lanes|=n),py(a,n,t),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===t){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}zn(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,El(t,n),s=Br(s),r=r(s),t.flags|=1,zn(e,t,r,n),t.child;case 14:return r=t.type,s=qr(r,t.pendingProps),s=qr(r.type,s),JS(e,t,r,s,n);case 15:return Rk(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),ap(e,t),t.tag=1,nr(r)?(e=!0,Fp(t)):e=!1,El(t,n),kk(t,r,s),gy(t,r,s,n),yy(null,t,r,!0,e,n);case 19:return Ik(e,t,n);case 22:return Pk(e,t,n)}throw Error(te(156,t.tag))};function Qk(e,t){return CT(e,t)}function HF(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ar(e,t,n,r){return new HF(e,t,n,r)}function Sx(e){return e=e.prototype,!(!e||!e.isReactComponent)}function KF(e){if(typeof e=="function")return Sx(e)?1:0;if(e!=null){if(e=e.$$typeof,e===zb)return 11;if(e===Ub)return 14}return 2}function ca(e,t){var n=e.alternate;return n===null?(n=Ar(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function up(e,t,n,r,s,o){var a=2;if(r=e,typeof e=="function")Sx(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case sl:return li(n.children,s,o,t);case Bb:a=8,s|=8;break;case $v:return e=Ar(12,n,t,s|2),e.elementType=$v,e.lanes=o,e;case Bv:return e=Ar(13,n,t,s),e.elementType=Bv,e.lanes=o,e;case zv:return e=Ar(19,n,t,s),e.elementType=zv,e.lanes=o,e;case aT:return Hh(n,s,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case sT:a=10;break e;case oT:a=9;break e;case zb:a=11;break e;case Ub:a=14;break e;case $o:a=16,r=null;break e}throw Error(te(130,e==null?e:typeof e,""))}return t=Ar(a,n,t,s),t.elementType=e,t.type=r,t.lanes=o,t}function li(e,t,n,r){return e=Ar(7,e,r,t),e.lanes=n,e}function Hh(e,t,n,r){return e=Ar(22,e,r,t),e.elementType=aT,e.lanes=n,e.stateNode={isHidden:!1},e}function Pm(e,t,n){return e=Ar(6,e,null,t),e.lanes=n,e}function Mm(e,t,n){return t=Ar(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function qF(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=dm(0),this.expirationTimes=dm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=dm(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Cx(e,t,n,r,s,o,a,l,c){return e=new qF(e,t,n,l,c),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Ar(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ax(o),e}function WF(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e_)}catch(e){console.error(e)}}e_(),eT.exports=Cr;var ka=eT.exports;const t_=jb(ka),YF=jE({__proto__:null,default:t_},[ka]);var u0=ka;Fv.createRoot=u0.createRoot,Fv.hydrateRoot=u0.hydrateRoot;const XF=(...e)=>{console!=null&&console.warn&&(ui(e[0])&&(e[0]=`react-i18next:: ${e[0]}`),console.warn(...e))},c0={},Py=(...e)=>{ui(e[0])&&c0[e[0]]||(ui(e[0])&&(c0[e[0]]=new Date),XF(...e))},n_=(e,t)=>()=>{if(e.isInitialized)t();else{const n=()=>{setTimeout(()=>{e.off("initialized",n)},0),t()};e.on("initialized",n)}},d0=(e,t,n)=>{e.loadNamespaces(t,n_(e,n))},f0=(e,t,n,r)=>{ui(n)&&(n=[n]),n.forEach(s=>{e.options.ns.indexOf(s)<0&&e.options.ns.push(s)}),e.loadLanguages(t,n_(e,r))},e2=(e,t,n={})=>!t.languages||!t.languages.length?(Py("i18n.languages were undefined or empty",t.languages),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(r,s)=>{var o;if(((o=n.bindI18n)==null?void 0:o.indexOf("languageChanging"))>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!s(r.isLanguageChangingTo,e))return!1}}),ui=e=>typeof e=="string",t2=e=>typeof e=="object"&&e!==null,n2=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,r2={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},s2=e=>r2[e],o2=e=>e.replace(n2,s2);let My={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:o2};const a2=(e={})=>{My={...My,...e}},i2=()=>My;let r_;const l2=e=>{r_=e},u2=()=>r_,c2={type:"3rdParty",init(e){a2(e.options.react),l2(e)}},s_=v.createContext();class d2{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(n=>{var r;(r=this.usedNamespaces)[n]??(r[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const f2=(e,t)=>{const n=v.useRef();return v.useEffect(()=>{n.current=e},[e,t]),n.current},o_=(e,t,n,r)=>e.getFixedT(t,n,r),p2=(e,t,n,r)=>v.useCallback(o_(e,t,n,r),[e,t,n,r]),ze=(e,t={})=>{var S,E,C,k;const{i18n:n}=t,{i18n:r,defaultNS:s}=v.useContext(s_)||{},o=n||r||u2();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new d2),!o){Py("You will need to pass in an i18next instance by using initReactI18next");const T=(N,U)=>ui(U)?U:t2(U)&&ui(U.defaultValue)?U.defaultValue:Array.isArray(N)?N[N.length-1]:N,P=[T,{},!1];return P.t=T,P.i18n={},P.ready=!1,P}(S=o.options.react)!=null&&S.wait&&Py("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const a={...i2(),...o.options.react,...t},{useSuspense:l,keyPrefix:c}=a;let i=s||((E=o.options)==null?void 0:E.defaultNS);i=ui(i)?[i]:i||["translation"],(k=(C=o.reportNamespaces).addUsedNamespaces)==null||k.call(C,i);const d=(o.isInitialized||o.initializedStoreOnce)&&i.every(T=>e2(T,o,a)),p=p2(o,t.lng||null,a.nsMode==="fallback"?i:i[0],c),f=()=>p,h=()=>o_(o,t.lng||null,a.nsMode==="fallback"?i:i[0],c),[g,m]=v.useState(f);let x=i.join();t.lng&&(x=`${t.lng}${x}`);const b=f2(x),y=v.useRef(!0);v.useEffect(()=>{const{bindI18n:T,bindI18nStore:P}=a;y.current=!0,!d&&!l&&(t.lng?f0(o,t.lng,i,()=>{y.current&&m(h)}):d0(o,i,()=>{y.current&&m(h)})),d&&b&&b!==x&&y.current&&m(h);const N=()=>{y.current&&m(h)};return T&&(o==null||o.on(T,N)),P&&(o==null||o.store.on(P,N)),()=>{y.current=!1,o&&(T==null||T.split(" ").forEach(U=>o.off(U,N))),P&&o&&P.split(" ").forEach(U=>o.store.off(U,N))}},[o,x]),v.useEffect(()=>{y.current&&d&&m(f)},[o,c,d]);const w=[g,o,d];if(w.t=g,w.i18n=o,w.ready=d,d||!d&&!l)return w;throw new Promise(T=>{t.lng?f0(o,t.lng,i,()=>T()):d0(o,i,()=>T())})};function h2({i18n:e,defaultNS:t,children:n}){const r=v.useMemo(()=>({i18n:e,defaultNS:t}),[e,t]);return v.createElement(s_.Provider,{value:r},n)}/** - * @remix-run/router v1.18.0 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function At(){return At=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Xl(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function m2(){return Math.random().toString(36).substr(2,8)}function h0(e,t){return{usr:e.state,key:e.key,idx:t}}function Xc(e,t,n,r){return n===void 0&&(n=null),At({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?_a(t):t,{state:n,key:t&&t.key||r||m2()})}function wi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function _a(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function v2(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,a=s.history,l=en.Pop,c=null,i=d();i==null&&(i=0,a.replaceState(At({},a.state,{idx:i}),""));function d(){return(a.state||{idx:null}).idx}function p(){l=en.Pop;let x=d(),b=x==null?null:x-i;i=x,c&&c({action:l,location:m.location,delta:b})}function f(x,b){l=en.Push;let y=Xc(m.location,x,b);i=d()+1;let w=h0(y,i),S=m.createHref(y);try{a.pushState(w,"",S)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;s.location.assign(S)}o&&c&&c({action:l,location:m.location,delta:1})}function h(x,b){l=en.Replace;let y=Xc(m.location,x,b);i=d();let w=h0(y,i),S=m.createHref(y);a.replaceState(w,"",S),o&&c&&c({action:l,location:m.location,delta:0})}function g(x){let b=s.location.origin!=="null"?s.location.origin:s.location.href,y=typeof x=="string"?x:wi(x);return y=y.replace(/ $/,"%20"),Ze(b,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,b)}let m={get action(){return l},get location(){return e(s,a)},listen(x){if(c)throw new Error("A history only accepts one active listener");return s.addEventListener(p0,p),c=x,()=>{s.removeEventListener(p0,p),c=null}},createHref(x){return t(s,x)},createURL:g,encodeLocation(x){let b=g(x);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:f,replace:h,go(x){return a.go(x)}};return m}var Ct;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Ct||(Ct={}));const y2=new Set(["lazy","caseSensitive","path","id","index","children"]);function b2(e){return e.index===!0}function ed(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((s,o)=>{let a=[...n,String(o)],l=typeof s.id=="string"?s.id:a.join("-");if(Ze(s.index!==!0||!s.children,"Cannot specify children on an index route"),Ze(!r[l],'Found a route id collision on id "'+l+`". Route id's must be globally unique within Data Router usages`),b2(s)){let c=At({},s,t(s),{id:l});return r[l]=c,c}else{let c=At({},s,t(s),{id:l,children:void 0});return r[l]=c,s.children&&(c.children=ed(s.children,t,a,r)),c}})}function Ua(e,t,n){return n===void 0&&(n="/"),cp(e,t,n,!1)}function cp(e,t,n,r){let s=typeof t=="string"?_a(t):t,o=du(s.pathname||"/",n);if(o==null)return null;let a=a_(e);w2(a);let l=null;for(let c=0;l==null&&c{let c={relativePath:l===void 0?o.path||"":l,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};c.relativePath.startsWith("/")&&(Ze(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let i=uo([r,c.relativePath]),d=n.concat(c);o.children&&o.children.length>0&&(Ze(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+i+'".')),a_(o.children,t,d,i)),!(o.path==null&&!o.index)&&t.push({path:i,score:j2(i,o.index),routesMeta:d})};return e.forEach((o,a)=>{var l;if(o.path===""||!((l=o.path)!=null&&l.includes("?")))s(o,a);else for(let c of i_(o.path))s(o,a,c)}),t}function i_(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let a=i_(r.join("/")),l=[];return l.push(...a.map(c=>c===""?o:[o,c].join("/"))),s&&l.push(...a),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function w2(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:R2(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const S2=/^:[\w-]+$/,C2=3,E2=2,T2=1,k2=10,_2=-2,g0=e=>e==="*";function j2(e,t){let n=e.split("/"),r=n.length;return n.some(g0)&&(r+=_2),t&&(r+=E2),n.filter(s=>!g0(s)).reduce((s,o)=>s+(S2.test(o)?C2:o===""?T2:k2),r)}function R2(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function P2(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,s={},o="/",a=[];for(let l=0;l{let{paramName:f,isOptional:h}=d;if(f==="*"){let m=l[p]||"";a=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const g=l[p];return h&&!g?i[f]=void 0:i[f]=(g||"").replace(/%2F/g,"/"),i},{}),pathname:o,pathnameBase:a,pattern:e}}function M2(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Xl(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function O2(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Xl(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function du(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function N2(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?_a(e):e;return{pathname:n?n.startsWith("/")?n:I2(n,t):t,search:A2(r),hash:F2(s)}}function I2(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Om(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function l_(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Jh(e,t){let n=l_(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Qh(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=_a(e):(s=At({},e),Ze(!s.pathname||!s.pathname.includes("?"),Om("?","pathname","search",s)),Ze(!s.pathname||!s.pathname.includes("#"),Om("#","pathname","hash",s)),Ze(!s.search||!s.search.includes("#"),Om("#","search","hash",s)));let o=e===""||s.pathname==="",a=o?"/":s.pathname,l;if(a==null)l=n;else{let p=t.length-1;if(!r&&a.startsWith("..")){let f=a.split("/");for(;f[0]==="..";)f.shift(),p-=1;s.pathname=f.join("/")}l=p>=0?t[p]:"/"}let c=N2(s,l),i=a&&a!=="/"&&a.endsWith("/"),d=(o||a===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(i||d)&&(c.pathname+="/"),c}const uo=e=>e.join("/").replace(/\/\/+/g,"/"),D2=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),A2=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,F2=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class _x{constructor(t,n,r,s){s===void 0&&(s=!1),this.status=t,this.statusText=n||"",this.internal=s,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Zh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const u_=["post","put","patch","delete"],L2=new Set(u_),$2=["get",...u_],B2=new Set($2),z2=new Set([301,302,303,307,308]),U2=new Set([307,308]),Nm={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},V2={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ku={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},jx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,H2=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),c_="remix-router-transitions";function K2(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ze(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let s;if(e.mapRouteProperties)s=e.mapRouteProperties;else if(e.detectErrorBoundary){let M=e.detectErrorBoundary;s=O=>({hasErrorBoundary:M(O)})}else s=H2;let o={},a=ed(e.routes,s,void 0,o),l,c=e.basename||"/",i=e.unstable_dataStrategy||Q2,d=e.unstable_patchRoutesOnMiss,p=At({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),f=null,h=new Set,g=null,m=null,x=null,b=e.hydrationData!=null,y=Ua(a,e.history.location,c),w=null;if(y==null&&!d){let M=Bn(404,{pathname:e.history.location.pathname}),{matches:O,route:L}=k0(a);y=O,w={[L.id]:M}}y&&d&&!e.hydrationData&&rm(y,a,e.history.location.pathname).active&&(y=null);let S;if(!y)S=!1,y=[];else if(y.some(M=>M.route.lazy))S=!1;else if(!y.some(M=>M.route.loader))S=!0;else if(p.v7_partialHydration){let M=e.hydrationData?e.hydrationData.loaderData:null,O=e.hydrationData?e.hydrationData.errors:null,L=H=>H.route.loader?typeof H.route.loader=="function"&&H.route.loader.hydrate===!0?!1:M&&M[H.route.id]!==void 0||O&&O[H.route.id]!==void 0:!0;if(O){let H=y.findIndex(ye=>O[ye.route.id]!==void 0);S=y.slice(0,H+1).every(L)}else S=y.every(L)}else S=e.hydrationData!=null;let E,C={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,navigation:Nm,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||w,fetchers:new Map,blockers:new Map},k=en.Pop,T=!1,P,N=!1,U=new Map,I=null,Z=!1,V=!1,Q=[],ee=[],W=new Map,F=0,A=-1,Y=new Map,de=new Set,z=new Map,se=new Map,ne=new Set,ie=new Map,oe=new Map,J=new Map,Ce=!1;function Pe(){if(f=e.history.listen(M=>{let{action:O,location:L,delta:H}=M;if(Ce){Ce=!1;return}Xl(oe.size===0||H!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let ye=Ro({currentLocation:C.location,nextLocation:L,historyAction:O});if(ye&&H!=null){Ce=!0,e.history.go(H*-1),ms(ye,{state:"blocked",location:L,proceed(){ms(ye,{state:"proceeding",proceed:void 0,reset:void 0,location:L}),e.history.go(H)},reset(){let _e=new Map(C.blockers);_e.set(ye,Ku),me({blockers:_e})}});return}return Wt(O,L)}),n){uL(t,U);let M=()=>cL(t,U);t.addEventListener("pagehide",M),I=()=>t.removeEventListener("pagehide",M)}return C.initialized||Wt(en.Pop,C.location,{initialHydration:!0}),E}function Le(){f&&f(),I&&I(),h.clear(),P&&P.abort(),C.fetchers.forEach((M,O)=>gs(O)),C.blockers.forEach((M,O)=>_n(O))}function Me(M){return h.add(M),()=>h.delete(M)}function me(M,O){O===void 0&&(O={}),C=At({},C,M);let L=[],H=[];p.v7_fetcherPersist&&C.fetchers.forEach((ye,_e)=>{ye.state==="idle"&&(ne.has(_e)?H.push(_e):L.push(_e))}),[...h].forEach(ye=>ye(C,{deletedFetchers:H,unstable_viewTransitionOpts:O.viewTransitionOpts,unstable_flushSync:O.flushSync===!0})),p.v7_fetcherPersist&&(L.forEach(ye=>C.fetchers.delete(ye)),H.forEach(ye=>gs(ye)))}function rt(M,O,L){var H,ye;let{flushSync:_e}=L===void 0?{}:L,$e=C.actionData!=null&&C.navigation.formMethod!=null&&Jr(C.navigation.formMethod)&&C.navigation.state==="loading"&&((H=M.state)==null?void 0:H._isRedirect)!==!0,fe;O.actionData?Object.keys(O.actionData).length>0?fe=O.actionData:fe=null:$e?fe=C.actionData:fe=null;let qe=O.loaderData?E0(C.loaderData,O.loaderData,O.matches||[],O.errors):C.loaderData,Re=C.blockers;Re.size>0&&(Re=new Map(Re),Re.forEach((mt,bt)=>Re.set(bt,Ku)));let Oe=T===!0||C.navigation.formMethod!=null&&Jr(C.navigation.formMethod)&&((ye=M.state)==null?void 0:ye._isRedirect)!==!0;l&&(a=l,l=void 0),Z||k===en.Pop||(k===en.Push?e.history.push(M,M.state):k===en.Replace&&e.history.replace(M,M.state));let yt;if(k===en.Pop){let mt=U.get(C.location.pathname);mt&&mt.has(M.pathname)?yt={currentLocation:C.location,nextLocation:M}:U.has(M.pathname)&&(yt={currentLocation:M,nextLocation:C.location})}else if(N){let mt=U.get(C.location.pathname);mt?mt.add(M.pathname):(mt=new Set([M.pathname]),U.set(C.location.pathname,mt)),yt={currentLocation:C.location,nextLocation:M}}me(At({},O,{actionData:fe,loaderData:qe,historyAction:k,location:M,initialized:!0,navigation:Nm,revalidation:"idle",restoreScrollPosition:Kw(M,O.matches||C.matches),preventScrollReset:Oe,blockers:Re}),{viewTransitionOpts:yt,flushSync:_e===!0}),k=en.Pop,T=!1,N=!1,Z=!1,V=!1,Q=[],ee=[]}async function It(M,O){if(typeof M=="number"){e.history.go(M);return}let L=Oy(C.location,C.matches,c,p.v7_prependBasename,M,p.v7_relativeSplatPath,O==null?void 0:O.fromRouteId,O==null?void 0:O.relative),{path:H,submission:ye,error:_e}=v0(p.v7_normalizeFormMethod,!1,L,O),$e=C.location,fe=Xc(C.location,H,O&&O.state);fe=At({},fe,e.history.encodeLocation(fe));let qe=O&&O.replace!=null?O.replace:void 0,Re=en.Push;qe===!0?Re=en.Replace:qe===!1||ye!=null&&Jr(ye.formMethod)&&ye.formAction===C.location.pathname+C.location.search&&(Re=en.Replace);let Oe=O&&"preventScrollReset"in O?O.preventScrollReset===!0:void 0,yt=(O&&O.unstable_flushSync)===!0,mt=Ro({currentLocation:$e,nextLocation:fe,historyAction:Re});if(mt){ms(mt,{state:"blocked",location:fe,proceed(){ms(mt,{state:"proceeding",proceed:void 0,reset:void 0,location:fe}),It(M,O)},reset(){let bt=new Map(C.blockers);bt.set(mt,Ku),me({blockers:bt})}});return}return await Wt(Re,fe,{submission:ye,pendingError:_e,preventScrollReset:Oe,replace:O&&O.replace,enableViewTransition:O&&O.unstable_viewTransition,flushSync:yt})}function Zt(){if(hn(),me({revalidation:"loading"}),C.navigation.state!=="submitting"){if(C.navigation.state==="idle"){Wt(C.historyAction,C.location,{startUninterruptedRevalidation:!0});return}Wt(k||C.historyAction,C.navigation.location,{overrideNavigation:C.navigation})}}async function Wt(M,O,L){P&&P.abort(),P=null,k=M,Z=(L&&L.startUninterruptedRevalidation)===!0,UI(C.location,C.matches),T=(L&&L.preventScrollReset)===!0,N=(L&&L.enableViewTransition)===!0;let H=l||a,ye=L&&L.overrideNavigation,_e=Ua(H,O,c),$e=(L&&L.flushSync)===!0,fe=rm(_e,H,O.pathname);if(fe.active&&fe.matches&&(_e=fe.matches),!_e){let{error:pt,notFoundMatches:bn,route:Yt}=Iu(O.pathname);rt(O,{matches:bn,loaderData:{},errors:{[Yt.id]:pt}},{flushSync:$e});return}if(C.initialized&&!V&&nL(C.location,O)&&!(L&&L.submission&&Jr(L.submission.formMethod))){rt(O,{matches:_e},{flushSync:$e});return}P=new AbortController;let qe=Hi(e.history,O,P.signal,L&&L.submission),Re;if(L&&L.pendingError)Re=[gl(_e).route.id,{type:Ct.error,error:L.pendingError}];else if(L&&L.submission&&Jr(L.submission.formMethod)){let pt=await an(qe,O,L.submission,_e,fe.active,{replace:L.replace,flushSync:$e});if(pt.shortCircuited)return;if(pt.pendingActionResult){let[bn,Yt]=pt.pendingActionResult;if(fr(Yt)&&Zh(Yt.error)&&Yt.error.status===404){P=null,rt(O,{matches:pt.matches,loaderData:{},errors:{[bn]:Yt.error}});return}}_e=pt.matches||_e,Re=pt.pendingActionResult,ye=Im(O,L.submission),$e=!1,fe.active=!1,qe=Hi(e.history,qe.url,qe.signal)}let{shortCircuited:Oe,matches:yt,loaderData:mt,errors:bt}=await j(qe,O,_e,fe.active,ye,L&&L.submission,L&&L.fetcherSubmission,L&&L.replace,L&&L.initialHydration===!0,$e,Re);Oe||(P=null,rt(O,At({matches:yt||_e},T0(Re),{loaderData:mt,errors:bt})))}async function an(M,O,L,H,ye,_e){_e===void 0&&(_e={}),hn();let $e=iL(O,L);if(me({navigation:$e},{flushSync:_e.flushSync===!0}),ye){let Re=await sf(H,O.pathname,M.signal);if(Re.type==="aborted")return{shortCircuited:!0};if(Re.type==="error"){let{boundaryId:Oe,error:yt}=$i(O.pathname,Re);return{matches:Re.partialMatches,pendingActionResult:[Oe,{type:Ct.error,error:yt}]}}else if(Re.matches)H=Re.matches;else{let{notFoundMatches:Oe,error:yt,route:mt}=Iu(O.pathname);return{matches:Oe,pendingActionResult:[mt.id,{type:Ct.error,error:yt}]}}}let fe,qe=cc(H,O);if(!qe.route.action&&!qe.route.lazy)fe={type:Ct.error,error:Bn(405,{method:M.method,pathname:O.pathname,routeId:qe.route.id})};else if(fe=(await et("action",M,[qe],H))[0],M.signal.aborted)return{shortCircuited:!0};if(Wa(fe)){let Re;return _e&&_e.replace!=null?Re=_e.replace:Re=w0(fe.response.headers.get("Location"),new URL(M.url),c)===C.location.pathname+C.location.search,await Ee(M,fe,{submission:L,replace:Re}),{shortCircuited:!0}}if(qa(fe))throw Bn(400,{type:"defer-action"});if(fr(fe)){let Re=gl(H,qe.route.id);return(_e&&_e.replace)!==!0&&(k=en.Push),{matches:H,pendingActionResult:[Re.route.id,fe]}}return{matches:H,pendingActionResult:[qe.route.id,fe]}}async function j(M,O,L,H,ye,_e,$e,fe,qe,Re,Oe){let yt=ye||Im(O,_e),mt=_e||$e||R0(yt),bt=!Z&&(!p.v7_partialHydration||!qe);if(H){if(bt){let Vt=D(Oe);me(At({navigation:yt},Vt!==void 0?{actionData:Vt}:{}),{flushSync:Re})}let Ge=await sf(L,O.pathname,M.signal);if(Ge.type==="aborted")return{shortCircuited:!0};if(Ge.type==="error"){let{boundaryId:Vt,error:ar}=$i(O.pathname,Ge);return{matches:Ge.partialMatches,loaderData:{},errors:{[Vt]:ar}}}else if(Ge.matches)L=Ge.matches;else{let{error:Vt,notFoundMatches:ar,route:Mt}=Iu(O.pathname);return{matches:ar,loaderData:{},errors:{[Mt.id]:Vt}}}}let pt=l||a,[bn,Yt]=y0(e.history,C,L,mt,O,p.v7_partialHydration&&qe===!0,p.v7_skipActionErrorRevalidation,V,Q,ee,ne,z,de,pt,c,Oe);if(vs(Ge=>!(L&&L.some(Vt=>Vt.route.id===Ge))||bn&&bn.some(Vt=>Vt.route.id===Ge)),A=++F,bn.length===0&&Yt.length===0){let Ge=Ue();return rt(O,At({matches:L,loaderData:{},errors:Oe&&fr(Oe[1])?{[Oe[0]]:Oe[1].error}:null},T0(Oe),Ge?{fetchers:new Map(C.fetchers)}:{}),{flushSync:Re}),{shortCircuited:!0}}if(bt){let Ge={};if(!H){Ge.navigation=yt;let Vt=D(Oe);Vt!==void 0&&(Ge.actionData=Vt)}Yt.length>0&&(Ge.fetchers=B(Yt)),me(Ge,{flushSync:Re})}Yt.forEach(Ge=>{W.has(Ge.key)&&Fn(Ge.key),Ge.controller&&W.set(Ge.key,Ge.controller)});let Au=()=>Yt.forEach(Ge=>Fn(Ge.key));P&&P.signal.addEventListener("abort",Au);let{loaderResults:Po,fetcherResults:Bi}=await kt(C.matches,L,bn,Yt,M);if(M.signal.aborted)return{shortCircuited:!0};P&&P.signal.removeEventListener("abort",Au),Yt.forEach(Ge=>W.delete(Ge.key));let zi=_0([...Po,...Bi]);if(zi){if(zi.idx>=bn.length){let Ge=Yt[zi.idx-bn.length].key;de.add(Ge)}return await Ee(M,zi.result,{replace:fe}),{shortCircuited:!0}}let{loaderData:Ui,errors:ys}=C0(C,L,bn,Po,Oe,Yt,Bi,ie);ie.forEach((Ge,Vt)=>{Ge.subscribe(ar=>{(ar||Ge.done)&&ie.delete(Vt)})}),p.v7_partialHydration&&qe&&C.errors&&Object.entries(C.errors).filter(Ge=>{let[Vt]=Ge;return!bn.some(ar=>ar.route.id===Vt)}).forEach(Ge=>{let[Vt,ar]=Ge;ys=Object.assign(ys||{},{[Vt]:ar})});let of=Ue(),af=St(A),lf=of||af||Yt.length>0;return At({matches:L,loaderData:Ui,errors:ys},lf?{fetchers:new Map(C.fetchers)}:{})}function D(M){if(M&&!fr(M[1]))return{[M[0]]:M[1].data};if(C.actionData)return Object.keys(C.actionData).length===0?null:C.actionData}function B(M){return M.forEach(O=>{let L=C.fetchers.get(O.key),H=qu(void 0,L?L.data:void 0);C.fetchers.set(O.key,H)}),new Map(C.fetchers)}function pe(M,O,L,H){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");W.has(M)&&Fn(M);let ye=(H&&H.unstable_flushSync)===!0,_e=l||a,$e=Oy(C.location,C.matches,c,p.v7_prependBasename,L,p.v7_relativeSplatPath,O,H==null?void 0:H.relative),fe=Ua(_e,$e,c),qe=rm(fe,_e,$e);if(qe.active&&qe.matches&&(fe=qe.matches),!fe){gn(M,O,Bn(404,{pathname:$e}),{flushSync:ye});return}let{path:Re,submission:Oe,error:yt}=v0(p.v7_normalizeFormMethod,!0,$e,H);if(yt){gn(M,O,yt,{flushSync:ye});return}let mt=cc(fe,Re);if(T=(H&&H.preventScrollReset)===!0,Oe&&Jr(Oe.formMethod)){le(M,O,Re,mt,fe,qe.active,ye,Oe);return}z.set(M,{routeId:O,path:Re}),ae(M,O,Re,mt,fe,qe.active,ye,Oe)}async function le(M,O,L,H,ye,_e,$e,fe){hn(),z.delete(M);function qe(Mt){if(!Mt.route.action&&!Mt.route.lazy){let Ks=Bn(405,{method:fe.formMethod,pathname:L,routeId:O});return gn(M,O,Ks,{flushSync:$e}),!0}return!1}if(!_e&&qe(H))return;let Re=C.fetchers.get(M);yn(M,lL(fe,Re),{flushSync:$e});let Oe=new AbortController,yt=Hi(e.history,L,Oe.signal,fe);if(_e){let Mt=await sf(ye,L,yt.signal);if(Mt.type==="aborted")return;if(Mt.type==="error"){let{error:Ks}=$i(L,Mt);gn(M,O,Ks,{flushSync:$e});return}else if(Mt.matches){if(ye=Mt.matches,H=cc(ye,L),qe(H))return}else{gn(M,O,Bn(404,{pathname:L}),{flushSync:$e});return}}W.set(M,Oe);let mt=F,pt=(await et("action",yt,[H],ye))[0];if(yt.signal.aborted){W.get(M)===Oe&&W.delete(M);return}if(p.v7_fetcherPersist&&ne.has(M)){if(Wa(pt)||fr(pt)){yn(M,Fo(void 0));return}}else{if(Wa(pt))if(W.delete(M),A>mt){yn(M,Fo(void 0));return}else return de.add(M),yn(M,qu(fe)),Ee(yt,pt,{fetcherSubmission:fe});if(fr(pt)){gn(M,O,pt.error);return}}if(qa(pt))throw Bn(400,{type:"defer-action"});let bn=C.navigation.location||C.location,Yt=Hi(e.history,bn,Oe.signal),Au=l||a,Po=C.navigation.state!=="idle"?Ua(Au,C.navigation.location,c):C.matches;Ze(Po,"Didn't find any matches after fetcher action");let Bi=++F;Y.set(M,Bi);let zi=qu(fe,pt.data);C.fetchers.set(M,zi);let[Ui,ys]=y0(e.history,C,Po,fe,bn,!1,p.v7_skipActionErrorRevalidation,V,Q,ee,ne,z,de,Au,c,[H.route.id,pt]);ys.filter(Mt=>Mt.key!==M).forEach(Mt=>{let Ks=Mt.key,qw=C.fetchers.get(Ks),KI=qu(void 0,qw?qw.data:void 0);C.fetchers.set(Ks,KI),W.has(Ks)&&Fn(Ks),Mt.controller&&W.set(Ks,Mt.controller)}),me({fetchers:new Map(C.fetchers)});let of=()=>ys.forEach(Mt=>Fn(Mt.key));Oe.signal.addEventListener("abort",of);let{loaderResults:af,fetcherResults:lf}=await kt(C.matches,Po,Ui,ys,Yt);if(Oe.signal.aborted)return;Oe.signal.removeEventListener("abort",of),Y.delete(M),W.delete(M),ys.forEach(Mt=>W.delete(Mt.key));let Ge=_0([...af,...lf]);if(Ge){if(Ge.idx>=Ui.length){let Mt=ys[Ge.idx-Ui.length].key;de.add(Mt)}return Ee(Yt,Ge.result)}let{loaderData:Vt,errors:ar}=C0(C,C.matches,Ui,af,void 0,ys,lf,ie);if(C.fetchers.has(M)){let Mt=Fo(pt.data);C.fetchers.set(M,Mt)}St(Bi),C.navigation.state==="loading"&&Bi>A?(Ze(k,"Expected pending action"),P&&P.abort(),rt(C.navigation.location,{matches:Po,loaderData:Vt,errors:ar,fetchers:new Map(C.fetchers)})):(me({errors:ar,loaderData:E0(C.loaderData,Vt,Po,ar),fetchers:new Map(C.fetchers)}),V=!1)}async function ae(M,O,L,H,ye,_e,$e,fe){let qe=C.fetchers.get(M);yn(M,qu(fe,qe?qe.data:void 0),{flushSync:$e});let Re=new AbortController,Oe=Hi(e.history,L,Re.signal);if(_e){let pt=await sf(ye,L,Oe.signal);if(pt.type==="aborted")return;if(pt.type==="error"){let{error:bn}=$i(L,pt);gn(M,O,bn,{flushSync:$e});return}else if(pt.matches)ye=pt.matches,H=cc(ye,L);else{gn(M,O,Bn(404,{pathname:L}),{flushSync:$e});return}}W.set(M,Re);let yt=F,bt=(await et("loader",Oe,[H],ye))[0];if(qa(bt)&&(bt=await g_(bt,Oe.signal,!0)||bt),W.get(M)===Re&&W.delete(M),!Oe.signal.aborted){if(ne.has(M)){yn(M,Fo(void 0));return}if(Wa(bt))if(A>yt){yn(M,Fo(void 0));return}else{de.add(M),await Ee(Oe,bt);return}if(fr(bt)){gn(M,O,bt.error);return}Ze(!qa(bt),"Unhandled fetcher deferred data"),yn(M,Fo(bt.data))}}async function Ee(M,O,L){let{submission:H,fetcherSubmission:ye,replace:_e}=L===void 0?{}:L;O.response.headers.has("X-Remix-Revalidate")&&(V=!0);let $e=O.response.headers.get("Location");Ze($e,"Expected a Location header on the redirect Response"),$e=w0($e,new URL(M.url),c);let fe=Xc(C.location,$e,{_isRedirect:!0});if(n){let bt=!1;if(O.response.headers.has("X-Remix-Reload-Document"))bt=!0;else if(jx.test($e)){const pt=e.history.createURL($e);bt=pt.origin!==t.location.origin||du(pt.pathname,c)==null}if(bt){_e?t.location.replace($e):t.location.assign($e);return}}P=null;let qe=_e===!0?en.Replace:en.Push,{formMethod:Re,formAction:Oe,formEncType:yt}=C.navigation;!H&&!ye&&Re&&Oe&&yt&&(H=R0(C.navigation));let mt=H||ye;if(U2.has(O.response.status)&&mt&&Jr(mt.formMethod))await Wt(qe,fe,{submission:At({},mt,{formAction:$e}),preventScrollReset:T});else{let bt=Im(fe,H);await Wt(qe,fe,{overrideNavigation:bt,fetcherSubmission:ye,preventScrollReset:T})}}async function et(M,O,L,H){try{let ye=await Z2(i,M,O,L,H,o,s);return await Promise.all(ye.map((_e,$e)=>{if(sL(_e)){let fe=_e.result;return{type:Ct.redirect,response:eL(fe,O,L[$e].route.id,H,c,p.v7_relativeSplatPath)}}return X2(_e)}))}catch(ye){return L.map(()=>({type:Ct.error,error:ye}))}}async function kt(M,O,L,H,ye){let[_e,...$e]=await Promise.all([L.length?et("loader",ye,L,O):[],...H.map(fe=>{if(fe.matches&&fe.match&&fe.controller){let qe=Hi(e.history,fe.path,fe.controller.signal);return et("loader",qe,[fe.match],fe.matches).then(Re=>Re[0])}else return Promise.resolve({type:Ct.error,error:Bn(404,{pathname:fe.path})})})]);return await Promise.all([j0(M,L,_e,_e.map(()=>ye.signal),!1,C.loaderData),j0(M,H.map(fe=>fe.match),$e,H.map(fe=>fe.controller?fe.controller.signal:null),!0)]),{loaderResults:_e,fetcherResults:$e}}function hn(){V=!0,Q.push(...vs()),z.forEach((M,O)=>{W.has(O)&&(ee.push(O),Fn(O))})}function yn(M,O,L){L===void 0&&(L={}),C.fetchers.set(M,O),me({fetchers:new Map(C.fetchers)},{flushSync:(L&&L.flushSync)===!0})}function gn(M,O,L,H){H===void 0&&(H={});let ye=gl(C.matches,O);gs(M),me({errors:{[ye.route.id]:L},fetchers:new Map(C.fetchers)},{flushSync:(H&&H.flushSync)===!0})}function jo(M){return p.v7_fetcherPersist&&(se.set(M,(se.get(M)||0)+1),ne.has(M)&&ne.delete(M)),C.fetchers.get(M)||V2}function gs(M){let O=C.fetchers.get(M);W.has(M)&&!(O&&O.state==="loading"&&Y.has(M))&&Fn(M),z.delete(M),Y.delete(M),de.delete(M),ne.delete(M),C.fetchers.delete(M)}function Aa(M){if(p.v7_fetcherPersist){let O=(se.get(M)||0)-1;O<=0?(se.delete(M),ne.add(M)):se.set(M,O)}else gs(M);me({fetchers:new Map(C.fetchers)})}function Fn(M){let O=W.get(M);Ze(O,"Expected fetch controller: "+M),O.abort(),W.delete(M)}function ue(M){for(let O of M){let L=jo(O),H=Fo(L.data);C.fetchers.set(O,H)}}function Ue(){let M=[],O=!1;for(let L of de){let H=C.fetchers.get(L);Ze(H,"Expected fetcher: "+L),H.state==="loading"&&(de.delete(L),M.push(L),O=!0)}return ue(M),O}function St(M){let O=[];for(let[L,H]of Y)if(H0}function dt(M,O){let L=C.blockers.get(M)||Ku;return oe.get(M)!==O&&oe.set(M,O),L}function _n(M){C.blockers.delete(M),oe.delete(M)}function ms(M,O){let L=C.blockers.get(M)||Ku;Ze(L.state==="unblocked"&&O.state==="blocked"||L.state==="blocked"&&O.state==="blocked"||L.state==="blocked"&&O.state==="proceeding"||L.state==="blocked"&&O.state==="unblocked"||L.state==="proceeding"&&O.state==="unblocked","Invalid blocker state transition: "+L.state+" -> "+O.state);let H=new Map(C.blockers);H.set(M,O),me({blockers:H})}function Ro(M){let{currentLocation:O,nextLocation:L,historyAction:H}=M;if(oe.size===0)return;oe.size>1&&Xl(!1,"A router only supports one blocker at a time");let ye=Array.from(oe.entries()),[_e,$e]=ye[ye.length-1],fe=C.blockers.get(_e);if(!(fe&&fe.state==="proceeding")&&$e({currentLocation:O,nextLocation:L,historyAction:H}))return _e}function Iu(M){let O=Bn(404,{pathname:M}),L=l||a,{matches:H,route:ye}=k0(L);return vs(),{notFoundMatches:H,route:ye,error:O}}function $i(M,O){return{boundaryId:gl(O.partialMatches).route.id,error:Bn(400,{type:"route-discovery",pathname:M,message:O.error!=null&&"message"in O.error?O.error:String(O.error)})}}function vs(M){let O=[];return ie.forEach((L,H)=>{(!M||M(H))&&(L.cancel(),O.push(H),ie.delete(H))}),O}function Du(M,O,L){if(g=M,x=O,m=L||null,!b&&C.navigation===Nm){b=!0;let H=Kw(C.location,C.matches);H!=null&&me({restoreScrollPosition:H})}return()=>{g=null,x=null,m=null}}function Hw(M,O){return m&&m(M,O.map(H=>x2(H,C.loaderData)))||M.key}function UI(M,O){if(g&&x){let L=Hw(M,O);g[L]=x()}}function Kw(M,O){if(g){let L=Hw(M,O),H=g[L];if(typeof H=="number")return H}return null}function rm(M,O,L){if(d)if(M){let H=M[M.length-1].route;if(H.path&&(H.path==="*"||H.path.endsWith("/*")))return{active:!0,matches:cp(O,L,c,!0)}}else return{active:!0,matches:cp(O,L,c,!0)||[]};return{active:!1,matches:null}}async function sf(M,O,L){let H=M,ye=H.length>0?H[H.length-1].route:null;for(;;){let _e=l==null,$e=l||a;try{await J2(d,O,H,$e,o,s,J,L)}catch(Oe){return{type:"error",error:Oe,partialMatches:H}}finally{_e&&(a=[...a])}if(L.aborted)return{type:"aborted"};let fe=Ua($e,O,c),qe=!1;if(fe){let Oe=fe[fe.length-1].route;if(Oe.index)return{type:"success",matches:fe};if(Oe.path&&Oe.path.length>0)if(Oe.path==="*")qe=!0;else return{type:"success",matches:fe}}let Re=cp($e,O,c,!0);if(!Re||H.map(Oe=>Oe.route.id).join("-")===Re.map(Oe=>Oe.route.id).join("-"))return{type:"success",matches:qe?fe:null};if(H=Re,ye=H[H.length-1].route,ye.path==="*")return{type:"success",matches:H}}}function VI(M){o={},l=ed(M,s,void 0,o)}function HI(M,O){let L=l==null;f_(M,O,l||a,o,s),L&&(a=[...a],me({}))}return E={get basename(){return c},get future(){return p},get state(){return C},get routes(){return a},get window(){return t},initialize:Pe,subscribe:Me,enableScrollRestoration:Du,navigate:It,fetch:pe,revalidate:Zt,createHref:M=>e.history.createHref(M),encodeLocation:M=>e.history.encodeLocation(M),getFetcher:jo,deleteFetcher:Aa,dispose:Le,getBlocker:dt,deleteBlocker:_n,patchRoutes:HI,_internalFetchControllers:W,_internalActiveDeferreds:ie,_internalSetRoutes:VI},E}function q2(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Oy(e,t,n,r,s,o,a,l){let c,i;if(a){c=[];for(let p of t)if(c.push(p),p.route.id===a){i=p;break}}else c=t,i=t[t.length-1];let d=Qh(s||".",Jh(c,o),du(e.pathname,n)||e.pathname,l==="path");return s==null&&(d.search=e.search,d.hash=e.hash),(s==null||s===""||s===".")&&i&&i.route.index&&!Rx(d.search)&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(d.pathname=d.pathname==="/"?n:uo([n,d.pathname])),wi(d)}function v0(e,t,n,r){if(!r||!q2(r))return{path:n};if(r.formMethod&&!aL(r.formMethod))return{path:n,error:Bn(405,{method:r.formMethod})};let s=()=>({path:n,error:Bn(400,{type:"invalid-body"})}),o=r.formMethod||"get",a=e?o.toUpperCase():o.toLowerCase(),l=p_(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Jr(a))return s();let f=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((h,g)=>{let[m,x]=g;return""+h+m+"="+x+` -`},""):String(r.body);return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:void 0,text:f}}}else if(r.formEncType==="application/json"){if(!Jr(a))return s();try{let f=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:f,text:void 0}}}catch{return s()}}}Ze(typeof FormData=="function","FormData is not available in this environment");let c,i;if(r.formData)c=Ny(r.formData),i=r.formData;else if(r.body instanceof FormData)c=Ny(r.body),i=r.body;else if(r.body instanceof URLSearchParams)c=r.body,i=S0(c);else if(r.body==null)c=new URLSearchParams,i=new FormData;else try{c=new URLSearchParams(r.body),i=S0(c)}catch{return s()}let d={formMethod:a,formAction:l,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(Jr(d.formMethod))return{path:n,submission:d};let p=_a(n);return t&&p.search&&Rx(p.search)&&c.append("index",""),p.search="?"+c,{path:wi(p),submission:d}}function W2(e,t){let n=e;if(t){let r=e.findIndex(s=>s.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function y0(e,t,n,r,s,o,a,l,c,i,d,p,f,h,g,m){let x=m?fr(m[1])?m[1].error:m[1].data:void 0,b=e.createURL(t.location),y=e.createURL(s),w=m&&fr(m[1])?m[0]:void 0,S=w?W2(n,w):n,E=m?m[1].statusCode:void 0,C=a&&E&&E>=400,k=S.filter((P,N)=>{let{route:U}=P;if(U.lazy)return!0;if(U.loader==null)return!1;if(o)return typeof U.loader!="function"||U.loader.hydrate?!0:t.loaderData[U.id]===void 0&&(!t.errors||t.errors[U.id]===void 0);if(G2(t.loaderData,t.matches[N],P)||c.some(V=>V===P.route.id))return!0;let I=t.matches[N],Z=P;return b0(P,At({currentUrl:b,currentParams:I.params,nextUrl:y,nextParams:Z.params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:l||b.pathname+b.search===y.pathname+y.search||b.search!==y.search||d_(I,Z)}))}),T=[];return p.forEach((P,N)=>{if(o||!n.some(Q=>Q.route.id===P.routeId)||d.has(N))return;let U=Ua(h,P.path,g);if(!U){T.push({key:N,routeId:P.routeId,path:P.path,matches:null,match:null,controller:null});return}let I=t.fetchers.get(N),Z=cc(U,P.path),V=!1;f.has(N)?V=!1:i.includes(N)?V=!0:I&&I.state!=="idle"&&I.data===void 0?V=l:V=b0(Z,At({currentUrl:b,currentParams:t.matches[t.matches.length-1].params,nextUrl:y,nextParams:n[n.length-1].params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:l})),V&&T.push({key:N,routeId:P.routeId,path:P.path,matches:U,match:Z,controller:new AbortController})}),[k,T]}function G2(e,t,n){let r=!t||n.route.id!==t.route.id,s=e[n.route.id]===void 0;return r||s}function d_(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function b0(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function J2(e,t,n,r,s,o,a,l){let c=[t,...n.map(i=>i.route.id)].join("-");try{let i=a.get(c);i||(i=e({path:t,matches:n,patch:(d,p)=>{l.aborted||f_(d,p,r,s,o)}}),a.set(c,i)),i&&rL(i)&&await i}finally{a.delete(c)}}function f_(e,t,n,r,s){if(e){var o;let a=r[e];Ze(a,"No route found to patch children into: routeId = "+e);let l=ed(t,s,[e,"patch",String(((o=a.children)==null?void 0:o.length)||"0")],r);a.children?a.children.push(...l):a.children=l}else{let a=ed(t,s,["patch",String(n.length||"0")],r);n.push(...a)}}async function x0(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let s=n[e.id];Ze(s,"No route found in manifest");let o={};for(let a in r){let c=s[a]!==void 0&&a!=="hasErrorBoundary";Xl(!c,'Route "'+s.id+'" has a static property "'+a+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+a+'" will be ignored.')),!c&&!y2.has(a)&&(o[a]=r[a])}Object.assign(s,o),Object.assign(s,At({},t(s),{lazy:void 0}))}function Q2(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function Z2(e,t,n,r,s,o,a,l){let c=r.reduce((p,f)=>p.add(f.route.id),new Set),i=new Set,d=await e({matches:s.map(p=>{let f=c.has(p.route.id);return At({},p,{shouldLoad:f,resolve:g=>(i.add(p.route.id),f?Y2(t,n,p,o,a,g,l):Promise.resolve({type:Ct.data,result:void 0}))})}),request:n,params:s[0].params,context:l});return s.forEach(p=>Ze(i.has(p.route.id),'`match.resolve()` was not called for route id "'+p.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),d.filter((p,f)=>c.has(s[f].route.id))}async function Y2(e,t,n,r,s,o,a){let l,c,i=d=>{let p,f=new Promise((m,x)=>p=x);c=()=>p(),t.signal.addEventListener("abort",c);let h=m=>typeof d!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):d({request:t,params:n.params,context:a},...m!==void 0?[m]:[]),g;return o?g=o(m=>h(m)):g=(async()=>{try{return{type:"data",result:await h()}}catch(m){return{type:"error",result:m}}})(),Promise.race([g,f])};try{let d=n.route[e];if(n.route.lazy)if(d){let p,[f]=await Promise.all([i(d).catch(h=>{p=h}),x0(n.route,s,r)]);if(p!==void 0)throw p;l=f}else if(await x0(n.route,s,r),d=n.route[e],d)l=await i(d);else if(e==="action"){let p=new URL(t.url),f=p.pathname+p.search;throw Bn(405,{method:t.method,pathname:f,routeId:n.route.id})}else return{type:Ct.data,result:void 0};else if(d)l=await i(d);else{let p=new URL(t.url),f=p.pathname+p.search;throw Bn(404,{pathname:f})}Ze(l.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(d){return{type:Ct.error,result:d}}finally{c&&t.signal.removeEventListener("abort",c)}return l}async function X2(e){let{result:t,type:n,status:r}=e;if(h_(t)){let a;try{let l=t.headers.get("Content-Type");l&&/\bapplication\/json\b/.test(l)?t.body==null?a=null:a=await t.json():a=await t.text()}catch(l){return{type:Ct.error,error:l}}return n===Ct.error?{type:Ct.error,error:new _x(t.status,t.statusText,a),statusCode:t.status,headers:t.headers}:{type:Ct.data,data:a,statusCode:t.status,headers:t.headers}}if(n===Ct.error)return{type:Ct.error,error:t,statusCode:Zh(t)?t.status:r};if(oL(t)){var s,o;return{type:Ct.deferred,deferredData:t,statusCode:(s=t.init)==null?void 0:s.status,headers:((o=t.init)==null?void 0:o.headers)&&new Headers(t.init.headers)}}return{type:Ct.data,data:t,statusCode:r}}function eL(e,t,n,r,s,o){let a=e.headers.get("Location");if(Ze(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!jx.test(a)){let l=r.slice(0,r.findIndex(c=>c.route.id===n)+1);a=Oy(new URL(t.url),l,s,!0,a,o),e.headers.set("Location",a)}return e}function w0(e,t,n){if(jx.test(e)){let r=e,s=r.startsWith("//")?new URL(t.protocol+r):new URL(r),o=du(s.pathname,n)!=null;if(s.origin===t.origin&&o)return s.pathname+s.search+s.hash}return e}function Hi(e,t,n,r){let s=e.createURL(p_(t)).toString(),o={signal:n};if(r&&Jr(r.formMethod)){let{formMethod:a,formEncType:l}=r;o.method=a.toUpperCase(),l==="application/json"?(o.headers=new Headers({"Content-Type":l}),o.body=JSON.stringify(r.json)):l==="text/plain"?o.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?o.body=Ny(r.formData):o.body=r.formData}return new Request(s,o)}function Ny(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function S0(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function tL(e,t,n,r,s,o){let a={},l=null,c,i=!1,d={},p=r&&fr(r[1])?r[1].error:void 0;return n.forEach((f,h)=>{let g=t[h].route.id;if(Ze(!Wa(f),"Cannot handle redirect results in processLoaderData"),fr(f)){let m=f.error;p!==void 0&&(m=p,p=void 0),l=l||{};{let x=gl(e,g);l[x.route.id]==null&&(l[x.route.id]=m)}a[g]=void 0,i||(i=!0,c=Zh(f.error)?f.error.status:500),f.headers&&(d[g]=f.headers)}else qa(f)?(s.set(g,f.deferredData),a[g]=f.deferredData.data,f.statusCode!=null&&f.statusCode!==200&&!i&&(c=f.statusCode),f.headers&&(d[g]=f.headers)):(a[g]=f.data,f.statusCode&&f.statusCode!==200&&!i&&(c=f.statusCode),f.headers&&(d[g]=f.headers))}),p!==void 0&&r&&(l={[r[0]]:p},a[r[0]]=void 0),{loaderData:a,errors:l,statusCode:c||200,loaderHeaders:d}}function C0(e,t,n,r,s,o,a,l){let{loaderData:c,errors:i}=tL(t,n,r,s,l);for(let d=0;dr.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function k0(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Bn(e,t){let{pathname:n,routeId:r,method:s,type:o,message:a}=t===void 0?{}:t,l="Unknown Server Error",c="Unknown @remix-run/router error";return e===400?(l="Bad Request",o==="route-discovery"?c='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error: -`+a):s&&n&&r?c="You made a "+s+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":o==="defer-action"?c="defer() is not supported in actions":o==="invalid-body"&&(c="Unable to encode submission body")):e===403?(l="Forbidden",c='Route "'+r+'" does not match URL "'+n+'"'):e===404?(l="Not Found",c='No route matches URL "'+n+'"'):e===405&&(l="Method Not Allowed",s&&n&&r?c="You made a "+s.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":s&&(c='Invalid request method "'+s.toUpperCase()+'"')),new _x(e||500,l,new Error(c),!0)}function _0(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(Wa(n))return{result:n,idx:t}}}function p_(e){let t=typeof e=="string"?_a(e):e;return wi(At({},t,{hash:""}))}function nL(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function rL(e){return typeof e=="object"&&e!=null&&"then"in e}function sL(e){return h_(e.result)&&z2.has(e.result.status)}function qa(e){return e.type===Ct.deferred}function fr(e){return e.type===Ct.error}function Wa(e){return(e&&e.type)===Ct.redirect}function oL(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function h_(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function aL(e){return B2.has(e.toLowerCase())}function Jr(e){return L2.has(e.toLowerCase())}async function j0(e,t,n,r,s,o){for(let a=0;ap.route.id===c.route.id),d=i!=null&&!d_(i,c)&&(o&&o[c.route.id])!==void 0;if(qa(l)&&(s||d)){let p=r[a];Ze(p,"Expected an AbortSignal for revalidating fetcher deferred result"),await g_(l,p,s).then(f=>{f&&(n[a]=f||n[a])})}}}async function g_(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:Ct.data,data:e.deferredData.unwrappedData}}catch(s){return{type:Ct.error,error:s}}return{type:Ct.data,data:e.deferredData.data}}}function Rx(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function cc(e,t){let n=typeof t=="string"?_a(t).search:t.search;if(e[e.length-1].route.index&&Rx(n||""))return e[e.length-1];let r=l_(e);return r[r.length-1]}function R0(e){let{formMethod:t,formAction:n,formEncType:r,text:s,formData:o,json:a}=e;if(!(!t||!n||!r)){if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:s};if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:o,json:void 0,text:void 0};if(a!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:a,text:void 0}}}function Im(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function iL(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function qu(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function lL(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Fo(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function uL(e,t){try{let n=e.sessionStorage.getItem(c_);if(n){let r=JSON.parse(n);for(let[s,o]of Object.entries(r||{}))o&&Array.isArray(o)&&t.set(s,new Set(o||[]))}}catch{}}function cL(e,t){if(t.size>0){let n={};for(let[r,s]of t)n[r]=[...s];try{e.sessionStorage.setItem(c_,JSON.stringify(n))}catch(r){Xl(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** - * React Router v6.25.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Zp(){return Zp=Object.assign?Object.assign.bind():function(e){for(var t=1;t{l.current=!0}),v.useCallback(function(i,d){if(d===void 0&&(d={}),!l.current)return;if(typeof i=="number"){r.go(i);return}let p=Qh(i,JSON.parse(a),o,d.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:uo([t,p.pathname])),(d.replace?r.replace:r.push)(p,d.state,d)},[t,r,a,o,e])}function So(){let{matches:e}=v.useContext(wo),t=e[e.length-1];return t?t.params:{}}function b_(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=v.useContext(ja),{matches:s}=v.useContext(wo),{pathname:o}=pu(),a=JSON.stringify(Jh(s,r.v7_relativeSplatPath));return v.useMemo(()=>Qh(e,JSON.parse(a),o,n==="path"),[e,a,o,n])}function pL(e,t,n,r){fu()||Ze(!1);let{navigator:s}=v.useContext(ja),{matches:o}=v.useContext(wo),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let c=a?a.pathnameBase:"/";a&&a.route;let i=pu(),d;d=i;let p=d.pathname||"/",f=p;if(c!=="/"){let m=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(m.length).join("/")}let h=Ua(e,{pathname:f});return yL(h&&h.map(m=>Object.assign({},m,{params:Object.assign({},l,m.params),pathname:uo([c,s.encodeLocation?s.encodeLocation(m.pathname).pathname:m.pathname]),pathnameBase:m.pathnameBase==="/"?c:uo([c,s.encodeLocation?s.encodeLocation(m.pathnameBase).pathname:m.pathnameBase])})),o,n,r)}function hL(){let e=SL(),t=Zh(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),n?v.createElement("pre",{style:s},n):null,null)}const gL=v.createElement(hL,null);class mL extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?v.createElement(wo.Provider,{value:this.props.routeContext},v.createElement(v_.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function vL(e){let{routeContext:t,match:n,children:r}=e,s=v.useContext(Yh);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),v.createElement(wo.Provider,{value:t},r)}function yL(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if((o=n)!=null&&o.errors)e=n.matches;else return null}let a=e,l=(s=n)==null?void 0:s.errors;if(l!=null){let d=a.findIndex(p=>p.route.id&&(l==null?void 0:l[p.route.id])!==void 0);d>=0||Ze(!1),a=a.slice(0,Math.min(a.length,d+1))}let c=!1,i=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?a=a.slice(0,i+1):a=[a[0]];break}}}return a.reduceRight((d,p,f)=>{let h,g=!1,m=null,x=null;n&&(h=l&&p.route.id?l[p.route.id]:void 0,m=p.route.errorElement||gL,c&&(i<0&&f===0?(EL("route-fallback"),g=!0,x=null):i===f&&(g=!0,x=p.route.hydrateFallbackElement||null)));let b=t.concat(a.slice(0,f+1)),y=()=>{let w;return h?w=m:g?w=x:p.route.Component?w=v.createElement(p.route.Component,null):p.route.element?w=p.route.element:w=d,v.createElement(vL,{match:p,routeContext:{outlet:d,matches:b,isDataRoute:n!=null},children:w})};return n&&(p.route.ErrorBoundary||p.route.errorElement||f===0)?v.createElement(mL,{location:n.location,revalidation:n.revalidation,component:m,error:h,children:y(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):y()},null)}var x_=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(x_||{}),Yp=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Yp||{});function bL(e){let t=v.useContext(Yh);return t||Ze(!1),t}function xL(e){let t=v.useContext(m_);return t||Ze(!1),t}function wL(e){let t=v.useContext(wo);return t||Ze(!1),t}function w_(e){let t=wL(),n=t.matches[t.matches.length-1];return n.route.id||Ze(!1),n.route.id}function SL(){var e;let t=v.useContext(v_),n=xL(Yp.UseRouteError),r=w_(Yp.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function CL(){let{router:e}=bL(x_.UseNavigateStable),t=w_(Yp.UseNavigateStable),n=v.useRef(!1);return y_(()=>{n.current=!0}),v.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Zp({fromRouteId:t},o)))},[e,t])}const P0={};function EL(e,t,n){P0[e]||(P0[e]=!0)}function S_(e){let{to:t,replace:n,state:r,relative:s}=e;fu()||Ze(!1);let{future:o,static:a}=v.useContext(ja),{matches:l}=v.useContext(wo),{pathname:c}=pu(),i=An(),d=Qh(t,Jh(l,o.v7_relativeSplatPath),c,s==="path"),p=JSON.stringify(d);return v.useEffect(()=>i(JSON.parse(p),{replace:n,state:r,relative:s}),[i,p,s,n,r]),null}function TL(e){let{basename:t="/",children:n=null,location:r,navigationType:s=en.Pop,navigator:o,static:a=!1,future:l}=e;fu()&&Ze(!1);let c=t.replace(/^\/*/,"/"),i=v.useMemo(()=>({basename:c,navigator:o,static:a,future:Zp({v7_relativeSplatPath:!1},l)}),[c,l,o,a]);typeof r=="string"&&(r=_a(r));let{pathname:d="/",search:p="",hash:f="",state:h=null,key:g="default"}=r,m=v.useMemo(()=>{let x=du(d,c);return x==null?null:{location:{pathname:x,search:p,hash:f,state:h,key:g},navigationType:s}},[c,d,p,f,h,g,s]);return m==null?null:v.createElement(ja.Provider,{value:i},v.createElement(Px.Provider,{children:n,value:m}))}new Promise(()=>{});function kL(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:v.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:v.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:v.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** - * React Router DOM v6.25.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function td(){return td=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function jL(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function RL(e,t){return e.button===0&&(!t||t==="_self")&&!jL(e)}const PL=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],ML="6";try{window.__reactRouterVersion=ML}catch{}function OL(e,t){return K2({basename:void 0,future:td({},void 0,{v7_prependBasename:!0}),history:g2({window:void 0}),hydrationData:NL(),routes:e,mapRouteProperties:kL,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function NL(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=td({},t,{errors:IL(t.errors)})),t}function IL(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,s]of t)if(s&&s.__type==="RouteErrorResponse")n[r]=new _x(s.status,s.statusText,s.data,s.internal===!0);else if(s&&s.__type==="Error"){if(s.__subType){let o=window[s.__subType];if(typeof o=="function")try{let a=new o(s.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let o=new Error(s.message);o.stack="",n[r]=o}}else n[r]=s;return n}const DL=v.createContext({isTransitioning:!1}),AL=v.createContext(new Map),FL="startTransition",M0=Nh[FL],LL="flushSync",O0=YF[LL];function $L(e){M0?M0(e):e()}function Wu(e){O0?O0(e):e()}class BL{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function zL(e){let{fallbackElement:t,router:n,future:r}=e,[s,o]=v.useState(n.state),[a,l]=v.useState(),[c,i]=v.useState({isTransitioning:!1}),[d,p]=v.useState(),[f,h]=v.useState(),[g,m]=v.useState(),x=v.useRef(new Map),{v7_startTransition:b}=r||{},y=v.useCallback(T=>{b?$L(T):T()},[b]),w=v.useCallback((T,P)=>{let{deletedFetchers:N,unstable_flushSync:U,unstable_viewTransitionOpts:I}=P;N.forEach(V=>x.current.delete(V)),T.fetchers.forEach((V,Q)=>{V.data!==void 0&&x.current.set(Q,V.data)});let Z=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!I||Z){U?Wu(()=>o(T)):y(()=>o(T));return}if(U){Wu(()=>{f&&(d&&d.resolve(),f.skipTransition()),i({isTransitioning:!0,flushSync:!0,currentLocation:I.currentLocation,nextLocation:I.nextLocation})});let V=n.window.document.startViewTransition(()=>{Wu(()=>o(T))});V.finished.finally(()=>{Wu(()=>{p(void 0),h(void 0),l(void 0),i({isTransitioning:!1})})}),Wu(()=>h(V));return}f?(d&&d.resolve(),f.skipTransition(),m({state:T,currentLocation:I.currentLocation,nextLocation:I.nextLocation})):(l(T),i({isTransitioning:!0,flushSync:!1,currentLocation:I.currentLocation,nextLocation:I.nextLocation}))},[n.window,f,d,x,y]);v.useLayoutEffect(()=>n.subscribe(w),[n,w]),v.useEffect(()=>{c.isTransitioning&&!c.flushSync&&p(new BL)},[c]),v.useEffect(()=>{if(d&&a&&n.window){let T=a,P=d.promise,N=n.window.document.startViewTransition(async()=>{y(()=>o(T)),await P});N.finished.finally(()=>{p(void 0),h(void 0),l(void 0),i({isTransitioning:!1})}),h(N)}},[y,a,d,n.window]),v.useEffect(()=>{d&&a&&s.location.key===a.location.key&&d.resolve()},[d,f,s.location,a]),v.useEffect(()=>{!c.isTransitioning&&g&&(l(g.state),i({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),m(void 0))},[c.isTransitioning,g]),v.useEffect(()=>{},[]);let S=v.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:T=>n.navigate(T),push:(T,P,N)=>n.navigate(T,{state:P,preventScrollReset:N==null?void 0:N.preventScrollReset}),replace:(T,P,N)=>n.navigate(T,{replace:!0,state:P,preventScrollReset:N==null?void 0:N.preventScrollReset})}),[n]),E=n.basename||"/",C=v.useMemo(()=>({router:n,navigator:S,static:!1,basename:E}),[n,S,E]),k=v.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return v.createElement(v.Fragment,null,v.createElement(Yh.Provider,{value:C},v.createElement(m_.Provider,{value:s},v.createElement(AL.Provider,{value:x.current},v.createElement(DL.Provider,{value:c},v.createElement(TL,{basename:E,location:s.location,navigationType:s.historyAction,navigator:S,future:k},s.initialized||n.future.v7_partialHydration?v.createElement(UL,{routes:n.routes,future:n.future,state:s}):t))))),null)}const UL=v.memo(VL);function VL(e){let{routes:t,future:n,state:r}=e;return pL(t,void 0,r,n)}const HL=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",KL=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nd=v.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:o,replace:a,state:l,target:c,to:i,preventScrollReset:d,unstable_viewTransition:p}=t,f=_L(t,PL),{basename:h}=v.useContext(ja),g,m=!1;if(typeof i=="string"&&KL.test(i)&&(g=i,HL))try{let w=new URL(window.location.href),S=i.startsWith("//")?new URL(w.protocol+i):new URL(i),E=du(S.pathname,h);S.origin===w.origin&&E!=null?i=E+S.search+S.hash:m=!0}catch{}let x=dL(i,{relative:s}),b=qL(i,{replace:a,state:l,target:c,preventScrollReset:d,relative:s,unstable_viewTransition:p});function y(w){r&&r(w),w.defaultPrevented||b(w)}return v.createElement("a",td({},f,{href:g||x,onClick:m||o?r:y,ref:n,target:c}))});var N0;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(N0||(N0={}));var I0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(I0||(I0={}));function qL(e,t){let{target:n,replace:r,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:l}=t===void 0?{}:t,c=An(),i=pu(),d=b_(e,{relative:a});return v.useCallback(p=>{if(RL(p,n)){p.preventDefault();let f=r!==void 0?r:wi(i)===wi(d);c(e,{replace:f,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:l})}},[i,c,d,r,s,n,e,o,a,l])}function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;ttypeof e=="number"&&!isNaN(e),ci=e=>typeof e=="string",gr=e=>typeof e=="function",dp=e=>ci(e)||gr(e)?e:null,Iy=e=>v.isValidElement(e)||ci(e)||gr(e)||rd(e);function WL(e,t,n){n===void 0&&(n=300);const{scrollHeight:r,style:s}=e;requestAnimationFrame(()=>{s.minHeight="initial",s.height=r+"px",s.transition=`all ${n}ms`,requestAnimationFrame(()=>{s.height="0",s.padding="0",s.margin="0",setTimeout(t,n)})})}function Xh(e){let{enter:t,exit:n,appendPosition:r=!1,collapse:s=!0,collapseDuration:o=300}=e;return function(a){let{children:l,position:c,preventExitTransition:i,done:d,nodeRef:p,isIn:f,playToast:h}=a;const g=r?`${t}--${c}`:t,m=r?`${n}--${c}`:n,x=v.useRef(0);return v.useLayoutEffect(()=>{const b=p.current,y=g.split(" "),w=S=>{S.target===p.current&&(h(),b.removeEventListener("animationend",w),b.removeEventListener("animationcancel",w),x.current===0&&S.type!=="animationcancel"&&b.classList.remove(...y))};b.classList.add(...y),b.addEventListener("animationend",w),b.addEventListener("animationcancel",w)},[]),v.useEffect(()=>{const b=p.current,y=()=>{b.removeEventListener("animationend",y),s?WL(b,d,o):d()};f||(i?y():(x.current=1,b.className+=` ${m}`,b.addEventListener("animationend",y)))},[f]),Te.createElement(Te.Fragment,null,l)}}function D0(e,t){return e!=null?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const Vn=new Map;let sd=[];const Dy=new Set,GL=e=>Dy.forEach(t=>t(e)),E_=()=>Vn.size>0;function T_(e,t){var n;if(t)return!((n=Vn.get(t))==null||!n.isToastActive(e));let r=!1;return Vn.forEach(s=>{s.isToastActive(e)&&(r=!0)}),r}function k_(e,t){Iy(e)&&(E_()||sd.push({content:e,options:t}),Vn.forEach(n=>{n.buildToast(e,t)}))}function A0(e,t){Vn.forEach(n=>{t!=null&&t!=null&&t.containerId?(t==null?void 0:t.containerId)===n.id&&n.toggle(e,t==null?void 0:t.id):n.toggle(e,t==null?void 0:t.id)})}function JL(e){const{subscribe:t,getSnapshot:n,setProps:r}=v.useRef(function(o){const a=o.containerId||1;return{subscribe(l){const c=function(d,p,f){let h=1,g=0,m=[],x=[],b=[],y=p;const w=new Map,S=new Set,E=()=>{b=Array.from(w.values()),S.forEach(T=>T())},C=T=>{x=T==null?[]:x.filter(P=>P!==T),E()},k=T=>{const{toastId:P,onOpen:N,updateId:U,children:I}=T.props,Z=U==null;T.staleId&&w.delete(T.staleId),w.set(P,T),x=[...x,T.props.toastId].filter(V=>V!==T.staleId),E(),f(D0(T,Z?"added":"updated")),Z&&gr(N)&&N(v.isValidElement(I)&&I.props)};return{id:d,props:y,observe:T=>(S.add(T),()=>S.delete(T)),toggle:(T,P)=>{w.forEach(N=>{P!=null&&P!==N.props.toastId||gr(N.toggle)&&N.toggle(T)})},removeToast:C,toasts:w,clearQueue:()=>{g-=m.length,m=[]},buildToast:(T,P)=>{if((z=>{let{containerId:se,toastId:ne,updateId:ie}=z;const oe=se?se!==d:d!==1,J=w.has(ne)&&ie==null;return oe||J})(P))return;const{toastId:N,updateId:U,data:I,staleId:Z,delay:V}=P,Q=()=>{C(N)},ee=U==null;ee&&g++;const W={...y,style:y.toastStyle,key:h++,...Object.fromEntries(Object.entries(P).filter(z=>{let[se,ne]=z;return ne!=null})),toastId:N,updateId:U,data:I,closeToast:Q,isIn:!1,className:dp(P.className||y.toastClassName),bodyClassName:dp(P.bodyClassName||y.bodyClassName),progressClassName:dp(P.progressClassName||y.progressClassName),autoClose:!P.isLoading&&(F=P.autoClose,A=y.autoClose,F===!1||rd(F)&&F>0?F:A),deleteToast(){const z=w.get(N),{onClose:se,children:ne}=z.props;gr(se)&&se(v.isValidElement(ne)&&ne.props),f(D0(z,"removed")),w.delete(N),g--,g<0&&(g=0),m.length>0?k(m.shift()):E()}};var F,A;W.closeButton=y.closeButton,P.closeButton===!1||Iy(P.closeButton)?W.closeButton=P.closeButton:P.closeButton===!0&&(W.closeButton=!Iy(y.closeButton)||y.closeButton);let Y=T;v.isValidElement(T)&&!ci(T.type)?Y=v.cloneElement(T,{closeToast:Q,toastProps:W,data:I}):gr(T)&&(Y=T({closeToast:Q,toastProps:W,data:I}));const de={content:Y,props:W,staleId:Z};y.limit&&y.limit>0&&g>y.limit&&ee?m.push(de):rd(V)?setTimeout(()=>{k(de)},V):k(de)},setProps(T){y=T},setToggle:(T,P)=>{w.get(T).toggle=P},isToastActive:T=>x.some(P=>P===T),getSnapshot:()=>y.newestOnTop?b.reverse():b}}(a,o,GL);Vn.set(a,c);const i=c.observe(l);return sd.forEach(d=>k_(d.content,d.options)),sd=[],()=>{i(),Vn.delete(a)}},setProps(l){var c;(c=Vn.get(a))==null||c.setProps(l)},getSnapshot(){var l;return(l=Vn.get(a))==null?void 0:l.getSnapshot()}}}(e)).current;r(e);const s=v.useSyncExternalStore(t,n,n);return{getToastToRender:function(o){if(!s)return[];const a=new Map;return s.forEach(l=>{const{position:c}=l.props;a.has(c)||a.set(c,[]),a.get(c).push(l)}),Array.from(a,l=>o(l[0],l[1]))},isToastActive:T_,count:s==null?void 0:s.length}}function QL(e){const[t,n]=v.useState(!1),[r,s]=v.useState(!1),o=v.useRef(null),a=v.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:l,pauseOnHover:c,closeToast:i,onClick:d,closeOnClick:p}=e;var f,h;function g(){n(!0)}function m(){n(!1)}function x(w){const S=o.current;a.canDrag&&S&&(a.didMove=!0,t&&m(),a.delta=e.draggableDirection==="x"?w.clientX-a.start:w.clientY-a.start,a.start!==w.clientX&&(a.canCloseOnClick=!1),S.style.transform=`translate3d(${e.draggableDirection==="x"?`${a.delta}px, var(--y)`:`0, calc(${a.delta}px + var(--y))`},0)`,S.style.opacity=""+(1-Math.abs(a.delta/a.removalDistance)))}function b(){document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",b);const w=o.current;if(a.canDrag&&a.didMove&&w){if(a.canDrag=!1,Math.abs(a.delta)>a.removalDistance)return s(!0),e.closeToast(),void e.collapseAll();w.style.transition="transform 0.2s, opacity 0.2s",w.style.removeProperty("transform"),w.style.removeProperty("opacity")}}(h=Vn.get((f={id:e.toastId,containerId:e.containerId,fn:n}).containerId||1))==null||h.setToggle(f.id,f.fn),v.useEffect(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||m(),window.addEventListener("focus",g),window.addEventListener("blur",m),()=>{window.removeEventListener("focus",g),window.removeEventListener("blur",m)}},[e.pauseOnFocusLoss]);const y={onPointerDown:function(w){if(e.draggable===!0||e.draggable===w.pointerType){a.didMove=!1,document.addEventListener("pointermove",x),document.addEventListener("pointerup",b);const S=o.current;a.canCloseOnClick=!0,a.canDrag=!0,S.style.transition="none",e.draggableDirection==="x"?(a.start=w.clientX,a.removalDistance=S.offsetWidth*(e.draggablePercent/100)):(a.start=w.clientY,a.removalDistance=S.offsetHeight*(e.draggablePercent===80?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(w){const{top:S,bottom:E,left:C,right:k}=o.current.getBoundingClientRect();w.nativeEvent.type!=="touchend"&&e.pauseOnHover&&w.clientX>=C&&w.clientX<=k&&w.clientY>=S&&w.clientY<=E?m():g()}};return l&&c&&(y.onMouseEnter=m,e.stacked||(y.onMouseLeave=g)),p&&(y.onClick=w=>{d&&d(w),a.canCloseOnClick&&i()}),{playToast:g,pauseToast:m,isRunning:t,preventExitTransition:r,toastRef:o,eventHandlers:y}}function ZL(e){let{delay:t,isRunning:n,closeToast:r,type:s="default",hide:o,className:a,style:l,controlledProgress:c,progress:i,rtl:d,isIn:p,theme:f}=e;const h=o||c&&i===0,g={...l,animationDuration:`${t}ms`,animationPlayState:n?"running":"paused"};c&&(g.transform=`scaleX(${i})`);const m=oo("Toastify__progress-bar",c?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${f}`,`Toastify__progress-bar--${s}`,{"Toastify__progress-bar--rtl":d}),x=gr(a)?a({rtl:d,type:s,defaultClassName:m}):oo(m,a),b={[c&&i>=1?"onTransitionEnd":"onAnimationEnd"]:c&&i<1?null:()=>{p&&r()}};return Te.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":h},Te.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${f} Toastify__progress-bar--${s}`}),Te.createElement("div",{role:"progressbar","aria-hidden":h?"true":"false","aria-label":"notification timer",className:x,style:g,...b}))}let YL=1;const __=()=>""+YL++;function XL(e){return e&&(ci(e.toastId)||rd(e.toastId))?e.toastId:__()}function _c(e,t){return k_(e,t),t.toastId}function Xp(e,t){return{...t,type:t&&t.type||e,toastId:XL(t)}}function jf(e){return(t,n)=>_c(t,Xp(e,n))}function X(e,t){return _c(e,Xp("default",t))}X.loading=(e,t)=>_c(e,Xp("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),X.promise=function(e,t,n){let r,{pending:s,error:o,success:a}=t;s&&(r=ci(s)?X.loading(s,n):X.loading(s.render,{...n,...s}));const l={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},c=(d,p,f)=>{if(p==null)return void X.dismiss(r);const h={type:d,...l,...n,data:f},g=ci(p)?{render:p}:p;return r?X.update(r,{...h,...g}):X(g.render,{...h,...g}),f},i=gr(e)?e():e;return i.then(d=>c("success",a,d)).catch(d=>c("error",o,d)),i},X.success=jf("success"),X.info=jf("info"),X.error=jf("error"),X.warning=jf("warning"),X.warn=X.warning,X.dark=(e,t)=>_c(e,Xp("default",{theme:"dark",...t})),X.dismiss=function(e){(function(t){var n;if(E_()){if(t==null||ci(n=t)||rd(n))Vn.forEach(r=>{r.removeToast(t)});else if(t&&("containerId"in t||"id"in t)){const r=Vn.get(t.containerId);r?r.removeToast(t.id):Vn.forEach(s=>{s.removeToast(t.id)})}}else sd=sd.filter(r=>t!=null&&r.options.toastId!==t)})(e)},X.clearWaitingQueue=function(e){e===void 0&&(e={}),Vn.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},X.isActive=T_,X.update=function(e,t){t===void 0&&(t={});const n=((r,s)=>{var o;let{containerId:a}=s;return(o=Vn.get(a||1))==null?void 0:o.toasts.get(r)})(e,t);if(n){const{props:r,content:s}=n,o={delay:100,...r,...t,toastId:t.toastId||e,updateId:__()};o.toastId!==e&&(o.staleId=e);const a=o.render||s;delete o.render,_c(a,o)}},X.done=e=>{X.update(e,{progress:1})},X.onChange=function(e){return Dy.add(e),()=>{Dy.delete(e)}},X.play=e=>A0(!0,e),X.pause=e=>A0(!1,e);const e$=typeof window<"u"?v.useLayoutEffect:v.useEffect,Rf=e=>{let{theme:t,type:n,isLoading:r,...s}=e;return Te.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:t==="colored"?"currentColor":`var(--toastify-icon-color-${n})`,...s})},Dm={info:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return Te.createElement("div",{className:"Toastify__spinner"})}},t$=e=>{const{isRunning:t,preventExitTransition:n,toastRef:r,eventHandlers:s,playToast:o}=QL(e),{closeButton:a,children:l,autoClose:c,onClick:i,type:d,hideProgressBar:p,closeToast:f,transition:h,position:g,className:m,style:x,bodyClassName:b,bodyStyle:y,progressClassName:w,progressStyle:S,updateId:E,role:C,progress:k,rtl:T,toastId:P,deleteToast:N,isIn:U,isLoading:I,closeOnClick:Z,theme:V}=e,Q=oo("Toastify__toast",`Toastify__toast-theme--${V}`,`Toastify__toast--${d}`,{"Toastify__toast--rtl":T},{"Toastify__toast--close-on-click":Z}),ee=gr(m)?m({rtl:T,position:g,type:d,defaultClassName:Q}):oo(Q,m),W=function(de){let{theme:z,type:se,isLoading:ne,icon:ie}=de,oe=null;const J={theme:z,type:se};return ie===!1||(gr(ie)?oe=ie({...J,isLoading:ne}):v.isValidElement(ie)?oe=v.cloneElement(ie,J):ne?oe=Dm.spinner():(Ce=>Ce in Dm)(se)&&(oe=Dm[se](J))),oe}(e),F=!!k||!c,A={closeToast:f,type:d,theme:V};let Y=null;return a===!1||(Y=gr(a)?a(A):v.isValidElement(a)?v.cloneElement(a,A):function(de){let{closeToast:z,theme:se,ariaLabel:ne="close"}=de;return Te.createElement("button",{className:`Toastify__close-button Toastify__close-button--${se}`,type:"button",onClick:ie=>{ie.stopPropagation(),z(ie)},"aria-label":ne},Te.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},Te.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(A)),Te.createElement(h,{isIn:U,done:N,position:g,preventExitTransition:n,nodeRef:r,playToast:o},Te.createElement("div",{id:P,onClick:i,"data-in":U,className:ee,...s,style:x,ref:r},Te.createElement("div",{...U&&{role:C},className:gr(b)?b({type:d}):oo("Toastify__toast-body",b),style:y},W!=null&&Te.createElement("div",{className:oo("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!I})},W),Te.createElement("div",null,l)),Y,Te.createElement(ZL,{...E&&!F?{key:`pb-${E}`}:{},rtl:T,theme:V,delay:c,isRunning:t,isIn:U,closeToast:f,hide:p,type:d,style:S,className:w,controlledProgress:F,progress:k||0})))},eg=function(e,t){return t===void 0&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},n$=Xh(eg("bounce",!0));Xh(eg("slide",!0));Xh(eg("zoom"));Xh(eg("flip"));const r$={position:"top-right",transition:n$,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function s$(e){let t={...r$,...e};const n=e.stacked,[r,s]=v.useState(!0),o=v.useRef(null),{getToastToRender:a,isToastActive:l,count:c}=JL(t),{className:i,style:d,rtl:p,containerId:f}=t;function h(m){const x=oo("Toastify__toast-container",`Toastify__toast-container--${m}`,{"Toastify__toast-container--rtl":p});return gr(i)?i({position:m,rtl:p,defaultClassName:x}):oo(x,dp(i))}function g(){n&&(s(!0),X.play())}return e$(()=>{if(n){var m;const x=o.current.querySelectorAll('[data-in="true"]'),b=12,y=(m=t.position)==null?void 0:m.includes("top");let w=0,S=0;Array.from(x).reverse().forEach((E,C)=>{const k=E;k.classList.add("Toastify__toast--stacked"),C>0&&(k.dataset.collapsed=`${r}`),k.dataset.pos||(k.dataset.pos=y?"top":"bot");const T=w*(r?.2:1)+(r?0:b*C);k.style.setProperty("--y",`${y?T:-1*T}px`),k.style.setProperty("--g",`${b}`),k.style.setProperty("--s",""+(1-(r?S:0))),w+=k.offsetHeight,S+=.025})}},[r,c,n]),Te.createElement("div",{ref:o,className:"Toastify",id:f,onMouseEnter:()=>{n&&(s(!1),X.pause())},onMouseLeave:g},a((m,x)=>{const b=x.length?{...d}:{...d,pointerEvents:"none"};return Te.createElement("div",{className:h(m),style:b,key:`container-${m}`},x.map(y=>{let{content:w,props:S}=y;return Te.createElement(t$,{...S,stacked:n,collapseAll:g,isIn:l(S.toastId,S.containerId),style:S.style,key:`toast-${S.key}`},w)}))}))}const o$={theme:"system",setTheme:()=>null},j_=v.createContext(o$);function a$({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const[s,o]=v.useState(()=>localStorage.getItem(n)||t);v.useEffect(()=>{const l=window.document.documentElement;if(l.classList.remove("light","dark"),s==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";l.classList.add(c);return}l.classList.add(s)},[s]);const a={theme:s,setTheme:l=>{localStorage.setItem(n,l),o(l)}};return u.jsx(j_.Provider,{...r,value:a,children:e})}const R_=()=>{const e=v.useContext(j_);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e};let Am=!1;const i$=new RD({defaultOptions:{queries:{staleTime:1e3*60*5,retry(e){return e>=3?(Am===!1&&(Am=!0,X.error("The application is taking longer than expected to load, please try again in a few minutes.",{onClose:()=>{Am=!1}})),!1):!0}}}});var rs=(e=>(e.API_URL="apiUrl",e.TOKEN="token",e.VERSION="version",e.FACEBOOK_APP_ID="facebookAppId",e.FACEBOOK_CONFIG_ID="facebookConfigId",e.FACEBOOK_USER_TOKEN="facebookUserToken",e.CLIENT_NAME="clientName",e))(rs||{});const P_=async e=>{if(e.url){const t=e.url.endsWith("/")?e.url.slice(0,-1):e.url;localStorage.setItem("apiUrl",t)}e.token&&localStorage.setItem("token",e.token),e.version&&localStorage.setItem("version",e.version),e.facebookAppId&&localStorage.setItem("facebookAppId",e.facebookAppId),e.facebookConfigId&&localStorage.setItem("facebookConfigId",e.facebookConfigId),e.facebookUserToken&&localStorage.setItem("facebookUserToken",e.facebookUserToken),e.clientName&&localStorage.setItem("clientName",e.clientName)},M_=()=>{localStorage.removeItem("apiUrl"),localStorage.removeItem("token"),localStorage.removeItem("version"),localStorage.removeItem("facebookAppId"),localStorage.removeItem("facebookConfigId"),localStorage.removeItem("facebookUserToken"),localStorage.removeItem("clientName")},Fs=e=>localStorage.getItem(e),Gt=({children:e})=>{const t=Fs(rs.API_URL),n=Fs(rs.TOKEN),r=Fs(rs.VERSION);return!t||!n||!r?u.jsx(S_,{to:"/manager/login"}):e},l$=({children:e})=>{const t=Fs(rs.API_URL),n=Fs(rs.TOKEN),r=Fs(rs.VERSION);return t&&n&&r?u.jsx(S_,{to:"/"}):e};function O_(e,t){return function(){return e.apply(t,arguments)}}const{toString:u$}=Object.prototype,{getPrototypeOf:Mx}=Object,tg=(e=>t=>{const n=u$.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),fs=e=>(e=e.toLowerCase(),t=>tg(t)===e),ng=e=>t=>typeof t===e,{isArray:hu}=Array,od=ng("undefined");function c$(e){return e!==null&&!od(e)&&e.constructor!==null&&!od(e.constructor)&&Lr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const N_=fs("ArrayBuffer");function d$(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&N_(e.buffer),t}const f$=ng("string"),Lr=ng("function"),I_=ng("number"),rg=e=>e!==null&&typeof e=="object",p$=e=>e===!0||e===!1,fp=e=>{if(tg(e)!=="object")return!1;const t=Mx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},h$=fs("Date"),g$=fs("File"),m$=fs("Blob"),v$=fs("FileList"),y$=e=>rg(e)&&Lr(e.pipe),b$=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Lr(e.append)&&((t=tg(e))==="formdata"||t==="object"&&Lr(e.toString)&&e.toString()==="[object FormData]"))},x$=fs("URLSearchParams"),[w$,S$,C$,E$]=["ReadableStream","Request","Response","Headers"].map(fs),T$=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Bd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),hu(e))for(r=0,s=e.length;r0;)if(s=n[r],t===s.toLowerCase())return s;return null}const A_=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F_=e=>!od(e)&&e!==A_;function Ay(){const{caseless:e}=F_(this)&&this||{},t={},n=(r,s)=>{const o=e&&D_(t,s)||s;fp(t[o])&&fp(r)?t[o]=Ay(t[o],r):fp(r)?t[o]=Ay({},r):hu(r)?t[o]=r.slice():t[o]=r};for(let r=0,s=arguments.length;r(Bd(t,(s,o)=>{n&&Lr(s)?e[o]=O_(s,n):e[o]=s},{allOwnKeys:r}),e),_$=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),j$=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},R$=(e,t,n,r)=>{let s,o,a;const l={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)a=s[o],(!r||r(a,e,t))&&!l[a]&&(t[a]=e[a],l[a]=!0);e=n!==!1&&Mx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},P$=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},M$=e=>{if(!e)return null;if(hu(e))return e;let t=e.length;if(!I_(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},O$=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Mx(Uint8Array)),N$=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},I$=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},D$=fs("HTMLFormElement"),A$=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),F0=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),F$=fs("RegExp"),L_=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Bd(n,(s,o)=>{let a;(a=t(s,o,e))!==!1&&(r[o]=a||s)}),Object.defineProperties(e,r)},L$=e=>{L_(e,(t,n)=>{if(Lr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Lr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$$=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return hu(e)?r(e):r(String(e).split(t)),n},B$=()=>{},z$=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,Fm="abcdefghijklmnopqrstuvwxyz",L0="0123456789",$_={DIGIT:L0,ALPHA:Fm,ALPHA_DIGIT:Fm+Fm.toUpperCase()+L0},U$=(e=16,t=$_.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function V$(e){return!!(e&&Lr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const H$=e=>{const t=new Array(10),n=(r,s)=>{if(rg(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[s]=r;const o=hu(r)?[]:{};return Bd(r,(a,l)=>{const c=n(a,s+1);!od(c)&&(o[l]=c)}),t[s]=void 0,o}}return r};return n(e,0)},K$=fs("AsyncFunction"),q$=e=>e&&(rg(e)||Lr(e))&&Lr(e.then)&&Lr(e.catch),$={isArray:hu,isArrayBuffer:N_,isBuffer:c$,isFormData:b$,isArrayBufferView:d$,isString:f$,isNumber:I_,isBoolean:p$,isObject:rg,isPlainObject:fp,isReadableStream:w$,isRequest:S$,isResponse:C$,isHeaders:E$,isUndefined:od,isDate:h$,isFile:g$,isBlob:m$,isRegExp:F$,isFunction:Lr,isStream:y$,isURLSearchParams:x$,isTypedArray:O$,isFileList:v$,forEach:Bd,merge:Ay,extend:k$,trim:T$,stripBOM:_$,inherits:j$,toFlatObject:R$,kindOf:tg,kindOfTest:fs,endsWith:P$,toArray:M$,forEachEntry:N$,matchAll:I$,isHTMLForm:D$,hasOwnProperty:F0,hasOwnProp:F0,reduceDescriptors:L_,freezeMethods:L$,toObjectSet:$$,toCamelCase:A$,noop:B$,toFiniteNumber:z$,findKey:D_,global:A_,isContextDefined:F_,ALPHABET:$_,generateString:U$,isSpecCompliantForm:V$,toJSONObject:H$,isAsyncFn:K$,isThenable:q$};function He(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s)}$.inherits(He,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:$.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const B_=He.prototype,z_={};["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(e=>{z_[e]={value:e}});Object.defineProperties(He,z_);Object.defineProperty(B_,"isAxiosError",{value:!0});He.from=(e,t,n,r,s,o)=>{const a=Object.create(B_);return $.toFlatObject(e,a,function(c){return c!==Error.prototype},l=>l!=="isAxiosError"),He.call(a,e.message,t,n,r,s),a.cause=e,a.name=e.name,o&&Object.assign(a,o),a};const W$=null;function Fy(e){return $.isPlainObject(e)||$.isArray(e)}function U_(e){return $.endsWith(e,"[]")?e.slice(0,-2):e}function $0(e,t,n){return e?e.concat(t).map(function(s,o){return s=U_(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function G$(e){return $.isArray(e)&&!e.some(Fy)}const J$=$.toFlatObject($,{},null,function(t){return/^is[A-Z]/.test(t)});function sg(e,t,n){if(!$.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,x){return!$.isUndefined(x[m])});const r=n.metaTokens,s=n.visitor||d,o=n.dots,a=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&$.isSpecCompliantForm(t);if(!$.isFunction(s))throw new TypeError("visitor must be a function");function i(g){if(g===null)return"";if($.isDate(g))return g.toISOString();if(!c&&$.isBlob(g))throw new He("Blob is not supported. Use a Buffer instead.");return $.isArrayBuffer(g)||$.isTypedArray(g)?c&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function d(g,m,x){let b=g;if(g&&!x&&typeof g=="object"){if($.endsWith(m,"{}"))m=r?m:m.slice(0,-2),g=JSON.stringify(g);else if($.isArray(g)&&G$(g)||($.isFileList(g)||$.endsWith(m,"[]"))&&(b=$.toArray(g)))return m=U_(m),b.forEach(function(w,S){!($.isUndefined(w)||w===null)&&t.append(a===!0?$0([m],S,o):a===null?m:m+"[]",i(w))}),!1}return Fy(g)?!0:(t.append($0(x,m,o),i(g)),!1)}const p=[],f=Object.assign(J$,{defaultVisitor:d,convertValue:i,isVisitable:Fy});function h(g,m){if(!$.isUndefined(g)){if(p.indexOf(g)!==-1)throw Error("Circular reference detected in "+m.join("."));p.push(g),$.forEach(g,function(b,y){(!($.isUndefined(b)||b===null)&&s.call(t,b,$.isString(y)?y.trim():y,m,f))===!0&&h(b,m?m.concat(y):[y])}),p.pop()}}if(!$.isObject(e))throw new TypeError("data must be an object");return h(e),t}function B0(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Ox(e,t){this._pairs=[],e&&sg(e,this,t)}const V_=Ox.prototype;V_.append=function(t,n){this._pairs.push([t,n])};V_.toString=function(t){const n=t?function(r){return t.call(this,r,B0)}:B0;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Q$(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function H_(e,t,n){if(!t)return e;const r=n&&n.encode||Q$,s=n&&n.serialize;let o;if(s?o=s(t,n):o=$.isURLSearchParams(t)?t.toString():new Ox(t,n).toString(r),o){const a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class z0{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){$.forEach(this.handlers,function(r){r!==null&&t(r)})}}const K_={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Z$=typeof URLSearchParams<"u"?URLSearchParams:Ox,Y$=typeof FormData<"u"?FormData:null,X$=typeof Blob<"u"?Blob:null,e4={isBrowser:!0,classes:{URLSearchParams:Z$,FormData:Y$,Blob:X$},protocols:["http","https","file","blob","url","data"]},Nx=typeof window<"u"&&typeof document<"u",t4=(e=>Nx&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),n4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",r4=Nx&&window.location.href||"http://localhost",s4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Nx,hasStandardBrowserEnv:t4,hasStandardBrowserWebWorkerEnv:n4,origin:r4},Symbol.toStringTag,{value:"Module"})),ss={...s4,...e4};function o4(e,t){return sg(e,new ss.classes.URLSearchParams,Object.assign({visitor:function(n,r,s,o){return ss.isNode&&$.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}function a4(e){return $.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function i4(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r=n.length;return a=!a&&$.isArray(s)?s.length:a,c?($.hasOwnProp(s,a)?s[a]=[s[a],r]:s[a]=r,!l):((!s[a]||!$.isObject(s[a]))&&(s[a]=[]),t(n,r,s[a],o)&&$.isArray(s[a])&&(s[a]=i4(s[a])),!l)}if($.isFormData(e)&&$.isFunction(e.entries)){const n={};return $.forEachEntry(e,(r,s)=>{t(a4(r),s,n,0)}),n}return null}function l4(e,t,n){if($.isString(e))try{return(t||JSON.parse)(e),$.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const zd={transitional:K_,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=$.isObject(t);if(o&&$.isHTMLForm(t)&&(t=new FormData(t)),$.isFormData(t))return s?JSON.stringify(q_(t)):t;if($.isArrayBuffer(t)||$.isBuffer(t)||$.isStream(t)||$.isFile(t)||$.isBlob(t)||$.isReadableStream(t))return t;if($.isArrayBufferView(t))return t.buffer;if($.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return o4(t,this.formSerializer).toString();if((l=$.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return sg(l?{"files[]":t}:t,c&&new c,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),l4(t)):t}],transformResponse:[function(t){const n=this.transitional||zd.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if($.isResponse(t)||$.isReadableStream(t))return t;if(t&&$.isString(t)&&(r&&!this.responseType||s)){const a=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t)}catch(l){if(a)throw l.name==="SyntaxError"?He.from(l,He.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ss.classes.FormData,Blob:ss.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$.forEach(["delete","get","head","post","put","patch"],e=>{zd.headers[e]={}});const u4=$.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"]),c4=e=>{const t={};let n,r,s;return e&&e.split(` -`).forEach(function(a){s=a.indexOf(":"),n=a.substring(0,s).trim().toLowerCase(),r=a.substring(s+1).trim(),!(!n||t[n]&&u4[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},U0=Symbol("internals");function Gu(e){return e&&String(e).trim().toLowerCase()}function pp(e){return e===!1||e==null?e:$.isArray(e)?e.map(pp):String(e)}function d4(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const f4=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Lm(e,t,n,r,s){if($.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!$.isString(t)){if($.isString(r))return t.indexOf(r)!==-1;if($.isRegExp(r))return r.test(t)}}function p4(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function h4(e,t){const n=$.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,a){return this[r].call(this,t,s,o,a)},configurable:!0})})}let sr=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(l,c,i){const d=Gu(c);if(!d)throw new Error("header name must be a non-empty string");const p=$.findKey(s,d);(!p||s[p]===void 0||i===!0||i===void 0&&s[p]!==!1)&&(s[p||c]=pp(l))}const a=(l,c)=>$.forEach(l,(i,d)=>o(i,d,c));if($.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if($.isString(t)&&(t=t.trim())&&!f4(t))a(c4(t),n);else if($.isHeaders(t))for(const[l,c]of t.entries())o(c,l,r);else t!=null&&o(n,t,r);return this}get(t,n){if(t=Gu(t),t){const r=$.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return d4(s);if($.isFunction(n))return n.call(this,s,r);if($.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Gu(t),t){const r=$.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Lm(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(a){if(a=Gu(a),a){const l=$.findKey(r,a);l&&(!n||Lm(r,r[l],l,n))&&(delete r[l],s=!0)}}return $.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||Lm(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return $.forEach(this,(s,o)=>{const a=$.findKey(r,o);if(a){n[a]=pp(s),delete n[o];return}const l=t?p4(o):String(o).trim();l!==o&&delete n[o],n[l]=pp(s),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return $.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&$.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[U0]=this[U0]={accessors:{}}).accessors,s=this.prototype;function o(a){const l=Gu(a);r[l]||(h4(s,a),r[l]=!0)}return $.isArray(t)?t.forEach(o):o(t),this}};sr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);$.reduceDescriptors(sr.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});$.freezeMethods(sr);function $m(e,t){const n=this||zd,r=t||n,s=sr.from(r.headers);let o=r.data;return $.forEach(e,function(l){o=l.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function W_(e){return!!(e&&e.__CANCEL__)}function gu(e,t,n){He.call(this,e??"canceled",He.ERR_CANCELED,t,n),this.name="CanceledError"}$.inherits(gu,He,{__CANCEL__:!0});function G_(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new He("Request failed with status code "+n.status,[He.ERR_BAD_REQUEST,He.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function g4(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function m4(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,a;return t=t!==void 0?t:1e3,function(c){const i=Date.now(),d=r[o];a||(a=i),n[s]=c,r[s]=i;let p=o,f=0;for(;p!==s;)f+=n[p++],p=p%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),i-ar)return s&&(clearTimeout(s),s=null),n=l,e.apply(null,arguments);s||(s=setTimeout(()=>(s=null,n=Date.now(),e.apply(null,arguments)),r-(l-n)))}}const eh=(e,t,n=3)=>{let r=0;const s=m4(50,250);return v4(o=>{const a=o.loaded,l=o.lengthComputable?o.total:void 0,c=a-r,i=s(c),d=a<=l;r=a;const p={loaded:a,total:l,progress:l?a/l:void 0,bytes:c,rate:i||void 0,estimated:i&&l&&d?(l-a)/i:void 0,event:o,lengthComputable:l!=null};p[t?"download":"upload"]=!0,e(p)},n)},y4=ss.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function s(o){let a=o;return t&&(n.setAttribute("href",a),a=n.href),n.setAttribute("href",a),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=s(window.location.href),function(a){const l=$.isString(a)?s(a):a;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}(),b4=ss.hasStandardBrowserEnv?{write(e,t,n,r,s,o){const a=[e+"="+encodeURIComponent(t)];$.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),$.isString(r)&&a.push("path="+r),$.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function x4(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function w4(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function J_(e,t){return e&&!x4(t)?w4(e,t):t}const V0=e=>e instanceof sr?{...e}:e;function Si(e,t){t=t||{};const n={};function r(i,d,p){return $.isPlainObject(i)&&$.isPlainObject(d)?$.merge.call({caseless:p},i,d):$.isPlainObject(d)?$.merge({},d):$.isArray(d)?d.slice():d}function s(i,d,p){if($.isUndefined(d)){if(!$.isUndefined(i))return r(void 0,i,p)}else return r(i,d,p)}function o(i,d){if(!$.isUndefined(d))return r(void 0,d)}function a(i,d){if($.isUndefined(d)){if(!$.isUndefined(i))return r(void 0,i)}else return r(void 0,d)}function l(i,d,p){if(p in t)return r(i,d);if(p in e)return r(void 0,i)}const c={url:o,method:o,data:o,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:l,headers:(i,d)=>s(V0(i),V0(d),!0)};return $.forEach(Object.keys(Object.assign({},e,t)),function(d){const p=c[d]||s,f=p(e[d],t[d],d);$.isUndefined(f)&&p!==l||(n[d]=f)}),n}const Q_=e=>{const t=Si({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:l}=t;t.headers=a=sr.from(a),t.url=H_(J_(t.baseURL,t.url),e.params,e.paramsSerializer),l&&a.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let c;if($.isFormData(n)){if(ss.hasStandardBrowserEnv||ss.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if((c=a.getContentType())!==!1){const[i,...d]=c?c.split(";").map(p=>p.trim()).filter(Boolean):[];a.setContentType([i||"multipart/form-data",...d].join("; "))}}if(ss.hasStandardBrowserEnv&&(r&&$.isFunction(r)&&(r=r(t)),r||r!==!1&&y4(t.url))){const i=s&&o&&b4.read(o);i&&a.set(s,i)}return t},S4=typeof XMLHttpRequest<"u",C4=S4&&function(e){return new Promise(function(n,r){const s=Q_(e);let o=s.data;const a=sr.from(s.headers).normalize();let{responseType:l}=s,c;function i(){s.cancelToken&&s.cancelToken.unsubscribe(c),s.signal&&s.signal.removeEventListener("abort",c)}let d=new XMLHttpRequest;d.open(s.method.toUpperCase(),s.url,!0),d.timeout=s.timeout;function p(){if(!d)return;const h=sr.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),m={data:!l||l==="text"||l==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:h,config:e,request:d};G_(function(b){n(b),i()},function(b){r(b),i()},m),d=null}"onloadend"in d?d.onloadend=p:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(p)},d.onabort=function(){d&&(r(new He("Request aborted",He.ECONNABORTED,s,d)),d=null)},d.onerror=function(){r(new He("Network Error",He.ERR_NETWORK,s,d)),d=null},d.ontimeout=function(){let g=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const m=s.transitional||K_;s.timeoutErrorMessage&&(g=s.timeoutErrorMessage),r(new He(g,m.clarifyTimeoutError?He.ETIMEDOUT:He.ECONNABORTED,s,d)),d=null},o===void 0&&a.setContentType(null),"setRequestHeader"in d&&$.forEach(a.toJSON(),function(g,m){d.setRequestHeader(m,g)}),$.isUndefined(s.withCredentials)||(d.withCredentials=!!s.withCredentials),l&&l!=="json"&&(d.responseType=s.responseType),typeof s.onDownloadProgress=="function"&&d.addEventListener("progress",eh(s.onDownloadProgress,!0)),typeof s.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",eh(s.onUploadProgress)),(s.cancelToken||s.signal)&&(c=h=>{d&&(r(!h||h.type?new gu(null,e,d):h),d.abort(),d=null)},s.cancelToken&&s.cancelToken.subscribe(c),s.signal&&(s.signal.aborted?c():s.signal.addEventListener("abort",c)));const f=g4(s.url);if(f&&ss.protocols.indexOf(f)===-1){r(new He("Unsupported protocol "+f+":",He.ERR_BAD_REQUEST,e));return}d.send(o||null)})},E4=(e,t)=>{let n=new AbortController,r;const s=function(c){if(!r){r=!0,a();const i=c instanceof Error?c:this.reason;n.abort(i instanceof He?i:new gu(i instanceof Error?i.message:i))}};let o=t&&setTimeout(()=>{s(new He(`timeout ${t} of ms exceeded`,He.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(c=>{c&&(c.removeEventListener?c.removeEventListener("abort",s):c.unsubscribe(s))}),e=null)};e.forEach(c=>c&&c.addEventListener&&c.addEventListener("abort",s));const{signal:l}=n;return l.unsubscribe=a,[l,()=>{o&&clearTimeout(o),o=null}]},T4=function*(e,t){let n=e.byteLength;if(!t||n{const o=k4(e,t,s);let a=0;return new ReadableStream({type:"bytes",async pull(l){const{done:c,value:i}=await o.next();if(c){l.close(),r();return}let d=i.byteLength;n&&n(a+=d),l.enqueue(new Uint8Array(i))},cancel(l){return r(l),o.return()}},{highWaterMark:2})},K0=(e,t)=>{const n=e!=null;return r=>setTimeout(()=>t({lengthComputable:n,total:e,loaded:r}))},og=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Z_=og&&typeof ReadableStream=="function",Ly=og&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),_4=Z_&&(()=>{let e=!1;const t=new Request(ss.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})(),q0=64*1024,$y=Z_&&!!(()=>{try{return $.isReadableStream(new Response("").body)}catch{}})(),th={stream:$y&&(e=>e.body)};og&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!th[t]&&(th[t]=$.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new He(`Response type '${t}' is not supported`,He.ERR_NOT_SUPPORT,r)})})})(new Response);const j4=async e=>{if(e==null)return 0;if($.isBlob(e))return e.size;if($.isSpecCompliantForm(e))return(await new Request(e).arrayBuffer()).byteLength;if($.isArrayBufferView(e))return e.byteLength;if($.isURLSearchParams(e)&&(e=e+""),$.isString(e))return(await Ly(e)).byteLength},R4=async(e,t)=>{const n=$.toFiniteNumber(e.getContentLength());return n??j4(t)},P4=og&&(async e=>{let{url:t,method:n,data:r,signal:s,cancelToken:o,timeout:a,onDownloadProgress:l,onUploadProgress:c,responseType:i,headers:d,withCredentials:p="same-origin",fetchOptions:f}=Q_(e);i=i?(i+"").toLowerCase():"text";let[h,g]=s||o||a?E4([s,o],a):[],m,x;const b=()=>{!m&&setTimeout(()=>{h&&h.unsubscribe()}),m=!0};let y;try{if(c&&_4&&n!=="get"&&n!=="head"&&(y=await R4(d,r))!==0){let C=new Request(t,{method:"POST",body:r,duplex:"half"}),k;$.isFormData(r)&&(k=C.headers.get("content-type"))&&d.setContentType(k),C.body&&(r=H0(C.body,q0,K0(y,eh(c)),null,Ly))}$.isString(p)||(p=p?"cors":"omit"),x=new Request(t,{...f,signal:h,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:r,duplex:"half",withCredentials:p});let w=await fetch(x);const S=$y&&(i==="stream"||i==="response");if($y&&(l||S)){const C={};["status","statusText","headers"].forEach(T=>{C[T]=w[T]});const k=$.toFiniteNumber(w.headers.get("content-length"));w=new Response(H0(w.body,q0,l&&K0(k,eh(l,!0)),S&&b,Ly),C)}i=i||"text";let E=await th[$.findKey(th,i)||"text"](w,e);return!S&&b(),g&&g(),await new Promise((C,k)=>{G_(C,k,{data:E,headers:sr.from(w.headers),status:w.status,statusText:w.statusText,config:e,request:x})})}catch(w){throw b(),w&&w.name==="TypeError"&&/fetch/i.test(w.message)?Object.assign(new He("Network Error",He.ERR_NETWORK,e,x),{cause:w.cause||w}):He.from(w,w&&w.code,e,x)}}),By={http:W$,xhr:C4,fetch:P4};$.forEach(By,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const W0=e=>`- ${e}`,M4=e=>$.isFunction(e)||e===null||e===!1,Y_={getAdapter:e=>{e=$.isArray(e)?e:[e];const{length:t}=e;let n,r;const s={};for(let o=0;o`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=t?o.length>1?`since : -`+o.map(W0).join(` -`):" "+W0(o[0]):"as no adapter specified";throw new He("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return r},adapters:By};function Bm(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new gu(null,e)}function G0(e){return Bm(e),e.headers=sr.from(e.headers),e.data=$m.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Y_.getAdapter(e.adapter||zd.adapter)(e).then(function(r){return Bm(e),r.data=$m.call(e,e.transformResponse,r),r.headers=sr.from(r.headers),r},function(r){return W_(r)||(Bm(e),r&&r.response&&(r.response.data=$m.call(e,e.transformResponse,r.response),r.response.headers=sr.from(r.response.headers))),Promise.reject(r)})}const X_="1.7.2",Ix={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ix[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const J0={};Ix.transitional=function(t,n,r){function s(o,a){return"[Axios v"+X_+"] Transitional option '"+o+"'"+a+(r?". "+r:"")}return(o,a,l)=>{if(t===!1)throw new He(s(a," has been removed"+(n?" in "+n:"")),He.ERR_DEPRECATED);return n&&!J0[a]&&(J0[a]=!0,console.warn(s(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,a,l):!0}};function O4(e,t,n){if(typeof e!="object")throw new He("options must be an object",He.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],a=t[o];if(a){const l=e[o],c=l===void 0||a(l,o,e);if(c!==!0)throw new He("option "+o+" must be "+c,He.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new He("Unknown option "+o,He.ERR_BAD_OPTION)}}const zy={assertOptions:O4,validators:Ix},Oo=zy.validators;let di=class{constructor(t){this.defaults=t,this.interceptors={request:new z0,response:new z0}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` -`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Si(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&zy.assertOptions(r,{silentJSONParsing:Oo.transitional(Oo.boolean),forcedJSONParsing:Oo.transitional(Oo.boolean),clarifyTimeoutError:Oo.transitional(Oo.boolean)},!1),s!=null&&($.isFunction(s)?n.paramsSerializer={serialize:s}:zy.assertOptions(s,{encode:Oo.function,serialize:Oo.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=o&&$.merge(o.common,o[n.method]);o&&$.forEach(["delete","get","head","post","put","patch","common"],g=>{delete o[g]}),n.headers=sr.concat(a,o);const l=[];let c=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(c=c&&m.synchronous,l.unshift(m.fulfilled,m.rejected))});const i=[];this.interceptors.response.forEach(function(m){i.push(m.fulfilled,m.rejected)});let d,p=0,f;if(!c){const g=[G0.bind(this),void 0];for(g.unshift.apply(g,l),g.push.apply(g,i),f=g.length,d=Promise.resolve(n);p{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const a=new Promise(l=>{r.subscribe(l),o=l}).then(s);return a.cancel=function(){r.unsubscribe(o)},a},t(function(o,a,l){r.reason||(r.reason=new gu(o,a,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ej(function(s){t=s}),cancel:t}}};function I4(e){return function(n){return e.apply(null,n)}}function D4(e){return $.isObject(e)&&e.isAxiosError===!0}const Uy={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(Uy).forEach(([e,t])=>{Uy[t]=e});function tj(e){const t=new di(e),n=O_(di.prototype.request,t);return $.extend(n,di.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return tj(Si(e,s))},n}const zt=tj(zd);zt.Axios=di;zt.CanceledError=gu;zt.CancelToken=N4;zt.isCancel=W_;zt.VERSION=X_;zt.toFormData=sg;zt.AxiosError=He;zt.Cancel=zt.CanceledError;zt.all=function(t){return Promise.all(t)};zt.spread=I4;zt.isAxiosError=D4;zt.mergeConfig=Si;zt.AxiosHeaders=sr;zt.formToJSON=e=>q_($.isHTMLForm(e)?new FormData(e):e);zt.getAdapter=Y_.getAdapter;zt.HttpStatusCode=Uy;zt.default=zt;const{Axios:Mse,AxiosError:Ose,CanceledError:Nse,isCancel:Ise,CancelToken:Dse,VERSION:Ase,all:Fse,Cancel:Lse,isAxiosError:A4,spread:$se,toFormData:Bse,AxiosHeaders:zse,HttpStatusCode:Use,formToJSON:Vse,getAdapter:Hse,mergeConfig:Kse}=zt,F4=e=>["auth","verifyServer",JSON.stringify(e)],nj=async({url:e})=>(await zt.get(`${e}/`)).data,L4=e=>{const{url:t,...n}=e;return lt({...n,queryKey:F4({url:t}),queryFn:()=>nj({url:t}),enabled:!!t})};function $4(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function ag(...e){return t=>e.forEach(n=>$4(n,t))}function it(...e){return v.useCallback(ag(...e),e)}var mo=v.forwardRef((e,t)=>{const{children:n,...r}=e,s=v.Children.toArray(n),o=s.find(z4);if(o){const a=o.props.children,l=s.map(c=>c===o?v.Children.count(a)>1?v.Children.only(null):v.isValidElement(a)?a.props.children:null:c);return u.jsx(Vy,{...r,ref:t,children:v.isValidElement(a)?v.cloneElement(a,void 0,l):null})}return u.jsx(Vy,{...r,ref:t,children:n})});mo.displayName="Slot";var Vy=v.forwardRef((e,t)=>{const{children:n,...r}=e;if(v.isValidElement(n)){const s=V4(n);return v.cloneElement(n,{...U4(r,n.props),ref:t?ag(t,s):s})}return v.Children.count(n)>1?v.Children.only(null):null});Vy.displayName="SlotClone";var B4=({children:e})=>u.jsx(u.Fragment,{children:e});function z4(e){return v.isValidElement(e)&&e.type===B4}function U4(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...l)=>{o(...l),s(...l)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function V4(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function rj(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;ttypeof e=="boolean"?"".concat(e):e===0?"0":e,Z0=H4,ig=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return Z0(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:s,defaultVariants:o}=t,a=Object.keys(s).map(i=>{const d=n==null?void 0:n[i],p=o==null?void 0:o[i];if(d===null)return null;const f=Q0(d)||Q0(p);return s[i][f]}),l=n&&Object.entries(n).reduce((i,d)=>{let[p,f]=d;return f===void 0||(i[p]=f),i},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((i,d)=>{let{class:p,className:f,...h}=d;return Object.entries(h).every(g=>{let[m,x]=g;return Array.isArray(x)?x.includes({...o,...l}[m]):{...o,...l}[m]===x})?[...i,p,f]:i},[]);return Z0(e,a,c,n==null?void 0:n.class,n==null?void 0:n.className)},Dx="-";function K4(e){const t=W4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;function s(a){const l=a.split(Dx);return l[0]===""&&l.length!==1&&l.shift(),sj(l,t)||q4(a)}function o(a,l){const c=n[a]||[];return l&&r[a]?[...c,...r[a]]:c}return{getClassGroupId:s,getConflictingClassGroupIds:o}}function sj(e,t){var a;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?sj(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Dx);return(a=t.validators.find(({validator:l})=>l(o)))==null?void 0:a.classGroupId}const Y0=/^\[(.+)\]$/;function q4(e){if(Y0.test(e)){const t=Y0.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function W4(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return J4(Object.entries(e.classGroups),n).forEach(([o,a])=>{Hy(a,r,o,t)}),r}function Hy(e,t,n,r){e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:X0(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(G4(s)){Hy(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,a])=>{Hy(a,X0(t,o),n,r)})})}function X0(e,t){let n=e;return t.split(Dx).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function G4(e){return e.isThemeGetter}function J4(e,t){return t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,l])=>[t+a,l])):o);return[n,s]}):e}function Q4(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function s(o,a){n.set(o,a),t++,t>e&&(t=0,r=n,n=new Map)}return{get(o){let a=n.get(o);if(a!==void 0)return a;if((a=r.get(o))!==void 0)return s(o,a),a},set(o,a){n.has(o)?n.set(o,a):s(o,a)}}}const oj="!";function Z4(e){const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length;function a(l){const c=[];let i=0,d=0,p;for(let x=0;xd?p-d:void 0;return{modifiers:c,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:m}}return n?function(c){return n({className:c,parseClassName:a})}:a}function Y4(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function X4(e){return{cache:Q4(e.cacheSize),parseClassName:Z4(e),...K4(e)}}const e3=/\s+/;function t3(e,t){const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=new Set;return e.trim().split(e3).map(a=>{const{modifiers:l,hasImportantModifier:c,baseClassName:i,maybePostfixModifierPosition:d}=n(a);let p=!!d,f=r(p?i.substring(0,d):i);if(!f){if(!p)return{isTailwindClass:!1,originalClassName:a};if(f=r(i),!f)return{isTailwindClass:!1,originalClassName:a};p=!1}const h=Y4(l).join(":");return{isTailwindClass:!0,modifierId:c?h+oj:h,classGroupId:f,originalClassName:a,hasPostfixModifier:p}}).reverse().filter(a=>{if(!a.isTailwindClass)return!0;const{modifierId:l,classGroupId:c,hasPostfixModifier:i}=a,d=l+c;return o.has(d)?!1:(o.add(d),s(c,i).forEach(p=>o.add(l+p)),!0)}).reverse().map(a=>a.originalClassName).join(" ")}function n3(){let e=0,t,n,r="";for(;ep(d),e());return n=X4(i),r=n.cache.get,s=n.cache.set,o=l,l(c)}function l(c){const i=r(c);if(i)return i;const d=t3(c,n);return s(c,d),d}return function(){return o(n3.apply(null,arguments))}}function _t(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const ij=/^\[(?:([a-z-]+):)?(.+)\]$/i,s3=/^\d+\/\d+$/,o3=new Set(["px","full","screen"]),a3=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,i3=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,l3=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,u3=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,c3=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function qs(e){return Ga(e)||o3.has(e)||s3.test(e)}function No(e){return mu(e,"length",y3)}function Ga(e){return!!e&&!Number.isNaN(Number(e))}function Pf(e){return mu(e,"number",Ga)}function Ju(e){return!!e&&Number.isInteger(Number(e))}function d3(e){return e.endsWith("%")&&Ga(e.slice(0,-1))}function We(e){return ij.test(e)}function Io(e){return a3.test(e)}const f3=new Set(["length","size","percentage"]);function p3(e){return mu(e,f3,lj)}function h3(e){return mu(e,"position",lj)}const g3=new Set(["image","url"]);function m3(e){return mu(e,g3,x3)}function v3(e){return mu(e,"",b3)}function Qu(){return!0}function mu(e,t,n){const r=ij.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function y3(e){return i3.test(e)&&!l3.test(e)}function lj(){return!1}function b3(e){return u3.test(e)}function x3(e){return c3.test(e)}function w3(){const e=_t("colors"),t=_t("spacing"),n=_t("blur"),r=_t("brightness"),s=_t("borderColor"),o=_t("borderRadius"),a=_t("borderSpacing"),l=_t("borderWidth"),c=_t("contrast"),i=_t("grayscale"),d=_t("hueRotate"),p=_t("invert"),f=_t("gap"),h=_t("gradientColorStops"),g=_t("gradientColorStopPositions"),m=_t("inset"),x=_t("margin"),b=_t("opacity"),y=_t("padding"),w=_t("saturate"),S=_t("scale"),E=_t("sepia"),C=_t("skew"),k=_t("space"),T=_t("translate"),P=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto",We,t],I=()=>[We,t],Z=()=>["",qs,No],V=()=>["auto",Ga,We],Q=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ee=()=>["solid","dashed","dotted","double","none"],W=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>["start","end","center","between","around","evenly","stretch"],A=()=>["","0",We],Y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],de=()=>[Ga,Pf],z=()=>[Ga,We];return{cacheSize:500,separator:":",theme:{colors:[Qu],spacing:[qs,No],blur:["none","",Io,We],brightness:de(),borderColor:[e],borderRadius:["none","","full",Io,We],borderSpacing:I(),borderWidth:Z(),contrast:de(),grayscale:A(),hueRotate:z(),invert:A(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[d3,No],inset:U(),margin:U(),opacity:de(),padding:I(),saturate:de(),scale:de(),sepia:A(),skew:z(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",We]}],container:["container"],columns:[{columns:[Io]}],"break-after":[{"break-after":Y()}],"break-before":[{"break-before":Y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...Q(),We]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[m]}],"inset-x":[{"inset-x":[m]}],"inset-y":[{"inset-y":[m]}],start:[{start:[m]}],end:[{end:[m]}],top:[{top:[m]}],right:[{right:[m]}],bottom:[{bottom:[m]}],left:[{left:[m]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ju,We]}],basis:[{basis:U()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",We]}],grow:[{grow:A()}],shrink:[{shrink:A()}],order:[{order:["first","last","none",Ju,We]}],"grid-cols":[{"grid-cols":[Qu]}],"col-start-end":[{col:["auto",{span:["full",Ju,We]},We]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[Qu]}],"row-start-end":[{row:["auto",{span:[Ju,We]},We]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",We]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",We]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...F()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...F(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...F(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",We,t]}],"min-w":[{"min-w":[We,t,"min","max","fit"]}],"max-w":[{"max-w":[We,t,"none","full","min","max","fit","prose",{screen:[Io]},Io]}],h:[{h:[We,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[We,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Io,No]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Pf]}],"font-family":[{font:[Qu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",We]}],"line-clamp":[{"line-clamp":["none",Ga,Pf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",qs,We]}],"list-image":[{"list-image":["none",We]}],"list-style-type":[{list:["none","disc","decimal",We]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ee(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",qs,No]}],"underline-offset":[{"underline-offset":["auto",qs,We]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",We]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",We]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Q(),h3]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",p3]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},m3]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...ee(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:ee()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...ee()]}],"outline-offset":[{"outline-offset":[qs,We]}],"outline-w":[{outline:[qs,No]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[qs,No]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Io,v3]}],"shadow-color":[{shadow:[Qu]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...W(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":W()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Io,We]}],grayscale:[{grayscale:[i]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[p]}],saturate:[{saturate:[w]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[i]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",We]}],duration:[{duration:z()}],ease:[{ease:["linear","in","out","in-out",We]}],delay:[{delay:z()}],animate:[{animate:["none","spin","ping","pulse","bounce",We]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Ju,We]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",We]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",We]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",We]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[qs,No,Pf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const S3=r3(w3);function ge(...e){return S3(oo(e))}const C3=ig("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",warning:"bg-amber-600 shadow-sm hover:bg-amber-600/90 data-active:bg-amber-600/90 text-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),q=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...s},o)=>{const a=r?mo:"button";return u.jsx(a,{className:ge(C3({variant:t,size:n,className:e})),ref:o,...s})});q.displayName="Button";function Ax(){const{t:e}=ze(),t=Fs(rs.API_URL),{data:n}=L4({url:t}),r=v.useMemo(()=>n==null?void 0:n.clientName,[n]),s=v.useMemo(()=>n==null?void 0:n.version,[n]),o=[{name:"Discord",url:"https://evolution-api.com/discord"},{name:"Postman",url:"https://evolution-api.com/postman"},{name:"GitHub",url:"https://github.com/EvolutionAPI/evolution-api"},{name:"Docs",url:"https://doc.evolution-api.com"}];return u.jsxs("footer",{className:"flex w-full flex-col items-center justify-between p-6 text-xs text-secondary-foreground sm:flex-row",children:[u.jsxs("div",{className:"flex items-center space-x-3 divide-x",children:[r&&r!==""&&u.jsxs("span",{children:[e("footer.clientName"),": ",u.jsx("strong",{children:r})]}),s&&s!==""&&u.jsxs("span",{className:"pl-3",children:[e("footer.version"),": ",u.jsx("strong",{children:s})]})]}),u.jsx("div",{className:"flex gap-2",children:o.map(a=>u.jsx(q,{variant:"link",asChild:!0,size:"sm",className:"text-xs",children:u.jsx("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:a.name})},a.url))})]})}/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const E3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),uj=(...e)=>e.filter((t,n,r)=>!!t&&r.indexOf(t)===n).join(" ");/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var T3={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const k3=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:o,iconNode:a,...l},c)=>v.createElement("svg",{ref:c,...T3,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:uj("lucide",s),...l},[...a.map(([i,d])=>v.createElement(i,d)),...Array.isArray(o)?o:[o]]));/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Xe=(e,t)=>{const n=v.forwardRef(({className:r,...s},o)=>v.createElement(k3,{ref:o,iconNode:t,className:uj(`lucide-${E3(e)}`,r),...s}));return n.displayName=`${e}`,n};/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const _3=Xe("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const j3=Xe("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const cj=Xe("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const lg=Xe("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const R3=Xe("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const P3=Xe("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const M3=Xe("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const O3=Xe("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ud=Xe("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{width:"6",height:"6",x:"9",y:"9",key:"1wrtvo"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dj=Xe("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const N3=Xe("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Oi=Xe("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const I3=Xe("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Vd=Xe("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const D3=Xe("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const vu=Xe("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const A3=Xe("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const F3=Xe("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const L3=Xe("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const $3=Xe("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const B3=Xe("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const z3=Xe("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const U3=Xe("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const V3=Xe("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Hd=Xe("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const H3=Xe("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ug=Xe("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const K3=Xe("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const q3=Xe("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Kd=Xe("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const qd=Xe("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ni=Xe("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fj=Xe("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Wd=Xe("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const W3=Xe("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const G3=Xe("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const J3=Xe("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Q3=Xe("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const pj=Xe("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),he=zt.create({timeout:3e4});he.interceptors.request.use(async e=>{const t=Fs(rs.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=Fs(rs.TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const Z3=e=>["instance","fetchInstance",JSON.stringify(e)],Y3=async({instanceId:e})=>{const t=await he.get("/instance/fetchInstances",{params:{instanceId:e}});return Array.isArray(t.data)?t.data[0]:t.data},hj=e=>{const{instanceId:t,...n}=e;return lt({...n,queryKey:Z3({instanceId:t}),queryFn:()=>Y3({instanceId:t}),enabled:!!t})};function Se(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function X3(e,t){const n=v.createContext(t);function r(o){const{children:a,...l}=o,c=v.useMemo(()=>l,Object.values(l));return u.jsx(n.Provider,{value:c,children:a})}function s(o){const a=v.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function Vr(e,t=[]){let n=[];function r(o,a){const l=v.createContext(a),c=n.length;n=[...n,a];function i(p){const{scope:f,children:h,...g}=p,m=(f==null?void 0:f[e][c])||l,x=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:x,children:h})}function d(p,f){const h=(f==null?void 0:f[e][c])||l,g=v.useContext(h);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${o}\``)}return i.displayName=o+"Provider",[i,d]}const s=()=>{const o=n.map(a=>v.createContext(a));return function(l){const c=(l==null?void 0:l[e])||o;return v.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return s.scopeName=e,[r,eB(s,...t)]}function eB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const a=r.reduce((l,{useScope:c,scopeName:i})=>{const p=c(o)[`__scope${i}`];return{...l,...p}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function nn(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function pa({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,s]=tB({defaultProp:t,onChange:n}),o=e!==void 0,a=o?e:r,l=nn(n),c=v.useCallback(i=>{if(o){const p=typeof i=="function"?i(e):i;p!==e&&l(p)}else s(i)},[o,e,s,l]);return[a,c]}function tB({defaultProp:e,onChange:t}){const n=v.useState(e),[r]=n,s=v.useRef(r),o=nn(t);return v.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),n}var nB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ne=nB.reduce((e,t)=>{const n=v.forwardRef((r,s)=>{const{asChild:o,...a}=r,l=o?mo:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function gj(e,t){e&&ka.flushSync(()=>e.dispatchEvent(t))}function Fx(e){const t=e+"CollectionProvider",[n,r]=Vr(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=h=>{const{scope:g,children:m}=h,x=Te.useRef(null),b=Te.useRef(new Map).current;return u.jsx(s,{scope:g,itemMap:b,collectionRef:x,children:m})};a.displayName=t;const l=e+"CollectionSlot",c=Te.forwardRef((h,g)=>{const{scope:m,children:x}=h,b=o(l,m),y=it(g,b.collectionRef);return u.jsx(mo,{ref:y,children:x})});c.displayName=l;const i=e+"CollectionItemSlot",d="data-radix-collection-item",p=Te.forwardRef((h,g)=>{const{scope:m,children:x,...b}=h,y=Te.useRef(null),w=it(g,y),S=o(i,m);return Te.useEffect(()=>(S.itemMap.set(y,{ref:y,...b}),()=>void S.itemMap.delete(y))),u.jsx(mo,{[d]:"",ref:w,children:x})});p.displayName=i;function f(h){const g=o(e+"CollectionConsumer",h);return Te.useCallback(()=>{const x=g.collectionRef.current;if(!x)return[];const b=Array.from(x.querySelectorAll(`[${d}]`));return Array.from(g.itemMap.values()).sort((S,E)=>b.indexOf(S.ref.current)-b.indexOf(E.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:a,Slot:c,ItemSlot:p},f,r]}var rB=v.createContext(void 0);function Gd(e){const t=v.useContext(rB);return e||t||"ltr"}function sB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e);v.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var oB="DismissableLayer",Ky="dismissableLayer.update",aB="dismissableLayer.pointerDownOutside",iB="dismissableLayer.focusOutside",eC,mj=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),cg=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:a,onDismiss:l,...c}=e,i=v.useContext(mj),[d,p]=v.useState(null),f=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=it(t,k=>p(k)),m=Array.from(i.layers),[x]=[...i.layersWithOutsidePointerEventsDisabled].slice(-1),b=m.indexOf(x),y=d?m.indexOf(d):-1,w=i.layersWithOutsidePointerEventsDisabled.size>0,S=y>=b,E=cB(k=>{const T=k.target,P=[...i.branches].some(N=>N.contains(T));!S||P||(s==null||s(k),a==null||a(k),k.defaultPrevented||l==null||l())},f),C=dB(k=>{const T=k.target;[...i.branches].some(N=>N.contains(T))||(o==null||o(k),a==null||a(k),k.defaultPrevented||l==null||l())},f);return sB(k=>{y===i.layers.size-1&&(r==null||r(k),!k.defaultPrevented&&l&&(k.preventDefault(),l()))},f),v.useEffect(()=>{if(d)return n&&(i.layersWithOutsidePointerEventsDisabled.size===0&&(eC=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),i.layersWithOutsidePointerEventsDisabled.add(d)),i.layers.add(d),tC(),()=>{n&&i.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=eC)}},[d,f,n,i]),v.useEffect(()=>()=>{d&&(i.layers.delete(d),i.layersWithOutsidePointerEventsDisabled.delete(d),tC())},[d,i]),v.useEffect(()=>{const k=()=>h({});return document.addEventListener(Ky,k),()=>document.removeEventListener(Ky,k)},[]),u.jsx(Ne.div,{...c,ref:g,style:{pointerEvents:w?S?"auto":"none":void 0,...e.style},onFocusCapture:Se(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Se(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Se(e.onPointerDownCapture,E.onPointerDownCapture)})});cg.displayName=oB;var lB="DismissableLayerBranch",uB=v.forwardRef((e,t)=>{const n=v.useContext(mj),r=v.useRef(null),s=it(t,r);return v.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),u.jsx(Ne.div,{...e,ref:s})});uB.displayName=lB;function cB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=v.useRef(!1),s=v.useRef(()=>{});return v.useEffect(()=>{const o=l=>{if(l.target&&!r.current){let c=function(){vj(aB,n,i,{discrete:!0})};const i={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=c,t.addEventListener("click",s.current,{once:!0})):c()}else t.removeEventListener("click",s.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",o),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function dB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=v.useRef(!1);return v.useEffect(()=>{const s=o=>{o.target&&!r.current&&vj(iB,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function tC(){const e=new CustomEvent(Ky);document.dispatchEvent(e)}function vj(e,t,n,{discrete:r}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?gj(s,o):s.dispatchEvent(o)}var zm=0;function Lx(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??nC()),document.body.insertAdjacentElement("beforeend",e[1]??nC()),zm++,()=>{zm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zm--}},[])}function nC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Um="focusScope.autoFocusOnMount",Vm="focusScope.autoFocusOnUnmount",rC={bubbles:!1,cancelable:!0},fB="FocusScope",dg=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[l,c]=v.useState(null),i=nn(s),d=nn(o),p=v.useRef(null),f=it(t,m=>c(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(w){if(h.paused||!l)return;const S=w.target;l.contains(S)?p.current=S:Lo(p.current,{select:!0})},x=function(w){if(h.paused||!l)return;const S=w.relatedTarget;S!==null&&(l.contains(S)||Lo(p.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const E of w)E.removedNodes.length>0&&Lo(l)};document.addEventListener("focusin",m),document.addEventListener("focusout",x);const y=new MutationObserver(b);return l&&y.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",x),y.disconnect()}}},[r,l,h.paused]),v.useEffect(()=>{if(l){oC.add(h);const m=document.activeElement;if(!l.contains(m)){const b=new CustomEvent(Um,rC);l.addEventListener(Um,i),l.dispatchEvent(b),b.defaultPrevented||(pB(yB(yj(l)),{select:!0}),document.activeElement===m&&Lo(l))}return()=>{l.removeEventListener(Um,i),setTimeout(()=>{const b=new CustomEvent(Vm,rC);l.addEventListener(Vm,d),l.dispatchEvent(b),b.defaultPrevented||Lo(m??document.body,{select:!0}),l.removeEventListener(Vm,d),oC.remove(h)},0)}}},[l,i,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const x=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,b=document.activeElement;if(x&&b){const y=m.currentTarget,[w,S]=hB(y);w&&S?!m.shiftKey&&b===S?(m.preventDefault(),n&&Lo(w,{select:!0})):m.shiftKey&&b===w&&(m.preventDefault(),n&&Lo(S,{select:!0})):b===y&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ne.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});dg.displayName=fB;function pB(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Lo(r,{select:t}),document.activeElement!==n)return}function hB(e){const t=yj(e),n=sC(t,e),r=sC(t.reverse(),e);return[n,r]}function yj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function sC(e,t){for(const n of e)if(!gB(n,{upTo:t}))return n}function gB(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function mB(e){return e instanceof HTMLInputElement&&"select"in e}function Lo(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&mB(e)&&t&&e.select()}}var oC=vB();function vB(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=aC(e,t),e.unshift(t)},remove(t){var n;e=aC(e,t),(n=e[0])==null||n.resume()}}}function aC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function yB(e){return e.filter(t=>t.tagName!=="A")}var fn=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},bB=Nh.useId||(()=>{}),xB=0;function os(e){const[t,n]=v.useState(bB());return fn(()=>{n(r=>r??String(xB++))},[e]),t?`radix-${t}`:""}const wB=["top","right","bottom","left"],Ms=Math.min,pr=Math.max,nh=Math.round,Mf=Math.floor,ha=e=>({x:e,y:e}),SB={left:"right",right:"left",bottom:"top",top:"bottom"},CB={start:"end",end:"start"};function qy(e,t,n){return pr(e,Ms(t,n))}function vo(e,t){return typeof e=="function"?e(t):e}function yo(e){return e.split("-")[0]}function yu(e){return e.split("-")[1]}function $x(e){return e==="x"?"y":"x"}function Bx(e){return e==="y"?"height":"width"}function ga(e){return["top","bottom"].includes(yo(e))?"y":"x"}function zx(e){return $x(ga(e))}function EB(e,t,n){n===void 0&&(n=!1);const r=yu(e),s=zx(e),o=Bx(s);let a=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=rh(a)),[a,rh(a)]}function TB(e){const t=rh(e);return[Wy(e),t,Wy(t)]}function Wy(e){return e.replace(/start|end/g,t=>CB[t])}function kB(e,t,n){const r=["left","right"],s=["right","left"],o=["top","bottom"],a=["bottom","top"];switch(e){case"top":case"bottom":return n?t?s:r:t?r:s;case"left":case"right":return t?o:a;default:return[]}}function _B(e,t,n,r){const s=yu(e);let o=kB(yo(e),n==="start",r);return s&&(o=o.map(a=>a+"-"+s),t&&(o=o.concat(o.map(Wy)))),o}function rh(e){return e.replace(/left|right|bottom|top/g,t=>SB[t])}function jB(e){return{top:0,right:0,bottom:0,left:0,...e}}function bj(e){return typeof e!="number"?jB(e):{top:e,right:e,bottom:e,left:e}}function sh(e){const{x:t,y:n,width:r,height:s}=e;return{width:r,height:s,top:n,left:t,right:t+r,bottom:n+s,x:t,y:n}}function iC(e,t,n){let{reference:r,floating:s}=e;const o=ga(t),a=zx(t),l=Bx(a),c=yo(t),i=o==="y",d=r.x+r.width/2-s.width/2,p=r.y+r.height/2-s.height/2,f=r[l]/2-s[l]/2;let h;switch(c){case"top":h={x:d,y:r.y-s.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-s.width,y:p};break;default:h={x:r.x,y:r.y}}switch(yu(t)){case"start":h[a]-=f*(n&&i?-1:1);break;case"end":h[a]+=f*(n&&i?-1:1);break}return h}const RB=async(e,t,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:o=[],platform:a}=n,l=o.filter(Boolean),c=await(a.isRTL==null?void 0:a.isRTL(t));let i=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:d,y:p}=iC(i,r,c),f=r,h={},g=0;for(let m=0;m({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:o,platform:a,elements:l,middlewareData:c}=t,{element:i,padding:d=0}=vo(e,t)||{};if(i==null)return{};const p=bj(d),f={x:n,y:r},h=zx(s),g=Bx(h),m=await a.getDimensions(i),x=h==="y",b=x?"top":"left",y=x?"bottom":"right",w=x?"clientHeight":"clientWidth",S=o.reference[g]+o.reference[h]-f[h]-o.floating[g],E=f[h]-o.reference[h],C=await(a.getOffsetParent==null?void 0:a.getOffsetParent(i));let k=C?C[w]:0;(!k||!await(a.isElement==null?void 0:a.isElement(C)))&&(k=l.floating[w]||o.floating[g]);const T=S/2-E/2,P=k/2-m[g]/2-1,N=Ms(p[b],P),U=Ms(p[y],P),I=N,Z=k-m[g]-U,V=k/2-m[g]/2+T,Q=qy(I,V,Z),ee=!c.arrow&&yu(s)!=null&&V!==Q&&o.reference[g]/2-(VV<=0)){var U,I;const V=(((U=o.flip)==null?void 0:U.index)||0)+1,Q=k[V];if(Q)return{data:{index:V,overflows:N},reset:{placement:Q}};let ee=(I=N.filter(W=>W.overflows[0]<=0).sort((W,F)=>W.overflows[1]-F.overflows[1])[0])==null?void 0:I.placement;if(!ee)switch(h){case"bestFit":{var Z;const W=(Z=N.filter(F=>{if(C){const A=ga(F.placement);return A===y||A==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(A=>A>0).reduce((A,Y)=>A+Y,0)]).sort((F,A)=>F[1]-A[1])[0])==null?void 0:Z[0];W&&(ee=W);break}case"initialPlacement":ee=l;break}if(s!==ee)return{reset:{placement:ee}}}return{}}}};function lC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function uC(e){return wB.some(t=>e[t]>=0)}const OB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...s}=vo(e,t);switch(r){case"referenceHidden":{const o=await ad(t,{...s,elementContext:"reference"}),a=lC(o,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:uC(a)}}}case"escaped":{const o=await ad(t,{...s,altBoundary:!0}),a=lC(o,n.floating);return{data:{escapedOffsets:a,escaped:uC(a)}}}default:return{}}}}};async function NB(e,t){const{placement:n,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),a=yo(n),l=yu(n),c=ga(n)==="y",i=["left","top"].includes(a)?-1:1,d=o&&c?-1:1,p=vo(t,e);let{mainAxis:f,crossAxis:h,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof g=="number"&&(h=l==="end"?g*-1:g),c?{x:h*d,y:f*i}:{x:f*i,y:h*d}}const IB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:s,y:o,placement:a,middlewareData:l}=t,c=await NB(t,e);return a===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:s+c.x,y:o+c.y,data:{...c,placement:a}}}}},DB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:s}=t,{mainAxis:o=!0,crossAxis:a=!1,limiter:l={fn:x=>{let{x:b,y}=x;return{x:b,y}}},...c}=vo(e,t),i={x:n,y:r},d=await ad(t,c),p=ga(yo(s)),f=$x(p);let h=i[f],g=i[p];if(o){const x=f==="y"?"top":"left",b=f==="y"?"bottom":"right",y=h+d[x],w=h-d[b];h=qy(y,h,w)}if(a){const x=p==="y"?"top":"left",b=p==="y"?"bottom":"right",y=g+d[x],w=g-d[b];g=qy(y,g,w)}const m=l.fn({...t,[f]:h,[p]:g});return{...m,data:{x:m.x-n,y:m.y-r}}}}},AB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:s,rects:o,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:i=!0}=vo(e,t),d={x:n,y:r},p=ga(s),f=$x(p);let h=d[f],g=d[p];const m=vo(l,t),x=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const w=f==="y"?"height":"width",S=o.reference[f]-o.floating[w]+x.mainAxis,E=o.reference[f]+o.reference[w]-x.mainAxis;hE&&(h=E)}if(i){var b,y;const w=f==="y"?"width":"height",S=["top","left"].includes(yo(s)),E=o.reference[p]-o.floating[w]+(S&&((b=a.offset)==null?void 0:b[p])||0)+(S?0:x.crossAxis),C=o.reference[p]+o.reference[w]+(S?0:((y=a.offset)==null?void 0:y[p])||0)-(S?x.crossAxis:0);gC&&(g=C)}return{[f]:h,[p]:g}}}},FB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:s,elements:o}=t,{apply:a=()=>{},...l}=vo(e,t),c=await ad(t,l),i=yo(n),d=yu(n),p=ga(n)==="y",{width:f,height:h}=r.floating;let g,m;i==="top"||i==="bottom"?(g=i,m=d===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(m=i,g=d==="end"?"top":"bottom");const x=h-c.top-c.bottom,b=f-c.left-c.right,y=Ms(h-c[g],x),w=Ms(f-c[m],b),S=!t.middlewareData.shift;let E=y,C=w;if(p?C=d||S?Ms(w,b):b:E=d||S?Ms(y,x):x,S&&!d){const T=pr(c.left,0),P=pr(c.right,0),N=pr(c.top,0),U=pr(c.bottom,0);p?C=f-2*(T!==0||P!==0?T+P:pr(c.left,c.right)):E=h-2*(N!==0||U!==0?N+U:pr(c.top,c.bottom))}await a({...t,availableWidth:C,availableHeight:E});const k=await s.getDimensions(o.floating);return f!==k.width||h!==k.height?{reset:{rects:!0}}:{}}}};function bu(e){return xj(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Co(e){var t;return(t=(xj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xj(e){return e instanceof Node||e instanceof vr(e).Node}function $s(e){return e instanceof Element||e instanceof vr(e).Element}function Bs(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function cC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Jd(e){const{overflow:t,overflowX:n,overflowY:r,display:s}=cs(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(s)}function LB(e){return["table","td","th"].includes(bu(e))}function fg(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function Ux(e){const t=Vx(),n=cs(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function $B(e){let t=ma(e);for(;Bs(t)&&!eu(t);){if(fg(t))return null;if(Ux(t))return t;t=ma(t)}return null}function Vx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function eu(e){return["html","body","#document"].includes(bu(e))}function cs(e){return vr(e).getComputedStyle(e)}function pg(e){return $s(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ma(e){if(bu(e)==="html")return e;const t=e.assignedSlot||e.parentNode||cC(e)&&e.host||Co(e);return cC(t)?t.host:t}function wj(e){const t=ma(e);return eu(t)?e.ownerDocument?e.ownerDocument.body:e.body:Bs(t)&&Jd(t)?t:wj(t)}function id(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const s=wj(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),a=vr(s);return o?t.concat(a,a.visualViewport||[],Jd(s)?s:[],a.frameElement&&n?id(a.frameElement):[]):t.concat(s,id(s,[],n))}function Sj(e){const t=cs(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=Bs(e),o=s?e.offsetWidth:n,a=s?e.offsetHeight:r,l=nh(n)!==o||nh(r)!==a;return l&&(n=o,r=a),{width:n,height:r,$:l}}function Hx(e){return $s(e)?e:e.contextElement}function kl(e){const t=Hx(e);if(!Bs(t))return ha(1);const n=t.getBoundingClientRect(),{width:r,height:s,$:o}=Sj(t);let a=(o?nh(n.width):n.width)/r,l=(o?nh(n.height):n.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const BB=ha(0);function Cj(e){const t=vr(e);return!Vx()||!t.visualViewport?BB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function zB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ci(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const s=e.getBoundingClientRect(),o=Hx(e);let a=ha(1);t&&(r?$s(r)&&(a=kl(r)):a=kl(e));const l=zB(o,n,r)?Cj(o):ha(0);let c=(s.left+l.x)/a.x,i=(s.top+l.y)/a.y,d=s.width/a.x,p=s.height/a.y;if(o){const f=vr(o),h=r&&$s(r)?vr(r):r;let g=f,m=g.frameElement;for(;m&&r&&h!==g;){const x=kl(m),b=m.getBoundingClientRect(),y=cs(m),w=b.left+(m.clientLeft+parseFloat(y.paddingLeft))*x.x,S=b.top+(m.clientTop+parseFloat(y.paddingTop))*x.y;c*=x.x,i*=x.y,d*=x.x,p*=x.y,c+=w,i+=S,g=vr(m),m=g.frameElement}}return sh({width:d,height:p,x:c,y:i})}function UB(e){let{elements:t,rect:n,offsetParent:r,strategy:s}=e;const o=s==="fixed",a=Co(r),l=t?fg(t.floating):!1;if(r===a||l&&o)return n;let c={scrollLeft:0,scrollTop:0},i=ha(1);const d=ha(0),p=Bs(r);if((p||!p&&!o)&&((bu(r)!=="body"||Jd(a))&&(c=pg(r)),Bs(r))){const f=Ci(r);i=kl(r),d.x=f.x+r.clientLeft,d.y=f.y+r.clientTop}return{width:n.width*i.x,height:n.height*i.y,x:n.x*i.x-c.scrollLeft*i.x+d.x,y:n.y*i.y-c.scrollTop*i.y+d.y}}function VB(e){return Array.from(e.getClientRects())}function Ej(e){return Ci(Co(e)).left+pg(e).scrollLeft}function HB(e){const t=Co(e),n=pg(e),r=e.ownerDocument.body,s=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+Ej(e);const l=-n.scrollTop;return cs(r).direction==="rtl"&&(a+=pr(t.clientWidth,r.clientWidth)-s),{width:s,height:o,x:a,y:l}}function KB(e,t){const n=vr(e),r=Co(e),s=n.visualViewport;let o=r.clientWidth,a=r.clientHeight,l=0,c=0;if(s){o=s.width,a=s.height;const i=Vx();(!i||i&&t==="fixed")&&(l=s.offsetLeft,c=s.offsetTop)}return{width:o,height:a,x:l,y:c}}function qB(e,t){const n=Ci(e,!0,t==="fixed"),r=n.top+e.clientTop,s=n.left+e.clientLeft,o=Bs(e)?kl(e):ha(1),a=e.clientWidth*o.x,l=e.clientHeight*o.y,c=s*o.x,i=r*o.y;return{width:a,height:l,x:c,y:i}}function dC(e,t,n){let r;if(t==="viewport")r=KB(e,n);else if(t==="document")r=HB(Co(e));else if($s(t))r=qB(t,n);else{const s=Cj(e);r={...t,x:t.x-s.x,y:t.y-s.y}}return sh(r)}function Tj(e,t){const n=ma(e);return n===t||!$s(n)||eu(n)?!1:cs(n).position==="fixed"||Tj(n,t)}function WB(e,t){const n=t.get(e);if(n)return n;let r=id(e,[],!1).filter(l=>$s(l)&&bu(l)!=="body"),s=null;const o=cs(e).position==="fixed";let a=o?ma(e):e;for(;$s(a)&&!eu(a);){const l=cs(a),c=Ux(a);!c&&l.position==="fixed"&&(s=null),(o?!c&&!s:!c&&l.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||Jd(a)&&!c&&Tj(e,a))?r=r.filter(d=>d!==a):s=l,a=ma(a)}return t.set(e,r),r}function GB(e){let{element:t,boundary:n,rootBoundary:r,strategy:s}=e;const a=[...n==="clippingAncestors"?fg(t)?[]:WB(t,this._c):[].concat(n),r],l=a[0],c=a.reduce((i,d)=>{const p=dC(t,d,s);return i.top=pr(p.top,i.top),i.right=Ms(p.right,i.right),i.bottom=Ms(p.bottom,i.bottom),i.left=pr(p.left,i.left),i},dC(t,l,s));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function JB(e){const{width:t,height:n}=Sj(e);return{width:t,height:n}}function QB(e,t,n){const r=Bs(t),s=Co(t),o=n==="fixed",a=Ci(e,!0,o,t);let l={scrollLeft:0,scrollTop:0};const c=ha(0);if(r||!r&&!o)if((bu(t)!=="body"||Jd(s))&&(l=pg(t)),r){const p=Ci(t,!0,o,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else s&&(c.x=Ej(s));const i=a.left+l.scrollLeft-c.x,d=a.top+l.scrollTop-c.y;return{x:i,y:d,width:a.width,height:a.height}}function Hm(e){return cs(e).position==="static"}function fC(e,t){return!Bs(e)||cs(e).position==="fixed"?null:t?t(e):e.offsetParent}function kj(e,t){const n=vr(e);if(fg(e))return n;if(!Bs(e)){let s=ma(e);for(;s&&!eu(s);){if($s(s)&&!Hm(s))return s;s=ma(s)}return n}let r=fC(e,t);for(;r&&LB(r)&&Hm(r);)r=fC(r,t);return r&&eu(r)&&Hm(r)&&!Ux(r)?n:r||$B(e)||n}const ZB=async function(e){const t=this.getOffsetParent||kj,n=this.getDimensions,r=await n(e.floating);return{reference:QB(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function YB(e){return cs(e).direction==="rtl"}const XB={convertOffsetParentRelativeRectToViewportRelativeRect:UB,getDocumentElement:Co,getClippingRect:GB,getOffsetParent:kj,getElementRects:ZB,getClientRects:VB,getDimensions:JB,getScale:kl,isElement:$s,isRTL:YB};function ez(e,t){let n=null,r;const s=Co(e);function o(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function a(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),o();const{left:i,top:d,width:p,height:f}=e.getBoundingClientRect();if(l||t(),!p||!f)return;const h=Mf(d),g=Mf(s.clientWidth-(i+p)),m=Mf(s.clientHeight-(d+f)),x=Mf(i),y={rootMargin:-h+"px "+-g+"px "+-m+"px "+-x+"px",threshold:pr(0,Ms(1,c))||1};let w=!0;function S(E){const C=E[0].intersectionRatio;if(C!==c){if(!w)return a();C?a(!1,C):r=setTimeout(()=>{a(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(S,{...y,root:s.ownerDocument})}catch{n=new IntersectionObserver(S,y)}n.observe(e)}return a(!0),o}function tz(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,i=Hx(e),d=s||o?[...i?id(i):[],...id(t)]:[];d.forEach(b=>{s&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=i&&l?ez(i,n):null;let f=-1,h=null;a&&(h=new ResizeObserver(b=>{let[y]=b;y&&y.target===i&&h&&(h.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var w;(w=h)==null||w.observe(t)})),n()}),i&&!c&&h.observe(i),h.observe(t));let g,m=c?Ci(e):null;c&&x();function x(){const b=Ci(e);m&&(b.x!==m.x||b.y!==m.y||b.width!==m.width||b.height!==m.height)&&n(),m=b,g=requestAnimationFrame(x)}return n(),()=>{var b;d.forEach(y=>{s&&y.removeEventListener("scroll",n),o&&y.removeEventListener("resize",n)}),p==null||p(),(b=h)==null||b.disconnect(),h=null,c&&cancelAnimationFrame(g)}}const nz=IB,rz=DB,sz=MB,oz=FB,az=OB,pC=PB,iz=AB,lz=(e,t,n)=>{const r=new Map,s={platform:XB,...n},o={...s.platform,_c:r};return RB(e,t,{...s,platform:o})};var hp=typeof document<"u"?v.useLayoutEffect:v.useEffect;function oh(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!oh(e[r],t[r]))return!1;return!0}if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,s[r]))return!1;for(r=n;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!oh(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function _j(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function hC(e,t){const n=_j(e);return Math.round(t*n)/n}function gC(e){const t=v.useRef(e);return hp(()=>{t.current=e}),t}function uz(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:a}={},transform:l=!0,whileElementsMounted:c,open:i}=e,[d,p]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,h]=v.useState(r);oh(f,r)||h(r);const[g,m]=v.useState(null),[x,b]=v.useState(null),y=v.useCallback(W=>{W!==C.current&&(C.current=W,m(W))},[]),w=v.useCallback(W=>{W!==k.current&&(k.current=W,b(W))},[]),S=o||g,E=a||x,C=v.useRef(null),k=v.useRef(null),T=v.useRef(d),P=c!=null,N=gC(c),U=gC(s),I=v.useCallback(()=>{if(!C.current||!k.current)return;const W={placement:t,strategy:n,middleware:f};U.current&&(W.platform=U.current),lz(C.current,k.current,W).then(F=>{const A={...F,isPositioned:!0};Z.current&&!oh(T.current,A)&&(T.current=A,ka.flushSync(()=>{p(A)}))})},[f,t,n,U]);hp(()=>{i===!1&&T.current.isPositioned&&(T.current.isPositioned=!1,p(W=>({...W,isPositioned:!1})))},[i]);const Z=v.useRef(!1);hp(()=>(Z.current=!0,()=>{Z.current=!1}),[]),hp(()=>{if(S&&(C.current=S),E&&(k.current=E),S&&E){if(N.current)return N.current(S,E,I);I()}},[S,E,I,N,P]);const V=v.useMemo(()=>({reference:C,floating:k,setReference:y,setFloating:w}),[y,w]),Q=v.useMemo(()=>({reference:S,floating:E}),[S,E]),ee=v.useMemo(()=>{const W={position:n,left:0,top:0};if(!Q.floating)return W;const F=hC(Q.floating,d.x),A=hC(Q.floating,d.y);return l?{...W,transform:"translate("+F+"px, "+A+"px)",..._j(Q.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:A}},[n,l,Q.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:I,refs:V,elements:Q,floatingStyles:ee}),[d,I,V,Q,ee])}const cz=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:s}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?pC({element:r.current,padding:s}).fn(n):{}:r?pC({element:r,padding:s}).fn(n):{}}}},dz=(e,t)=>({...nz(e),options:[e,t]}),fz=(e,t)=>({...rz(e),options:[e,t]}),pz=(e,t)=>({...iz(e),options:[e,t]}),hz=(e,t)=>({...sz(e),options:[e,t]}),gz=(e,t)=>({...oz(e),options:[e,t]}),mz=(e,t)=>({...az(e),options:[e,t]}),vz=(e,t)=>({...cz(e),options:[e,t]});var yz="Arrow",jj=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...o}=e;return u.jsx(Ne.svg,{...o,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});jj.displayName=yz;var bz=jj;function Rj(e){const[t,n]=v.useState(void 0);return fn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let a,l;if("borderBoxSize"in o){const c=o.borderBoxSize,i=Array.isArray(c)?c[0]:c;a=i.inlineSize,l=i.blockSize}else a=e.offsetWidth,l=e.offsetHeight;n({width:a,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Kx="Popper",[Pj,hg]=Vr(Kx),[xz,Mj]=Pj(Kx),Oj=e=>{const{__scopePopper:t,children:n}=e,[r,s]=v.useState(null);return u.jsx(xz,{scope:t,anchor:r,onAnchorChange:s,children:n})};Oj.displayName=Kx;var Nj="PopperAnchor",Ij=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,o=Mj(Nj,n),a=v.useRef(null),l=it(t,a);return v.useEffect(()=>{o.onAnchorChange((r==null?void 0:r.current)||a.current)}),r?null:u.jsx(Ne.div,{...s,ref:l})});Ij.displayName=Nj;var qx="PopperContent",[wz,Sz]=Pj(qx),Dj=v.forwardRef((e,t)=>{var J,Ce,Pe,Le,Me,me;const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:i=[],collisionPadding:d=0,sticky:p="partial",hideWhenDetached:f=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,x=Mj(qx,n),[b,y]=v.useState(null),w=it(t,rt=>y(rt)),[S,E]=v.useState(null),C=Rj(S),k=(C==null?void 0:C.width)??0,T=(C==null?void 0:C.height)??0,P=r+(o!=="center"?"-"+o:""),N=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},U=Array.isArray(i)?i:[i],I=U.length>0,Z={padding:N,boundary:U.filter(Ez),altBoundary:I},{refs:V,floatingStyles:Q,placement:ee,isPositioned:W,middlewareData:F}=uz({strategy:"fixed",placement:P,whileElementsMounted:(...rt)=>tz(...rt,{animationFrame:h==="always"}),elements:{reference:x.anchor},middleware:[dz({mainAxis:s+T,alignmentAxis:a}),c&&fz({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?pz():void 0,...Z}),c&&hz({...Z}),gz({...Z,apply:({elements:rt,rects:It,availableWidth:Zt,availableHeight:Wt})=>{const{width:an,height:j}=It.reference,D=rt.floating.style;D.setProperty("--radix-popper-available-width",`${Zt}px`),D.setProperty("--radix-popper-available-height",`${Wt}px`),D.setProperty("--radix-popper-anchor-width",`${an}px`),D.setProperty("--radix-popper-anchor-height",`${j}px`)}}),S&&vz({element:S,padding:l}),Tz({arrowWidth:k,arrowHeight:T}),f&&mz({strategy:"referenceHidden",...Z})]}),[A,Y]=Lj(ee),de=nn(g);fn(()=>{W&&(de==null||de())},[W,de]);const z=(J=F.arrow)==null?void 0:J.x,se=(Ce=F.arrow)==null?void 0:Ce.y,ne=((Pe=F.arrow)==null?void 0:Pe.centerOffset)!==0,[ie,oe]=v.useState();return fn(()=>{b&&oe(window.getComputedStyle(b).zIndex)},[b]),u.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...Q,transform:W?Q.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ie,"--radix-popper-transform-origin":[(Le=F.transformOrigin)==null?void 0:Le.x,(Me=F.transformOrigin)==null?void 0:Me.y].join(" "),...((me=F.hide)==null?void 0:me.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(wz,{scope:n,placedSide:A,onArrowChange:E,arrowX:z,arrowY:se,shouldHideArrow:ne,children:u.jsx(Ne.div,{"data-side":A,"data-align":Y,...m,ref:w,style:{...m.style,animation:W?void 0:"none"}})})})});Dj.displayName=qx;var Aj="PopperArrow",Cz={top:"bottom",right:"left",bottom:"top",left:"right"},Fj=v.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,o=Sz(Aj,r),a=Cz[o.placedSide];return u.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:u.jsx(bz,{...s,ref:n,style:{...s.style,display:"block"}})})});Fj.displayName=Aj;function Ez(e){return e!==null}var Tz=e=>({name:"transformOrigin",options:e,fn(t){var x,b,y;const{placement:n,rects:r,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[i,d]=Lj(n),p={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+l/2,h=(((y=s.arrow)==null?void 0:y.y)??0)+c/2;let g="",m="";return i==="bottom"?(g=a?p:`${f}px`,m=`${-c}px`):i==="top"?(g=a?p:`${f}px`,m=`${r.floating.height+c}px`):i==="right"?(g=`${-c}px`,m=a?p:`${h}px`):i==="left"&&(g=`${r.floating.width+c}px`,m=a?p:`${h}px`),{data:{x:g,y:m}}}});function Lj(e){const[t,n="center"]=e.split("-");return[t,n]}var $j=Oj,Bj=Ij,zj=Dj,Uj=Fj,kz="Portal",gg=v.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[s,o]=v.useState(!1);fn(()=>o(!0),[]);const a=n||s&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?t_.createPortal(u.jsx(Ne.div,{...r,ref:t}),a):null});gg.displayName=kz;function _z(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var or=e=>{const{present:t,children:n}=e,r=jz(t),s=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),o=it(r.ref,Rz(s));return typeof n=="function"||r.isPresent?v.cloneElement(s,{ref:o}):null};or.displayName="Presence";function jz(e){const[t,n]=v.useState(),r=v.useRef({}),s=v.useRef(e),o=v.useRef("none"),a=e?"mounted":"unmounted",[l,c]=_z(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const i=Of(r.current);o.current=l==="mounted"?i:"none"},[l]),fn(()=>{const i=r.current,d=s.current;if(d!==e){const f=o.current,h=Of(i);e?c("MOUNT"):h==="none"||(i==null?void 0:i.display)==="none"?c("UNMOUNT"):c(d&&f!==h?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,c]),fn(()=>{if(t){const i=p=>{const h=Of(r.current).includes(p.animationName);p.target===t&&h&&ka.flushSync(()=>c("ANIMATION_END"))},d=p=>{p.target===t&&(o.current=Of(r.current))};return t.addEventListener("animationstart",d),t.addEventListener("animationcancel",i),t.addEventListener("animationend",i),()=>{t.removeEventListener("animationstart",d),t.removeEventListener("animationcancel",i),t.removeEventListener("animationend",i)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:v.useCallback(i=>{i&&(r.current=getComputedStyle(i)),n(i)},[])}}function Of(e){return(e==null?void 0:e.animationName)||"none"}function Rz(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Km="rovingFocusGroup.onEntryFocus",Pz={bubbles:!1,cancelable:!0},mg="RovingFocusGroup",[Gy,Vj,Mz]=Fx(mg),[Oz,vg]=Vr(mg,[Mz]),[Nz,Iz]=Oz(mg),Hj=v.forwardRef((e,t)=>u.jsx(Gy.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Gy.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Dz,{...e,ref:t})})}));Hj.displayName=mg;var Dz=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:o,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:i,preventScrollOnEntryFocus:d=!1,...p}=e,f=v.useRef(null),h=it(t,f),g=Gd(o),[m=null,x]=pa({prop:a,defaultProp:l,onChange:c}),[b,y]=v.useState(!1),w=nn(i),S=Vj(n),E=v.useRef(!1),[C,k]=v.useState(0);return v.useEffect(()=>{const T=f.current;if(T)return T.addEventListener(Km,w),()=>T.removeEventListener(Km,w)},[w]),u.jsx(Nz,{scope:n,orientation:r,dir:g,loop:s,currentTabStopId:m,onItemFocus:v.useCallback(T=>x(T),[x]),onItemShiftTab:v.useCallback(()=>y(!0),[]),onFocusableItemAdd:v.useCallback(()=>k(T=>T+1),[]),onFocusableItemRemove:v.useCallback(()=>k(T=>T-1),[]),children:u.jsx(Ne.div,{tabIndex:b||C===0?-1:0,"data-orientation":r,...p,ref:h,style:{outline:"none",...e.style},onMouseDown:Se(e.onMouseDown,()=>{E.current=!0}),onFocus:Se(e.onFocus,T=>{const P=!E.current;if(T.target===T.currentTarget&&P&&!b){const N=new CustomEvent(Km,Pz);if(T.currentTarget.dispatchEvent(N),!N.defaultPrevented){const U=S().filter(ee=>ee.focusable),I=U.find(ee=>ee.active),Z=U.find(ee=>ee.id===m),Q=[I,Z,...U].filter(Boolean).map(ee=>ee.ref.current);Wj(Q,d)}}E.current=!1}),onBlur:Se(e.onBlur,()=>y(!1))})})}),Kj="RovingFocusGroupItem",qj=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:o,...a}=e,l=os(),c=o||l,i=Iz(Kj,n),d=i.currentTabStopId===c,p=Vj(n),{onFocusableItemAdd:f,onFocusableItemRemove:h}=i;return v.useEffect(()=>{if(r)return f(),()=>h()},[r,f,h]),u.jsx(Gy.ItemSlot,{scope:n,id:c,focusable:r,active:s,children:u.jsx(Ne.span,{tabIndex:d?0:-1,"data-orientation":i.orientation,...a,ref:t,onMouseDown:Se(e.onMouseDown,g=>{r?i.onItemFocus(c):g.preventDefault()}),onFocus:Se(e.onFocus,()=>i.onItemFocus(c)),onKeyDown:Se(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){i.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const m=Lz(g,i.orientation,i.dir);if(m!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let b=p().filter(y=>y.focusable).map(y=>y.ref.current);if(m==="last")b.reverse();else if(m==="prev"||m==="next"){m==="prev"&&b.reverse();const y=b.indexOf(g.currentTarget);b=i.loop?$z(b,y+1):b.slice(y+1)}setTimeout(()=>Wj(b))}})})})});qj.displayName=Kj;var Az={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Fz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Lz(e,t,n){const r=Fz(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Az[r]}function Wj(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function $z(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Gj=Hj,Jj=qj,Bz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ki=new WeakMap,Nf=new WeakMap,If={},qm=0,Qj=function(e){return e&&(e.host||Qj(e.parentNode))},zz=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Qj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Uz=function(e,t,n,r){var s=zz(t,Array.isArray(e)?e:[e]);If[n]||(If[n]=new WeakMap);var o=If[n],a=[],l=new Set,c=new Set(s),i=function(p){!p||l.has(p)||(l.add(p),i(p.parentNode))};s.forEach(i);var d=function(p){!p||c.has(p)||Array.prototype.forEach.call(p.children,function(f){if(l.has(f))d(f);else try{var h=f.getAttribute(r),g=h!==null&&h!=="false",m=(Ki.get(f)||0)+1,x=(o.get(f)||0)+1;Ki.set(f,m),o.set(f,x),a.push(f),m===1&&g&&Nf.set(f,!0),x===1&&f.setAttribute(n,"true"),g||f.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",f,b)}})};return d(t),l.clear(),qm++,function(){a.forEach(function(p){var f=Ki.get(p)-1,h=o.get(p)-1;Ki.set(p,f),o.set(p,h),f||(Nf.has(p)||p.removeAttribute(r),Nf.delete(p)),h||p.removeAttribute(n)}),qm--,qm||(Ki=new WeakMap,Ki=new WeakMap,Nf=new WeakMap,If={})}},Wx=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=Bz(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),Uz(r,s,n,"aria-hidden")):function(){return null}},_s=function(){return _s=Object.assign||function(t){for(var n,r=1,s=arguments.length;r"u")return oU;var t=aU(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},lU=eR(),_l="data-scroll-locked",uU=function(e,t,n,r){var s=e.left,o=e.top,a=e.right,l=e.gap;return n===void 0&&(n="margin"),` - .`.concat(Hz,` { - overflow: hidden `).concat(r,`; - padding-right: `).concat(l,"px ").concat(r,`; - } - body[`).concat(_l,`] { - overflow: hidden `).concat(r,`; - overscroll-behavior: contain; - `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` - padding-left: `.concat(s,`px; - padding-top: `).concat(o,`px; - padding-right: `).concat(a,`px; - margin-left:0; - margin-top:0; - margin-right: `).concat(l,"px ").concat(r,`; - `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` - } - - .`).concat(gp,` { - right: `).concat(l,"px ").concat(r,`; - } - - .`).concat(mp,` { - margin-right: `).concat(l,"px ").concat(r,`; - } - - .`).concat(gp," .").concat(gp,` { - right: 0 `).concat(r,`; - } - - .`).concat(mp," .").concat(mp,` { - margin-right: 0 `).concat(r,`; - } - - body[`).concat(_l,`] { - `).concat(Kz,": ").concat(l,`px; - } -`)},vC=function(){var e=parseInt(document.body.getAttribute(_l)||"0",10);return isFinite(e)?e:0},cU=function(){v.useEffect(function(){return document.body.setAttribute(_l,(vC()+1).toString()),function(){var e=vC()-1;e<=0?document.body.removeAttribute(_l):document.body.setAttribute(_l,e.toString())}},[])},dU=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;cU();var o=v.useMemo(function(){return iU(s)},[s]);return v.createElement(lU,{styles:uU(o,!t,s,n?"":"!important")})},Jy=!1;if(typeof window<"u")try{var Df=Object.defineProperty({},"passive",{get:function(){return Jy=!0,!0}});window.addEventListener("test",Df,Df),window.removeEventListener("test",Df,Df)}catch{Jy=!1}var qi=Jy?{passive:!1}:!1,fU=function(e){return e.tagName==="TEXTAREA"},tR=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!fU(e)&&n[t]==="visible")},pU=function(e){return tR(e,"overflowY")},hU=function(e){return tR(e,"overflowX")},yC=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=nR(e,r);if(s){var o=rR(e,r),a=o[1],l=o[2];if(a>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},gU=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},mU=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},nR=function(e,t){return e==="v"?pU(t):hU(t)},rR=function(e,t){return e==="v"?gU(t):mU(t)},vU=function(e,t){return e==="h"&&t==="rtl"?-1:1},yU=function(e,t,n,r,s){var o=vU(e,window.getComputedStyle(t).direction),a=o*r,l=n.target,c=t.contains(l),i=!1,d=a>0,p=0,f=0;do{var h=rR(e,l),g=h[0],m=h[1],x=h[2],b=m-x-o*g;(g||b)&&nR(e,l)&&(p+=b,f+=g),l instanceof ShadowRoot?l=l.host:l=l.parentNode}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(d&&(Math.abs(p)<1||!s)||!d&&(Math.abs(f)<1||!s))&&(i=!0),i},Af=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},bC=function(e){return[e.deltaX,e.deltaY]},xC=function(e){return e&&"current"in e?e.current:e},bU=function(e,t){return e[0]===t[0]&&e[1]===t[1]},xU=function(e){return` - .block-interactivity-`.concat(e,` {pointer-events: none;} - .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},wU=0,Wi=[];function SU(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),s=v.useState(wU++)[0],o=v.useState(eR)[0],a=v.useRef(e);v.useEffect(function(){a.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var m=Vz([e.lockRef.current],(e.shards||[]).map(xC),!0).filter(Boolean);return m.forEach(function(x){return x.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),m.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var l=v.useCallback(function(m,x){if("touches"in m&&m.touches.length===2)return!a.current.allowPinchZoom;var b=Af(m),y=n.current,w="deltaX"in m?m.deltaX:y[0]-b[0],S="deltaY"in m?m.deltaY:y[1]-b[1],E,C=m.target,k=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&k==="h"&&C.type==="range")return!1;var T=yC(k,C);if(!T)return!0;if(T?E=k:(E=k==="v"?"h":"v",T=yC(k,C)),!T)return!1;if(!r.current&&"changedTouches"in m&&(w||S)&&(r.current=E),!E)return!0;var P=r.current||E;return yU(P,x,m,P==="h"?w:S,!0)},[]),c=v.useCallback(function(m){var x=m;if(!(!Wi.length||Wi[Wi.length-1]!==o)){var b="deltaY"in x?bC(x):Af(x),y=t.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&bU(E.delta,b)})[0];if(y&&y.should){x.cancelable&&x.preventDefault();return}if(!y){var w=(a.current.shards||[]).map(xC).filter(Boolean).filter(function(E){return E.contains(x.target)}),S=w.length>0?l(x,w[0]):!a.current.noIsolation;S&&x.cancelable&&x.preventDefault()}}},[]),i=v.useCallback(function(m,x,b,y){var w={name:m,delta:x,target:b,should:y,shadowParent:CU(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),d=v.useCallback(function(m){n.current=Af(m),r.current=void 0},[]),p=v.useCallback(function(m){i(m.type,bC(m),m.target,l(m,e.lockRef.current))},[]),f=v.useCallback(function(m){i(m.type,Af(m),m.target,l(m,e.lockRef.current))},[]);v.useEffect(function(){return Wi.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",c,qi),document.addEventListener("touchmove",c,qi),document.addEventListener("touchstart",d,qi),function(){Wi=Wi.filter(function(m){return m!==o}),document.removeEventListener("wheel",c,qi),document.removeEventListener("touchmove",c,qi),document.removeEventListener("touchstart",d,qi)}},[]);var h=e.removeScrollBar,g=e.inert;return v.createElement(v.Fragment,null,g?v.createElement(o,{styles:xU(s)}):null,h?v.createElement(dU,{gapMode:e.gapMode}):null)}function CU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const EU=Yz(Xj,SU);var bg=v.forwardRef(function(e,t){return v.createElement(yg,_s({},e,{ref:t,sideCar:EU}))});bg.classNames=yg.classNames;var Qy=["Enter"," "],TU=["ArrowDown","PageUp","Home"],sR=["ArrowUp","PageDown","End"],kU=[...TU,...sR],_U={ltr:[...Qy,"ArrowRight"],rtl:[...Qy,"ArrowLeft"]},jU={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Qd="Menu",[ld,RU,PU]=Fx(Qd),[Ii,oR]=Vr(Qd,[PU,hg,vg]),xg=hg(),aR=vg(),[MU,Di]=Ii(Qd),[OU,Zd]=Ii(Qd),iR=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:s,onOpenChange:o,modal:a=!0}=e,l=xg(t),[c,i]=v.useState(null),d=v.useRef(!1),p=nn(o),f=Gd(s);return v.useEffect(()=>{const h=()=>{d.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>d.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),u.jsx($j,{...l,children:u.jsx(MU,{scope:t,open:n,onOpenChange:p,content:c,onContentChange:i,children:u.jsx(OU,{scope:t,onClose:v.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:d,dir:f,modal:a,children:r})})})};iR.displayName=Qd;var NU="MenuAnchor",Gx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=xg(n);return u.jsx(Bj,{...s,...r,ref:t})});Gx.displayName=NU;var Jx="MenuPortal",[IU,lR]=Ii(Jx,{forceMount:void 0}),uR=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:s}=e,o=Di(Jx,t);return u.jsx(IU,{scope:t,forceMount:n,children:u.jsx(or,{present:n||o.open,children:u.jsx(gg,{asChild:!0,container:s,children:r})})})};uR.displayName=Jx;var $r="MenuContent",[DU,Qx]=Ii($r),cR=v.forwardRef((e,t)=>{const n=lR($r,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Di($r,e.__scopeMenu),a=Zd($r,e.__scopeMenu);return u.jsx(ld.Provider,{scope:e.__scopeMenu,children:u.jsx(or,{present:r||o.open,children:u.jsx(ld.Slot,{scope:e.__scopeMenu,children:a.modal?u.jsx(AU,{...s,ref:t}):u.jsx(FU,{...s,ref:t})})})})}),AU=v.forwardRef((e,t)=>{const n=Di($r,e.__scopeMenu),r=v.useRef(null),s=it(t,r);return v.useEffect(()=>{const o=r.current;if(o)return Wx(o)},[]),u.jsx(Zx,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Se(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),FU=v.forwardRef((e,t)=>{const n=Di($r,e.__scopeMenu);return u.jsx(Zx,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Zx=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:i,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:h,disableOutsideScroll:g,...m}=e,x=Di($r,n),b=Zd($r,n),y=xg(n),w=aR(n),S=RU(n),[E,C]=v.useState(null),k=v.useRef(null),T=it(t,k,x.onContentChange),P=v.useRef(0),N=v.useRef(""),U=v.useRef(0),I=v.useRef(null),Z=v.useRef("right"),V=v.useRef(0),Q=g?bg:v.Fragment,ee=g?{as:mo,allowPinchZoom:!0}:void 0,W=A=>{var J,Ce;const Y=N.current+A,de=S().filter(Pe=>!Pe.disabled),z=document.activeElement,se=(J=de.find(Pe=>Pe.ref.current===z))==null?void 0:J.textValue,ne=de.map(Pe=>Pe.textValue),ie=JU(ne,Y,se),oe=(Ce=de.find(Pe=>Pe.textValue===ie))==null?void 0:Ce.ref.current;(function Pe(Le){N.current=Le,window.clearTimeout(P.current),Le!==""&&(P.current=window.setTimeout(()=>Pe(""),1e3))})(Y),oe&&setTimeout(()=>oe.focus())};v.useEffect(()=>()=>window.clearTimeout(P.current),[]),Lx();const F=v.useCallback(A=>{var de,z;return Z.current===((de=I.current)==null?void 0:de.side)&&ZU(A,(z=I.current)==null?void 0:z.area)},[]);return u.jsx(DU,{scope:n,searchRef:N,onItemEnter:v.useCallback(A=>{F(A)&&A.preventDefault()},[F]),onItemLeave:v.useCallback(A=>{var Y;F(A)||((Y=k.current)==null||Y.focus(),C(null))},[F]),onTriggerLeave:v.useCallback(A=>{F(A)&&A.preventDefault()},[F]),pointerGraceTimerRef:U,onPointerGraceIntentChange:v.useCallback(A=>{I.current=A},[]),children:u.jsx(Q,{...ee,children:u.jsx(dg,{asChild:!0,trapped:s,onMountAutoFocus:Se(o,A=>{var Y;A.preventDefault(),(Y=k.current)==null||Y.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:u.jsx(cg,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:i,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:h,children:u.jsx(Gj,{asChild:!0,...w,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:C,onEntryFocus:Se(c,A=>{b.isUsingKeyboardRef.current||A.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(zj,{role:"menu","aria-orientation":"vertical","data-state":kR(x.open),"data-radix-menu-content":"",dir:b.dir,...y,...m,ref:T,style:{outline:"none",...m.style},onKeyDown:Se(m.onKeyDown,A=>{const de=A.target.closest("[data-radix-menu-content]")===A.currentTarget,z=A.ctrlKey||A.altKey||A.metaKey,se=A.key.length===1;de&&(A.key==="Tab"&&A.preventDefault(),!z&&se&&W(A.key));const ne=k.current;if(A.target!==ne||!kU.includes(A.key))return;A.preventDefault();const oe=S().filter(J=>!J.disabled).map(J=>J.ref.current);sR.includes(A.key)&&oe.reverse(),WU(oe)}),onBlur:Se(e.onBlur,A=>{A.currentTarget.contains(A.target)||(window.clearTimeout(P.current),N.current="")}),onPointerMove:Se(e.onPointerMove,ud(A=>{const Y=A.target,de=V.current!==A.clientX;if(A.currentTarget.contains(Y)&&de){const z=A.clientX>V.current?"right":"left";Z.current=z,V.current=A.clientX}}))})})})})})})});cR.displayName=$r;var LU="MenuGroup",Yx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ne.div,{role:"group",...r,ref:t})});Yx.displayName=LU;var $U="MenuLabel",dR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ne.div,{...r,ref:t})});dR.displayName=$U;var ah="MenuItem",wC="menu.itemSelect",wg=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...s}=e,o=v.useRef(null),a=Zd(ah,e.__scopeMenu),l=Qx(ah,e.__scopeMenu),c=it(t,o),i=v.useRef(!1),d=()=>{const p=o.current;if(!n&&p){const f=new CustomEvent(wC,{bubbles:!0,cancelable:!0});p.addEventListener(wC,h=>r==null?void 0:r(h),{once:!0}),gj(p,f),f.defaultPrevented?i.current=!1:a.onClose()}};return u.jsx(fR,{...s,ref:c,disabled:n,onClick:Se(e.onClick,d),onPointerDown:p=>{var f;(f=e.onPointerDown)==null||f.call(e,p),i.current=!0},onPointerUp:Se(e.onPointerUp,p=>{var f;i.current||(f=p.currentTarget)==null||f.click()}),onKeyDown:Se(e.onKeyDown,p=>{const f=l.searchRef.current!=="";n||f&&p.key===" "||Qy.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});wg.displayName=ah;var fR=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...o}=e,a=Qx(ah,n),l=aR(n),c=v.useRef(null),i=it(t,c),[d,p]=v.useState(!1),[f,h]=v.useState("");return v.useEffect(()=>{const g=c.current;g&&h((g.textContent??"").trim())},[o.children]),u.jsx(ld.ItemSlot,{scope:n,disabled:r,textValue:s??f,children:u.jsx(Jj,{asChild:!0,...l,focusable:!r,children:u.jsx(Ne.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:i,onPointerMove:Se(e.onPointerMove,ud(g=>{r?a.onItemLeave(g):(a.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Se(e.onPointerLeave,ud(g=>a.onItemLeave(g))),onFocus:Se(e.onFocus,()=>p(!0)),onBlur:Se(e.onBlur,()=>p(!1))})})})}),BU="MenuCheckboxItem",pR=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...s}=e;return u.jsx(yR,{scope:e.__scopeMenu,checked:n,children:u.jsx(wg,{role:"menuitemcheckbox","aria-checked":ih(n)?"mixed":n,...s,ref:t,"data-state":ew(n),onSelect:Se(s.onSelect,()=>r==null?void 0:r(ih(n)?!0:!n),{checkForDefaultPrevented:!1})})})});pR.displayName=BU;var hR="MenuRadioGroup",[zU,UU]=Ii(hR,{value:void 0,onValueChange:()=>{}}),gR=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...s}=e,o=nn(r);return u.jsx(zU,{scope:e.__scopeMenu,value:n,onValueChange:o,children:u.jsx(Yx,{...s,ref:t})})});gR.displayName=hR;var mR="MenuRadioItem",vR=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=UU(mR,e.__scopeMenu),o=n===s.value;return u.jsx(yR,{scope:e.__scopeMenu,checked:o,children:u.jsx(wg,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":ew(o),onSelect:Se(r.onSelect,()=>{var a;return(a=s.onValueChange)==null?void 0:a.call(s,n)},{checkForDefaultPrevented:!1})})})});vR.displayName=mR;var Xx="MenuItemIndicator",[yR,VU]=Ii(Xx,{checked:!1}),bR=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...s}=e,o=VU(Xx,n);return u.jsx(or,{present:r||ih(o.checked)||o.checked===!0,children:u.jsx(Ne.span,{...s,ref:t,"data-state":ew(o.checked)})})});bR.displayName=Xx;var HU="MenuSeparator",xR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ne.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});xR.displayName=HU;var KU="MenuArrow",wR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=xg(n);return u.jsx(Uj,{...s,...r,ref:t})});wR.displayName=KU;var qU="MenuSub",[qse,SR]=Ii(qU),dc="MenuSubTrigger",CR=v.forwardRef((e,t)=>{const n=Di(dc,e.__scopeMenu),r=Zd(dc,e.__scopeMenu),s=SR(dc,e.__scopeMenu),o=Qx(dc,e.__scopeMenu),a=v.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=o,i={__scopeMenu:e.__scopeMenu},d=v.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return v.useEffect(()=>d,[d]),v.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),c(null)}},[l,c]),u.jsx(Gx,{asChild:!0,...i,children:u.jsx(fR,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":kR(n.open),...e,ref:ag(t,s.onTriggerChange),onClick:p=>{var f;(f=e.onClick)==null||f.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Se(e.onPointerMove,ud(p=>{o.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(o.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:Se(e.onPointerLeave,ud(p=>{var h,g;d();const f=(h=n.content)==null?void 0:h.getBoundingClientRect();if(f){const m=(g=n.content)==null?void 0:g.dataset.side,x=m==="right",b=x?-5:5,y=f[x?"left":"right"],w=f[x?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+b,y:p.clientY},{x:y,y:f.top},{x:w,y:f.top},{x:w,y:f.bottom},{x:y,y:f.bottom}],side:m}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Se(e.onKeyDown,p=>{var h;const f=o.searchRef.current!=="";e.disabled||f&&p.key===" "||_U[r.dir].includes(p.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),p.preventDefault())})})})});CR.displayName=dc;var ER="MenuSubContent",TR=v.forwardRef((e,t)=>{const n=lR($r,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Di($r,e.__scopeMenu),a=Zd($r,e.__scopeMenu),l=SR(ER,e.__scopeMenu),c=v.useRef(null),i=it(t,c);return u.jsx(ld.Provider,{scope:e.__scopeMenu,children:u.jsx(or,{present:r||o.open,children:u.jsx(ld.Slot,{scope:e.__scopeMenu,children:u.jsx(Zx,{id:l.contentId,"aria-labelledby":l.triggerId,...s,ref:i,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var p;a.isUsingKeyboardRef.current&&((p=c.current)==null||p.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:Se(e.onFocusOutside,d=>{d.target!==l.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Se(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:Se(e.onKeyDown,d=>{var h;const p=d.currentTarget.contains(d.target),f=jU[a.dir].includes(d.key);p&&f&&(o.onOpenChange(!1),(h=l.trigger)==null||h.focus(),d.preventDefault())})})})})})});TR.displayName=ER;function kR(e){return e?"open":"closed"}function ih(e){return e==="indeterminate"}function ew(e){return ih(e)?"indeterminate":e?"checked":"unchecked"}function WU(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function GU(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function JU(e,t,n){const s=t.length>1&&Array.from(t).every(i=>i===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=GU(e,Math.max(o,0));s.length===1&&(a=a.filter(i=>i!==n));const c=a.find(i=>i.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function QU(e,t){const{x:n,y:r}=e;let s=!1;for(let o=0,a=t.length-1;or!=d>r&&n<(i-l)*(r-c)/(d-c)+l&&(s=!s)}return s}function ZU(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return QU(n,t)}function ud(e){return t=>t.pointerType==="mouse"?e(t):void 0}var YU=iR,XU=Gx,e5=uR,t5=cR,n5=Yx,r5=dR,s5=wg,o5=pR,a5=gR,i5=vR,l5=bR,u5=xR,c5=wR,d5=CR,f5=TR,tw="DropdownMenu",[p5,Wse]=Vr(tw,[oR]),Gn=oR(),[h5,_R]=p5(tw),nw=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:s,defaultOpen:o,onOpenChange:a,modal:l=!0}=e,c=Gn(t),i=v.useRef(null),[d=!1,p]=pa({prop:s,defaultProp:o,onChange:a});return u.jsx(h5,{scope:t,triggerId:os(),triggerRef:i,contentId:os(),open:d,onOpenChange:p,onOpenToggle:v.useCallback(()=>p(f=>!f),[p]),modal:l,children:u.jsx(YU,{...c,open:d,onOpenChange:p,dir:r,modal:l,children:n})})};nw.displayName=tw;var jR="DropdownMenuTrigger",rw=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=e,o=_R(jR,n),a=Gn(n);return u.jsx(XU,{asChild:!0,...a,children:u.jsx(Ne.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:ag(t,o.triggerRef),onPointerDown:Se(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(o.onOpenToggle(),o.open||l.preventDefault())}),onKeyDown:Se(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&o.onOpenToggle(),l.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});rw.displayName=jR;var g5="DropdownMenuPortal",RR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Gn(t);return u.jsx(e5,{...r,...n})};RR.displayName=g5;var PR="DropdownMenuContent",MR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=_R(PR,n),o=Gn(n),a=v.useRef(!1);return u.jsx(t5,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:t,onCloseAutoFocus:Se(e.onCloseAutoFocus,l=>{var c;a.current||(c=s.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:Se(e.onInteractOutside,l=>{const c=l.detail.originalEvent,i=c.button===0&&c.ctrlKey===!0,d=c.button===2||i;(!s.modal||d)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});MR.displayName=PR;var m5="DropdownMenuGroup",v5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(n5,{...s,...r,ref:t})});v5.displayName=m5;var y5="DropdownMenuLabel",OR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(r5,{...s,...r,ref:t})});OR.displayName=y5;var b5="DropdownMenuItem",NR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(s5,{...s,...r,ref:t})});NR.displayName=b5;var x5="DropdownMenuCheckboxItem",IR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(o5,{...s,...r,ref:t})});IR.displayName=x5;var w5="DropdownMenuRadioGroup",S5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(a5,{...s,...r,ref:t})});S5.displayName=w5;var C5="DropdownMenuRadioItem",DR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(i5,{...s,...r,ref:t})});DR.displayName=C5;var E5="DropdownMenuItemIndicator",AR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(l5,{...s,...r,ref:t})});AR.displayName=E5;var T5="DropdownMenuSeparator",FR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(u5,{...s,...r,ref:t})});FR.displayName=T5;var k5="DropdownMenuArrow",_5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(c5,{...s,...r,ref:t})});_5.displayName=k5;var j5="DropdownMenuSubTrigger",LR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(d5,{...s,...r,ref:t})});LR.displayName=j5;var R5="DropdownMenuSubContent",$R=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(f5,{...s,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});$R.displayName=R5;var P5=nw,M5=rw,O5=RR,BR=MR,zR=OR,UR=NR,VR=IR,HR=DR,KR=AR,Ra=FR,qR=LR,WR=$R;const Eo=P5,To=M5,N5=v.forwardRef(({className:e,inset:t,children:n,...r},s)=>u.jsxs(qR,{ref:s,className:ge("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,u.jsx(R3,{className:"ml-auto h-4 w-4"})]}));N5.displayName=qR.displayName;const I5=v.forwardRef(({className:e,...t},n)=>u.jsx(WR,{ref:n,className:ge("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));I5.displayName=WR.displayName;const ps=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(O5,{children:u.jsx(BR,{ref:r,sideOffset:t,className:ge("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));ps.displayName=BR.displayName;const ft=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(UR,{ref:r,className:ge("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));ft.displayName=UR.displayName;const GR=v.forwardRef(({className:e,children:t,checked:n,...r},s)=>u.jsxs(VR,{ref:s,className:ge("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KR,{children:u.jsx(cj,{className:"h-4 w-4"})})}),t]}));GR.displayName=VR.displayName;const D5=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(HR,{ref:r,className:ge("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KR,{children:u.jsx(N3,{className:"h-2 w-2 fill-current"})})}),t]}));D5.displayName=HR.displayName;const Ai=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(zR,{ref:r,className:ge("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));Ai.displayName=zR.displayName;const Pa=v.forwardRef(({className:e,...t},n)=>u.jsx(Ra,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));Pa.displayName=Ra.displayName;function A5(){const{t:e,i18n:t}=ze(),n=r=>{t.changeLanguage(r),localStorage.setItem("i18nextLng",r),window.location.reload()};return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"outline",size:"icon",children:[u.jsx(z3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all"}),u.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(ft,{className:t.language==="pt-BR"?"font-bold":"",onClick:()=>n("pt-BR"),children:e("header.language.portuguese")}),u.jsx(ft,{className:t.language==="en-US"?"font-bold":"",onClick:()=>n("en-US"),children:e("header.language.english")}),u.jsx(ft,{className:t.language==="es-ES"?"font-bold":"",onClick:()=>n("es-ES"),children:e("header.language.spanish")}),u.jsx(ft,{className:t.language==="fr-FR"?"font-bold":"",onClick:()=>n("fr-FR"),children:e("header.language.french")})]})]})}function F5(){const{t:e}=ze(),{setTheme:t}=R_();return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"outline",size:"icon",children:[u.jsx(G3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),u.jsx(K3,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),u.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(ft,{onClick:()=>t("light"),children:e("header.theme.light")}),u.jsx(ft,{onClick:()=>t("dark"),children:e("header.theme.dark")}),u.jsx(ft,{onClick:()=>t("system"),children:e("header.theme.system")})]})]})}var sw="Avatar",[L5,Gse]=Vr(sw),[$5,JR]=L5(sw),QR=v.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[s,o]=v.useState("idle");return u.jsx($5,{scope:n,imageLoadingStatus:s,onImageLoadingStatusChange:o,children:u.jsx(Ne.span,{...r,ref:t})})});QR.displayName=sw;var ZR="AvatarImage",YR=v.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:s=()=>{},...o}=e,a=JR(ZR,n),l=B5(r),c=nn(i=>{s(i),a.onImageLoadingStatusChange(i)});return fn(()=>{l!=="idle"&&c(l)},[l,c]),l==="loaded"?u.jsx(Ne.img,{...o,ref:t,src:r}):null});YR.displayName=ZR;var XR="AvatarFallback",eP=v.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...s}=e,o=JR(XR,n),[a,l]=v.useState(r===void 0);return v.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>l(!0),r);return()=>window.clearTimeout(c)}},[r]),a&&o.imageLoadingStatus!=="loaded"?u.jsx(Ne.span,{...s,ref:t}):null});eP.displayName=XR;function B5(e){const[t,n]=v.useState("idle");return fn(()=>{if(!e){n("error");return}let r=!0;const s=new window.Image,o=a=>()=>{r&&n(a)};return n("loading"),s.onload=o("loaded"),s.onerror=o("error"),s.src=e,()=>{r=!1}},[e]),t}var tP=QR,nP=YR,rP=eP;const Sg=v.forwardRef(({className:e,...t},n)=>u.jsx(tP,{ref:n,className:ge("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Sg.displayName=tP.displayName;const Cg=v.forwardRef(({className:e,...t},n)=>u.jsx(nP,{ref:n,className:ge("aspect-square h-full w-full",e),...t}));Cg.displayName=nP.displayName;const z5=v.forwardRef(({className:e,...t},n)=>u.jsx(rP,{ref:n,className:ge("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));z5.displayName=rP.displayName;var ow="Dialog",[sP,Jse]=Vr(ow),[U5,hs]=sP(ow),oP=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:a=!0}=e,l=v.useRef(null),c=v.useRef(null),[i=!1,d]=pa({prop:r,defaultProp:s,onChange:o});return u.jsx(U5,{scope:t,triggerRef:l,contentRef:c,contentId:os(),titleId:os(),descriptionId:os(),open:i,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(p=>!p),[d]),modal:a,children:n})};oP.displayName=ow;var aP="DialogTrigger",iP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(aP,n),o=it(t,s.triggerRef);return u.jsx(Ne.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":lw(s.open),...r,ref:o,onClick:Se(e.onClick,s.onOpenToggle)})});iP.displayName=aP;var aw="DialogPortal",[V5,lP]=sP(aw,{forceMount:void 0}),uP=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:s}=e,o=hs(aw,t);return u.jsx(V5,{scope:t,forceMount:n,children:v.Children.map(r,a=>u.jsx(or,{present:n||o.open,children:u.jsx(gg,{asChild:!0,container:s,children:a})}))})};uP.displayName=aw;var lh="DialogOverlay",cP=v.forwardRef((e,t)=>{const n=lP(lh,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=hs(lh,e.__scopeDialog);return o.modal?u.jsx(or,{present:r||o.open,children:u.jsx(H5,{...s,ref:t})}):null});cP.displayName=lh;var H5=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(lh,n);return u.jsx(bg,{as:mo,allowPinchZoom:!0,shards:[s.contentRef],children:u.jsx(Ne.div,{"data-state":lw(s.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Ei="DialogContent",dP=v.forwardRef((e,t)=>{const n=lP(Ei,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=hs(Ei,e.__scopeDialog);return u.jsx(or,{present:r||o.open,children:o.modal?u.jsx(K5,{...s,ref:t}):u.jsx(q5,{...s,ref:t})})});dP.displayName=Ei;var K5=v.forwardRef((e,t)=>{const n=hs(Ei,e.__scopeDialog),r=v.useRef(null),s=it(t,n.contentRef,r);return v.useEffect(()=>{const o=r.current;if(o)return Wx(o)},[]),u.jsx(fP,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Se(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Se(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0;(a.button===2||l)&&o.preventDefault()}),onFocusOutside:Se(e.onFocusOutside,o=>o.preventDefault())})}),q5=v.forwardRef((e,t)=>{const n=hs(Ei,e.__scopeDialog),r=v.useRef(!1),s=v.useRef(!1);return u.jsx(fP,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,o),o.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var c,i;(c=e.onInteractOutside)==null||c.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=o.target;((i=n.triggerRef.current)==null?void 0:i.contains(a))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),fP=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...a}=e,l=hs(Ei,n),c=v.useRef(null),i=it(t,c);return Lx(),u.jsxs(u.Fragment,{children:[u.jsx(dg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:u.jsx(cg,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":lw(l.open),...a,ref:i,onDismiss:()=>l.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(W5,{titleId:l.titleId}),u.jsx(J5,{contentRef:c,descriptionId:l.descriptionId})]})]})}),iw="DialogTitle",pP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(iw,n);return u.jsx(Ne.h2,{id:s.titleId,...r,ref:t})});pP.displayName=iw;var hP="DialogDescription",gP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(hP,n);return u.jsx(Ne.p,{id:s.descriptionId,...r,ref:t})});gP.displayName=hP;var mP="DialogClose",vP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(mP,n);return u.jsx(Ne.button,{type:"button",...r,ref:t,onClick:Se(e.onClick,()=>s.onOpenChange(!1))})});vP.displayName=mP;function lw(e){return e?"open":"closed"}var yP="DialogTitleWarning",[Qse,bP]=X3(yP,{contentName:Ei,titleName:iw,docsSlug:"dialog"}),W5=({titleId:e})=>{const t=bP(yP),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. - -If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. - -For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return v.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},G5="DialogDescriptionWarning",J5=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${bP(G5).contentName}}.`;return v.useEffect(()=>{var o;const s=(o=e.current)==null?void 0:o.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},Q5=oP,Z5=iP,Y5=uP,xP=cP,wP=dP,SP=pP,CP=gP,EP=vP;const Tt=Q5,Nt=Z5,X5=Y5,TP=EP,kP=v.forwardRef(({className:e,...t},n)=>u.jsx(xP,{ref:n,className:ge("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));kP.displayName=xP.displayName;const xt=v.forwardRef(({className:e,children:t,closeBtn:n=!0,...r},s)=>u.jsx(X5,{children:u.jsx(kP,{className:"fixed inset-0 grid place-items-center overflow-y-auto",children:u.jsxs(wP,{ref:s,className:ge("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:m-4 sm:rounded-lg md:w-full",e),...r,children:[t,n&&u.jsxs(EP,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(Q3,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})})}));xt.displayName=wP.displayName;const wt=({className:e,...t})=>u.jsx("div",{className:ge("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});wt.displayName="DialogHeader";const rn=({className:e,...t})=>u.jsx("div",{className:ge("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});rn.displayName="DialogFooter";const Ut=v.forwardRef(({className:e,...t},n)=>u.jsx(SP,{ref:n,className:ge("text-lg font-semibold leading-none tracking-tight",e),...t}));Ut.displayName=SP.displayName;const Fi=v.forwardRef(({className:e,...t},n)=>u.jsx(CP,{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));Fi.displayName=CP.displayName;function _P({instanceId:e}){const[t,n]=v.useState(!1),r=An(),s=()=>{M_(),r("/manager/login")},o=()=>{r("/manager/")},{data:a}=hj({instanceId:e});return u.jsxs("header",{className:"flex items-center justify-between px-4 py-2",children:[u.jsxs(nd,{to:"/manager",onClick:o,className:"flex h-8 items-center gap-4",children:[u.jsx("img",{src:"/assets/images/evolution-logo.png",alt:"Logo",className:"h-full"}),u.jsx("span",{children:"Evolution Manager"})]}),u.jsxs("div",{className:"flex items-center gap-4",children:[e&&u.jsx(Sg,{className:"h-8 w-8",children:u.jsx(Cg,{src:(a==null?void 0:a.profilePicUrl)||"/assets/images/evolution-logo.png",alt:a==null?void 0:a.name})}),u.jsx(A5,{}),u.jsx(F5,{}),u.jsx(q,{onClick:()=>n(!0),variant:"destructive",size:"icon",children:u.jsx(D3,{size:"18"})})]}),t&&u.jsx(Tt,{onOpenChange:n,open:t,children:u.jsxs(xt,{children:[u.jsx(TP,{}),u.jsx(wt,{children:"Deseja realmente sair?"}),u.jsx(rn,{children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx(q,{onClick:()=>n(!1),size:"sm",variant:"outline",children:"Cancelar"}),u.jsx(q,{onClick:s,variant:"destructive",children:"Sair"})]})})]})})]})}const jP=v.createContext(null),nt=()=>{const e=v.useContext(jP);if(!e)throw new Error("useInstance must be used within an InstanceProvider");return e},eV=({children:e})=>{const t=So(),[n,r]=v.useState(null),{data:s,refetch:o}=hj({instanceId:n});return v.useEffect(()=>{t.instanceId?r(t.instanceId):r(null)},[t]),u.jsx(jP.Provider,{value:{instance:s??null,reloadInstance:async()=>{await o()}},children:e})};var uw="Collapsible",[tV,Zse]=Vr(uw),[nV,cw]=tV(uw),RP=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:a,...l}=e,[c=!1,i]=pa({prop:r,defaultProp:s,onChange:a});return u.jsx(nV,{scope:n,disabled:o,contentId:os(),open:c,onOpenToggle:v.useCallback(()=>i(d=>!d),[i]),children:u.jsx(Ne.div,{"data-state":fw(c),"data-disabled":o?"":void 0,...l,ref:t})})});RP.displayName=uw;var PP="CollapsibleTrigger",MP=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=cw(PP,n);return u.jsx(Ne.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":fw(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Se(e.onClick,s.onOpenToggle)})});MP.displayName=PP;var dw="CollapsibleContent",OP=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=cw(dw,e.__scopeCollapsible);return u.jsx(or,{present:n||s.open,children:({present:o})=>u.jsx(rV,{...r,ref:t,present:o})})});OP.displayName=dw;var rV=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,a=cw(dw,n),[l,c]=v.useState(r),i=v.useRef(null),d=it(t,i),p=v.useRef(0),f=p.current,h=v.useRef(0),g=h.current,m=a.open||l,x=v.useRef(m),b=v.useRef();return v.useEffect(()=>{const y=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(y)},[]),fn(()=>{const y=i.current;if(y){b.current=b.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const w=y.getBoundingClientRect();p.current=w.height,h.current=w.width,x.current||(y.style.transitionDuration=b.current.transitionDuration,y.style.animationName=b.current.animationName),c(r)}},[a.open,r]),u.jsx(Ne.div,{"data-state":fw(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...o,ref:d,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:m&&s})});function fw(e){return e?"open":"closed"}var sV=RP;const oV=sV,aV=MP,iV=OP;function lV(){const{t:e}=ze(),t=v.useMemo(()=>[{id:"dashboard",title:e("sidebar.dashboard"),icon:U3,path:"dashboard"},{navLabel:!0,title:e("sidebar.configurations"),icon:Oi,children:[{id:"settings",title:e("sidebar.settings"),path:"settings"},{id:"proxy",title:e("sidebar.proxy"),path:"proxy"}]},{title:e("sidebar.events"),icon:B3,children:[{id:"webhook",title:e("sidebar.webhook"),path:"webhook"},{id:"websocket",title:e("sidebar.websocket"),path:"websocket"},{id:"rabbitmq",title:e("sidebar.rabbitmq"),path:"rabbitmq"},{id:"sqs",title:e("sidebar.sqs"),path:"sqs"}]},{title:e("sidebar.integrations"),icon:pj,children:[{id:"evolutionBot",title:e("sidebar.evolutionBot"),path:"evolutionBot"},{id:"chatwoot",title:e("sidebar.chatwoot"),path:"chatwoot"},{id:"typebot",title:e("sidebar.typebot"),path:"typebot"},{id:"openai",title:e("sidebar.openai"),path:"openai"},{id:"dify",title:e("sidebar.dify"),path:"dify"},{id:"flowise",title:e("sidebar.flowise"),path:"flowise"}]},{id:"documentation",title:e("sidebar.documentation"),icon:L3,link:"https://doc.evolution-api.com",divider:!0},{id:"postman",title:e("sidebar.postman"),icon:O3,link:"https://evolution-api.com/postman"},{id:"discord",title:e("sidebar.discord"),icon:ug,link:"https://evolution-api.com/discord"},{id:"support-premium",title:e("sidebar.supportPremium"),icon:V3,link:"https://evolution-api.com/suporte-pro"}],[e]),n=An(),{pathname:r}=pu(),{instance:s}=nt(),o=l=>{!l||!s||(l.path&&n(`/manager/instance/${s.id}/${l.path}`),l.link&&window.open(l.link,"_blank"))},a=v.useMemo(()=>t.map(l=>{var c;return{...l,children:"children"in l?(c=l.children)==null?void 0:c.map(i=>({...i,isActive:"path"in i?r.includes(i.path):!1})):void 0,isActive:"path"in l&&l.path?r.includes(l.path):!1}}).map(l=>{var c;return{...l,isActive:l.isActive||"children"in l&&((c=l.children)==null?void 0:c.some(i=>i.isActive))}}),[t,r]);return u.jsx("ul",{className:"flex h-full w-full flex-col gap-2 border-r border-border px-2",children:a.map(l=>u.jsx("li",{className:"divider"in l?"mt-auto":void 0,children:l.children?u.jsxs(oV,{defaultOpen:l.isActive,children:[u.jsx(aV,{asChild:!0,children:u.jsxs(q,{className:ge("flex w-full items-center justify-start gap-2"),variant:l.isActive?"secondary":"link",children:[l.icon&&u.jsx(l.icon,{size:"15"}),u.jsx("span",{children:l.title}),u.jsx(lg,{size:"15",className:"ml-auto"})]})}),u.jsx(iV,{children:u.jsx("ul",{className:"my-4 ml-6 flex flex-col gap-2 text-sm",children:l.children.map(c=>u.jsx("li",{children:u.jsx("button",{onClick:()=>o(c),className:ge(c.isActive?"text-foreground":"text-muted-foreground"),children:u.jsx("span",{className:"nav-label",children:c.title})})},c.id))})})]}):u.jsxs(q,{className:ge("relative flex w-full items-center justify-start gap-2",l.isActive&&"pointer-events-none"),variant:l.isActive?"secondary":"link",children:["link"in l&&u.jsx("a",{href:l.link,target:"_blank",rel:"noreferrer",className:"absolute inset-0 h-full w-full"}),"path"in l&&u.jsx(nd,{to:`/manager/instance/${s==null?void 0:s.id}/${l.path}`,className:"absolute inset-0 h-full w-full"}),l.icon&&u.jsx(l.icon,{size:"15"}),u.jsx("span",{children:l.title})]})},l.title))})}function Zy(e,[t,n]){return Math.min(n,Math.max(t,e))}function uV(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var pw="ScrollArea",[NP,Yse]=Vr(pw),[cV,Hr]=NP(pw),IP=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...a}=e,[l,c]=v.useState(null),[i,d]=v.useState(null),[p,f]=v.useState(null),[h,g]=v.useState(null),[m,x]=v.useState(null),[b,y]=v.useState(0),[w,S]=v.useState(0),[E,C]=v.useState(!1),[k,T]=v.useState(!1),P=it(t,U=>c(U)),N=Gd(s);return u.jsx(cV,{scope:n,type:r,dir:N,scrollHideDelay:o,scrollArea:l,viewport:i,onViewportChange:d,content:p,onContentChange:f,scrollbarX:h,onScrollbarXChange:g,scrollbarXEnabled:E,onScrollbarXEnabledChange:C,scrollbarY:m,onScrollbarYChange:x,scrollbarYEnabled:k,onScrollbarYEnabledChange:T,onCornerWidthChange:y,onCornerHeightChange:S,children:u.jsx(Ne.div,{dir:N,...a,ref:P,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":w+"px",...e.style}})})});IP.displayName=pw;var DP="ScrollAreaViewport",AP=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,a=Hr(DP,n),l=v.useRef(null),c=it(t,l,a.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),u.jsx(Ne.div,{"data-radix-scroll-area-viewport":"",...o,ref:c,style:{overflowX:a.scrollbarXEnabled?"scroll":"hidden",overflowY:a.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:a.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});AP.displayName=DP;var Hs="ScrollAreaScrollbar",hw=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:a}=s,l=e.orientation==="horizontal";return v.useEffect(()=>(l?o(!0):a(!0),()=>{l?o(!1):a(!1)}),[l,o,a]),s.type==="hover"?u.jsx(dV,{...r,ref:t,forceMount:n}):s.type==="scroll"?u.jsx(fV,{...r,ref:t,forceMount:n}):s.type==="auto"?u.jsx(FP,{...r,ref:t,forceMount:n}):s.type==="always"?u.jsx(gw,{...r,ref:t}):null});hw.displayName=Hs;var dV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),[o,a]=v.useState(!1);return v.useEffect(()=>{const l=s.scrollArea;let c=0;if(l){const i=()=>{window.clearTimeout(c),a(!0)},d=()=>{c=window.setTimeout(()=>a(!1),s.scrollHideDelay)};return l.addEventListener("pointerenter",i),l.addEventListener("pointerleave",d),()=>{window.clearTimeout(c),l.removeEventListener("pointerenter",i),l.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),u.jsx(or,{present:n||o,children:u.jsx(FP,{"data-state":o?"visible":"hidden",...r,ref:t})})}),fV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),o=e.orientation==="horizontal",a=Tg(()=>c("SCROLL_END"),100),[l,c]=uV("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(l==="idle"){const i=window.setTimeout(()=>c("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(i)}},[l,s.scrollHideDelay,c]),v.useEffect(()=>{const i=s.viewport,d=o?"scrollLeft":"scrollTop";if(i){let p=i[d];const f=()=>{const h=i[d];p!==h&&(c("SCROLL"),a()),p=h};return i.addEventListener("scroll",f),()=>i.removeEventListener("scroll",f)}},[s.viewport,o,c,a]),u.jsx(or,{present:n||l!=="hidden",children:u.jsx(gw,{"data-state":l==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Se(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Se(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),FP=v.forwardRef((e,t)=>{const n=Hr(Hs,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,a]=v.useState(!1),l=e.orientation==="horizontal",c=Tg(()=>{if(n.viewport){const i=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,s=Hr(Hs,e.__scopeScrollArea),o=v.useRef(null),a=v.useRef(0),[l,c]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),i=UP(l.viewport,l.content),d={...r,sizes:l,onSizesChange:c,hasThumb:i>0&&i<1,onThumbChange:f=>o.current=f,onThumbPointerUp:()=>a.current=0,onThumbPointerDown:f=>a.current=f};function p(f,h){return yV(f,a.current,l,h)}return n==="horizontal"?u.jsx(pV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollLeft,h=SC(f,l,s.dir);o.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollLeft=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollLeft=p(f,s.dir))}}):n==="vertical"?u.jsx(hV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollTop,h=SC(f,l);o.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollTop=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollTop=p(f))}}):null}),pV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Hr(Hs,e.__scopeScrollArea),[a,l]=v.useState(),c=v.useRef(null),i=it(t,c,o.onScrollbarXChange);return v.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),u.jsx($P,{"data-orientation":"horizontal",...s,ref:i,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Eg(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollLeft+d.deltaX;e.onWheelScroll(f),HP(f,p)&&d.preventDefault()}},onResize:()=>{c.current&&o.viewport&&a&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:ch(a.paddingLeft),paddingEnd:ch(a.paddingRight)}})}})}),hV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Hr(Hs,e.__scopeScrollArea),[a,l]=v.useState(),c=v.useRef(null),i=it(t,c,o.onScrollbarYChange);return v.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),u.jsx($P,{"data-orientation":"vertical",...s,ref:i,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Eg(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollTop+d.deltaY;e.onWheelScroll(f),HP(f,p)&&d.preventDefault()}},onResize:()=>{c.current&&o.viewport&&a&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:ch(a.paddingTop),paddingEnd:ch(a.paddingBottom)}})}})}),[gV,LP]=NP(Hs),$P=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:a,onThumbPointerDown:l,onThumbPositionChange:c,onDragScroll:i,onWheelScroll:d,onResize:p,...f}=e,h=Hr(Hs,n),[g,m]=v.useState(null),x=it(t,P=>m(P)),b=v.useRef(null),y=v.useRef(""),w=h.viewport,S=r.content-r.viewport,E=nn(d),C=nn(c),k=Tg(p,10);function T(P){if(b.current){const N=P.clientX-b.current.left,U=P.clientY-b.current.top;i({x:N,y:U})}}return v.useEffect(()=>{const P=N=>{const U=N.target;(g==null?void 0:g.contains(U))&&E(N,S)};return document.addEventListener("wheel",P,{passive:!1}),()=>document.removeEventListener("wheel",P,{passive:!1})},[w,g,S,E]),v.useEffect(C,[r,C]),tu(g,k),tu(h.content,k),u.jsx(gV,{scope:n,scrollbar:g,hasThumb:s,onThumbChange:nn(o),onThumbPointerUp:nn(a),onThumbPositionChange:C,onThumbPointerDown:nn(l),children:u.jsx(Ne.div,{...f,ref:x,style:{position:"absolute",...f.style},onPointerDown:Se(e.onPointerDown,P=>{P.button===0&&(P.target.setPointerCapture(P.pointerId),b.current=g.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),T(P))}),onPointerMove:Se(e.onPointerMove,T),onPointerUp:Se(e.onPointerUp,P=>{const N=P.target;N.hasPointerCapture(P.pointerId)&&N.releasePointerCapture(P.pointerId),document.body.style.webkitUserSelect=y.current,h.viewport&&(h.viewport.style.scrollBehavior=""),b.current=null})})})}),uh="ScrollAreaThumb",BP=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=LP(uh,e.__scopeScrollArea);return u.jsx(or,{present:n||s.hasThumb,children:u.jsx(mV,{ref:t,...r})})}),mV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=Hr(uh,n),a=LP(uh,n),{onThumbPositionChange:l}=a,c=it(t,p=>a.onThumbChange(p)),i=v.useRef(),d=Tg(()=>{i.current&&(i.current(),i.current=void 0)},100);return v.useEffect(()=>{const p=o.viewport;if(p){const f=()=>{if(d(),!i.current){const h=bV(p,l);i.current=h,l()}};return l(),p.addEventListener("scroll",f),()=>p.removeEventListener("scroll",f)}},[o.viewport,d,l]),u.jsx(Ne.div,{"data-state":a.hasThumb?"visible":"hidden",...s,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Se(e.onPointerDownCapture,p=>{const h=p.target.getBoundingClientRect(),g=p.clientX-h.left,m=p.clientY-h.top;a.onThumbPointerDown({x:g,y:m})}),onPointerUp:Se(e.onPointerUp,a.onThumbPointerUp)})});BP.displayName=uh;var mw="ScrollAreaCorner",zP=v.forwardRef((e,t)=>{const n=Hr(mw,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(vV,{...e,ref:t}):null});zP.displayName=mw;var vV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=Hr(mw,n),[o,a]=v.useState(0),[l,c]=v.useState(0),i=!!(o&&l);return tu(s.scrollbarX,()=>{var p;const d=((p=s.scrollbarX)==null?void 0:p.offsetHeight)||0;s.onCornerHeightChange(d),c(d)}),tu(s.scrollbarY,()=>{var p;const d=((p=s.scrollbarY)==null?void 0:p.offsetWidth)||0;s.onCornerWidthChange(d),a(d)}),i?u.jsx(Ne.div,{...r,ref:t,style:{width:o,height:l,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function ch(e){return e?parseInt(e,10):0}function UP(e,t){const n=e/t;return isNaN(n)?0:n}function Eg(e){const t=UP(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function yV(e,t,n,r="ltr"){const s=Eg(n),o=s/2,a=t||o,l=s-a,c=n.scrollbar.paddingStart+a,i=n.scrollbar.size-n.scrollbar.paddingEnd-l,d=n.content-n.viewport,p=r==="ltr"?[0,d]:[d*-1,0];return VP([c,i],p)(e)}function SC(e,t,n="ltr"){const r=Eg(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,a=t.content-t.viewport,l=o-r,c=n==="ltr"?[0,a]:[a*-1,0],i=Zy(e,c);return VP([0,a],[0,l])(i)}function VP(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function HP(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function s(){const o={left:e.scrollLeft,top:e.scrollTop},a=n.left!==o.left,l=n.top!==o.top;(a||l)&&t(),n=o,r=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(r)};function Tg(e,t){const n=nn(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function tu(e,t){const n=nn(t);fn(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var KP=IP,xV=AP,wV=zP;const Yy=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(KP,{ref:r,className:ge("relative overflow-hidden",e),...n,children:[u.jsx(xV,{className:"h-full w-full rounded-[inherit] [&>div[style]]:!block [&>div[style]]:h-full",children:t}),u.jsx(qP,{}),u.jsx(wV,{})]}));Yy.displayName=KP.displayName;const qP=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(hw,{ref:r,orientation:t,className:ge("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(BP,{className:ge("relative rounded-full bg-border",t==="vertical"&&"flex-1")})}));qP.displayName=hw.displayName;function Xt({children:e}){const{instanceId:t}=So();return u.jsx(eV,{children:u.jsxs("div",{className:"flex h-screen flex-col",children:[u.jsx(_P,{instanceId:t}),u.jsxs("div",{className:"flex min-h-[calc(100vh_-_56px)] flex-1 flex-col md:flex-row",children:[u.jsx(Yy,{className:"mr-2 py-6 md:w-64",children:u.jsx("div",{className:"flex h-full",children:u.jsx(lV,{})})}),u.jsx(Yy,{className:"w-full",children:u.jsxs("div",{className:"flex h-full flex-col",children:[u.jsx("div",{className:"my-6 flex flex-1 flex-col gap-2 pl-2 pr-4",children:e}),u.jsx(Ax,{})]})})]})]})})}function SV({children:e}){return u.jsxs("div",{className:"flex h-full min-h-screen flex-col",children:[u.jsx(_P,{}),u.jsx("main",{className:"flex-1",children:e}),u.jsx(Ax,{})]})}const CV=ig("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",warning:"border-transparent bg-amber-600 text-amber-100 hover:bg-amber-600/80"}},defaultVariants:{variant:"default"}});function Ff({className:e,variant:t,...n}){return u.jsx("div",{className:ge(CV({variant:t}),e),...n})}function WP({status:e}){const{t}=ze();return e?e==="open"?u.jsx(Ff,{children:t("status.open")}):e==="connecting"?u.jsx(Ff,{variant:"warning",children:t("status.connecting")}):e==="close"||e==="closed"?u.jsx(Ff,{variant:"destructive",children:t("status.closed")}):u.jsx(Ff,{variant:"secondary",children:e}):null}const EV=e=>{navigator.clipboard.writeText(e),X.success("Copiado para a área de transferência")};function GP({token:e,className:t}){const[n,r]=v.useState(!1);return u.jsxs("div",{className:ge("flex items-center gap-3 truncate rounded-sm bg-primary/20 px-2 py-1",t),children:[u.jsx("pre",{className:"block truncate text-xs",children:n?e:e==null?void 0:e.replace(/\w/g,"*")}),u.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{EV(e)},children:u.jsx(I3,{size:"15"})}),u.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{r(s=>!s)},children:n?u.jsx(A3,{size:"15"}):u.jsx(F3,{size:"15"})})]})}const Ja=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex flex-col rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Ja.displayName="Card";const Qa=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex flex-col space-y-1.5 p-6",e),...t}));Qa.displayName="CardHeader";const jc=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ge("text-2xl font-semibold leading-none tracking-tight",e),...t}));jc.displayName="CardTitle";const JP=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));JP.displayName="CardDescription";const Za=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("p-6 pt-0",e),...t}));Za.displayName="CardContent";const kg=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex items-center p-6 pt-0",e),...t}));kg.displayName="CardFooter";const QP="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",K=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:ge(QP,e),ref:r,...n}));K.displayName="Input";const TV=["instance","fetchInstances"],kV=async()=>(await he.get("/instance/fetchInstances")).data,_V=e=>lt({...e,queryKey:TV,queryFn:()=>kV()});function Ye(e,t){const n=Ab(),r=WD({mutationFn:e});return(s,o)=>r.mutateAsync(s,{onSuccess:async(a,l,c)=>{var i;t!=null&&t.invalidateKeys&&await Promise.all(t.invalidateKeys.map(d=>n.invalidateQueries({queryKey:d}))),(i=o==null?void 0:o.onSuccess)==null||i.call(o,a,l,c)},onError(a,l,c){var i;(i=o==null?void 0:o.onError)==null||i.call(o,a,l,c)},onSettled(a,l,c,i){var d;(d=o==null?void 0:o.onSettled)==null||d.call(o,a,l,c,i)}})}const jV=async e=>(await he.post("/instance/create",e)).data,RV=async e=>(await he.post(`/instance/restart/${e}`)).data,PV=async e=>(await he.delete(`/instance/logout/${e}`)).data,MV=async e=>(await he.delete(`/instance/delete/${e}`)).data,OV=async({instanceName:e,token:t,number:n})=>(await he.get(`/instance/connect/${e}`,{headers:{apikey:t},params:{number:n}})).data,NV=async({instanceName:e,token:t,data:n})=>(await he.post(`/settings/set/${e}`,n,{headers:{apikey:t}})).data;function _g(){const e=Ye(OV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),t=Ye(NV,{invalidateKeys:[["instance","fetchSettings"]]}),n=Ye(MV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),r=Ye(PV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),s=Ye(RV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),o=Ye(jV,{invalidateKeys:[["instance","fetchInstances"]]});return{connect:e,updateSettings:t,deleteInstance:n,logout:r,restart:s,createInstance:o}}var Yd=e=>e.type==="checkbox",ml=e=>e instanceof Date,Un=e=>e==null;const ZP=e=>typeof e=="object";var pn=e=>!Un(e)&&!Array.isArray(e)&&ZP(e)&&!ml(e),YP=e=>pn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,IV=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,XP=(e,t)=>e.has(IV(t)),DV=e=>{const t=e.constructor&&e.constructor.prototype;return pn(t)&&t.hasOwnProperty("isPrototypeOf")},vw=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Jn(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(vw&&(e instanceof Blob||e instanceof FileList))&&(n||pn(e)))if(t=n?[]:{},!n&&!DV(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=Jn(e[r]));else return e;return t}var jg=e=>Array.isArray(e)?e.filter(Boolean):[],qt=e=>e===void 0,ce=(e,t,n)=>{if(!t||!pn(e))return n;const r=jg(t.split(/[,[\].]+?/)).reduce((s,o)=>Un(s)?s:s[o],e);return qt(r)||r===e?qt(e[t])?n:e[t]:r},js=e=>typeof e=="boolean",yw=e=>/^\w*$/.test(e),eM=e=>jg(e.replace(/["|']|\]/g,"").split(/\.|\[/)),ht=(e,t,n)=>{let r=-1;const s=yw(t)?[t]:eM(t),o=s.length,a=o-1;for(;++rTe.useContext(tM),Tr=e=>{const{children:t,...n}=e;return Te.createElement(tM.Provider,{value:n},t)};var nM=(e,t,n,r=!0)=>{const s={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(s,o,{get:()=>{const a=o;return t._proxyFormState[a]!==Yr.all&&(t._proxyFormState[a]=!r||Yr.all),n&&(n[a]=!0),e[a]}});return s},ur=e=>pn(e)&&!Object.keys(e).length,rM=(e,t,n,r)=>{n(e);const{name:s,...o}=e;return ur(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(a=>t[a]===(!r||Yr.all))},Rc=e=>Array.isArray(e)?e:[e],sM=(e,t,n)=>!e||!t||e===t||Rc(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function bw(e){const t=Te.useRef(e);t.current=e,Te.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function AV(e){const t=Rg(),{control:n=t.control,disabled:r,name:s,exact:o}=e||{},[a,l]=Te.useState(n._formState),c=Te.useRef(!0),i=Te.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),d=Te.useRef(s);return d.current=s,bw({disabled:r,next:p=>c.current&&sM(d.current,p.name,o)&&rM(p,i.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Te.useEffect(()=>(c.current=!0,i.current.isValid&&n._updateValid(!0),()=>{c.current=!1}),[n]),nM(a,n,i.current,!1)}var Os=e=>typeof e=="string",oM=(e,t,n,r,s)=>Os(e)?(r&&t.watch.add(e),ce(n,e,s)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),ce(n,o))):(r&&(t.watchAll=!0),n);function FV(e){const t=Rg(),{control:n=t.control,name:r,defaultValue:s,disabled:o,exact:a}=e||{},l=Te.useRef(r);l.current=r,bw({disabled:o,subject:n._subjects.values,next:d=>{sM(l.current,d.name,a)&&i(Jn(oM(l.current,n._names,d.values||n._formValues,!1,s)))}});const[c,i]=Te.useState(n._getWatch(r,s));return Te.useEffect(()=>n._removeUnmounted()),c}function LV(e){const t=Rg(),{name:n,disabled:r,control:s=t.control,shouldUnregister:o}=e,a=XP(s._names.array,n),l=FV({control:s,name:n,defaultValue:ce(s._formValues,n,ce(s._defaultValues,n,e.defaultValue)),exact:!0}),c=AV({control:s,name:n}),i=Te.useRef(s.register(n,{...e.rules,value:l,...js(e.disabled)?{disabled:e.disabled}:{}}));return Te.useEffect(()=>{const d=s._options.shouldUnregister||o,p=(f,h)=>{const g=ce(s._fields,f);g&&g._f&&(g._f.mount=h)};if(p(n,!0),d){const f=Jn(ce(s._options.defaultValues,n));ht(s._defaultValues,n,f),qt(ce(s._formValues,n))&&ht(s._formValues,n,f)}return()=>{(a?d&&!s._state.action:d)?s.unregister(n):p(n,!1)}},[n,s,a,o]),Te.useEffect(()=>{ce(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:ce(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:l,...js(r)||c.disabled?{disabled:c.disabled||r}:{},onChange:Te.useCallback(d=>i.current.onChange({target:{value:YP(d),name:n},type:dh.CHANGE}),[n]),onBlur:Te.useCallback(()=>i.current.onBlur({target:{value:ce(s._formValues,n),name:n},type:dh.BLUR}),[n,s]),ref:d=>{const p=ce(s._fields,n);p&&d&&(p._f.ref={focus:()=>d.focus(),select:()=>d.select(),setCustomValidity:f=>d.setCustomValidity(f),reportValidity:()=>d.reportValidity()})}},formState:c,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ce(c.errors,n)},isDirty:{enumerable:!0,get:()=>!!ce(c.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ce(c.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!ce(c.validatingFields,n)},error:{enumerable:!0,get:()=>ce(c.errors,n)}})}}const $V=e=>e.render(LV(e));var aM=(e,t,n,r,s)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:s||!0}}:{},CC=e=>({isOnSubmit:!e||e===Yr.onSubmit,isOnBlur:e===Yr.onBlur,isOnChange:e===Yr.onChange,isOnAll:e===Yr.all,isOnTouch:e===Yr.onTouched}),EC=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Pc=(e,t,n,r)=>{for(const s of n||Object.keys(e)){const o=ce(e,s);if(o){const{_f:a,...l}=o;if(a){if(a.refs&&a.refs[0]&&t(a.refs[0],s)&&!r)break;if(a.ref&&t(a.ref,a.name)&&!r)break;Pc(l,t)}else pn(l)&&Pc(l,t)}}};var BV=(e,t,n)=>{const r=Rc(ce(e,n));return ht(r,"root",t[n]),ht(e,n,r),e},xw=e=>e.type==="file",ta=e=>typeof e=="function",fh=e=>{if(!vw)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},vp=e=>Os(e),ww=e=>e.type==="radio",ph=e=>e instanceof RegExp;const TC={value:!1,isValid:!1},kC={value:!0,isValid:!0};var iM=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!qt(e[0].attributes.value)?qt(e[0].value)||e[0].value===""?kC:{value:e[0].value,isValid:!0}:kC:TC}return TC};const _C={isValid:!1,value:null};var lM=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,_C):_C;function jC(e,t,n="validate"){if(vp(e)||Array.isArray(e)&&e.every(vp)||js(e)&&!e)return{type:n,message:vp(e)?e:"",ref:t}}var Gi=e=>pn(e)&&!ph(e)?e:{value:e,message:""},RC=async(e,t,n,r,s)=>{const{ref:o,refs:a,required:l,maxLength:c,minLength:i,min:d,max:p,pattern:f,validate:h,name:g,valueAsNumber:m,mount:x,disabled:b}=e._f,y=ce(t,g);if(!x||b)return{};const w=a?a[0]:o,S=I=>{r&&w.reportValidity&&(w.setCustomValidity(js(I)?"":I||""),w.reportValidity())},E={},C=ww(o),k=Yd(o),T=C||k,P=(m||xw(o))&&qt(o.value)&&qt(y)||fh(o)&&o.value===""||y===""||Array.isArray(y)&&!y.length,N=aM.bind(null,g,n,E),U=(I,Z,V,Q=Ws.maxLength,ee=Ws.minLength)=>{const W=I?Z:V;E[g]={type:I?Q:ee,message:W,ref:o,...N(I?Q:ee,W)}};if(s?!Array.isArray(y)||!y.length:l&&(!T&&(P||Un(y))||js(y)&&!y||k&&!iM(a).isValid||C&&!lM(a).isValid)){const{value:I,message:Z}=vp(l)?{value:!!l,message:l}:Gi(l);if(I&&(E[g]={type:Ws.required,message:Z,ref:w,...N(Ws.required,Z)},!n))return S(Z),E}if(!P&&(!Un(d)||!Un(p))){let I,Z;const V=Gi(p),Q=Gi(d);if(!Un(y)&&!isNaN(y)){const ee=o.valueAsNumber||y&&+y;Un(V.value)||(I=ee>V.value),Un(Q.value)||(Z=eenew Date(new Date().toDateString()+" "+Y),F=o.type=="time",A=o.type=="week";Os(V.value)&&y&&(I=F?W(y)>W(V.value):A?y>V.value:ee>new Date(V.value)),Os(Q.value)&&y&&(Z=F?W(y)+I.value,Q=!Un(Z.value)&&y.length<+Z.value;if((V||Q)&&(U(V,I.message,Z.message),!n))return S(E[g].message),E}if(f&&!P&&Os(y)){const{value:I,message:Z}=Gi(f);if(ph(I)&&!y.match(I)&&(E[g]={type:Ws.pattern,message:Z,ref:o,...N(Ws.pattern,Z)},!n))return S(Z),E}if(h){if(ta(h)){const I=await h(y,t),Z=jC(I,w);if(Z&&(E[g]={...Z,...N(Ws.validate,Z.message)},!n))return S(Z.message),E}else if(pn(h)){let I={};for(const Z in h){if(!ur(I)&&!n)break;const V=jC(await h[Z](y,t),w,Z);V&&(I={...V,...N(Z,V.message)},S(V.message),n&&(E[g]=I))}if(!ur(I)&&(E[g]={ref:w,...I},!n))return E}}return S(!0),E};function zV(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{let e=[];return{get observers(){return e},next:s=>{for(const o of e)o.next&&o.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(o=>o!==s)}}),unsubscribe:()=>{e=[]}}},hh=e=>Un(e)||!ZP(e);function Ya(e,t){if(hh(e)||hh(t))return e===t;if(ml(e)&&ml(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n){const o=e[s];if(!r.includes(s))return!1;if(s!=="ref"){const a=t[s];if(ml(o)&&ml(a)||pn(o)&&pn(a)||Array.isArray(o)&&Array.isArray(a)?!Ya(o,a):o!==a)return!1}}return!0}var uM=e=>e.type==="select-multiple",VV=e=>ww(e)||Yd(e),Zm=e=>fh(e)&&e.isConnected,cM=e=>{for(const t in e)if(ta(e[t]))return!0;return!1};function gh(e,t={}){const n=Array.isArray(e);if(pn(e)||n)for(const r in e)Array.isArray(e[r])||pn(e[r])&&!cM(e[r])?(t[r]=Array.isArray(e[r])?[]:{},gh(e[r],t[r])):Un(e[r])||(t[r]=!0);return t}function dM(e,t,n){const r=Array.isArray(e);if(pn(e)||r)for(const s in e)Array.isArray(e[s])||pn(e[s])&&!cM(e[s])?qt(t)||hh(n[s])?n[s]=Array.isArray(e[s])?gh(e[s],[]):{...gh(e[s])}:dM(e[s],Un(t)?{}:t[s],n[s]):n[s]=!Ya(e[s],t[s]);return n}var Lf=(e,t)=>dM(e,t,gh(t)),fM=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>qt(e)?e:t?e===""?NaN:e&&+e:n&&Os(e)?new Date(e):r?r(e):e;function Ym(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return xw(t)?t.files:ww(t)?lM(e.refs).value:uM(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?iM(e.refs).value:fM(qt(t.value)?e.ref.value:t.value,e)}var HV=(e,t,n,r)=>{const s={};for(const o of e){const a=ce(t,o);a&&ht(s,o,a._f)}return{criteriaMode:n,names:[...e],fields:s,shouldUseNativeValidation:r}},Zu=e=>qt(e)?e:ph(e)?e.source:pn(e)?ph(e.value)?e.value.source:e.value:e,KV=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function PC(e,t,n){const r=ce(e,n);if(r||yw(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const o=s.join("."),a=ce(t,o),l=ce(e,o);if(a&&!Array.isArray(a)&&n!==o)return{name:n};if(l&&l.type)return{name:o,error:l};s.pop()}return{name:n}}var qV=(e,t,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(t||e):(n?r.isOnBlur:s.isOnBlur)?!e:(n?r.isOnChange:s.isOnChange)?e:!0,WV=(e,t)=>!jg(ce(e,t)).length&&ln(e,t);const GV={mode:Yr.onSubmit,reValidateMode:Yr.onChange,shouldFocusError:!0};function JV(e={}){let t={...GV,...e},n={submitCount:0,isDirty:!1,isLoading:ta(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},s=pn(t.defaultValues)||pn(t.values)?Jn(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Jn(s),a={action:!1,mount:!1,watch:!1},l={mount:new Set,unMount:new Set,array:new Set,watch:new Set},c,i=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},p={values:Qm(),array:Qm(),state:Qm()},f=CC(t.mode),h=CC(t.reValidateMode),g=t.criteriaMode===Yr.all,m=j=>D=>{clearTimeout(i),i=setTimeout(j,D)},x=async j=>{if(d.isValid||j){const D=t.resolver?ur((await T()).errors):await N(r,!0);D!==n.isValid&&p.state.next({isValid:D})}},b=(j,D)=>{(d.isValidating||d.validatingFields)&&((j||Array.from(l.mount)).forEach(B=>{B&&(D?ht(n.validatingFields,B,D):ln(n.validatingFields,B))}),p.state.next({validatingFields:n.validatingFields,isValidating:!ur(n.validatingFields)}))},y=(j,D=[],B,pe,le=!0,ae=!0)=>{if(pe&&B){if(a.action=!0,ae&&Array.isArray(ce(r,j))){const Ee=B(ce(r,j),pe.argA,pe.argB);le&&ht(r,j,Ee)}if(ae&&Array.isArray(ce(n.errors,j))){const Ee=B(ce(n.errors,j),pe.argA,pe.argB);le&&ht(n.errors,j,Ee),WV(n.errors,j)}if(d.touchedFields&&ae&&Array.isArray(ce(n.touchedFields,j))){const Ee=B(ce(n.touchedFields,j),pe.argA,pe.argB);le&&ht(n.touchedFields,j,Ee)}d.dirtyFields&&(n.dirtyFields=Lf(s,o)),p.state.next({name:j,isDirty:I(j,D),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else ht(o,j,D)},w=(j,D)=>{ht(n.errors,j,D),p.state.next({errors:n.errors})},S=j=>{n.errors=j,p.state.next({errors:n.errors,isValid:!1})},E=(j,D,B,pe)=>{const le=ce(r,j);if(le){const ae=ce(o,j,qt(B)?ce(s,j):B);qt(ae)||pe&&pe.defaultChecked||D?ht(o,j,D?ae:Ym(le._f)):Q(j,ae),a.mount&&x()}},C=(j,D,B,pe,le)=>{let ae=!1,Ee=!1;const et={name:j},kt=!!(ce(r,j)&&ce(r,j)._f&&ce(r,j)._f.disabled);if(!B||pe){d.isDirty&&(Ee=n.isDirty,n.isDirty=et.isDirty=I(),ae=Ee!==et.isDirty);const hn=kt||Ya(ce(s,j),D);Ee=!!(!kt&&ce(n.dirtyFields,j)),hn||kt?ln(n.dirtyFields,j):ht(n.dirtyFields,j,!0),et.dirtyFields=n.dirtyFields,ae=ae||d.dirtyFields&&Ee!==!hn}if(B){const hn=ce(n.touchedFields,j);hn||(ht(n.touchedFields,j,B),et.touchedFields=n.touchedFields,ae=ae||d.touchedFields&&hn!==B)}return ae&&le&&p.state.next(et),ae?et:{}},k=(j,D,B,pe)=>{const le=ce(n.errors,j),ae=d.isValid&&js(D)&&n.isValid!==D;if(e.delayError&&B?(c=m(()=>w(j,B)),c(e.delayError)):(clearTimeout(i),c=null,B?ht(n.errors,j,B):ln(n.errors,j)),(B?!Ya(le,B):le)||!ur(pe)||ae){const Ee={...pe,...ae&&js(D)?{isValid:D}:{},errors:n.errors,name:j};n={...n,...Ee},p.state.next(Ee)}},T=async j=>{b(j,!0);const D=await t.resolver(o,t.context,HV(j||l.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return b(j),D},P=async j=>{const{errors:D}=await T(j);if(j)for(const B of j){const pe=ce(D,B);pe?ht(n.errors,B,pe):ln(n.errors,B)}else n.errors=D;return D},N=async(j,D,B={valid:!0})=>{for(const pe in j){const le=j[pe];if(le){const{_f:ae,...Ee}=le;if(ae){const et=l.array.has(ae.name);b([pe],!0);const kt=await RC(le,o,g,t.shouldUseNativeValidation&&!D,et);if(b([pe]),kt[ae.name]&&(B.valid=!1,D))break;!D&&(ce(kt,ae.name)?et?BV(n.errors,kt,ae.name):ht(n.errors,ae.name,kt[ae.name]):ln(n.errors,ae.name))}Ee&&await N(Ee,D,B)}}return B.valid},U=()=>{for(const j of l.unMount){const D=ce(r,j);D&&(D._f.refs?D._f.refs.every(B=>!Zm(B)):!Zm(D._f.ref))&&oe(j)}l.unMount=new Set},I=(j,D)=>(j&&D&&ht(o,j,D),!Ya(de(),s)),Z=(j,D,B)=>oM(j,l,{...a.mount?o:qt(D)?s:Os(j)?{[j]:D}:D},B,D),V=j=>jg(ce(a.mount?o:s,j,e.shouldUnregister?ce(s,j,[]):[])),Q=(j,D,B={})=>{const pe=ce(r,j);let le=D;if(pe){const ae=pe._f;ae&&(!ae.disabled&&ht(o,j,fM(D,ae)),le=fh(ae.ref)&&Un(D)?"":D,uM(ae.ref)?[...ae.ref.options].forEach(Ee=>Ee.selected=le.includes(Ee.value)):ae.refs?Yd(ae.ref)?ae.refs.length>1?ae.refs.forEach(Ee=>(!Ee.defaultChecked||!Ee.disabled)&&(Ee.checked=Array.isArray(le)?!!le.find(et=>et===Ee.value):le===Ee.value)):ae.refs[0]&&(ae.refs[0].checked=!!le):ae.refs.forEach(Ee=>Ee.checked=Ee.value===le):xw(ae.ref)?ae.ref.value="":(ae.ref.value=le,ae.ref.type||p.values.next({name:j,values:{...o}})))}(B.shouldDirty||B.shouldTouch)&&C(j,le,B.shouldTouch,B.shouldDirty,!0),B.shouldValidate&&Y(j)},ee=(j,D,B)=>{for(const pe in D){const le=D[pe],ae=`${j}.${pe}`,Ee=ce(r,ae);(l.array.has(j)||!hh(le)||Ee&&!Ee._f)&&!ml(le)?ee(ae,le,B):Q(ae,le,B)}},W=(j,D,B={})=>{const pe=ce(r,j),le=l.array.has(j),ae=Jn(D);ht(o,j,ae),le?(p.array.next({name:j,values:{...o}}),(d.isDirty||d.dirtyFields)&&B.shouldDirty&&p.state.next({name:j,dirtyFields:Lf(s,o),isDirty:I(j,ae)})):pe&&!pe._f&&!Un(ae)?ee(j,ae,B):Q(j,ae,B),EC(j,l)&&p.state.next({...n}),p.values.next({name:a.mount?j:void 0,values:{...o}})},F=async j=>{a.mount=!0;const D=j.target;let B=D.name,pe=!0;const le=ce(r,B),ae=()=>D.type?Ym(le._f):YP(j),Ee=et=>{pe=Number.isNaN(et)||et===ce(o,B,et)};if(le){let et,kt;const hn=ae(),yn=j.type===dh.BLUR||j.type===dh.FOCUS_OUT,gn=!KV(le._f)&&!t.resolver&&!ce(n.errors,B)&&!le._f.deps||qV(yn,ce(n.touchedFields,B),n.isSubmitted,h,f),jo=EC(B,l,yn);ht(o,B,hn),yn?(le._f.onBlur&&le._f.onBlur(j),c&&c(0)):le._f.onChange&&le._f.onChange(j);const gs=C(B,hn,yn,!1),Aa=!ur(gs)||jo;if(!yn&&p.values.next({name:B,type:j.type,values:{...o}}),gn)return d.isValid&&x(),Aa&&p.state.next({name:B,...jo?{}:gs});if(!yn&&jo&&p.state.next({...n}),t.resolver){const{errors:Fn}=await T([B]);if(Ee(hn),pe){const ue=PC(n.errors,r,B),Ue=PC(Fn,r,ue.name||B);et=Ue.error,B=Ue.name,kt=ur(Fn)}}else b([B],!0),et=(await RC(le,o,g,t.shouldUseNativeValidation))[B],b([B]),Ee(hn),pe&&(et?kt=!1:d.isValid&&(kt=await N(r,!0)));pe&&(le._f.deps&&Y(le._f.deps),k(B,kt,et,gs))}},A=(j,D)=>{if(ce(n.errors,D)&&j.focus)return j.focus(),1},Y=async(j,D={})=>{let B,pe;const le=Rc(j);if(t.resolver){const ae=await P(qt(j)?j:le);B=ur(ae),pe=j?!le.some(Ee=>ce(ae,Ee)):B}else j?(pe=(await Promise.all(le.map(async ae=>{const Ee=ce(r,ae);return await N(Ee&&Ee._f?{[ae]:Ee}:Ee)}))).every(Boolean),!(!pe&&!n.isValid)&&x()):pe=B=await N(r);return p.state.next({...!Os(j)||d.isValid&&B!==n.isValid?{}:{name:j},...t.resolver||!j?{isValid:B}:{},errors:n.errors}),D.shouldFocus&&!pe&&Pc(r,A,j?le:l.mount),pe},de=j=>{const D={...a.mount?o:s};return qt(j)?D:Os(j)?ce(D,j):j.map(B=>ce(D,B))},z=(j,D)=>({invalid:!!ce((D||n).errors,j),isDirty:!!ce((D||n).dirtyFields,j),error:ce((D||n).errors,j),isValidating:!!ce(n.validatingFields,j),isTouched:!!ce((D||n).touchedFields,j)}),se=j=>{j&&Rc(j).forEach(D=>ln(n.errors,D)),p.state.next({errors:j?n.errors:{}})},ne=(j,D,B)=>{const pe=(ce(r,j,{_f:{}})._f||{}).ref,le=ce(n.errors,j)||{},{ref:ae,message:Ee,type:et,...kt}=le;ht(n.errors,j,{...kt,...D,ref:pe}),p.state.next({name:j,errors:n.errors,isValid:!1}),B&&B.shouldFocus&&pe&&pe.focus&&pe.focus()},ie=(j,D)=>ta(j)?p.values.subscribe({next:B=>j(Z(void 0,D),B)}):Z(j,D,!0),oe=(j,D={})=>{for(const B of j?Rc(j):l.mount)l.mount.delete(B),l.array.delete(B),D.keepValue||(ln(r,B),ln(o,B)),!D.keepError&&ln(n.errors,B),!D.keepDirty&&ln(n.dirtyFields,B),!D.keepTouched&&ln(n.touchedFields,B),!D.keepIsValidating&&ln(n.validatingFields,B),!t.shouldUnregister&&!D.keepDefaultValue&&ln(s,B);p.values.next({values:{...o}}),p.state.next({...n,...D.keepDirty?{isDirty:I()}:{}}),!D.keepIsValid&&x()},J=({disabled:j,name:D,field:B,fields:pe,value:le})=>{if(js(j)&&a.mount||j){const ae=j?void 0:qt(le)?Ym(B?B._f:ce(pe,D)._f):le;ht(o,D,ae),C(D,ae,!1,!1,!0)}},Ce=(j,D={})=>{let B=ce(r,j);const pe=js(D.disabled);return ht(r,j,{...B||{},_f:{...B&&B._f?B._f:{ref:{name:j}},name:j,mount:!0,...D}}),l.mount.add(j),B?J({field:B,disabled:D.disabled,name:j,value:D.value}):E(j,!0,D.value),{...pe?{disabled:D.disabled}:{},...t.progressive?{required:!!D.required,min:Zu(D.min),max:Zu(D.max),minLength:Zu(D.minLength),maxLength:Zu(D.maxLength),pattern:Zu(D.pattern)}:{},name:j,onChange:F,onBlur:F,ref:le=>{if(le){Ce(j,D),B=ce(r,j);const ae=qt(le.value)&&le.querySelectorAll&&le.querySelectorAll("input,select,textarea")[0]||le,Ee=VV(ae),et=B._f.refs||[];if(Ee?et.find(kt=>kt===ae):ae===B._f.ref)return;ht(r,j,{_f:{...B._f,...Ee?{refs:[...et.filter(Zm),ae,...Array.isArray(ce(s,j))?[{}]:[]],ref:{type:ae.type,name:j}}:{ref:ae}}}),E(j,!1,void 0,ae)}else B=ce(r,j,{}),B._f&&(B._f.mount=!1),(t.shouldUnregister||D.shouldUnregister)&&!(XP(l.array,j)&&a.action)&&l.unMount.add(j)}}},Pe=()=>t.shouldFocusError&&Pc(r,A,l.mount),Le=j=>{js(j)&&(p.state.next({disabled:j}),Pc(r,(D,B)=>{const pe=ce(r,B);pe&&(D.disabled=pe._f.disabled||j,Array.isArray(pe._f.refs)&&pe._f.refs.forEach(le=>{le.disabled=pe._f.disabled||j}))},0,!1))},Me=(j,D)=>async B=>{let pe;B&&(B.preventDefault&&B.preventDefault(),B.persist&&B.persist());let le=Jn(o);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:ae,values:Ee}=await T();n.errors=ae,le=Ee}else await N(r);if(ln(n.errors,"root"),ur(n.errors)){p.state.next({errors:{}});try{await j(le,B)}catch(ae){pe=ae}}else D&&await D({...n.errors},B),Pe(),setTimeout(Pe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ur(n.errors)&&!pe,submitCount:n.submitCount+1,errors:n.errors}),pe)throw pe},me=(j,D={})=>{ce(r,j)&&(qt(D.defaultValue)?W(j,Jn(ce(s,j))):(W(j,D.defaultValue),ht(s,j,Jn(D.defaultValue))),D.keepTouched||ln(n.touchedFields,j),D.keepDirty||(ln(n.dirtyFields,j),n.isDirty=D.defaultValue?I(j,Jn(ce(s,j))):I()),D.keepError||(ln(n.errors,j),d.isValid&&x()),p.state.next({...n}))},rt=(j,D={})=>{const B=j?Jn(j):s,pe=Jn(B),le=ur(j),ae=le?s:pe;if(D.keepDefaultValues||(s=B),!D.keepValues){if(D.keepDirtyValues)for(const Ee of l.mount)ce(n.dirtyFields,Ee)?ht(ae,Ee,ce(o,Ee)):W(Ee,ce(ae,Ee));else{if(vw&&qt(j))for(const Ee of l.mount){const et=ce(r,Ee);if(et&&et._f){const kt=Array.isArray(et._f.refs)?et._f.refs[0]:et._f.ref;if(fh(kt)){const hn=kt.closest("form");if(hn){hn.reset();break}}}}r={}}o=e.shouldUnregister?D.keepDefaultValues?Jn(s):{}:Jn(ae),p.array.next({values:{...ae}}),p.values.next({values:{...ae}})}l={mount:D.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!d.isValid||!!D.keepIsValid||!!D.keepDirtyValues,a.watch=!!e.shouldUnregister,p.state.next({submitCount:D.keepSubmitCount?n.submitCount:0,isDirty:le?!1:D.keepDirty?n.isDirty:!!(D.keepDefaultValues&&!Ya(j,s)),isSubmitted:D.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:le?{}:D.keepDirtyValues?D.keepDefaultValues&&o?Lf(s,o):n.dirtyFields:D.keepDefaultValues&&j?Lf(s,j):D.keepDirty?n.dirtyFields:{},touchedFields:D.keepTouched?n.touchedFields:{},errors:D.keepErrors?n.errors:{},isSubmitSuccessful:D.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},It=(j,D)=>rt(ta(j)?j(o):j,D);return{control:{register:Ce,unregister:oe,getFieldState:z,handleSubmit:Me,setError:ne,_executeSchema:T,_getWatch:Z,_getDirty:I,_updateValid:x,_removeUnmounted:U,_updateFieldArray:y,_updateDisabledField:J,_getFieldArray:V,_reset:rt,_resetDefaultValues:()=>ta(t.defaultValues)&&t.defaultValues().then(j=>{It(j,t.resetOptions),p.state.next({isLoading:!1})}),_updateFormState:j=>{n={...n,...j}},_disableForm:Le,_subjects:p,_proxyFormState:d,_setErrors:S,get _fields(){return r},get _formValues(){return o},get _state(){return a},set _state(j){a=j},get _defaultValues(){return s},get _names(){return l},set _names(j){l=j},get _formState(){return n},set _formState(j){n=j},get _options(){return t},set _options(j){t={...t,...j}}},trigger:Y,register:Ce,handleSubmit:Me,watch:ie,setValue:W,getValues:de,reset:It,resetField:me,clearErrors:se,unregister:oe,setError:ne,setFocus:(j,D={})=>{const B=ce(r,j),pe=B&&B._f;if(pe){const le=pe.refs?pe.refs[0]:pe.ref;le.focus&&(le.focus(),D.shouldSelect&&le.select())}},getFieldState:z}}function sn(e={}){const t=Te.useRef(),n=Te.useRef(),[r,s]=Te.useState({isDirty:!1,isValidating:!1,isLoading:ta(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:ta(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...JV(e),formState:r});const o=t.current.control;return o._options=e,bw({subject:o._subjects.state,next:a=>{rM(a,o._proxyFormState,o._updateFormState,!0)&&s({...o._formState})}}),Te.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),Te.useEffect(()=>{if(o._proxyFormState.isDirty){const a=o._getDirty();a!==r.isDirty&&o._subjects.state.next({isDirty:a})}},[o,r.isDirty]),Te.useEffect(()=>{e.values&&!Ya(e.values,n.current)?(o._reset(e.values,o._options.resetOptions),n.current=e.values,s(a=>({...a}))):o._resetDefaultValues()},[e.values,o]),Te.useEffect(()=>{e.errors&&o._setErrors(e.errors)},[e.errors,o]),Te.useEffect(()=>{o._state.mount||(o._updateValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),Te.useEffect(()=>{e.shouldUnregister&&o._subjects.values.next({values:o._getWatch()})},[e.shouldUnregister,o]),t.current.formState=nM(r,o),t.current}const MC=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ce(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},pM=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?MC(r.ref,n,e):r.refs&&r.refs.forEach(s=>MC(s,n,e))}},QV=(e,t)=>{t.shouldUseNativeValidation&&pM(e,t);const n={};for(const r in e){const s=ce(t.fields,r),o=Object.assign(e[r]||{},{ref:s&&s.ref});if(ZV(t.names||Object.keys(e),r)){const a=Object.assign({},ce(n,r));ht(a,"root",o),ht(n,r,a)}else ht(n,r,o)}return n},ZV=(e,t)=>e.some(n=>n.startsWith(t+"."));var YV=function(e,t){for(var n={};e.length;){var r=e[0],s=r.code,o=r.message,a=r.path.join(".");if(!n[a])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[a]={message:l.message,type:l.code}}else n[a]={message:o,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(d){return d.errors.forEach(function(p){return e.push(p)})}),t){var c=n[a].types,i=c&&c[r.code];n[a]=aM(a,t,n,s,i?[].concat(i,r.message):r.message)}e.shift()}return n},on=function(e,t,n){return n===void 0&&(n={}),function(r,s,o){try{return Promise.resolve(function(a,l){try{var c=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(i){return o.shouldUseNativeValidation&&pM({},o),{errors:{},values:n.raw?r:i}})}catch(i){return l(i)}return c&&c.then?c.then(void 0,l):c}(0,function(a){if(function(l){return Array.isArray(l==null?void 0:l.errors)}(a))return{values:{},errors:QV(YV(a.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw a}))}catch(a){return Promise.reject(a)}}},xn=[];for(var Xm=0;Xm<256;++Xm)xn.push((Xm+256).toString(16).slice(1));function XV(e,t=0){return(xn[e[t+0]]+xn[e[t+1]]+xn[e[t+2]]+xn[e[t+3]]+"-"+xn[e[t+4]]+xn[e[t+5]]+"-"+xn[e[t+6]]+xn[e[t+7]]+"-"+xn[e[t+8]]+xn[e[t+9]]+"-"+xn[e[t+10]]+xn[e[t+11]]+xn[e[t+12]]+xn[e[t+13]]+xn[e[t+14]]+xn[e[t+15]]).toLowerCase()}var $f,e6=new Uint8Array(16);function t6(){if(!$f&&($f=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!$f))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return $f(e6)}var n6=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const OC={randomUUID:n6};function NC(e,t,n){if(OC.randomUUID&&!t&&!e)return OC.randomUUID();e=e||{};var r=e.random||(e.rng||t6)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,XV(r)}var ut;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),a={};for(const l of o)a[l]=s[l];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},e.find=(s,o)=>{for(const a of s)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ut||(ut={}));var Xy;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Xy||(Xy={}));const be=ut.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Vo=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},re=ut.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),r6=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class yr extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let l=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}yr.create=e=>new yr(e);const nu=(e,t)=>{let n;switch(e.code){case re.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case re.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ut.jsonStringifyReplacer)}`;break;case re.unrecognized_keys:n=`Unrecognized key(s) in object: ${ut.joinValues(e.keys,", ")}`;break;case re.invalid_union:n="Invalid input";break;case re.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ut.joinValues(e.options)}`;break;case re.invalid_enum_value:n=`Invalid enum value. Expected ${ut.joinValues(e.options)}, received '${e.received}'`;break;case re.invalid_arguments:n="Invalid function arguments";break;case re.invalid_return_type:n="Invalid function return type";break;case re.invalid_date:n="Invalid date";break;case re.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ut.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case re.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case re.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case re.custom:n="Invalid input";break;case re.invalid_intersection_types:n="Intersection results could not be merged";break;case re.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case re.not_finite:n="Number must be finite";break;default:n=t.defaultError,ut.assertNever(e)}return{message:n}};let hM=nu;function s6(e){hM=e}function mh(){return hM}const vh=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let l="";const c=r.filter(i=>!!i).slice().reverse();for(const i of c)l=i(a,{data:t,defaultError:l}).message;return{...s,path:o,message:l}},o6=[];function ve(e,t){const n=mh(),r=vh({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===nu?void 0:nu].filter(s=>!!s)});e.common.issues.push(r)}class Dn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return Be;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const o=await s.key,a=await s.value;r.push({key:o,value:a})}return Dn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return Be;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}}const Be=Object.freeze({status:"aborted"}),vl=e=>({status:"dirty",value:e}),Kn=e=>({status:"valid",value:e}),eb=e=>e.status==="aborted",tb=e=>e.status==="dirty",cd=e=>e.status==="valid",dd=e=>typeof Promise<"u"&&e instanceof Promise;function yh(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function gM(e,t,n,r,s){if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var je;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(je||(je={}));var fc,pc;class zs{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const IC=(e,t)=>{if(cd(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new yr(e.common.issues);return this._error=n,this._error}}};function Ke(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,l)=>{var c,i;const{message:d}=e;return a.code==="invalid_enum_value"?{message:d??l.defaultError}:typeof l.data>"u"?{message:(c=d??r)!==null&&c!==void 0?c:l.defaultError}:a.code!=="invalid_type"?{message:l.defaultError}:{message:(i=d??n)!==null&&i!==void 0?i:l.defaultError}},description:s}}class Qe{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return Vo(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Vo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Dn,ctx:{common:t.parent.common,data:t.data,parsedType:Vo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(dd(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vo(t)},o=this._parseSync({data:t,path:s.path,parent:s});return IC(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vo(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(dd(s)?s:Promise.resolve(s));return IC(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const a=t(s),l=()=>o.addIssue({code:re.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ds({schema:this,typeName:Fe.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Ls.create(this,this._def)}nullable(){return xa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return as.create(this,this._def)}promise(){return su.create(this,this._def)}or(t){return gd.create([this,t],this._def)}and(t){return md.create(this,t,this._def)}transform(t){return new ds({...Ke(this._def),schema:this,typeName:Fe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new wd({...Ke(this._def),innerType:this,defaultValue:n,typeName:Fe.ZodDefault})}brand(){return new Sw({typeName:Fe.ZodBranded,type:this,...Ke(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Sd({...Ke(this._def),innerType:this,catchValue:n,typeName:Fe.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Xd.create(this,t)}readonly(){return Cd.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const a6=/^c[^\s-]{8,}$/i,i6=/^[0-9a-z]+$/,l6=/^[0-9A-HJKMNP-TV-Z]{26}$/,u6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,c6=/^[a-z0-9_-]{21}$/i,d6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,f6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,p6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ev;const h6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,g6=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,m6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mM="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",v6=new RegExp(`^${mM}$`);function vM(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function y6(e){return new RegExp(`^${vM(e)}$`)}function yM(e){let t=`${mM}T${vM(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function b6(e,t){return!!((t==="v4"||!t)&&h6.test(e)||(t==="v6"||!t)&&g6.test(e))}class es extends Qe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.string,received:o.parsedType}),Be}const r=new Dn;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),ve(s,{code:re.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const a=t.data.length>o.value,l=t.data.lengtht.test(s),{validation:n,code:re.invalid_string,...je.errToObj(r)})}_addCheck(t){return new es({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...je.errToObj(t)})}url(t){return this._addCheck({kind:"url",...je.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...je.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...je.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...je.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...je.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...je.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...je.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...je.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...je.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,local:(r=t==null?void 0:t.local)!==null&&r!==void 0?r:!1,...je.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...je.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...je.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...je.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...je.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...je.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...je.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...je.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...je.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...je.errToObj(n)})}nonempty(t){return this.min(1,je.errToObj(t))}trim(){return new es({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new es({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new es({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new es({checks:[],typeName:Fe.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ke(e)})};function x6(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class va extends Qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.number,received:o.parsedType}),Be}let r;const s=new Dn;for(const o of this._def.checks)o.kind==="int"?ut.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ve(r,{code:re.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?x6(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_finite,message:o.message}),s.dirty()):ut.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,je.toString(n))}gt(t,n){return this.setLimit("min",t,!1,je.toString(n))}lte(t,n){return this.setLimit("max",t,!0,je.toString(n))}lt(t,n){return this.setLimit("max",t,!1,je.toString(n))}setLimit(t,n,r,s){return new va({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:je.toString(s)}]})}_addCheck(t){return new va({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:je.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:je.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:je.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:je.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:je.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:je.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:je.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:je.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:je.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&ut.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew va({checks:[],typeName:Fe.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Ke(e)});class ya extends Qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.bigint,received:o.parsedType}),Be}let r;const s=new Dn;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ut.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,je.toString(n))}gt(t,n){return this.setLimit("min",t,!1,je.toString(n))}lte(t,n){return this.setLimit("max",t,!0,je.toString(n))}lt(t,n){return this.setLimit("max",t,!1,je.toString(n))}setLimit(t,n,r,s){return new ya({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:je.toString(s)}]})}_addCheck(t){return new ya({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:je.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:je.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:je.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:je.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:je.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new ya({checks:[],typeName:Fe.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ke(e)})};class fd extends Qe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.boolean,received:r.parsedType}),Be}return Kn(t.data)}}fd.create=e=>new fd({typeName:Fe.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Ke(e)});class Ti extends Qe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.date,received:o.parsedType}),Be}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_date}),Be}const r=new Dn;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),ve(s,{code:re.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ut.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ti({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:je.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:je.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Ti({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Fe.ZodDate,...Ke(e)});class bh extends Qe{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.symbol,received:r.parsedType}),Be}return Kn(t.data)}}bh.create=e=>new bh({typeName:Fe.ZodSymbol,...Ke(e)});class pd extends Qe{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.undefined,received:r.parsedType}),Be}return Kn(t.data)}}pd.create=e=>new pd({typeName:Fe.ZodUndefined,...Ke(e)});class hd extends Qe{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.null,received:r.parsedType}),Be}return Kn(t.data)}}hd.create=e=>new hd({typeName:Fe.ZodNull,...Ke(e)});class ru extends Qe{constructor(){super(...arguments),this._any=!0}_parse(t){return Kn(t.data)}}ru.create=e=>new ru({typeName:Fe.ZodAny,...Ke(e)});class fi extends Qe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Kn(t.data)}}fi.create=e=>new fi({typeName:Fe.ZodUnknown,...Ke(e)});class bo extends Qe{_parse(t){const n=this._getOrReturnCtx(t);return ve(n,{code:re.invalid_type,expected:be.never,received:n.parsedType}),Be}}bo.create=e=>new bo({typeName:Fe.ZodNever,...Ke(e)});class xh extends Qe{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.void,received:r.parsedType}),Be}return Kn(t.data)}}xh.create=e=>new xh({typeName:Fe.ZodVoid,...Ke(e)});class as extends Qe{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==be.array)return ve(n,{code:re.invalid_type,expected:be.array,received:n.parsedType}),Be;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,l=n.data.lengths.maxLength.value&&(ve(n,{code:re.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,l)=>s.type._parseAsync(new zs(n,a,n.path,l)))).then(a=>Dn.mergeArray(r,a));const o=[...n.data].map((a,l)=>s.type._parseSync(new zs(n,a,n.path,l)));return Dn.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new as({...this._def,minLength:{value:t,message:je.toString(n)}})}max(t,n){return new as({...this._def,maxLength:{value:t,message:je.toString(n)}})}length(t,n){return new as({...this._def,exactLength:{value:t,message:je.toString(n)}})}nonempty(t){return this.min(1,t)}}as.create=(e,t)=>new as({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Fe.ZodArray,...Ke(t)});function tl(e){if(e instanceof Dt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ls.create(tl(r))}return new Dt({...e._def,shape:()=>t})}else return e instanceof as?new as({...e._def,type:tl(e.element)}):e instanceof Ls?Ls.create(tl(e.unwrap())):e instanceof xa?xa.create(tl(e.unwrap())):e instanceof Us?Us.create(e.items.map(t=>tl(t))):e}class Dt extends Qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ut.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const i=this._getOrReturnCtx(t);return ve(i,{code:re.invalid_type,expected:be.object,received:i.parsedType}),Be}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof bo&&this._def.unknownKeys==="strip"))for(const i in s.data)a.includes(i)||l.push(i);const c=[];for(const i of a){const d=o[i],p=s.data[i];c.push({key:{status:"valid",value:i},value:d._parse(new zs(s,p,s.path,i)),alwaysSet:i in s.data})}if(this._def.catchall instanceof bo){const i=this._def.unknownKeys;if(i==="passthrough")for(const d of l)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(i==="strict")l.length>0&&(ve(s,{code:re.unrecognized_keys,keys:l}),r.dirty());else if(i!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const i=this._def.catchall;for(const d of l){const p=s.data[d];c.push({key:{status:"valid",value:d},value:i._parse(new zs(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const i=[];for(const d of c){const p=await d.key,f=await d.value;i.push({key:p,value:f,alwaysSet:d.alwaysSet})}return i}).then(i=>Dn.mergeObjectSync(r,i)):Dn.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return je.errToObj,new Dt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,a,l;const c=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=je.errToObj(t).message)!==null&&l!==void 0?l:c}:{message:c}}}:{}})}strip(){return new Dt({...this._def,unknownKeys:"strip"})}passthrough(){return new Dt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Dt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Dt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Fe.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Dt({...this._def,catchall:t})}pick(t){const n={};return ut.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Dt({...this._def,shape:()=>n})}omit(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Dt({...this._def,shape:()=>n})}deepPartial(){return tl(this)}partial(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Dt({...this._def,shape:()=>n})}required(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ls;)o=o._def.innerType;n[r]=o}}),new Dt({...this._def,shape:()=>n})}keyof(){return bM(ut.objectKeys(this.shape))}}Dt.create=(e,t)=>new Dt({shape:()=>e,unknownKeys:"strip",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});Dt.strictCreate=(e,t)=>new Dt({shape:()=>e,unknownKeys:"strict",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});Dt.lazycreate=(e,t)=>new Dt({shape:e,unknownKeys:"strip",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});class gd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const l of o)if(l.result.status==="valid")return l.result;for(const l of o)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const a=o.map(l=>new yr(l.ctx.common.issues));return ve(n,{code:re.invalid_union,unionErrors:a}),Be}if(n.common.async)return Promise.all(r.map(async o=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const c of r){const i={...n,common:{...n.common,issues:[]},parent:null},d=c._parseSync({data:n.data,path:n.path,parent:i});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:i}),i.common.issues.length&&a.push(i.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const l=a.map(c=>new yr(c));return ve(n,{code:re.invalid_union,unionErrors:l}),Be}}get options(){return this._def.options}}gd.create=(e,t)=>new gd({options:e,typeName:Fe.ZodUnion,...Ke(t)});const Qs=e=>e instanceof yd?Qs(e.schema):e instanceof ds?Qs(e.innerType()):e instanceof bd?[e.value]:e instanceof ba?e.options:e instanceof xd?ut.objectValues(e.enum):e instanceof wd?Qs(e._def.innerType):e instanceof pd?[void 0]:e instanceof hd?[null]:e instanceof Ls?[void 0,...Qs(e.unwrap())]:e instanceof xa?[null,...Qs(e.unwrap())]:e instanceof Sw||e instanceof Cd?Qs(e.unwrap()):e instanceof Sd?Qs(e._def.innerType):[];class Pg extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return ve(n,{code:re.invalid_type,expected:be.object,received:n.parsedType}),Be;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(ve(n,{code:re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const a=Qs(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of a){if(s.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);s.set(l,o)}}return new Pg({typeName:Fe.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Ke(r)})}}function nb(e,t){const n=Vo(e),r=Vo(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const s=ut.objectKeys(t),o=ut.objectKeys(e).filter(l=>s.indexOf(l)!==-1),a={...e,...t};for(const l of o){const c=nb(e[l],t[l]);if(!c.valid)return{valid:!1};a[l]=c.data}return{valid:!0,data:a}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(eb(o)||eb(a))return Be;const l=nb(o.value,a.value);return l.valid?((tb(o)||tb(a))&&n.dirty(),{status:n.value,value:l.data}):(ve(r,{code:re.invalid_intersection_types}),Be)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}md.create=(e,t,n)=>new md({left:e,right:t,typeName:Fe.ZodIntersection,...Ke(n)});class Us extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return ve(r,{code:re.invalid_type,expected:be.array,received:r.parsedType}),Be;if(r.data.lengththis._def.items.length&&(ve(r,{code:re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((a,l)=>{const c=this._def.items[l]||this._def.rest;return c?c._parse(new zs(r,a,r.path,l)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>Dn.mergeArray(n,a)):Dn.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Us({...this._def,rest:t})}}Us.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Us({items:e,typeName:Fe.ZodTuple,rest:null,...Ke(t)})};class vd extends Qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return ve(r,{code:re.invalid_type,expected:be.object,received:r.parsedType}),Be;const s=[],o=this._def.keyType,a=this._def.valueType;for(const l in r.data)s.push({key:o._parse(new zs(r,l,r.path,l)),value:a._parse(new zs(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Dn.mergeObjectAsync(n,s):Dn.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Qe?new vd({keyType:t,valueType:n,typeName:Fe.ZodRecord,...Ke(r)}):new vd({keyType:es.create(),valueType:t,typeName:Fe.ZodRecord,...Ke(n)})}}class wh extends Qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return ve(r,{code:re.invalid_type,expected:be.map,received:r.parsedType}),Be;const s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([l,c],i)=>({key:s._parse(new zs(r,l,r.path,[i,"key"])),value:o._parse(new zs(r,c,r.path,[i,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const c of a){const i=await c.key,d=await c.value;if(i.status==="aborted"||d.status==="aborted")return Be;(i.status==="dirty"||d.status==="dirty")&&n.dirty(),l.set(i.value,d.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const c of a){const i=c.key,d=c.value;if(i.status==="aborted"||d.status==="aborted")return Be;(i.status==="dirty"||d.status==="dirty")&&n.dirty(),l.set(i.value,d.value)}return{status:n.value,value:l}}}}wh.create=(e,t,n)=>new wh({valueType:t,keyType:e,typeName:Fe.ZodMap,...Ke(n)});class ki extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return ve(r,{code:re.invalid_type,expected:be.set,received:r.parsedType}),Be;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(ve(r,{code:re.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function a(c){const i=new Set;for(const d of c){if(d.status==="aborted")return Be;d.status==="dirty"&&n.dirty(),i.add(d.value)}return{status:n.value,value:i}}const l=[...r.data.values()].map((c,i)=>o._parse(new zs(r,c,r.path,i)));return r.common.async?Promise.all(l).then(c=>a(c)):a(l)}min(t,n){return new ki({...this._def,minSize:{value:t,message:je.toString(n)}})}max(t,n){return new ki({...this._def,maxSize:{value:t,message:je.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ki.create=(e,t)=>new ki({valueType:e,minSize:null,maxSize:null,typeName:Fe.ZodSet,...Ke(t)});class jl extends Qe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return ve(n,{code:re.invalid_type,expected:be.function,received:n.parsedType}),Be;function r(l,c){return vh({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mh(),nu].filter(i=>!!i),issueData:{code:re.invalid_arguments,argumentsError:c}})}function s(l,c){return vh({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mh(),nu].filter(i=>!!i),issueData:{code:re.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof su){const l=this;return Kn(async function(...c){const i=new yr([]),d=await l._def.args.parseAsync(c,o).catch(h=>{throw i.addIssue(r(c,h)),i}),p=await Reflect.apply(a,this,d);return await l._def.returns._def.type.parseAsync(p,o).catch(h=>{throw i.addIssue(s(p,h)),i})})}else{const l=this;return Kn(function(...c){const i=l._def.args.safeParse(c,o);if(!i.success)throw new yr([r(c,i.error)]);const d=Reflect.apply(a,this,i.data),p=l._def.returns.safeParse(d,o);if(!p.success)throw new yr([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new jl({...this._def,args:Us.create(t).rest(fi.create())})}returns(t){return new jl({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new jl({args:t||Us.create([]).rest(fi.create()),returns:n||fi.create(),typeName:Fe.ZodFunction,...Ke(r)})}}class yd extends Qe{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}yd.create=(e,t)=>new yd({getter:e,typeName:Fe.ZodLazy,...Ke(t)});class bd extends Qe{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return ve(n,{received:n.data,code:re.invalid_literal,expected:this._def.value}),Be}return{status:"valid",value:t.data}}get value(){return this._def.value}}bd.create=(e,t)=>new bd({value:e,typeName:Fe.ZodLiteral,...Ke(t)});function bM(e,t){return new ba({values:e,typeName:Fe.ZodEnum,...Ke(t)})}class ba extends Qe{constructor(){super(...arguments),fc.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return ve(n,{expected:ut.joinValues(r),received:n.parsedType,code:re.invalid_type}),Be}if(yh(this,fc)||gM(this,fc,new Set(this._def.values)),!yh(this,fc).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return ve(n,{received:n.data,code:re.invalid_enum_value,options:r}),Be}return Kn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return ba.create(t,{...this._def,...n})}exclude(t,n=this._def){return ba.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}fc=new WeakMap;ba.create=bM;class xd extends Qe{constructor(){super(...arguments),pc.set(this,void 0)}_parse(t){const n=ut.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const s=ut.objectValues(n);return ve(r,{expected:ut.joinValues(s),received:r.parsedType,code:re.invalid_type}),Be}if(yh(this,pc)||gM(this,pc,new Set(ut.getValidEnumValues(this._def.values))),!yh(this,pc).has(t.data)){const s=ut.objectValues(n);return ve(r,{received:r.data,code:re.invalid_enum_value,options:s}),Be}return Kn(t.data)}get enum(){return this._def.values}}pc=new WeakMap;xd.create=(e,t)=>new xd({values:e,typeName:Fe.ZodNativeEnum,...Ke(t)});class su extends Qe{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return ve(n,{code:re.invalid_type,expected:be.promise,received:n.parsedType}),Be;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return Kn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}su.create=(e,t)=>new su({type:e,typeName:Fe.ZodPromise,...Ke(t)});class ds extends Qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Fe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:a=>{ve(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async l=>{if(n.value==="aborted")return Be;const c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?Be:c.status==="dirty"||n.value==="dirty"?vl(c.value):c});{if(n.value==="aborted")return Be;const l=this._def.schema._parseSync({data:a,path:r.path,parent:r});return l.status==="aborted"?Be:l.status==="dirty"||n.value==="dirty"?vl(l.value):l}}if(s.type==="refinement"){const a=l=>{const c=s.refinement(l,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Be:(l.status==="dirty"&&n.dirty(),a(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Be:(l.status==="dirty"&&n.dirty(),a(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!cd(a))return a;const l=s.transform(a.value,o);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>cd(a)?Promise.resolve(s.transform(a.value,o)).then(l=>({status:n.value,value:l})):a);ut.assertNever(s)}}ds.create=(e,t,n)=>new ds({schema:e,typeName:Fe.ZodEffects,effect:t,...Ke(n)});ds.createWithPreprocess=(e,t,n)=>new ds({schema:t,effect:{type:"preprocess",transform:e},typeName:Fe.ZodEffects,...Ke(n)});class Ls extends Qe{_parse(t){return this._getType(t)===be.undefined?Kn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ls.create=(e,t)=>new Ls({innerType:e,typeName:Fe.ZodOptional,...Ke(t)});class xa extends Qe{_parse(t){return this._getType(t)===be.null?Kn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}xa.create=(e,t)=>new xa({innerType:e,typeName:Fe.ZodNullable,...Ke(t)});class wd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}wd.create=(e,t)=>new wd({innerType:e,typeName:Fe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ke(t)});class Sd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return dd(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new yr(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new yr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Sd.create=(e,t)=>new Sd({innerType:e,typeName:Fe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ke(t)});class Sh extends Qe{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.nan,received:r.parsedType}),Be}return{status:"valid",value:t.data}}}Sh.create=e=>new Sh({typeName:Fe.ZodNaN,...Ke(e)});const w6=Symbol("zod_brand");class Sw extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Xd extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Be:o.status==="dirty"?(n.dirty(),vl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Be:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Xd({in:t,out:n,typeName:Fe.ZodPipeline})}}class Cd extends Qe{_parse(t){const n=this._def.innerType._parse(t),r=s=>(cd(s)&&(s.value=Object.freeze(s.value)),s);return dd(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Cd.create=(e,t)=>new Cd({innerType:e,typeName:Fe.ZodReadonly,...Ke(t)});function xM(e,t={},n){return e?ru.create().superRefine((r,s)=>{var o,a;if(!e(r)){const l=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,c=(a=(o=l.fatal)!==null&&o!==void 0?o:n)!==null&&a!==void 0?a:!0,i=typeof l=="string"?{message:l}:l;s.addIssue({code:"custom",...i,fatal:c})}}):ru.create()}const S6={object:Dt.lazycreate};var Fe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Fe||(Fe={}));const C6=(e,t={message:`Input not instance of ${e.name}`})=>xM(n=>n instanceof e,t),wM=es.create,SM=va.create,E6=Sh.create,T6=ya.create,CM=fd.create,k6=Ti.create,_6=bh.create,j6=pd.create,R6=hd.create,P6=ru.create,M6=fi.create,O6=bo.create,N6=xh.create,I6=as.create,D6=Dt.create,A6=Dt.strictCreate,F6=gd.create,L6=Pg.create,$6=md.create,B6=Us.create,z6=vd.create,U6=wh.create,V6=ki.create,H6=jl.create,K6=yd.create,q6=bd.create,W6=ba.create,G6=xd.create,J6=su.create,DC=ds.create,Q6=Ls.create,Z6=xa.create,Y6=ds.createWithPreprocess,X6=Xd.create,e8=()=>wM().optional(),t8=()=>SM().optional(),n8=()=>CM().optional(),r8={string:e=>es.create({...e,coerce:!0}),number:e=>va.create({...e,coerce:!0}),boolean:e=>fd.create({...e,coerce:!0}),bigint:e=>ya.create({...e,coerce:!0}),date:e=>Ti.create({...e,coerce:!0})},s8=Be;var _=Object.freeze({__proto__:null,defaultErrorMap:nu,setErrorMap:s6,getErrorMap:mh,makeIssue:vh,EMPTY_PATH:o6,addIssueToContext:ve,ParseStatus:Dn,INVALID:Be,DIRTY:vl,OK:Kn,isAborted:eb,isDirty:tb,isValid:cd,isAsync:dd,get util(){return ut},get objectUtil(){return Xy},ZodParsedType:be,getParsedType:Vo,ZodType:Qe,datetimeRegex:yM,ZodString:es,ZodNumber:va,ZodBigInt:ya,ZodBoolean:fd,ZodDate:Ti,ZodSymbol:bh,ZodUndefined:pd,ZodNull:hd,ZodAny:ru,ZodUnknown:fi,ZodNever:bo,ZodVoid:xh,ZodArray:as,ZodObject:Dt,ZodUnion:gd,ZodDiscriminatedUnion:Pg,ZodIntersection:md,ZodTuple:Us,ZodRecord:vd,ZodMap:wh,ZodSet:ki,ZodFunction:jl,ZodLazy:yd,ZodLiteral:bd,ZodEnum:ba,ZodNativeEnum:xd,ZodPromise:su,ZodEffects:ds,ZodTransformer:ds,ZodOptional:Ls,ZodNullable:xa,ZodDefault:wd,ZodCatch:Sd,ZodNaN:Sh,BRAND:w6,ZodBranded:Sw,ZodPipeline:Xd,ZodReadonly:Cd,custom:xM,Schema:Qe,ZodSchema:Qe,late:S6,get ZodFirstPartyTypeKind(){return Fe},coerce:r8,any:P6,array:I6,bigint:T6,boolean:CM,date:k6,discriminatedUnion:L6,effect:DC,enum:W6,function:H6,instanceof:C6,intersection:$6,lazy:K6,literal:q6,map:U6,nan:E6,nativeEnum:G6,never:O6,null:R6,nullable:Z6,number:SM,object:D6,oboolean:n8,onumber:t8,optional:Q6,ostring:e8,pipeline:X6,preprocess:Y6,promise:J6,record:z6,set:V6,strictObject:A6,string:wM,symbol:_6,transformer:DC,tuple:B6,undefined:j6,union:F6,unknown:M6,void:N6,NEVER:s8,ZodIssueCode:re,quotelessJson:r6,ZodError:yr}),EM=v.createContext({dragDropManager:void 0}),Dr;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(Dr||(Dr={}));function Ve(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),s=2;s-1})}var u8={type:Cw,payload:{clientOffset:null,sourceClientOffset:null}};function c8(e){return function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},s=r.publishSource,o=s===void 0?!0:s,a=r.clientOffset,l=r.getSourceClientOffset,c=e.getMonitor(),i=e.getRegistry();e.dispatch(AC(a)),d8(n,c,i);var d=h8(n,c);if(d===null){e.dispatch(u8);return}var p=null;if(a){if(!l)throw new Error("getSourceClientOffset must be defined");f8(l),p=l(d)}e.dispatch(AC(a,p));var f=i.getSource(d),h=f.beginDrag(c,d);if(h!=null){p8(h),i.pinSource(d);var g=i.getSourceType(d);return{type:Mg,payload:{itemType:g,item:h,sourceId:d,clientOffset:a||null,sourceClientOffset:p||null,isSourcePublic:!!o}}}}}function d8(e,t,n){Ve(!t.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(r){Ve(n.getSource(r),"Expected sourceIds to be registered.")})}function f8(e){Ve(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function p8(e){Ve(TM(e),"Item must be an object.")}function h8(e,t){for(var n=null,r=e.length-1;r>=0;r--)if(t.canDragSource(e[r])){n=e[r];break}return n}function g8(e){return function(){var n=e.getMonitor();if(n.isDragging())return{type:Ew}}}function rb(e,t){return t===null?e===null:Array.isArray(e)?e.some(function(n){return n===t}):e===t}function m8(e){return function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=r.clientOffset;v8(n);var o=n.slice(0),a=e.getMonitor(),l=e.getRegistry();y8(o,a,l);var c=a.getItemType();return b8(o,l,c),x8(o,a,l),{type:Og,payload:{targetIds:o,clientOffset:s||null}}}}function v8(e){Ve(Array.isArray(e),"Expected targetIds to be an array.")}function y8(e,t,n){Ve(t.isDragging(),"Cannot call hover while not dragging."),Ve(!t.didDrop(),"Cannot call hover after drop.");for(var r=0;r=0;r--){var s=e[r],o=t.getTargetType(s);rb(o,n)||e.splice(r,1)}}function x8(e,t,n){e.forEach(function(r){var s=n.getTarget(r);s.hover(t,r)})}function FC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function LC(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},r=e.getMonitor(),s=e.getRegistry();C8(r);var o=k8(r);o.forEach(function(a,l){var c=E8(a,l,s,r),i={type:Ng,payload:{dropResult:LC(LC({},n),c)}};e.dispatch(i)})}}function C8(e){Ve(e.isDragging(),"Cannot call drop while not dragging."),Ve(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function E8(e,t,n,r){var s=n.getTarget(e),o=s?s.drop(r,e):void 0;return T8(o),typeof o>"u"&&(o=t===0?{}:r.getDropResult()),o}function T8(e){Ve(typeof e>"u"||TM(e),"Drop result must either be an object or undefined.")}function k8(e){var t=e.getTargetIds().filter(e.canDropOnTarget,e);return t.reverse(),t}function _8(e){return function(){var n=e.getMonitor(),r=e.getRegistry();j8(n);var s=n.getSourceId();if(s!=null){var o=r.getSource(s,!0);o.endDrag(n,s),r.unpinSource()}return{type:Ig}}}function j8(e){Ve(e.isDragging(),"Cannot call endDrag while not dragging.")}function R8(e){return{beginDrag:c8(e),publishDragSource:g8(e),hover:m8(e),drop:S8(e),endDrag:_8(e)}}function P8(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M8(e,t){for(var n=0;n0;r.backend&&(s&&!r.isSetUp?(r.backend.setup(),r.isSetUp=!0):!s&&r.isSetUp&&(r.backend.teardown(),r.isSetUp=!1))}),this.store=t,this.monitor=n,t.subscribe(this.handleRefCountChange)}return O8(e,[{key:"receiveBackend",value:function(n){this.backend=n}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var n=this,r=this.store.dispatch;function s(a){return function(){for(var l=arguments.length,c=new Array(l),i=0;i"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(_r(1));return n(kM)(e,t)}if(typeof e!="function")throw new Error(_r(2));var s=e,o=t,a=[],l=a,c=!1;function i(){l===a&&(l=a.slice())}function d(){if(c)throw new Error(_r(3));return o}function p(m){if(typeof m!="function")throw new Error(_r(4));if(c)throw new Error(_r(5));var x=!0;return i(),l.push(m),function(){if(x){if(c)throw new Error(_r(6));x=!1,i();var y=l.indexOf(m);l.splice(y,1),a=null}}}function f(m){if(!I8(m))throw new Error(_r(7));if(typeof m.type>"u")throw new Error(_r(8));if(c)throw new Error(_r(9));try{c=!0,o=s(o,m)}finally{c=!1}for(var x=a=l,b=0;b2&&arguments[2]!==void 0?arguments[2]:D8;if(e.length!==t.length)return!1;for(var r=0;r0&&arguments[0]!==void 0?arguments[0]:VC,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Cw:case Mg:return{initialSourceClientOffset:n.sourceClientOffset,initialClientOffset:n.clientOffset,clientOffset:n.clientOffset};case Og:return A8(e.clientOffset,n.clientOffset)?e:UC(UC({},e),{},{clientOffset:n.clientOffset});case Ig:case Ng:return VC;default:return e}}var Tw="dnd-core/ADD_SOURCE",kw="dnd-core/ADD_TARGET",_w="dnd-core/REMOVE_SOURCE",Dg="dnd-core/REMOVE_TARGET";function B8(e){return{type:Tw,payload:{sourceId:e}}}function z8(e){return{type:kw,payload:{targetId:e}}}function U8(e){return{type:_w,payload:{sourceId:e}}}function V8(e){return{type:Dg,payload:{targetId:e}}}function HC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function jr(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:K8,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Mg:return jr(jr({},e),{},{itemType:n.itemType,item:n.item,sourceId:n.sourceId,isSourcePublic:n.isSourcePublic,dropResult:null,didDrop:!1});case Ew:return jr(jr({},e),{},{isSourcePublic:!0});case Og:return jr(jr({},e),{},{targetIds:n.targetIds});case Dg:return e.targetIds.indexOf(n.targetId)===-1?e:jr(jr({},e),{},{targetIds:a8(e.targetIds,n.targetId)});case Ng:return jr(jr({},e),{},{dropResult:n.dropResult,didDrop:!0,targetIds:[]});case Ig:return jr(jr({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function W8(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case Tw:case kw:return e+1;case _w:case Dg:return e-1;default:return e}}var Ch=[],jw=[];Ch.__IS_NONE__=!0;jw.__IS_ALL__=!0;function G8(e,t){if(e===Ch)return!1;if(e===jw||typeof t>"u")return!0;var n=l8(t,e);return n.length>0}function J8(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case Og:break;case Tw:case kw:case Dg:case _w:return Ch;case Mg:case Ew:case Ig:case Ng:default:return jw}var t=e.payload,n=t.targetIds,r=n===void 0?[]:n,s=t.prevTargetIds,o=s===void 0?[]:s,a=i8(r,o),l=a.length>0||!F8(r,o);if(!l)return Ch;var c=o[o.length-1],i=r[r.length-1];return c!==i&&(c&&a.push(c),i&&a.push(i)),a}function Q8(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function KC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function qC(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:J8(e.dirtyHandlerIds,{type:t.type,payload:qC(qC({},t.payload),{},{prevTargetIds:o8(e,"dragOperation.targetIds",[])})}),dragOffset:$8(e.dragOffset,t),refCount:W8(e.refCount,t),dragOperation:q8(e.dragOperation,t),stateId:Q8(e.stateId)}}function X8(e,t){return{x:e.x+t.x,y:e.y+t.y}}function _M(e,t){return{x:e.x-t.x,y:e.y-t.y}}function eH(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return!t||!n||!r?null:_M(X8(t,r),n)}function tH(e){var t=e.clientOffset,n=e.initialClientOffset;return!t||!n?null:_M(t,n)}function nH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rH(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},o=s.handlerIds;Ve(typeof n=="function","listener must be a function."),Ve(typeof o>"u"||Array.isArray(o),"handlerIds, when specified, must be an array of strings.");var a=this.store.getState().stateId,l=function(){var i=r.store.getState(),d=i.stateId;try{var p=d===a||d===a+1&&!G8(i.dirtyHandlerIds,o);p||n()}finally{a=d}};return this.store.subscribe(l)}},{key:"subscribeToOffsetChange",value:function(n){var r=this;Ve(typeof n=="function","listener must be a function.");var s=this.store.getState().dragOffset,o=function(){var l=r.store.getState().dragOffset;l!==s&&(s=l,n())};return this.store.subscribe(o)}},{key:"canDragSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n);return Ve(r,"Expected to find a valid source. sourceId=".concat(n)),this.isDragging()?!1:r.canDrag(this,n)}},{key:"canDropOnTarget",value:function(n){if(!n)return!1;var r=this.registry.getTarget(n);if(Ve(r,"Expected to find a valid target. targetId=".concat(n)),!this.isDragging()||this.didDrop())return!1;var s=this.registry.getTargetType(n),o=this.getItemType();return rb(s,o)&&r.canDrop(this,n)}},{key:"isDragging",value:function(){return!!this.getItemType()}},{key:"isDraggingSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n,!0);if(Ve(r,"Expected to find a valid source. sourceId=".concat(n)),!this.isDragging()||!this.isSourcePublic())return!1;var s=this.registry.getSourceType(n),o=this.getItemType();return s!==o?!1:r.isDragging(this,n)}},{key:"isOverTarget",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!n)return!1;var s=r.shallow;if(!this.isDragging())return!1;var o=this.registry.getTargetType(n),a=this.getItemType();if(a&&!rb(o,a))return!1;var l=this.getTargetIds();if(!l.length)return!1;var c=l.indexOf(n);return s?c===l.length-1:c>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return!!this.store.getState().dragOperation.isSourcePublic}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return eH(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return tH(this.store.getState().dragOffset)}}]),e}(),aH=0;function iH(){return aH++}function bp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?bp=function(n){return typeof n}:bp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},bp(e)}function lH(e){Ve(typeof e.canDrag=="function","Expected canDrag to be a function."),Ve(typeof e.beginDrag=="function","Expected beginDrag to be a function."),Ve(typeof e.endDrag=="function","Expected endDrag to be a function.")}function uH(e){Ve(typeof e.canDrop=="function","Expected canDrop to be a function."),Ve(typeof e.hover=="function","Expected hover to be a function."),Ve(typeof e.drop=="function","Expected beginDrag to be a function.")}function sb(e,t){if(t&&Array.isArray(e)){e.forEach(function(n){return sb(n,!1)});return}Ve(typeof e=="string"||bp(e)==="symbol",t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}const GC=typeof global<"u"?global:self,jM=GC.MutationObserver||GC.WebKitMutationObserver;function RM(e){return function(){const n=setTimeout(s,0),r=setInterval(s,50);function s(){clearTimeout(n),clearInterval(r),e()}}}function cH(e){let t=1;const n=new jM(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}const dH=typeof jM=="function"?cH:RM;class fH{enqueueTask(t){const{queue:n,requestFlush:r}=this;n.length||(r(),this.flushing=!0),n[n.length]=t}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:t}=this;for(;this.indexthis.capacity){for(let r=0,s=t.length-this.index;r{this.pendingErrors.push(t),this.requestErrorThrow()},this.requestFlush=dH(this.flush),this.requestErrorThrow=RM(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class pH{call(){try{this.task&&this.task()}catch(t){this.onError(t)}finally{this.task=null,this.release(this)}}constructor(t,n){this.onError=t,this.release=n,this.task=null}}class hH{create(t){const n=this.freeTasks,r=n.length?n.pop():new pH(this.onError,s=>n[n.length]=s);return r.task=t,r}constructor(t){this.onError=t,this.freeTasks=[]}}const PM=new fH,gH=new hH(PM.registerPendingError);function mH(e){PM.enqueueTask(gH.create(e))}function vH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function yH(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:!1;Ve(this.isSourceId(n),"Expected a valid source ID.");var s=r&&n===this.pinnedSourceId,o=s?this.pinnedSource:this.dragSources.get(n);return o}},{key:"getTarget",value:function(n){return Ve(this.isTargetId(n),"Expected a valid target ID."),this.dropTargets.get(n)}},{key:"getSourceType",value:function(n){return Ve(this.isSourceId(n),"Expected a valid source ID."),this.types.get(n)}},{key:"getTargetType",value:function(n){return Ve(this.isTargetId(n),"Expected a valid target ID."),this.types.get(n)}},{key:"isSourceId",value:function(n){var r=QC(n);return r===Dr.SOURCE}},{key:"isTargetId",value:function(n){var r=QC(n);return r===Dr.TARGET}},{key:"removeSource",value:function(n){var r=this;Ve(this.getSource(n),"Expected an existing source."),this.store.dispatch(U8(n)),mH(function(){r.dragSources.delete(n),r.types.delete(n)})}},{key:"removeTarget",value:function(n){Ve(this.getTarget(n),"Expected an existing target."),this.store.dispatch(V8(n)),this.dropTargets.delete(n),this.types.delete(n)}},{key:"pinSource",value:function(n){var r=this.getSource(n);Ve(r,"Expected an existing source."),this.pinnedSourceId=n,this.pinnedSource=r}},{key:"unpinSource",value:function(){Ve(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(n,r,s){var o=TH(n);return this.types.set(o,r),n===Dr.SOURCE?this.dragSources.set(o,s):n===Dr.TARGET&&this.dropTargets.set(o,s),o}}]),e}();function _H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=jH(r),o=new oH(s,new kH(s)),a=new N8(s,o),l=e(a,t,n);return a.receiveBackend(l),a}function jH(e){var t=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__;return kM(Y8,e&&t&&t({name:"dnd-core",instanceId:"dnd-core"}))}var RH=["children"];function PH(e,t){return IH(e)||NH(e,t)||OH(e,t)||MH()}function MH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OH(e,t){if(e){if(typeof e=="string")return YC(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return YC(e,t)}}function YC(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function AH(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o=0)&&(n[s]=e[s]);return n}var XC=0,xp=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),FH=v.memo(function(t){var n=t.children,r=DH(t,RH),s=LH(r),o=PH(s,2),a=o[0],l=o[1];return v.useEffect(function(){if(l){var c=MM();return++XC,function(){--XC===0&&(c[xp]=null)}}},[]),u.jsx(EM.Provider,Object.assign({value:a},{children:n}),void 0)});function LH(e){if("manager"in e){var t={dragDropManager:e.manager};return[t,!1]}var n=$H(e.backend,e.context,e.options,e.debugMode),r=!e.context;return[n,r]}function $H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:MM(),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,s=t;return s[xp]||(s[xp]={dragDropManager:_H(e,t,n,r)}),s[xp]}function MM(){return typeof global<"u"?global:window}function BH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function zH(e,t){for(var n=0;n, or turn it into a ")+"drag source or a drop target itself.")}}function JH(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!v.isValidElement(t)){var r=t;return e(r,n),r}var s=t;GH(s);var o=n?function(a){return e(a,n)}:e;return QH(s,o)}}function OM(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n];if(n.endsWith("Ref"))t[n]=e[n];else{var s=JH(r);t[n]=function(){return s}}}),t}function n1(e,t){typeof e=="function"?e(t):e.current=t}function QH(e,t){var n=e.ref;return Ve(typeof n!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),n?v.cloneElement(e,{ref:function(s){n1(n,s),n1(t,s)}}):v.cloneElement(e,{ref:t})}function wp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?wp=function(n){return typeof n}:wp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},wp(e)}function ob(e){return e!==null&&wp(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ab(e,t,n,r){var s=void 0;if(s!==void 0)return!!s;if(e===t)return!0;if(typeof e!="object"||!e||typeof t!="object"||!t)return!1;var o=Object.keys(e),a=Object.keys(t);if(o.length!==a.length)return!1;for(var l=Object.prototype.hasOwnProperty.bind(t),c=0;ce.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"leave",value:function(n){var r=this.entered.length;return this.entered=oK(this.entered.filter(this.isNodeInDocument),n),r>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),e}(),dK=DM(function(){return/firefox/i.test(navigator.userAgent)}),AM=DM(function(){return!!window.safari});function fK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function pK(e,t){for(var n=0;nn)d=p-1;else return s[p]}c=Math.max(0,d);var h=n-r[c],g=h*h;return s[c]+o[c]*h+a[c]*g+l[c]*h*g}}]),e}(),gK=1;function FM(e){var t=e.nodeType===gK?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,s=n.left;return{x:s,y:r}}function Bf(e){return{x:e.clientX,y:e.clientY}}function mK(e){var t;return e.nodeName==="IMG"&&(dK()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(e)))}function vK(e,t,n,r){var s=e?t.width:n,o=e?t.height:r;return AM()&&e&&(o/=window.devicePixelRatio,s/=window.devicePixelRatio),{dragPreviewWidth:s,dragPreviewHeight:o}}function yK(e,t,n,r,s){var o=mK(t),a=o?e:t,l=FM(a),c={x:n.x-l.x,y:n.y-l.y},i=e.offsetWidth,d=e.offsetHeight,p=r.anchorX,f=r.anchorY,h=vK(o,t,i,d),g=h.dragPreviewWidth,m=h.dragPreviewHeight,x=function(){var k=new u1([0,.5,1],[c.y,c.y/d*m,c.y+m-d]),T=k.interpolate(f);return AM()&&o&&(T+=(window.devicePixelRatio-1)*m),T},b=function(){var k=new u1([0,.5,1],[c.x,c.x/i*g,c.x+g-i]);return k.interpolate(p)},y=s.offsetX,w=s.offsetY,S=y===0||y,E=w===0||w;return{x:S?y:b(),y:E?w:x()}}var LM="__NATIVE_FILE__",$M="__NATIVE_URL__",BM="__NATIVE_TEXT__",zM="__NATIVE_HTML__";const c1=Object.freeze(Object.defineProperty({__proto__:null,FILE:LM,HTML:zM,TEXT:BM,URL:$M},Symbol.toStringTag,{value:"Module"}));function av(e,t,n){var r=t.reduce(function(s,o){return s||e.getData(o)},"");return r??n}var Qi;function zf(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var lb=(Qi={},zf(Qi,LM,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items},dataTransfer:function(t){return t}},matchesTypes:["Files"]}),zf(Qi,zM,{exposeProperties:{html:function(t,n){return av(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Html","text/html"]}),zf(Qi,$M,{exposeProperties:{urls:function(t,n){return av(t,n,"").split(` -`)},dataTransfer:function(t){return t}},matchesTypes:["Url","text/uri-list"]}),zf(Qi,BM,{exposeProperties:{text:function(t,n){return av(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Text","text/plain"]}),Qi);function bK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function xK(e,t){for(var n=0;n-1})})[0]||null}function EK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function TK(e,t){for(var n=0;n0&&s.actions.hover(a,{clientOffset:Bf(o)});var l=a.some(function(c){return s.monitor.canDropOnTarget(c)});l&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect()))}}),st(this,"handleTopDragOverCapture",function(){s.dragOverTargetIds=[]}),st(this,"handleTopDragOver",function(o){var a=s.dragOverTargetIds;if(s.dragOverTargetIds=[],!s.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}s.altKeyPressed=o.altKey,s.lastClientOffset=Bf(o),s.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(s.hoverRafId=requestAnimationFrame(function(){s.monitor.isDragging()&&s.actions.hover(a||[],{clientOffset:s.lastClientOffset}),s.hoverRafId=null}));var l=(a||[]).some(function(c){return s.monitor.canDropOnTarget(c)});l?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect())):s.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))}),st(this,"handleTopDragLeaveCapture",function(o){s.isDraggingNativeItem()&&o.preventDefault();var a=s.enterLeaveCounter.leave(o.target);a&&s.isDraggingNativeItem()&&setTimeout(function(){return s.endDragNativeItem()},0)}),st(this,"handleTopDropCapture",function(o){if(s.dropTargetIds=[],s.isDraggingNativeItem()){var a;o.preventDefault(),(a=s.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}else iv(o.dataTransfer)&&o.preventDefault();s.enterLeaveCounter.reset()}),st(this,"handleTopDrop",function(o){var a=s.dropTargetIds;s.dropTargetIds=[],s.actions.hover(a,{clientOffset:Bf(o)}),s.actions.drop({dropEffect:s.getCurrentDropEffect()}),s.isDraggingNativeItem()?s.endDragNativeItem():s.monitor.isDragging()&&s.actions.endDrag()}),st(this,"handleSelectStart",function(o){var a=o.target;typeof a.dragDrop=="function"&&(a.tagName==="INPUT"||a.tagName==="SELECT"||a.tagName==="TEXTAREA"||a.isContentEditable||(o.preventDefault(),a.dragDrop()))}),this.options=new _K(n,r),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new cK(this.isNodeInDocument)}return PK(e,[{key:"profile",value:function(){var n,r;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((n=this.dragStartSourceIds)===null||n===void 0?void 0:n.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((r=this.dragOverTargetIds)===null||r===void 0?void 0:r.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var n=this.rootElement;if(n!==void 0){if(n.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");n.__isReactDndBackendSetUp=!0,this.addEventListeners(n)}}},{key:"teardown",value:function(){var n=this.rootElement;if(n!==void 0&&(n.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var r;(r=this.window)===null||r===void 0||r.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(n,r,s){var o=this;return this.sourcePreviewNodeOptions.set(n,s),this.sourcePreviewNodes.set(n,r),function(){o.sourcePreviewNodes.delete(n),o.sourcePreviewNodeOptions.delete(n)}}},{key:"connectDragSource",value:function(n,r,s){var o=this;this.sourceNodes.set(n,r),this.sourceNodeOptions.set(n,s);var a=function(i){return o.handleDragStart(i,n)},l=function(i){return o.handleSelectStart(i)};return r.setAttribute("draggable","true"),r.addEventListener("dragstart",a),r.addEventListener("selectstart",l),function(){o.sourceNodes.delete(n),o.sourceNodeOptions.delete(n),r.removeEventListener("dragstart",a),r.removeEventListener("selectstart",l),r.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(n,r){var s=this,o=function(i){return s.handleDragEnter(i,n)},a=function(i){return s.handleDragOver(i,n)},l=function(i){return s.handleDrop(i,n)};return r.addEventListener("dragenter",o),r.addEventListener("dragover",a),r.addEventListener("drop",l),function(){r.removeEventListener("dragenter",o),r.removeEventListener("dragover",a),r.removeEventListener("drop",l)}}},{key:"addEventListeners",value:function(n){n.addEventListener&&(n.addEventListener("dragstart",this.handleTopDragStart),n.addEventListener("dragstart",this.handleTopDragStartCapture,!0),n.addEventListener("dragend",this.handleTopDragEndCapture,!0),n.addEventListener("dragenter",this.handleTopDragEnter),n.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.addEventListener("dragover",this.handleTopDragOver),n.addEventListener("dragover",this.handleTopDragOverCapture,!0),n.addEventListener("drop",this.handleTopDrop),n.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(n){n.removeEventListener&&(n.removeEventListener("dragstart",this.handleTopDragStart),n.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),n.removeEventListener("dragend",this.handleTopDragEndCapture,!0),n.removeEventListener("dragenter",this.handleTopDragEnter),n.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.removeEventListener("dragover",this.handleTopDragOver),n.removeEventListener("dragover",this.handleTopDragOverCapture,!0),n.removeEventListener("drop",this.handleTopDrop),n.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(n);return p1({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(n);return p1({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}},{key:"isDraggingNativeItem",value:function(){var n=this.monitor.getItemType();return Object.keys(c1).some(function(r){return c1[r]===n})}},{key:"beginDragNativeItem",value:function(n,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=CK(n,r),this.currentNativeHandle=this.registry.addSource(n,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(n){var r=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=n;var s=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var o;return(o=r.rootElement)===null||o===void 0?void 0:o.addEventListener("mousemove",r.endDragIfSourceWasRemovedFromDOM,!0)},s)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var n;(n=this.window)===null||n===void 0||n.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(n,r){n.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}},{key:"handleDragEnter",value:function(n,r){this.dragEnterTargetIds.unshift(r)}},{key:"handleDragOver",value:function(n,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}},{key:"handleDrop",value:function(n,r){this.dropTargetIds.unshift(r)}}]),e}(),OK=function(t,n,r){return new MK(t,n,r)},NK=Object.create,UM=Object.defineProperty,IK=Object.getOwnPropertyDescriptor,VM=Object.getOwnPropertyNames,DK=Object.getPrototypeOf,AK=Object.prototype.hasOwnProperty,FK=(e,t)=>function(){return t||(0,e[VM(e)[0]])((t={exports:{}}).exports,t),t.exports},LK=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of VM(t))!AK.call(e,s)&&s!==n&&UM(e,s,{get:()=>t[s],enumerable:!(r=IK(t,s))||r.enumerable});return e},HM=(e,t,n)=>(n=e!=null?NK(DK(e)):{},LK(UM(n,"default",{value:e,enumerable:!0}),e)),KM=FK({"node_modules/classnames/index.js"(e,t){(function(){var n={}.hasOwnProperty;function r(){for(var s=[],o=0;o-1}var Wq=qq,Gq=9007199254740991,Jq=/^(?:0|[1-9]\d*)$/;function Qq(e,t){var n=typeof e;return t=t??Gq,!!t&&(n=="number"||n!="symbol"&&Jq.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=Xq}var YM=eW;function tW(e){return e!=null&&YM(e.length)&&!QM(e)}var nW=tW,rW=Object.prototype;function sW(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||rW;return e===n}var oW=sW;function aW(e,t){for(var n=-1,r=Array(e);++n-1}var FG=AG;function LG(e,t){var n=this.__data__,r=Ag(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var $G=LG;function Eu(e){var t=-1,n=e==null?0:e.length;for(this.clear();++tl))return!1;var i=o.get(e),d=o.get(t);if(i&&d)return i==t&&d==e;var p=-1,f=!0,h=n&q9?new oO:void 0;for(o.set(e,t),o.set(t,e);++p":">",'"':""","'":"'"},TJ=s9(EJ),kJ=TJ,uO=/[&<>"']/g,_J=RegExp(uO.source);function jJ(e){return e=sO(e),e&&_J.test(e)?e.replace(uO,kJ):e}var RJ=jJ,cO=/[\\^$.*+?()[\]{}|]/g,PJ=RegExp(cO.source);function MJ(e){return e=sO(e),e&&PJ.test(e)?e.replace(cO,"\\$&"):e}var OJ=MJ;function NJ(e,t){return wJ(e,t)}var IJ=NJ,DJ=1/0,AJ=Pl&&1/Rw(new Pl([,-0]))[1]==DJ?function(e){return new Pl(e)}:Fq,FJ=AJ,LJ=200;function $J(e,t,n){var r=-1,s=Wq,o=e.length,a=!0,l=[],c=l;if(n)a=!1,s=CJ;else if(o>=LJ){var i=t?null:FJ(e);if(i)return Rw(i);a=!1,s=aO,c=new oO}else c=t?[]:l;e:for(;++ru.jsx("button",{className:e.classNames.clearAll,onClick:e.onClick,children:"Clear all"}),HJ=VJ,KJ=(e,t)=>{const n=t.offsetHeight,r=e.offsetHeight,s=e.offsetTop-t.scrollTop;s+r>=n?t.scrollTop+=s-n+r:s<0&&(t.scrollTop+=s)},pb=(e,t,n,r)=>typeof r=="function"?r(e):e.length>=t&&n,qJ=e=>{const t=v.createRef(),{labelField:n,minQueryLength:r,isFocused:s,classNames:o,selectedIndex:a,query:l}=e;v.useEffect(()=>{if(!t.current)return;const p=t.current.querySelector(`.${o.activeSuggestion}`);p&&KJ(p,t.current)},[a]);const c=(p,f)=>{const h=f.trim().replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&"),{[n]:g}=p;return{__html:g.replace(RegExp(h,"gi"),m=>`${RJ(m)}`)}},i=(p,f)=>typeof e.renderSuggestion=="function"?e.renderSuggestion(p,f):u.jsx("span",{dangerouslySetInnerHTML:c(p,f)}),d=e.suggestions.map((p,f)=>u.jsx("li",{onMouseDown:e.handleClick.bind(null,f),onTouchStart:e.handleClick.bind(null,f),onMouseOver:e.handleHover.bind(null,f),className:f===e.selectedIndex?e.classNames.activeSuggestion:"",children:i(p,e.query)},f));return d.length===0||!pb(l,r||2,s,e.shouldRenderSuggestions)?null:u.jsx("div",{ref:t,className:o.suggestions,"data-testid":"suggestions",children:u.jsxs("ul",{children:[" ",d," "]})})},WJ=(e,t)=>{const{query:n,minQueryLength:r=2,isFocused:s,suggestions:o}=t;return!!(e.isFocused===s&&IJ(e.suggestions,o)&&pb(n,r,s,t.shouldRenderSuggestions)===pb(e.query,e.minQueryLength??2,e.isFocused,e.shouldRenderSuggestions)&&e.selectedIndex===t.selectedIndex)},GJ=v.memo(qJ,WJ),JJ=GJ,QJ=HM(KM()),ZJ=HM(KM());function YJ(e){const t=e.map(r=>{const s=r-48*Math.floor(r/48);return String.fromCharCode(96<=r?s:r)}).join(""),n=OJ(t);return new RegExp(`[${n}]+`)}function XJ(e){switch(e){case Rs.ENTER:return[10,13];case Rs.TAB:return 9;case Rs.COMMA:return 188;case Rs.SPACE:return 32;case Rs.SEMICOLON:return 186;default:return 0}}function $1(e){const{moveTag:t,readOnly:n,allowDragDrop:r}=e;return t!==void 0&&!n&&r}function eQ(e){const{readOnly:t,allowDragDrop:n}=e;return!t&&n}var tQ=e=>{const{readOnly:t,removeComponent:n,onRemove:r,className:s,tag:o,index:a}=e,l=i=>{if(Rl.ENTER.includes(i.keyCode)||i.keyCode===Rl.SPACE){i.preventDefault(),i.stopPropagation();return}i.keyCode===Rl.BACKSPACE&&r(i)};if(t)return u.jsx("span",{});const c=`Tag at index ${a} with value ${o.id} focussed. Press backspace to remove`;if(n){const i=n;return u.jsx(i,{"data-testid":"remove",onRemove:r,onKeyDown:l,className:s,"aria-label":c,tag:o,index:a})}return u.jsx("button",{"data-testid":"remove",onClick:r,onKeyDown:l,className:s,type:"button","aria-label":c,children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"12",width:"12",fill:"#fff",children:u.jsx("path",{d:"M376.6 84.5c11.3-13.6 9.5-33.8-4.1-45.1s-33.8-9.5-45.1 4.1L192 206 56.6 43.5C45.3 29.9 25.1 28.1 11.5 39.4S-3.9 70.9 7.4 84.5L150.3 256 7.4 427.5c-11.3 13.6-9.5 33.8 4.1 45.1s33.8 9.5 45.1-4.1L192 306 327.4 468.5c11.3 13.6 31.5 15.4 45.1 4.1s15.4-31.5 4.1-45.1L233.7 256 376.6 84.5z"})})})},nQ=tQ,B1={TAG:"tag"},rQ=e=>{const t=v.useRef(null),{readOnly:n=!1,tag:r,classNames:s,index:o,moveTag:a,allowDragDrop:l=!0,labelField:c="text",tags:i}=e,[{isDragging:d},p]=U7(()=>({type:B1.TAG,collect:x=>({isDragging:!!x.isDragging()}),item:e,canDrag:()=>$1({moveTag:a,readOnly:n,allowDragDrop:l})}),[i]),[,f]=sK(()=>({accept:B1.TAG,drop:x=>{var w;const b=x.index,y=o;b!==y&&((w=e==null?void 0:e.moveTag)==null||w.call(e,b,y))},canDrop:x=>eQ(x)}),[i]);p(f(t));const h=e.tag[c],{className:g=""}=r,m=d?0:1;return u.jsxs("span",{ref:t,className:(0,ZJ.default)("tag-wrapper",s.tag,g),style:{opacity:m,cursor:$1({moveTag:a,readOnly:n,allowDragDrop:l})?"move":"auto"},"data-testid":"tag",onClick:e.onTagClicked,onTouchStart:e.onTagClicked,children:[h,u.jsx(nQ,{tag:e.tag,className:s.remove,removeComponent:e.removeComponent,onRemove:e.onDelete,readOnly:n,index:o})]})},sQ=e=>{const{autofocus:t,autoFocus:n,readOnly:r,labelField:s,allowDeleteFromEmptyInput:o,allowAdditionFromPaste:a,allowDragDrop:l,minQueryLength:c,shouldRenderSuggestions:i,removeComponent:d,autocomplete:p,inline:f,maxTags:h,allowUnique:g,editable:m,placeholder:x,delimiters:b,separators:y,tags:w,inputFieldPosition:S,inputProps:E,classNames:C,maxLength:k,inputValue:T,clearAll:P}=e,[N,U]=v.useState(e.suggestions),[I,Z]=v.useState(""),[V,Q]=v.useState(!1),[ee,W]=v.useState(-1),[F,A]=v.useState(!1),[Y,de]=v.useState(""),[z,se]=v.useState(-1),[ne,ie]=v.useState(""),oe=v.createRef(),J=v.useRef(null),Ce=v.useRef(null);v.useEffect(()=>{b.length&&console.warn("[Deprecation] The delimiters prop is deprecated and will be removed in v7.x.x, please use separators instead. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/960")},[]),v.useEffect(()=>{typeof f<"u"&&console.warn("[Deprecation] The inline attribute is deprecated and will be removed in v7.x.x, please use inputFieldPosition instead.")},[f]),v.useEffect(()=>{typeof t<"u"&&console.warn("[Deprecated] autofocus prop will be removed in 7.x so please migrate to autoFocus prop."),(t||n&&t!==!1)&&!r&&Me()},[n,n,r]),v.useEffect(()=>{Wt()},[I,e.suggestions]);const Pe=ue=>{let Ue=e.suggestions.slice();if(g){const _n=w.map(ms=>ms.id.trim().toLowerCase());Ue=Ue.filter(ms=>!_n.includes(ms.id.toLowerCase()))}if(e.handleFilterSuggestions)return e.handleFilterSuggestions(ue,Ue);const St=Ue.filter(_n=>Le(ue,_n)===0),dt=Ue.filter(_n=>Le(ue,_n)>0);return St.concat(dt)},Le=(ue,Ue)=>Ue[s].toLowerCase().indexOf(ue.toLowerCase()),Me=()=>{Z(""),J.current&&(J.current.value="",J.current.focus())},me=(ue,Ue)=>{var dt;Ue.preventDefault(),Ue.stopPropagation();const St=w.slice();St.length!==0&&(ie(""),(dt=e==null?void 0:e.handleDelete)==null||dt.call(e,ue,Ue),rt(ue,St))},rt=(ue,Ue)=>{var _n;if(!(oe!=null&&oe.current))return;const St=oe.current.querySelectorAll(".ReactTags__remove");let dt="";ue===0&&Ue.length>1?(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Tag at index 0 with value ${Ue[1].id} focussed. Press backspace to remove`,St[0].focus()):ue>0?(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Tag at index ${ue-1} with value ${Ue[ue-1].id} focussed. Press backspace to remove`,St[ue-1].focus()):(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Input focussed. Press enter to add a new tag`,(_n=J.current)==null||_n.focus()),de(dt)},It=(ue,Ue,St)=>{var dt,_n;r||(m&&(se(ue),Z(Ue[s]),(dt=Ce.current)==null||dt.focus()),(_n=e.handleTagClick)==null||_n.call(e,ue,St))},Zt=ue=>{e.handleInputChange&&e.handleInputChange(ue.target.value,ue);const Ue=ue.target.value.trim();Z(Ue)},Wt=()=>{const ue=Pe(I);U(ue),W(ee>=ue.length?ue.length-1:ee)},an=ue=>{const Ue=ue.target.value;e.handleInputFocus&&e.handleInputFocus(Ue,ue),Q(!0)},j=ue=>{const Ue=ue.target.value;e.handleInputBlur&&(e.handleInputBlur(Ue,ue),J.current&&(J.current.value="")),Q(!1),se(-1)},D=ue=>{if(ue.key==="Escape"&&(ue.preventDefault(),ue.stopPropagation(),W(-1),A(!1),U([]),se(-1)),(y.indexOf(ue.key)!==-1||b.indexOf(ue.keyCode)!==-1)&&!ue.shiftKey){(ue.keyCode!==Rl.TAB||I!=="")&&ue.preventDefault();const Ue=F&&ee!==-1?N[ee]:{id:I.trim(),[s]:I.trim(),className:""};Object.keys(Ue)&&le(Ue)}ue.key==="Backspace"&&I===""&&(o||S===ec.INLINE)&&me(w.length-1,ue),ue.keyCode===Rl.UP_ARROW&&(ue.preventDefault(),W(ee<=0?N.length-1:ee-1),A(!0)),ue.keyCode===Rl.DOWN_ARROW&&(ue.preventDefault(),A(!0),N.length===0?W(-1):W((ee+1)%N.length))},B=()=>h&&w.length>=h,pe=ue=>{if(!a)return;if(B()){ie(g1.TAG_LIMIT),Me();return}ie(""),ue.preventDefault();const Ue=ue.clipboardData||window.clipboardData,St=Ue.getData("text"),{maxLength:dt=St.length}=e,_n=Math.min(dt,St.length),ms=Ue.getData("text").substr(0,_n);let Ro=b;y.length&&(Ro=[],y.forEach(vs=>{const Du=XJ(vs);Array.isArray(Du)?Ro=[...Ro,...Du]:Ro.push(Du)}));const Iu=YJ(Ro),$i=ms.split(Iu).map(vs=>vs.trim());UJ($i).forEach(vs=>le({id:vs.trim(),[s]:vs.trim(),className:""}))},le=ue=>{var St;if(!ue.id||!ue[s])return;if(z===-1){if(B()){ie(g1.TAG_LIMIT),Me();return}ie("")}const Ue=w.map(dt=>dt.id.toLowerCase());if(!(g&&Ue.indexOf(ue.id.trim().toLowerCase())>=0)){if(p){const dt=Pe(ue[s]);console.warn("[Deprecation] The autocomplete prop will be removed in 7.x to simplify the integration and make it more intutive. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/949"),(p===1&&dt.length===1||p===!0&&dt.length)&&(ue=dt[0])}z!==-1&&e.onTagUpdate?e.onTagUpdate(z,ue):(St=e==null?void 0:e.handleAddition)==null||St.call(e,ue),Z(""),A(!1),W(-1),se(-1),Me()}},ae=ue=>{le(N[ue])},Ee=()=>{e.onClearAll&&e.onClearAll(),ie(""),Me()},et=ue=>{W(ue),A(!0)},kt=(ue,Ue)=>{var dt;const St=w[ue];(dt=e==null?void 0:e.handleDrag)==null||dt.call(e,St,ue,Ue)},yn=(()=>{const ue={...h1,...e.classNames};return w.map((Ue,St)=>u.jsx(v.Fragment,{children:z===St?u.jsx("div",{className:ue.editTagInput,children:u.jsx("input",{ref:dt=>{Ce.current=dt},onFocus:an,value:I,onChange:Zt,onKeyDown:D,onBlur:j,className:ue.editTagInputField,onPaste:pe,"data-testid":"tag-edit"})}):u.jsx(rQ,{index:St,tag:Ue,tags:w,labelField:s,onDelete:dt=>me(St,dt),moveTag:l?kt:void 0,removeComponent:d,onTagClicked:dt=>It(St,Ue,dt),readOnly:r,classNames:ue,allowDragDrop:l})},St))})(),gn={...h1,...C},{name:jo,id:gs}=e,Aa=f===!1?ec.BOTTOM:S,Fn=r?null:u.jsxs("div",{className:gn.tagInput,children:[u.jsx("input",{...E,ref:ue=>{J.current=ue},className:gn.tagInputField,type:"text",placeholder:x,"aria-label":x,onFocus:an,onBlur:j,onChange:Zt,onKeyDown:D,onPaste:pe,name:jo,id:gs,maxLength:k,value:T,"data-automation":"input","data-testid":"input"}),u.jsx(JJ,{query:I.trim(),suggestions:N,labelField:s,selectedIndex:ee,handleClick:ae,handleHover:et,minQueryLength:c,shouldRenderSuggestions:i,isFocused:V,classNames:gn,renderSuggestion:e.renderSuggestion}),P&&w.length>0&&u.jsx(HJ,{classNames:gn,onClick:Ee}),ne&&u.jsxs("div",{"data-testid":"error",className:"ReactTags__error",children:[u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"24",width:"24",fill:"#e03131",children:u.jsx("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"})}),ne]})]});return u.jsxs("div",{className:(0,QJ.default)(gn.tags,"react-tags-wrapper"),ref:oe,children:[u.jsx("p",{role:"alert",className:"sr-only",style:{position:"absolute",overflow:"hidden",clip:"rect(0 0 0 0)",margin:"-1px",padding:0,width:"1px",height:"1px",border:0},children:Y}),Aa===ec.TOP&&Fn,u.jsxs("div",{className:gn.selected,children:[yn,Aa===ec.INLINE&&Fn]}),Aa===ec.BOTTOM&&Fn]})},oQ=sQ,aQ=e=>{var ne;const{placeholder:t=$K,labelField:n=BK,suggestions:r=[],delimiters:s=[],separators:o=(ne=e.delimiters)!=null&&ne.length?[]:[Rs.ENTER,Rs.TAB],autofocus:a,autoFocus:l=!0,inline:c,inputFieldPosition:i="inline",allowDeleteFromEmptyInput:d=!1,allowAdditionFromPaste:p=!0,autocomplete:f=!1,readOnly:h=!1,allowUnique:g=!0,allowDragDrop:m=!0,tags:x=[],inputProps:b={},editable:y=!1,clearAll:w=!1,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:k,handleFilterSuggestions:T,handleTagClick:P,handleInputChange:N,handleInputFocus:U,handleInputBlur:I,minQueryLength:Z,shouldRenderSuggestions:V,removeComponent:Q,onClearAll:ee,classNames:W,name:F,id:A,maxLength:Y,inputValue:de,maxTags:z,renderSuggestion:se}=e;return u.jsx(oQ,{placeholder:t,labelField:n,suggestions:r,delimiters:s,separators:o,autofocus:a,autoFocus:l,inline:c,inputFieldPosition:i,allowDeleteFromEmptyInput:d,allowAdditionFromPaste:p,autocomplete:f,readOnly:h,allowUnique:g,allowDragDrop:m,tags:x,inputProps:b,editable:y,clearAll:w,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:k,handleFilterSuggestions:T,handleTagClick:P,handleInputChange:N,handleInputFocus:U,handleInputBlur:I,minQueryLength:Z,shouldRenderSuggestions:V,removeComponent:Q,onClearAll:ee,classNames:W,name:F,id:A,maxLength:Y,inputValue:de,maxTags:z,renderSuggestion:se})},iQ=({...e})=>u.jsx(FH,{backend:OK,children:u.jsx(aQ,{...e})});/*! Bundled license information: - -classnames/index.js: - (*! - Copyright (c) 2018 Jed Watson. - Licensed under the MIT License (MIT), see - http://jedwatson.github.io/classnames - *) - -lodash-es/lodash.js: - (** - * @license - * Lodash (Custom Build) - * Build: `lodash modularize exports="es" -o ./` - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - *) -*/var lQ="Label",dO=v.forwardRef((e,t)=>u.jsx(Ne.label,{...e,ref:t,onMouseDown:n=>{var s;n.target.closest("button, input, select, textarea")||((s=e.onMouseDown)==null||s.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));dO.displayName=lQ;var fO=dO;const uQ=ig("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),pO=v.forwardRef(({className:e,...t},n)=>u.jsx(fO,{ref:n,className:ge(uQ(),e),...t}));pO.displayName=fO.displayName;function hO(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var cQ="VisuallyHidden",gO=v.forwardRef((e,t)=>u.jsx(Ne.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));gO.displayName=cQ;var dQ=[" ","Enter","ArrowUp","ArrowDown"],fQ=[" ","Enter"],ef="Select",[$g,Bg,pQ]=Fx(ef),[_u,Xse]=Vr(ef,[pQ,hg]),zg=hg(),[hQ,Ma]=_u(ef),[gQ,mQ]=_u(ef),mO=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:a,defaultValue:l,onValueChange:c,dir:i,name:d,autoComplete:p,disabled:f,required:h}=e,g=zg(t),[m,x]=v.useState(null),[b,y]=v.useState(null),[w,S]=v.useState(!1),E=Gd(i),[C=!1,k]=pa({prop:r,defaultProp:s,onChange:o}),[T,P]=pa({prop:a,defaultProp:l,onChange:c}),N=v.useRef(null),U=m?!!m.closest("form"):!0,[I,Z]=v.useState(new Set),V=Array.from(I).map(Q=>Q.props.value).join(";");return u.jsx($j,{...g,children:u.jsxs(hQ,{required:h,scope:t,trigger:m,onTriggerChange:x,valueNode:b,onValueNodeChange:y,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:os(),value:T,onValueChange:P,open:C,onOpenChange:k,dir:E,triggerPointerDownPosRef:N,disabled:f,children:[u.jsx($g.Provider,{scope:t,children:u.jsx(gQ,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(Q=>{Z(ee=>new Set(ee).add(Q))},[]),onNativeOptionRemove:v.useCallback(Q=>{Z(ee=>{const W=new Set(ee);return W.delete(Q),W})},[]),children:n})}),U?u.jsxs(zO,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:p,value:T,onChange:Q=>P(Q.target.value),disabled:f,children:[T===void 0?u.jsx("option",{value:""}):null,Array.from(I)]},V):null]})})};mO.displayName=ef;var vO="SelectTrigger",yO=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=zg(n),a=Ma(vO,n),l=a.disabled||r,c=it(t,a.onTriggerChange),i=Bg(n),[d,p,f]=UO(g=>{const m=i().filter(y=>!y.disabled),x=m.find(y=>y.value===a.value),b=VO(m,g,x);b!==void 0&&a.onValueChange(b.value)}),h=()=>{l||(a.onOpenChange(!0),f())};return u.jsx(Bj,{asChild:!0,...o,children:u.jsx(Ne.button,{type:"button",role:"combobox","aria-controls":a.contentId,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":BO(a.value)?"":void 0,...s,ref:c,onClick:Se(s.onClick,g=>{g.currentTarget.focus()}),onPointerDown:Se(s.onPointerDown,g=>{const m=g.target;m.hasPointerCapture(g.pointerId)&&m.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&(h(),a.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)},g.preventDefault())}),onKeyDown:Se(s.onKeyDown,g=>{const m=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(m&&g.key===" ")&&dQ.includes(g.key)&&(h(),g.preventDefault())})})})});yO.displayName=vO;var bO="SelectValue",xO=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:a="",...l}=e,c=Ma(bO,n),{onValueNodeHasChildrenChange:i}=c,d=o!==void 0,p=it(t,c.onValueNodeChange);return fn(()=>{i(d)},[i,d]),u.jsx(Ne.span,{...l,ref:p,style:{pointerEvents:"none"},children:BO(c.value)?u.jsx(u.Fragment,{children:a}):o})});xO.displayName=bO;var vQ="SelectIcon",wO=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return u.jsx(Ne.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});wO.displayName=vQ;var yQ="SelectPortal",SO=e=>u.jsx(gg,{asChild:!0,...e});SO.displayName=yQ;var ji="SelectContent",CO=v.forwardRef((e,t)=>{const n=Ma(ji,e.__scopeSelect),[r,s]=v.useState();if(fn(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?ka.createPortal(u.jsx(EO,{scope:e.__scopeSelect,children:u.jsx($g.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),o):null}return u.jsx(TO,{...e,ref:t})});CO.displayName=ji;var Ys=10,[EO,Oa]=_u(ji),bQ="SelectContentImpl",TO=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:a,side:l,sideOffset:c,align:i,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:x,...b}=e,y=Ma(ji,n),[w,S]=v.useState(null),[E,C]=v.useState(null),k=it(t,J=>S(J)),[T,P]=v.useState(null),[N,U]=v.useState(null),I=Bg(n),[Z,V]=v.useState(!1),Q=v.useRef(!1);v.useEffect(()=>{if(w)return Wx(w)},[w]),Lx();const ee=v.useCallback(J=>{const[Ce,...Pe]=I().map(me=>me.ref.current),[Le]=Pe.slice(-1),Me=document.activeElement;for(const me of J)if(me===Me||(me==null||me.scrollIntoView({block:"nearest"}),me===Ce&&E&&(E.scrollTop=0),me===Le&&E&&(E.scrollTop=E.scrollHeight),me==null||me.focus(),document.activeElement!==Me))return},[I,E]),W=v.useCallback(()=>ee([T,w]),[ee,T,w]);v.useEffect(()=>{Z&&W()},[Z,W]);const{onOpenChange:F,triggerPointerDownPosRef:A}=y;v.useEffect(()=>{if(w){let J={x:0,y:0};const Ce=Le=>{var Me,me;J={x:Math.abs(Math.round(Le.pageX)-(((Me=A.current)==null?void 0:Me.x)??0)),y:Math.abs(Math.round(Le.pageY)-(((me=A.current)==null?void 0:me.y)??0))}},Pe=Le=>{J.x<=10&&J.y<=10?Le.preventDefault():w.contains(Le.target)||F(!1),document.removeEventListener("pointermove",Ce),A.current=null};return A.current!==null&&(document.addEventListener("pointermove",Ce),document.addEventListener("pointerup",Pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ce),document.removeEventListener("pointerup",Pe,{capture:!0})}}},[w,F,A]),v.useEffect(()=>{const J=()=>F(!1);return window.addEventListener("blur",J),window.addEventListener("resize",J),()=>{window.removeEventListener("blur",J),window.removeEventListener("resize",J)}},[F]);const[Y,de]=UO(J=>{const Ce=I().filter(Me=>!Me.disabled),Pe=Ce.find(Me=>Me.ref.current===document.activeElement),Le=VO(Ce,J,Pe);Le&&setTimeout(()=>Le.ref.current.focus())}),z=v.useCallback((J,Ce,Pe)=>{const Le=!Q.current&&!Pe;(y.value!==void 0&&y.value===Ce||Le)&&(P(J),Le&&(Q.current=!0))},[y.value]),se=v.useCallback(()=>w==null?void 0:w.focus(),[w]),ne=v.useCallback((J,Ce,Pe)=>{const Le=!Q.current&&!Pe;(y.value!==void 0&&y.value===Ce||Le)&&U(J)},[y.value]),ie=r==="popper"?hb:kO,oe=ie===hb?{side:l,sideOffset:c,align:i,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:x}:{};return u.jsx(EO,{scope:n,content:w,viewport:E,onViewportChange:C,itemRefCallback:z,selectedItem:T,onItemLeave:se,itemTextRefCallback:ne,focusSelectedItem:W,selectedItemText:N,position:r,isPositioned:Z,searchRef:Y,children:u.jsx(bg,{as:mo,allowPinchZoom:!0,children:u.jsx(dg,{asChild:!0,trapped:y.open,onMountAutoFocus:J=>{J.preventDefault()},onUnmountAutoFocus:Se(s,J=>{var Ce;(Ce=y.trigger)==null||Ce.focus({preventScroll:!0}),J.preventDefault()}),children:u.jsx(cg,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:J=>J.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:u.jsx(ie,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:J=>J.preventDefault(),...b,...oe,onPlaced:()=>V(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Se(b.onKeyDown,J=>{const Ce=J.ctrlKey||J.altKey||J.metaKey;if(J.key==="Tab"&&J.preventDefault(),!Ce&&J.key.length===1&&de(J.key),["ArrowUp","ArrowDown","Home","End"].includes(J.key)){let Le=I().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);if(["ArrowUp","End"].includes(J.key)&&(Le=Le.slice().reverse()),["ArrowUp","ArrowDown"].includes(J.key)){const Me=J.target,me=Le.indexOf(Me);Le=Le.slice(me+1)}setTimeout(()=>ee(Le)),J.preventDefault()}})})})})})})});TO.displayName=bQ;var xQ="SelectItemAlignedPosition",kO=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Ma(ji,n),a=Oa(ji,n),[l,c]=v.useState(null),[i,d]=v.useState(null),p=it(t,k=>d(k)),f=Bg(n),h=v.useRef(!1),g=v.useRef(!0),{viewport:m,selectedItem:x,selectedItemText:b,focusSelectedItem:y}=a,w=v.useCallback(()=>{if(o.trigger&&o.valueNode&&l&&i&&m&&x&&b){const k=o.trigger.getBoundingClientRect(),T=i.getBoundingClientRect(),P=o.valueNode.getBoundingClientRect(),N=b.getBoundingClientRect();if(o.dir!=="rtl"){const Me=N.left-T.left,me=P.left-Me,rt=k.left-me,It=k.width+rt,Zt=Math.max(It,T.width),Wt=window.innerWidth-Ys,an=Zy(me,[Ys,Wt-Zt]);l.style.minWidth=It+"px",l.style.left=an+"px"}else{const Me=T.right-N.right,me=window.innerWidth-P.right-Me,rt=window.innerWidth-k.right-me,It=k.width+rt,Zt=Math.max(It,T.width),Wt=window.innerWidth-Ys,an=Zy(me,[Ys,Wt-Zt]);l.style.minWidth=It+"px",l.style.right=an+"px"}const U=f(),I=window.innerHeight-Ys*2,Z=m.scrollHeight,V=window.getComputedStyle(i),Q=parseInt(V.borderTopWidth,10),ee=parseInt(V.paddingTop,10),W=parseInt(V.borderBottomWidth,10),F=parseInt(V.paddingBottom,10),A=Q+ee+Z+F+W,Y=Math.min(x.offsetHeight*5,A),de=window.getComputedStyle(m),z=parseInt(de.paddingTop,10),se=parseInt(de.paddingBottom,10),ne=k.top+k.height/2-Ys,ie=I-ne,oe=x.offsetHeight/2,J=x.offsetTop+oe,Ce=Q+ee+J,Pe=A-Ce;if(Ce<=ne){const Me=x===U[U.length-1].ref.current;l.style.bottom="0px";const me=i.clientHeight-m.offsetTop-m.offsetHeight,rt=Math.max(ie,oe+(Me?se:0)+me+W),It=Ce+rt;l.style.height=It+"px"}else{const Me=x===U[0].ref.current;l.style.top="0px";const rt=Math.max(ne,Q+m.offsetTop+(Me?z:0)+oe)+Pe;l.style.height=rt+"px",m.scrollTop=Ce-ne+m.offsetTop}l.style.margin=`${Ys}px 0`,l.style.minHeight=Y+"px",l.style.maxHeight=I+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[f,o.trigger,o.valueNode,l,i,m,x,b,o.dir,r]);fn(()=>w(),[w]);const[S,E]=v.useState();fn(()=>{i&&E(window.getComputedStyle(i).zIndex)},[i]);const C=v.useCallback(k=>{k&&g.current===!0&&(w(),y==null||y(),g.current=!1)},[w,y]);return u.jsx(SQ,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:h,onScrollButtonChange:C,children:u.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:u.jsx(Ne.div,{...s,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});kO.displayName=xQ;var wQ="SelectPopperPosition",hb=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Ys,...o}=e,a=zg(n);return u.jsx(zj,{...a,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});hb.displayName=wQ;var[SQ,Pw]=_u(ji,{}),gb="SelectViewport",_O=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Oa(gb,n),a=Pw(gb,n),l=it(t,o.onViewportChange),c=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx($g.Slot,{scope:n,children:u.jsx(Ne.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:l,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:Se(s.onScroll,i=>{const d=i.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:f}=a;if(f!=null&&f.current&&p){const h=Math.abs(c.current-d.scrollTop);if(h>0){const g=window.innerHeight-Ys*2,m=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),b=Math.max(m,x);if(b0?S:0,p.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});_O.displayName=gb;var jO="SelectGroup",[CQ,EQ]=_u(jO),TQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=os();return u.jsx(CQ,{scope:n,id:s,children:u.jsx(Ne.div,{role:"group","aria-labelledby":s,...r,ref:t})})});TQ.displayName=jO;var RO="SelectLabel",PO=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=EQ(RO,n);return u.jsx(Ne.div,{id:s.id,...r,ref:t})});PO.displayName=RO;var Th="SelectItem",[kQ,MO]=_u(Th),OO=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...a}=e,l=Ma(Th,n),c=Oa(Th,n),i=l.value===r,[d,p]=v.useState(o??""),[f,h]=v.useState(!1),g=it(t,b=>{var y;return(y=c.itemRefCallback)==null?void 0:y.call(c,b,r,s)}),m=os(),x=()=>{s||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(kQ,{scope:n,value:r,disabled:s,textId:m,isSelected:i,onItemTextChange:v.useCallback(b=>{p(y=>y||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx($g.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:u.jsx(Ne.div,{role:"option","aria-labelledby":m,"data-highlighted":f?"":void 0,"aria-selected":i&&f,"data-state":i?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:g,onFocus:Se(a.onFocus,()=>h(!0)),onBlur:Se(a.onBlur,()=>h(!1)),onPointerUp:Se(a.onPointerUp,x),onPointerMove:Se(a.onPointerMove,b=>{var y;s?(y=c.onItemLeave)==null||y.call(c):b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Se(a.onPointerLeave,b=>{var y;b.currentTarget===document.activeElement&&((y=c.onItemLeave)==null||y.call(c))}),onKeyDown:Se(a.onKeyDown,b=>{var w;((w=c.searchRef)==null?void 0:w.current)!==""&&b.key===" "||(fQ.includes(b.key)&&x(),b.key===" "&&b.preventDefault())})})})})});OO.displayName=Th;var hc="SelectItemText",NO=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,a=Ma(hc,n),l=Oa(hc,n),c=MO(hc,n),i=mQ(hc,n),[d,p]=v.useState(null),f=it(t,b=>p(b),c.onItemTextChange,b=>{var y;return(y=l.itemTextRefCallback)==null?void 0:y.call(l,b,c.value,c.disabled)}),h=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:c.value,disabled:c.disabled,children:h},c.value),[c.disabled,c.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:x}=i;return fn(()=>(m(g),()=>x(g)),[m,x,g]),u.jsxs(u.Fragment,{children:[u.jsx(Ne.span,{id:c.textId,...o,ref:f}),c.isSelected&&a.valueNode&&!a.valueNodeHasChildren?ka.createPortal(o.children,a.valueNode):null]})});NO.displayName=hc;var IO="SelectItemIndicator",DO=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return MO(IO,n).isSelected?u.jsx(Ne.span,{"aria-hidden":!0,...r,ref:t}):null});DO.displayName=IO;var mb="SelectScrollUpButton",AO=v.forwardRef((e,t)=>{const n=Oa(mb,e.__scopeSelect),r=Pw(mb,e.__scopeSelect),[s,o]=v.useState(!1),a=it(t,r.onScrollButtonChange);return fn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const i=c.scrollTop>0;o(i)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?u.jsx(LO,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});AO.displayName=mb;var vb="SelectScrollDownButton",FO=v.forwardRef((e,t)=>{const n=Oa(vb,e.__scopeSelect),r=Pw(vb,e.__scopeSelect),[s,o]=v.useState(!1),a=it(t,r.onScrollButtonChange);return fn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const i=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?u.jsx(LO,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});FO.displayName=vb;var LO=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Oa("SelectScrollButton",n),a=v.useRef(null),l=Bg(n),c=v.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return v.useEffect(()=>()=>c(),[c]),fn(()=>{var d;const i=l().find(p=>p.ref.current===document.activeElement);(d=i==null?void 0:i.ref.current)==null||d.scrollIntoView({block:"nearest"})},[l]),u.jsx(Ne.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Se(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(r,50))}),onPointerMove:Se(s.onPointerMove,()=>{var i;(i=o.onItemLeave)==null||i.call(o),a.current===null&&(a.current=window.setInterval(r,50))}),onPointerLeave:Se(s.onPointerLeave,()=>{c()})})}),_Q="SelectSeparator",$O=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Ne.div,{"aria-hidden":!0,...r,ref:t})});$O.displayName=_Q;var yb="SelectArrow",jQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=zg(n),o=Ma(yb,n),a=Oa(yb,n);return o.open&&a.position==="popper"?u.jsx(Uj,{...s,...r,ref:t}):null});jQ.displayName=yb;function BO(e){return e===""||e===void 0}var zO=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=v.useRef(null),o=it(t,s),a=hO(n);return v.useEffect(()=>{const l=s.current,c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(a!==n&&d){const p=new Event("change",{bubbles:!0});d.call(l,n),l.dispatchEvent(p)}},[a,n]),u.jsx(gO,{asChild:!0,children:u.jsx("select",{...r,ref:o,defaultValue:n})})});zO.displayName="BubbleSelect";function UO(e){const t=nn(e),n=v.useRef(""),r=v.useRef(0),s=v.useCallback(a=>{const l=n.current+a;t(l),function c(i){n.current=i,window.clearTimeout(r.current),i!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),o=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function VO(e,t,n){const s=t.length>1&&Array.from(t).every(i=>i===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=RQ(e,Math.max(o,0));s.length===1&&(a=a.filter(i=>i!==n));const c=a.find(i=>i.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var PQ=mO,HO=yO,MQ=xO,OQ=wO,NQ=SO,KO=CO,IQ=_O,qO=PO,WO=OO,DQ=NO,AQ=DO,GO=AO,JO=FO,QO=$O;const FQ=PQ,LQ=MQ,ZO=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(HO,{ref:r,className:ge("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(OQ,{asChild:!0,children:u.jsx(lg,{className:"h-4 w-4 opacity-50"})})]}));ZO.displayName=HO.displayName;const YO=v.forwardRef(({className:e,...t},n)=>u.jsx(GO,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(P3,{className:"h-4 w-4"})}));YO.displayName=GO.displayName;const XO=v.forwardRef(({className:e,...t},n)=>u.jsx(JO,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(lg,{className:"h-4 w-4"})}));XO.displayName=JO.displayName;const eN=v.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>u.jsx(NQ,{children:u.jsxs(KO,{ref:s,className:ge("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(YO,{}),u.jsx(IQ,{className:ge("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(XO,{})]})}));eN.displayName=KO.displayName;const $Q=v.forwardRef(({className:e,...t},n)=>u.jsx(qO,{ref:n,className:ge("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));$Q.displayName=qO.displayName;const tN=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(WO,{ref:r,className:ge("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(AQ,{children:u.jsx(cj,{className:"h-4 w-4"})})}),u.jsx(DQ,{children:t})]}));tN.displayName=WO.displayName;const BQ=v.forwardRef(({className:e,...t},n)=>u.jsx(QO,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));BQ.displayName=QO.displayName;var Mw="Switch",[zQ,eoe]=Vr(Mw),[UQ,VQ]=zQ(Mw),nN=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:a,disabled:l,value:c="on",onCheckedChange:i,...d}=e,[p,f]=v.useState(null),h=it(t,y=>f(y)),g=v.useRef(!1),m=p?!!p.closest("form"):!0,[x=!1,b]=pa({prop:s,defaultProp:o,onChange:i});return u.jsxs(UQ,{scope:n,checked:x,disabled:l,children:[u.jsx(Ne.button,{type:"button",role:"switch","aria-checked":x,"aria-required":a,"data-state":oN(x),"data-disabled":l?"":void 0,disabled:l,value:c,...d,ref:h,onClick:Se(e.onClick,y=>{b(w=>!w),m&&(g.current=y.isPropagationStopped(),g.current||y.stopPropagation())})}),m&&u.jsx(HQ,{control:p,bubbles:!g.current,name:r,value:c,checked:x,required:a,disabled:l,style:{transform:"translateX(-100%)"}})]})});nN.displayName=Mw;var rN="SwitchThumb",sN=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=VQ(rN,n);return u.jsx(Ne.span,{"data-state":oN(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});sN.displayName=rN;var HQ=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=v.useRef(null),a=hO(n),l=Rj(t);return v.useEffect(()=>{const c=o.current,i=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(i,"checked").set;if(a!==n&&p){const f=new Event("click",{bubbles:r});p.call(c,n),c.dispatchEvent(f)}},[a,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function oN(e){return e?"checked":"unchecked"}var aN=nN,KQ=sN;const ju=v.forwardRef(({className:e,...t},n)=>u.jsx(aN,{className:ge("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:u.jsx(KQ,{className:ge("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));ju.displayName=aN.displayName;const Na=Tr,iN=v.createContext({}),Ia=({...e})=>u.jsx(iN.Provider,{value:{name:e.name},children:u.jsx($V,{...e})}),Ug=()=>{const e=v.useContext(iN),t=v.useContext(lN),{getFieldState:n,formState:r}=Rg(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},lN=v.createContext({}),_o=v.forwardRef(({className:e,...t},n)=>{const r=v.useId();return u.jsx(lN.Provider,{value:{id:r},children:u.jsx("div",{ref:n,className:ge("space-y-2",e),...t})})});_o.displayName="FormItem";const xr=v.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=Ug();return u.jsx(pO,{ref:n,className:ge(r&&"text-rose-600",e),htmlFor:s,...t})});xr.displayName="FormLabel";const Vs=v.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=Ug();return u.jsx(mo,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});Vs.displayName="FormControl";const Vg=v.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=Ug();return u.jsx("p",{ref:n,id:r,className:ge("text-sm text-muted-foreground",e),...t})});Vg.displayName="FormDescription";const tf=v.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=Ug(),a=s?String(s==null?void 0:s.message):t;return a?u.jsx("p",{ref:r,id:o,className:ge("text-sm font-medium text-rose-600",e),...n,children:a}):null});tf.displayName="FormMessage";const G=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:l})=>u.jsxs(_o,{className:o,children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:v.isValidElement(n)&&v.cloneElement(n,{...l,value:l.value??"",required:r,readOnly:s,checked:l.value,onCheckedChange:l.onChange})}),u.jsx(tf,{})]})}),ke=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:l})=>u.jsxs(_o,{className:ge("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[u.jsx("div",{className:"flex flex-col gap-2",children:t&&u.jsxs(xr,{children:[u.jsxs("p",{className:"break-all",children:[t,n&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&u.jsx(Vg,{className:"mt-2",children:s})]})}),u.jsx(Vs,{children:u.jsx(ju,{checked:l.value,onCheckedChange:l.onChange,required:n})}),u.jsx(tf,{})]})}),Qt=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:l})=>u.jsxs(_o,{children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:u.jsxs(FQ,{onValueChange:l.onChange,defaultValue:l.value,children:[u.jsx(Vs,{children:u.jsx(ZO,{children:u.jsx(LQ,{placeholder:o})})}),u.jsx(eN,{children:s.map(c=>u.jsx(tN,{value:c.value,children:c.label},c.value))})]})}),n&&u.jsx(Vg,{children:n}),u.jsx(tf,{})]})}),Ru=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>u.jsx(Ia,{...o,name:e,render:({field:a})=>{let l=[];return Array.isArray(a.value)&&(l=a.value),u.jsxs(_o,{children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:u.jsx(iQ,{tags:l.map(c=>({id:c,text:c,className:""})),handleDelete:c=>a.onChange(l.filter((i,d)=>d!==c)),handleAddition:c=>a.onChange([...l,c.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[Rs.ENTER,Rs.TAB,Rs.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:QP,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&u.jsx(Vg,{children:n}),u.jsx(tf,{})]})}}),pv=_.string().optional().transform(e=>e===""?void 0:e),qQ=_.object({name:_.string(),token:pv,number:pv,businessId:pv,integration:_.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","EVOLUTION"])});function WQ({resetTable:e}){const{t}=ze(),{createInstance:n}=_g(),[r,s]=v.useState(!1),o=[{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")},{value:"EVOLUTION",label:t("instance.form.integration.evolution")}],a=sn({resolver:on(qQ),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:NC().replace("-","").toUpperCase(),number:"",businessId:""}}),l=a.watch("integration"),c=async d=>{var p,f,h;try{const g={instanceName:d.name,integration:d.integration,token:d.token===""?null:d.token,number:d.number===""?null:d.number,businessId:d.businessId===""?null:d.businessId};await n(g),X.success(t("toast.instance.created")),s(!1),i(),e()}catch(g){console.error("Error:",g),X.error(`Error : ${(h=(f=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:f.response)==null?void 0:h.message}`)}},i=()=>{a.reset({name:"",integration:"WHATSAPP-BAILEYS",token:NC().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"default",size:"sm",children:[t("instance.button.create")," ",u.jsx(Ni,{size:"18"})]})}),u.jsxs(xt,{className:"sm:max-w-[650px]",onCloseAutoFocus:i,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("instance.modal.title")})}),u.jsx(Tr,{...a,children:u.jsxs("form",{onSubmit:a.handleSubmit(c),className:"grid gap-4 py-4",children:[u.jsx(G,{required:!0,name:"name",label:t("instance.form.name"),children:u.jsx(K,{})}),u.jsx(Qt,{name:"integration",label:t("instance.form.integration.label"),options:o}),u.jsx(G,{required:!0,name:"token",label:t("instance.form.token"),children:u.jsx(K,{})}),u.jsx(G,{name:"number",label:t("instance.form.number"),children:u.jsx(K,{type:"tel"})}),l==="WHATSAPP-BUSINESS"&&u.jsx(G,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:u.jsx(K,{})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:t("instance.button.save")})})]})})]})]})}function GQ(){const{t:e}=ze(),[t,n]=v.useState(null),{deleteInstance:r,logout:s}=_g(),{data:o,refetch:a}=_V(),[l,c]=v.useState([]),[i,d]=v.useState("all"),[p,f]=v.useState(""),h=async()=>{await a()},g=async b=>{var y,w,S;n(null),c([...l,b]);try{try{await s(b)}catch(E){console.error("Error logout:",E)}await r(b),await new Promise(E=>setTimeout(E,1e3)),h()}catch(E){console.error("Error instance delete:",E),X.error(`Error : ${(S=(w=(y=E==null?void 0:E.response)==null?void 0:y.data)==null?void 0:w.response)==null?void 0:S.message}`)}finally{c(l.filter(E=>E!==b))}},m=v.useMemo(()=>{let b=o?[...o]:[];return i!=="all"&&(b=b.filter(y=>y.connectionStatus===i)),p!==""&&(b=b.filter(y=>y.name.toLowerCase().includes(p.toLowerCase()))),b},[o,p,i]),x=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return u.jsxs("div",{className:"my-4 px-4",children:[u.jsxs("div",{className:"flex w-full items-center justify-between",children:[u.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(q,{variant:"outline",size:"icon",children:u.jsx(fj,{onClick:h,size:"20"})}),u.jsx(WQ,{resetTable:h})]})]}),u.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[u.jsx("div",{className:"flex-1",children:u.jsx(K,{placeholder:e("dashboard.search"),value:p,onChange:b=>f(b.target.value)})}),u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"secondary",children:[e("dashboard.status")," ",u.jsx(M3,{size:"15"})]})}),u.jsx(ps,{children:x.map(b=>u.jsx(GR,{checked:i===b.value,onCheckedChange:y=>{y&&d(b.value)},children:b.label},b.value))})]})]}),u.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:m.length>0&&Array.isArray(o)&&o.map(b=>{var y,w;return u.jsxs(Ja,{children:[u.jsx(Qa,{children:u.jsxs(nd,{to:`/manager/instance/${b.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[u.jsx("h3",{className:"text-wrap font-semibold",children:b.name}),u.jsx(q,{variant:"ghost",size:"icon",children:u.jsx(Oi,{className:"card-icon",size:"20"})})]})}),u.jsxs(Za,{className:"flex-1 space-y-6",children:[u.jsx(GP,{token:b.token}),u.jsxs("div",{className:"flex w-full flex-wrap",children:[u.jsx("div",{className:"flex flex-1 gap-2",children:b.profileName&&u.jsxs(u.Fragment,{children:[u.jsx(Sg,{children:u.jsx(Cg,{src:b.profilePicUrl,alt:""})}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("strong",{children:b.profileName}),u.jsx("p",{className:"text-sm text-muted-foreground",children:b.ownerJid&&b.ownerJid.split("@")[0]})]})]})}),u.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[u.jsx(dj,{className:"text-muted-foreground",size:"20"}),u.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((y=b==null?void 0:b._count)==null?void 0:y.Contact)||0)})]}),u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[u.jsx(ug,{className:"text-muted-foreground",size:"20"}),u.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((w=b==null?void 0:b._count)==null?void 0:w.Message)||0)})]})]})]})]}),u.jsxs(kg,{className:"justify-between",children:[u.jsx(WP,{status:b.connectionStatus}),u.jsx(q,{variant:"destructive",size:"sm",onClick:()=>n(b.name),disabled:l.includes(b.name),children:l.includes(b.name)?u.jsx("span",{children:e("button.deleting")}):u.jsx("span",{children:e("button.delete")})})]})]},b.id)})}),!!t&&u.jsx(Tt,{onOpenChange:()=>n(null),open:!0,children:u.jsxs(xt,{children:[u.jsx(TP,{}),u.jsx(wt,{children:e("modal.delete.title")}),u.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),u.jsx(rn,{children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx(q,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),u.jsx(q,{onClick:()=>g(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:au,createContext:JQ,createRef:toe,forwardRef:uN,useCallback:ir,useContext:cN,useEffect:pi,useImperativeHandle:dN,useLayoutEffect:QQ,useMemo:ZQ,useRef:Yn,useState:Oc}=Nh,z1=Nh.useId,YQ=QQ,Hg=JQ(null);Hg.displayName="PanelGroupContext";const hi=YQ,XQ=typeof z1=="function"?z1:()=>null;let eZ=0;function Ow(e=null){const t=XQ(),n=Yn(e||t||null);return n.current===null&&(n.current=""+eZ++),e??n.current}function fN({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:a,maxSize:l,minSize:c,onCollapse:i,onExpand:d,onResize:p,order:f,style:h,tagName:g="div",...m}){const x=cN(Hg);if(x===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:b,expandPanel:y,getPanelSize:w,getPanelStyle:S,groupId:E,isPanelCollapsed:C,reevaluatePanelConstraints:k,registerPanel:T,resizePanel:P,unregisterPanel:N}=x,U=Ow(a),I=Yn({callbacks:{onCollapse:i,onExpand:d,onResize:p},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:l,minSize:c},id:U,idIsFromProps:a!==void 0,order:f});Yn({didLogMissingDefaultSizeWarning:!1}),hi(()=>{const{callbacks:V,constraints:Q}=I.current,ee={...Q};I.current.id=U,I.current.idIsFromProps=a!==void 0,I.current.order=f,V.onCollapse=i,V.onExpand=d,V.onResize=p,Q.collapsedSize=n,Q.collapsible=r,Q.defaultSize=s,Q.maxSize=l,Q.minSize=c,(ee.collapsedSize!==Q.collapsedSize||ee.collapsible!==Q.collapsible||ee.maxSize!==Q.maxSize||ee.minSize!==Q.minSize)&&k(I.current,ee)}),hi(()=>{const V=I.current;return T(V),()=>{N(V)}},[f,U,T,N]),dN(o,()=>({collapse:()=>{b(I.current)},expand:V=>{y(I.current,V)},getId(){return U},getSize(){return w(I.current)},isCollapsed(){return C(I.current)},isExpanded(){return!C(I.current)},resize:V=>{P(I.current,V)}}),[b,y,w,C,U,P]);const Z=S(I.current,s);return au(g,{...m,children:e,className:t,id:a,style:{...Z,...h},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":E,"data-panel-id":U,"data-panel-size":parseFloat(""+Z.flexGrow).toFixed(1)})}const pN=uN((e,t)=>au(fN,{...e,forwardedRef:t}));fN.displayName="Panel";pN.displayName="forwardRef(Panel)";let bb=null,Xa=null;function tZ(e,t){if(t){const n=(t&yN)!==0,r=(t&bN)!==0,s=(t&xN)!==0,o=(t&wN)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function nZ(){Xa!==null&&(document.head.removeChild(Xa),bb=null,Xa=null)}function hv(e,t){const n=tZ(e,t);bb!==n&&(bb=n,Xa===null&&(Xa=document.createElement("style"),document.head.appendChild(Xa)),Xa.innerHTML=`*{cursor: ${n}!important;}`)}function hN(e){return e.type==="keydown"}function gN(e){return e.type.startsWith("pointer")}function mN(e){return e.type.startsWith("mouse")}function Kg(e){if(gN(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(mN(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function rZ(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function sZ(e,t,n){return e.xt.x&&e.yt.y}function oZ(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:H1(e),b:H1(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;tt(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:V1(U1(n.a)),b:V1(U1(n.b))};if(s.a===s.b){const o=r.childNodes,a={a:n.a.at(-1),b:n.b.at(-1)};let l=o.length;for(;l--;){const c=o[l];if(c===a.a)return 1;if(c===a.b)return-1}}return Math.sign(s.a-s.b)}const aZ=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function iZ(e){var t;const n=getComputedStyle((t=vN(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function lZ(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||iZ(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||aZ.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function U1(e){let t=e.length;for(;t--;){const n=e[t];if(tt(n,"Missing node"),lZ(n))return n}return null}function V1(e){return e&&Number(getComputedStyle(e).zIndex)||0}function H1(e){const t=[];for(;e;)t.push(e),e=vN(e);return t}function vN(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const yN=1,bN=2,xN=4,wN=8,uZ=rZ()==="coarse";let is=[],_d=!1,Ho=new Map,qg=new Map;const jd=new Set;function cZ(e,t,n,r,s){var o;const{ownerDocument:a}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},c=(o=Ho.get(a))!==null&&o!==void 0?o:0;return Ho.set(a,c+1),jd.add(l),kh(),function(){var d;qg.delete(e),jd.delete(l);const p=(d=Ho.get(a))!==null&&d!==void 0?d:1;if(Ho.set(a,p-1),kh(),p===1&&Ho.delete(a),is.includes(l)){const f=is.indexOf(l);f>=0&&is.splice(f,1),Iw()}}}function K1(e){const{target:t}=e,{x:n,y:r}=Kg(e);_d=!0,Nw({target:t,x:n,y:r}),kh(),is.length>0&&(_h("down",e),e.preventDefault(),e.stopPropagation())}function nc(e){const{x:t,y:n}=Kg(e);if(e.buttons===0&&(_d=!1,_h("up",e)),!_d){const{target:r}=e;Nw({target:r,x:t,y:n})}_h("move",e),Iw(),is.length>0&&e.preventDefault()}function Zi(e){const{target:t}=e,{x:n,y:r}=Kg(e);qg.clear(),_d=!1,is.length>0&&e.preventDefault(),_h("up",e),Nw({target:t,x:n,y:r}),Iw(),kh()}function Nw({target:e,x:t,y:n}){is.splice(0);let r=null;e instanceof HTMLElement&&(r=e),jd.forEach(s=>{const{element:o,hitAreaMargins:a}=s,l=o.getBoundingClientRect(),{bottom:c,left:i,right:d,top:p}=l,f=uZ?a.coarse:a.fine;if(t>=i-f&&t<=d+f&&n>=p-f&&n<=c+f){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&oZ(r,o)>0){let g=r,m=!1;for(;g&&!g.contains(o);){if(sZ(g.getBoundingClientRect(),l)){m=!0;break}g=g.parentElement}if(m)return}is.push(s)}})}function gv(e,t){qg.set(e,t)}function Iw(){let e=!1,t=!1;is.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;qg.forEach(r=>{n|=r}),e&&t?hv("intersection",n):e?hv("horizontal",n):t?hv("vertical",n):nZ()}function kh(){Ho.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",Zi),n.removeEventListener("pointerdown",K1),n.removeEventListener("pointerleave",nc),n.removeEventListener("pointermove",nc)}),window.removeEventListener("pointerup",Zi),window.removeEventListener("pointercancel",Zi),jd.size>0&&(_d?(is.length>0&&Ho.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",Zi),n.addEventListener("pointerleave",nc),n.addEventListener("pointermove",nc))}),window.addEventListener("pointerup",Zi),window.addEventListener("pointercancel",Zi)):Ho.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",K1,{capture:!0}),n.addEventListener("pointermove",nc))}))}function _h(e,t){jd.forEach(n=>{const{setResizeHandlerState:r}=n,s=is.includes(n);r(e,s,t)})}function tt(e,t){if(!e)throw console.error(t),Error(t)}const Dw=10;function Ri(e,t,n=Dw){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function no(e,t,n=Dw){return Ri(e,t,n)===0}function dr(e,t,n){return Ri(e,t,n)===0}function dZ(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-b:b)}}}{const p=e<0?l:c,f=n[p];tt(f,`No panel constraints found for index ${p}`);const{collapsedSize:h=0,collapsible:g,minSize:m=0}=f;if(g){const x=t[p];if(tt(x!=null,`Previous layout not found for panel index ${p}`),dr(x,m)){const b=x-h;Ri(b,Math.abs(e))>0&&(e=e<0?0-b:b)}}}}{const p=e<0?1:-1;let f=e<0?c:l,h=0;for(;;){const m=t[f];tt(m!=null,`Previous layout not found for panel index ${f}`);const b=yl({panelConstraints:n,panelIndex:f,size:100})-m;if(h+=b,f+=p,f<0||f>=n.length)break}const g=Math.min(Math.abs(e),Math.abs(h));e=e<0?0-g:g}{let f=e<0?l:c;for(;f>=0&&f=0))break;e<0?f--:f++}}if(dZ(s,a))return s;{const p=e<0?c:l,f=t[p];tt(f!=null,`Previous layout not found for panel index ${p}`);const h=f+i,g=yl({panelConstraints:n,panelIndex:p,size:h});if(a[p]=g,!dr(g,h)){let m=h-g,b=e<0?c:l;for(;b>=0&&b0?b--:b++}}}const d=a.reduce((p,f)=>f+p,0);return dr(d,100)?a:s}function fZ({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,a=0;const l=n[0];tt(l!=null,"No pivot index found"),t.forEach((p,f)=>{const{constraints:h}=p,{maxSize:g=100,minSize:m=0}=h;f===l?(r=m,s=g):(o+=m,a+=g)});const c=Math.min(s,100-o),i=Math.max(r,100-a),d=e[l];return{valueMax:c,valueMin:i,valueNow:d}}function Rd(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function SN(e,t,n=document){const s=Rd(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function CN(e,t,n){const r=SN(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function EN(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function Wg(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function pZ(e,t,n,r=document){var s,o,a,l;const c=Wg(t,r),i=Rd(e,r),d=c?i.indexOf(c):-1,p=(s=(o=n[d])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,f=(a=(l=n[d+1])===null||l===void 0?void 0:l.id)!==null&&a!==void 0?a:null;return[p,f]}function hZ({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:a}){Yn({didWarnAboutMissingResizeHandle:!1}),hi(()=>{if(!o)return;const l=Rd(n,o);for(let c=0;c{l.forEach((c,i)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,s,o]),pi(()=>{if(!o)return;const l=t.current;tt(l,"Eager values not found");const{panelDataArray:c}=l,i=EN(n,o);tt(i!=null,`No group found for id "${n}"`);const d=Rd(n,o);tt(d,`No resize handles found for group id "${n}"`);const p=d.map(f=>{const h=f.getAttribute("data-panel-resize-handle-id");tt(h,"Resize handle element has no handle id attribute");const[g,m]=pZ(n,h,c,o);if(g==null||m==null)return()=>{};const x=b=>{if(!b.defaultPrevented)switch(b.key){case"Enter":{b.preventDefault();const y=c.findIndex(w=>w.id===g);if(y>=0){const w=c[y];tt(w,`No panel data found for index ${y}`);const S=r[y],{collapsedSize:E=0,collapsible:C,minSize:k=0}=w.constraints;if(S!=null&&C){const T=gc({delta:dr(S,E)?k-E:E-S,initialLayout:r,panelConstraints:c.map(P=>P.constraints),pivotIndices:CN(n,h,o),prevLayout:r,trigger:"keyboard"});r!==T&&a(T)}}break}}};return f.addEventListener("keydown",x),()=>{f.removeEventListener("keydown",x)}});return()=>{p.forEach(f=>f())}},[o,e,t,n,r,s,a])}function q1(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];tt(o,`Panel data not found for index ${s}`);const{callbacks:a,constraints:l,id:c}=o,{collapsedSize:i=0,collapsible:d}=l,p=n[c];if(p==null||r!==p){n[c]=r;const{onCollapse:f,onExpand:h,onResize:g}=a;g&&g(r,p),d&&(f||h)&&(h&&(p==null||no(p,i))&&!no(r,i)&&h(),f&&(p==null||!no(p,i))&&no(r,i)&&f())}})}function Vf(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function W1(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function kN(e){return`react-resizable-panels:${e}`}function _N(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function jN(e,t){try{const n=kN(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function xZ(e,t,n){var r,s;const o=(r=jN(e,n))!==null&&r!==void 0?r:{},a=_N(t);return(s=o[a])!==null&&s!==void 0?s:null}function wZ(e,t,n,r,s){var o;const a=kN(e),l=_N(t),c=(o=jN(e,s))!==null&&o!==void 0?o:{};c[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(a,JSON.stringify(c))}catch(i){console.error(i)}}function G1({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,a)=>o+a,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!dr(r,100))for(let o=0;o(W1(mc),mc.getItem(e)),setItem:(e,t)=>{W1(mc),mc.setItem(e,t)}},J1={};function RN({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:a=null,keyboardResizeBy:l=null,storage:c=mc,style:i,tagName:d="div",...p}){const f=Ow(o),h=Yn(null),[g,m]=Oc(null),[x,b]=Oc([]),y=Yn({}),w=Yn(new Map),S=Yn(0),E=Yn({autoSaveId:e,direction:r,dragState:g,id:f,keyboardResizeBy:l,onLayout:a,storage:c}),C=Yn({layout:x,panelDataArray:[],panelDataArrayChanged:!1});Yn({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),dN(s,()=>({getId:()=>E.current.id,getLayout:()=>{const{layout:z}=C.current;return z},setLayout:z=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:ie}=C.current,oe=G1({layout:z,panelConstraints:ie.map(J=>J.constraints)});q1(ne,oe)||(b(oe),C.current.layout=oe,se&&se(oe),Yi(ie,oe,y.current))}}),[]),hi(()=>{E.current.autoSaveId=e,E.current.direction=r,E.current.dragState=g,E.current.id=f,E.current.onLayout=a,E.current.storage=c}),hZ({committedValuesRef:E,eagerValuesRef:C,groupId:f,layout:x,panelDataArray:C.current.panelDataArray,setLayout:b,panelGroupElement:h.current}),pi(()=>{const{panelDataArray:z}=C.current;if(e){if(x.length===0||x.length!==z.length)return;let se=J1[e];se==null&&(se=bZ(wZ,SZ),J1[e]=se);const ne=[...z],ie=new Map(w.current);se(e,ne,ie,x,c)}},[e,x,c]),pi(()=>{});const k=ir(z=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:ie}=C.current;if(z.constraints.collapsible){const oe=ie.map(Le=>Le.constraints),{collapsedSize:J=0,panelSize:Ce,pivotIndices:Pe}=Fa(ie,z,ne);if(tt(Ce!=null,`Panel size not found for panel "${z.id}"`),!no(Ce,J)){w.current.set(z.id,Ce);const Me=nl(ie,z)===ie.length-1?Ce-J:J-Ce,me=gc({delta:Me,initialLayout:ne,panelConstraints:oe,pivotIndices:Pe,prevLayout:ne,trigger:"imperative-api"});Vf(ne,me)||(b(me),C.current.layout=me,se&&se(me),Yi(ie,me,y.current))}}},[]),T=ir((z,se)=>{const{onLayout:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current;if(z.constraints.collapsible){const J=oe.map(rt=>rt.constraints),{collapsedSize:Ce=0,panelSize:Pe=0,minSize:Le=0,pivotIndices:Me}=Fa(oe,z,ie),me=se??Le;if(no(Pe,Ce)){const rt=w.current.get(z.id),It=rt!=null&&rt>=me?rt:me,Wt=nl(oe,z)===oe.length-1?Pe-It:It-Pe,an=gc({delta:Wt,initialLayout:ie,panelConstraints:J,pivotIndices:Me,prevLayout:ie,trigger:"imperative-api"});Vf(ie,an)||(b(an),C.current.layout=an,ne&&ne(an),Yi(oe,an,y.current))}}},[]),P=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{panelSize:ie}=Fa(ne,z,se);return tt(ie!=null,`Panel size not found for panel "${z.id}"`),ie},[]),N=ir((z,se)=>{const{panelDataArray:ne}=C.current,ie=nl(ne,z);return yZ({defaultSize:se,dragState:g,layout:x,panelData:ne,panelIndex:ie})},[g,x]),U=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:ie=0,collapsible:oe,panelSize:J}=Fa(ne,z,se);return tt(J!=null,`Panel size not found for panel "${z.id}"`),oe===!0&&no(J,ie)},[]),I=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:ie=0,collapsible:oe,panelSize:J}=Fa(ne,z,se);return tt(J!=null,`Panel size not found for panel "${z.id}"`),!oe||Ri(J,ie)>0},[]),Z=ir(z=>{const{panelDataArray:se}=C.current;se.push(z),se.sort((ne,ie)=>{const oe=ne.order,J=ie.order;return oe==null&&J==null?0:oe==null?-1:J==null?1:oe-J}),C.current.panelDataArrayChanged=!0},[]);hi(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:se,storage:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current;let J=null;if(z){const Pe=xZ(z,oe,ne);Pe&&(w.current=new Map(Object.entries(Pe.expandToSizes)),J=Pe.layout)}J==null&&(J=vZ({panelDataArray:oe}));const Ce=G1({layout:J,panelConstraints:oe.map(Pe=>Pe.constraints)});q1(ie,Ce)||(b(Ce),C.current.layout=Ce,se&&se(Ce),Yi(oe,Ce,y.current))}}),hi(()=>{const z=C.current;return()=>{z.layout=[]}},[]);const V=ir(z=>function(ne){ne.preventDefault();const ie=h.current;if(!ie)return()=>null;const{direction:oe,dragState:J,id:Ce,keyboardResizeBy:Pe,onLayout:Le}=E.current,{layout:Me,panelDataArray:me}=C.current,{initialLayout:rt}=J??{},It=CN(Ce,z,ie);let Zt=mZ(ne,z,oe,J,Pe,ie);const Wt=oe==="horizontal";document.dir==="rtl"&&Wt&&(Zt=-Zt);const an=me.map(B=>B.constraints),j=gc({delta:Zt,initialLayout:rt??Me,panelConstraints:an,pivotIndices:It,prevLayout:Me,trigger:hN(ne)?"keyboard":"mouse-or-touch"}),D=!Vf(Me,j);(gN(ne)||mN(ne))&&S.current!=Zt&&(S.current=Zt,D?gv(z,0):Wt?gv(z,Zt<0?yN:bN):gv(z,Zt<0?xN:wN)),D&&(b(j),C.current.layout=j,Le&&Le(j),Yi(me,j,y.current))},[]),Q=ir((z,se)=>{const{onLayout:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current,J=oe.map(rt=>rt.constraints),{panelSize:Ce,pivotIndices:Pe}=Fa(oe,z,ie);tt(Ce!=null,`Panel size not found for panel "${z.id}"`);const Me=nl(oe,z)===oe.length-1?Ce-se:se-Ce,me=gc({delta:Me,initialLayout:ie,panelConstraints:J,pivotIndices:Pe,prevLayout:ie,trigger:"imperative-api"});Vf(ie,me)||(b(me),C.current.layout=me,ne&&ne(me),Yi(oe,me,y.current))},[]),ee=ir((z,se)=>{const{layout:ne,panelDataArray:ie}=C.current,{collapsedSize:oe=0,collapsible:J}=se,{collapsedSize:Ce=0,collapsible:Pe,maxSize:Le=100,minSize:Me=0}=z.constraints,{panelSize:me}=Fa(ie,z,ne);me!=null&&(J&&Pe&&no(me,oe)?no(oe,Ce)||Q(z,Ce):meLe&&Q(z,Le))},[Q]),W=ir((z,se)=>{const{direction:ne}=E.current,{layout:ie}=C.current;if(!h.current)return;const oe=Wg(z,h.current);tt(oe,`Drag handle element not found for id "${z}"`);const J=TN(ne,se);m({dragHandleId:z,dragHandleRect:oe.getBoundingClientRect(),initialCursorPosition:J,initialLayout:ie})},[]),F=ir(()=>{m(null)},[]),A=ir(z=>{const{panelDataArray:se}=C.current,ne=nl(se,z);ne>=0&&(se.splice(ne,1),delete y.current[z.id],C.current.panelDataArrayChanged=!0)},[]),Y=ZQ(()=>({collapsePanel:k,direction:r,dragState:g,expandPanel:T,getPanelSize:P,getPanelStyle:N,groupId:f,isPanelCollapsed:U,isPanelExpanded:I,reevaluatePanelConstraints:ee,registerPanel:Z,registerResizeHandle:V,resizePanel:Q,startDragging:W,stopDragging:F,unregisterPanel:A,panelGroupElement:h.current}),[k,g,r,T,P,N,f,U,I,ee,Z,V,Q,W,F,A]),de={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return au(Hg.Provider,{value:Y},au(d,{...p,children:t,className:n,id:o,ref:h,style:{...de,...i},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":f}))}const PN=uN((e,t)=>au(RN,{...e,forwardedRef:t}));RN.displayName="PanelGroup";PN.displayName="forwardRef(PanelGroup)";function nl(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Fa(e,t,n){const r=nl(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:o}}function CZ({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){pi(()=>{if(e||n==null||r==null)return;const s=Wg(t,r);if(s==null)return;const o=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),n(a);break}case"F6":{a.preventDefault();const l=s.getAttribute("data-panel-group-id");tt(l,`No group element found for id "${l}"`);const c=Rd(l,r),i=SN(l,t,r);tt(i!==null,`No resize element found for id "${t}"`);const d=a.shiftKey?i>0?i-1:c.length-1:i+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function MN({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:a,onFocus:l,style:c={},tabIndex:i=0,tagName:d="div",...p}){var f,h;const g=Yn(null),m=Yn({onDragging:a});pi(()=>{m.current.onDragging=a});const x=cN(Hg);if(x===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:b,groupId:y,registerResizeHandle:w,startDragging:S,stopDragging:E,panelGroupElement:C}=x,k=Ow(s),[T,P]=Oc("inactive"),[N,U]=Oc(!1),[I,Z]=Oc(null),V=Yn({state:T});hi(()=>{V.current.state=T}),pi(()=>{if(n)Z(null);else{const F=w(k);Z(()=>F)}},[n,k,w]);const Q=(f=r==null?void 0:r.coarse)!==null&&f!==void 0?f:15,ee=(h=r==null?void 0:r.fine)!==null&&h!==void 0?h:5;return pi(()=>{if(n||I==null)return;const F=g.current;return tt(F,"Element ref not attached"),cZ(k,F,b,{coarse:Q,fine:ee},(Y,de,z)=>{if(de)switch(Y){case"down":{P("drag"),S(k,z);const{onDragging:se}=m.current;se&&se(!0);break}case"move":{const{state:se}=V.current;se!=="drag"&&P("hover"),I(z);break}case"up":{P("hover"),E();const{onDragging:se}=m.current;se&&se(!1);break}}else P("inactive")})},[Q,b,n,ee,w,k,I,S,E]),CZ({disabled:n,handleId:k,resizeHandler:I,panelGroupElement:C}),au(d,{...p,children:e,className:t,id:s,onBlur:()=>{U(!1),o==null||o()},onFocus:()=>{U(!0),l==null||l()},ref:g,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...c},tabIndex:i,"data-panel-group-direction":b,"data-panel-group-id":y,"data-resize-handle":"","data-resize-handle-active":T==="drag"?"pointer":N?"keyboard":void 0,"data-resize-handle-state":T,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":k})}MN.displayName="PanelResizeHandle";const Pu=({className:e,...t})=>u.jsx(PN,{className:ge("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),Ur=pN,Mu=({withHandle:e,className:t,...n})=>u.jsx(MN,{className:ge("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&u.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:u.jsx($3,{className:"h-2.5 w-2.5"})})});var Aw="Tabs",[EZ,noe]=Vr(Aw,[vg]),ON=vg(),[TZ,Fw]=EZ(Aw),NN=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:a="horizontal",dir:l,activationMode:c="automatic",...i}=e,d=Gd(l),[p,f]=pa({prop:r,onChange:s,defaultProp:o});return u.jsx(TZ,{scope:n,baseId:os(),value:p,onValueChange:f,orientation:a,dir:d,activationMode:c,children:u.jsx(Ne.div,{dir:d,"data-orientation":a,...i,ref:t})})});NN.displayName=Aw;var IN="TabsList",DN=v.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=Fw(IN,n),a=ON(n);return u.jsx(Gj,{asChild:!0,...a,orientation:o.orientation,dir:o.dir,loop:r,children:u.jsx(Ne.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});DN.displayName=IN;var AN="TabsTrigger",FN=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,a=Fw(AN,n),l=ON(n),c=BN(a.baseId,r),i=zN(a.baseId,r),d=r===a.value;return u.jsx(Jj,{asChild:!0,...l,focusable:!s,active:d,children:u.jsx(Ne.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":i,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...o,ref:t,onMouseDown:Se(e.onMouseDown,p=>{!s&&p.button===0&&p.ctrlKey===!1?a.onValueChange(r):p.preventDefault()}),onKeyDown:Se(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&a.onValueChange(r)}),onFocus:Se(e.onFocus,()=>{const p=a.activationMode!=="manual";!d&&!s&&p&&a.onValueChange(r)})})})});FN.displayName=AN;var LN="TabsContent",$N=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...a}=e,l=Fw(LN,n),c=BN(l.baseId,r),i=zN(l.baseId,r),d=r===l.value,p=v.useRef(d);return v.useEffect(()=>{const f=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(f)},[]),u.jsx(or,{present:s||d,children:({present:f})=>u.jsx(Ne.div,{"data-state":d?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!f,id:i,tabIndex:0,...a,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:f&&o})})});$N.displayName=LN;function BN(e,t){return`${e}-trigger-${t}`}function zN(e,t){return`${e}-content-${t}`}var kZ=NN,UN=DN,VN=FN,HN=$N;const _Z=kZ,KN=v.forwardRef(({className:e,...t},n)=>u.jsx(UN,{ref:n,className:ge("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));KN.displayName=UN.displayName;const xb=v.forwardRef(({className:e,...t},n)=>u.jsx(VN,{ref:n,className:ge("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));xb.displayName=VN.displayName;const wb=v.forwardRef(({className:e,...t},n)=>u.jsx(HN,{ref:n,className:ge("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));wb.displayName=HN.displayName;const jZ=e=>["chats","findChats",JSON.stringify(e)],RZ=async({instanceName:e})=>(await he.post(`/chat/findChats/${e}`,{where:{}})).data,PZ=e=>{const{instanceName:t,...n}=e;return lt({...n,queryKey:jZ({instanceName:t}),queryFn:()=>RZ({instanceName:t}),enabled:!!t})};function Ou(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=v.useState(t(e));function s(){r(t(e))}return v.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const Ml=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:ge("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Ml.displayName="Textarea";const MZ=e=>["chats","findChats",JSON.stringify(e)],OZ=async({instanceName:e,remoteJid:t})=>{const n=await he.post(`/chat/findChats/${e}`,{where:{remoteJid:t}});return Array.isArray(n.data)?n.data[0]:n.data},NZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return lt({...r,queryKey:MZ({instanceName:t,remoteJid:n}),queryFn:()=>OZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})},IZ=e=>["chats","findMessages",JSON.stringify(e)],DZ=async({instanceName:e,remoteJid:t})=>{var r,s;const n=await he.post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}});return(s=(r=n.data)==null?void 0:r.messages)!=null&&s.records?n.data.messages.records:n.data},AZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return lt({...r,queryKey:IZ({instanceName:t,remoteJid:n}),queryFn:()=>DZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})};function FZ({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=nt(),{remoteJid:a}=So(),{data:l}=NZ({remoteJid:a,instanceName:o==null?void 0:o.name}),{data:c,isSuccess:i}=AZ({remoteJid:a,instanceName:o==null?void 0:o.name});v.useEffect(()=>{i&&c&&s()},[i,c,s]);const d=f=>u.jsx("div",{className:"bubble-right",children:u.jsx("div",{className:"flex items-start gap-4 self-end",children:u.jsx("div",{className:"grid gap-1",children:u.jsx("div",{className:"prose text-muted-foreground",children:u.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})}),p=f=>u.jsx("div",{className:"bubble-left",children:u.jsx("div",{className:"flex items-start gap-4",children:u.jsx("div",{className:"grid gap-1",children:u.jsx("div",{className:"prose text-muted-foreground",children:u.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})});return u.jsxs("div",{className:"flex min-h-screen flex-col",children:[u.jsx("div",{className:"sticky top-0 p-2",children:u.jsxs(nw,{children:[u.jsx(rw,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-10 gap-1 rounded-xl px-3 text-lg data-[state=open]:bg-muted",children:[(l==null?void 0:l.pushName)||(l==null?void 0:l.remoteJid.split("@")[0]),u.jsx(lg,{className:"h-4 w-4 text-muted-foreground"})]})}),u.jsxs(ps,{align:"start",className:"max-w-[300px]",children:[u.jsxs(ft,{className:"items-start gap-2",children:[u.jsx(W3,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),u.jsxs("div",{children:[u.jsx("div",{className:"font-medium",children:"GPT-4"}),u.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),u.jsx(Pa,{}),u.jsxs(ft,{className:"items-start gap-2",children:[u.jsx(pj,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),u.jsxs("div",{children:[u.jsx("div",{className:"font-medium",children:"GPT-3"}),u.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),u.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-8 overflow-y-auto px-4",children:[c==null?void 0:c.map(f=>f.key.fromMe?d(f):p(f)),u.jsx("div",{ref:r})]}),u.jsx("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-4 py-2",children:u.jsxs("div",{className:"input-message relative",children:[u.jsxs(q,{type:"button",size:"icon",className:"absolute bottom-3 left-3 h-8 w-8 rounded-full bg-transparent text-white hover:bg-transparent",children:[u.jsx(q3,{className:"h-4 w-4 text-white"}),u.jsx("span",{className:"sr-only",children:"Anexar"})]}),u.jsx(Ml,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"max-h-[240px] min-h-[48px] resize-none rounded-3xl border border-none p-4 pl-12 pr-16 shadow-sm"}),u.jsxs(q,{type:"submit",size:"icon",className:"absolute bottom-3 right-3 h-8 w-8 rounded-full",children:[u.jsx(j3,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}function Q1(){const e=Ou("(min-width: 768px)"),t=v.useRef(null),[n]=v.useState("auto"),r=v.useRef(null),{instance:s}=nt(),{data:o,isSuccess:a}=PZ({instanceName:s==null?void 0:s.name}),{instanceId:l,remoteJid:c}=So(),i=An(),d=v.useCallback(()=>{t.current&&t.current.scrollIntoView({})},[]),p=()=>{if(r.current){r.current.style.height="auto";const h=r.current.scrollHeight,m=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(h,m)}px`}};v.useEffect(()=>{a&&d()},[a,d]);const f=h=>{i(`/manager/instance/${l}/chat/${h}`)};return u.jsxs(Pu,{direction:e?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:20,children:u.jsxs("div",{className:"hidden flex-col gap-2 bg-background text-foreground md:flex",children:[u.jsx("div",{className:"sticky top-0 p-2",children:u.jsxs(q,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[u.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:u.jsx(ug,{className:"h-4 w-4"})}),u.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),u.jsx(Ni,{className:"h-4 w-4"})]})}),u.jsxs(_Z,{defaultValue:"contacts",children:[u.jsxs(KN,{className:"tabs-chat",children:[u.jsx(xb,{value:"contacts",children:"Contatos"}),u.jsx(xb,{value:"groups",children:"Grupos"})]}),u.jsx(wb,{value:"contacts",children:u.jsx("div",{className:"flex-1 overflow-auto",children:u.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[u.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),o==null?void 0:o.map(h=>h.remoteJid.includes("@s.whatsapp.net")&&u.jsxs(nd,{to:"#",onClick:()=>f(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[u.jsx("span",{className:"chat-avatar mr-2",children:u.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),u.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid.split("@")[0]})]})]},h.id))]})})}),u.jsx(wb,{value:"groups",children:u.jsx("div",{className:"flex-1 overflow-auto",children:u.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:o==null?void 0:o.map(h=>h.remoteJid.includes("@g.us")&&u.jsxs(nd,{to:"#",onClick:()=>f(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[u.jsx("span",{className:"chat-avatar mr-2",children:u.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),u.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid})]})]},h.id))})})})]})]})}),u.jsx(Mu,{withHandle:!0,className:"border border-black"}),u.jsx(Ur,{children:c&&u.jsx(FZ,{textareaRef:r,handleTextareaChange:p,textareaHeight:n,lastMessageRef:t,scrollToBottom:d})})]})}const LZ=e=>["chatwoot","fetchChatwoot",JSON.stringify(e)],$Z=async({instanceName:e,token:t})=>(await he.get(`/chatwoot/find/${e}`,{headers:{apiKey:t}})).data,BZ=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:LZ({instanceName:t,token:n}),queryFn:()=>$Z({instanceName:t,token:n}),enabled:!!t})},zZ=async({instanceName:e,token:t,data:n})=>(await he.post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data;function UZ(){return{createChatwoot:Ye(zZ,{invalidateKeys:[["chatwoot","fetchChatwoot"]]})}}const Hf=_.string().optional().transform(e=>e===""?void 0:e),VZ=_.object({enabled:_.boolean(),accountId:_.string(),token:_.string(),url:_.string(),signMsg:_.boolean().optional(),signDelimiter:Hf,nameInbox:Hf,organization:Hf,logo:Hf,reopenConversation:_.boolean().optional(),conversationPending:_.boolean().optional(),mergeBrazilContacts:_.boolean().optional(),importContacts:_.boolean().optional(),importMessages:_.boolean().optional(),daysLimitImportMessages:_.coerce.number().optional(),autoCreate:_.boolean(),ignoreJids:_.array(_.string()).default([])});function HZ(){const{t:e}=ze(),{instance:t}=nt(),[,n]=v.useState(!1),{createChatwoot:r}=UZ(),{data:s}=BZ({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),o=sn({resolver:on(VZ),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});v.useEffect(()=>{if(s){o.setValue("ignoreJids",s.ignoreJids||[]);const l={enabled:s.enabled,accountId:s.accountId,token:s.token,url:s.url,signMsg:s.signMsg||!1,signDelimiter:s.signDelimiter||"\\n",nameInbox:s.nameInbox||"",organization:s.organization||"",logo:s.logo||"",reopenConversation:s.reopenConversation||!1,conversationPending:s.conversationPending||!1,mergeBrazilContacts:s.mergeBrazilContacts||!1,importContacts:s.importContacts||!1,importMessages:s.importMessages||!1,daysLimitImportMessages:s.daysLimitImportMessages||7,autoCreate:s.autoCreate||!1,ignoreJids:s.ignoreJids};o.reset(l)}},[s,o]);const a=async l=>{if(!t)return;n(!0);const c={enabled:l.enabled,accountId:l.accountId,token:l.token,url:l.url,signMsg:l.signMsg||!1,signDelimiter:l.signDelimiter||"\\n",nameInbox:l.nameInbox||"",organization:l.organization||"",logo:l.logo||"",reopenConversation:l.reopenConversation||!1,conversationPending:l.conversationPending||!1,mergeBrazilContacts:l.mergeBrazilContacts||!1,importContacts:l.importContacts||!1,importMessages:l.importMessages||!1,daysLimitImportMessages:l.daysLimitImportMessages||7,autoCreate:l.autoCreate,ignoreJids:l.ignoreJids};await r({instanceName:t.name,token:t.token,data:c},{onSuccess:()=>{X.success(e("chatwoot.toast.success"))},onError:i=>{var d,p,f;console.error(e("chatwoot.toast.error"),i),A4(i)?X.error(`Error: ${(f=(p=(d=i==null?void 0:i.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`):X.error(e("chatwoot.toast.error"))},onSettled:()=>{n(!1)}})};return u.jsx(u.Fragment,{children:u.jsx(Na,{...o,children:u.jsxs("form",{onSubmit:o.handleSubmit(a),className:"w-full space-y-6",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[u.jsx(ke,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),u.jsx(G,{name:"url",label:e("chatwoot.form.url.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"token",label:e("chatwoot.form.token.label"),children:u.jsx(K,{type:"password"})}),u.jsx(ke,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),u.jsx(G,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"organization",label:e("chatwoot.form.organization.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"logo",label:e("chatwoot.form.logo.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),u.jsx(ke,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),u.jsx(ke,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),u.jsx(ke,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),u.jsx(G,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),u.jsx(ke,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),u.jsx("div",{className:"mx-4 flex justify-end",children:u.jsx(q,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var Gg={},qN={exports:{}},KZ="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",qZ=KZ,WZ=qZ;function WN(){}function GN(){}GN.resetWarningCache=WN;var GZ=function(){function e(r,s,o,a,l,c){if(c!==WZ){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:GN,resetWarningCache:WN};return n.PropTypes=n,n};qN.exports=GZ();var JN=qN.exports,QN={L:1,M:0,Q:3,H:2},ZN={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},JZ=ZN;function YN(e){this.mode=JZ.MODE_8BIT_BYTE,this.data=e}YN.prototype={getLength:function(e){return this.data.length},write:function(e){for(var t=0;t>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var YZ=XN,Xr={glog:function(e){if(e<1)throw new Error("glog("+e+")");return Xr.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return Xr.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var Cn=0;Cn<8;Cn++)Xr.EXP_TABLE[Cn]=1<=0;)t^=wn.G15<=0;)t^=wn.G18<>>=1;return t},getPatternPosition:function(e){return wn.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case Do.PATTERN000:return(t+n)%2==0;case Do.PATTERN001:return t%2==0;case Do.PATTERN010:return n%3==0;case Do.PATTERN011:return(t+n)%3==0;case Do.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case Do.PATTERN101:return t*n%2+t*n%3==0;case Do.PATTERN110:return(t*n%2+t*n%3)%2==0;case Do.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new Z1([1],0),n=0;n5&&(n+=3+o-5)}for(var r=0;r=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=Ns.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)};kr.setupPositionProbePattern=function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r==0||r==6)||0<=r&&r<=6&&(n==0||n==6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)};kr.getBestMaskPattern=function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=Da.getLostPoint(this);(n==0||e>r)&&(e=r,t=n)}return t};kr.createMovieClip=function(e,t,n){var r=e.createEmptyMovieClip(t,n),s=1;this.make();for(var o=0;o>n&1)==1;this.modules[Math.floor(n/3)][n%3+this.moduleCount-8-3]=r}for(var n=0;n<18;n++){var r=!e&&(t>>n&1)==1;this.modules[n%3+this.moduleCount-8-3][Math.floor(n/3)]=r}};kr.setupTypeInfo=function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=Da.getBCHTypeInfo(n),s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<6?this.modules[s][8]=o:s<8?this.modules[s+1][8]=o:this.modules[this.moduleCount-15+s][8]=o}for(var s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=o:s<9?this.modules[8][15-s-1+1]=o:this.modules[8][15-s-1]=o}this.modules[this.moduleCount-8][8]=!e};kr.mapData=function(e,t){for(var n=-1,r=this.moduleCount-1,s=7,o=0,a=this.moduleCount-1;a>0;a-=2)for(a==6&&a--;;){for(var l=0;l<2;l++)if(this.modules[r][a-l]==null){var c=!1;o>>s&1)==1);var i=Da.getMask(t,r,a-l);i&&(c=!c),this.modules[r][a-l]=c,s--,s==-1&&(o++,s=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}};Ns.PAD0=236;Ns.PAD1=17;Ns.createData=function(e,t,n){for(var r=nI.getRSBlocks(e,t),s=new rI,o=0;ol*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+l*8+")");for(s.getLengthInBits()+4<=l*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=l*8||(s.put(Ns.PAD0,8),s.getLengthInBits()>=l*8));)s.put(Ns.PAD1,8);return Ns.createBytes(s,r)};Ns.createBytes=function(e,t){for(var n=0,r=0,s=0,o=new Array(t.length),a=new Array(t.length),l=0;l=0?h.get(g):0}}for(var m=0,d=0;d=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var iY={bgColor:Pr.default.oneOfType([Pr.default.object,Pr.default.string]).isRequired,bgD:Pr.default.string.isRequired,fgColor:Pr.default.oneOfType([Pr.default.object,Pr.default.string]).isRequired,fgD:Pr.default.string.isRequired,size:Pr.default.number.isRequired,title:Pr.default.string,viewBoxSize:Pr.default.number.isRequired,xmlns:Pr.default.string},$w=(0,sI.forwardRef)(function(e,t){var n=e.bgColor,r=e.bgD,s=e.fgD,o=e.fgColor,a=e.size,l=e.title,c=e.viewBoxSize,i=e.xmlns,d=i===void 0?"http://www.w3.org/2000/svg":i,p=aY(e,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return qf.default.createElement("svg",sY({},p,{height:a,ref:t,viewBox:"0 0 "+c+" "+c,width:a,xmlns:d}),l?qf.default.createElement("title",null,l):null,qf.default.createElement("path",{d:r,fill:n}),qf.default.createElement("path",{d:s,fill:o}))});$w.displayName="QRCodeSvg";$w.propTypes=iY;Lw.default=$w;Object.defineProperty(Gg,"__esModule",{value:!0});Gg.QRCode=void 0;var lY=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var yY={bgColor:Gs.default.oneOfType([Gs.default.object,Gs.default.string]),fgColor:Gs.default.oneOfType([Gs.default.object,Gs.default.string]),level:Gs.default.string,size:Gs.default.number,value:Gs.default.string.isRequired},Jg=(0,aI.forwardRef)(function(e,t){var n=e.bgColor,r=n===void 0?"#FFFFFF":n,s=e.fgColor,o=s===void 0?"#000000":s,a=e.level,l=a===void 0?"L":a,c=e.size,i=c===void 0?256:c,d=e.value,p=vY(e,["bgColor","fgColor","level","size","value"]),f=new pY.default(-1,dY.default[l]);f.addData(d),f.make();var h=f.modules;return hY.default.createElement(mY.default,lY({},p,{bgColor:r,bgD:h.map(function(g,m){return g.map(function(x,b){return x?"":"M "+b+" "+m+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:o,fgD:h.map(function(g,m){return g.map(function(x,b){return x?"M "+b+" "+m+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:t,size:i,viewBoxSize:h.length}))});Gg.QRCode=Jg;Jg.displayName="QRCode";Jg.propTypes=yY;var bY=Gg.default=Jg;const xY=ig("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),iI=v.forwardRef(({className:e,variant:t,...n},r)=>u.jsx("div",{ref:r,role:"alert",className:ge(xY({variant:t}),e),...n}));iI.displayName="Alert";const lI=v.forwardRef(({className:e,...t},n)=>u.jsx("h5",{ref:n,className:ge("font-medium leading-none tracking-tight",e),...t}));lI.displayName="AlertTitle";const wY=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("text-sm [&_p]:leading-relaxed",e),...t}));wY.displayName="AlertDescription";const wr=({size:e=45,className:t,...n})=>u.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:ge("animate-spin",t),children:u.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})});function SY(){const{t:e,i18n:t}=ze(),n=new Intl.NumberFormat(t.language),[r,s]=v.useState(null),[o,a]=v.useState(""),l=Fs(rs.TOKEN),{theme:c}=R_(),{connect:i,logout:d,restart:p}=_g(),{instance:f,reloadInstance:h}=nt(),g=async()=>{await h()},m=async E=>{try{await p(E),await h()}catch(C){console.error("Error:",C)}},x=async E=>{try{await d(E),await h()}catch(C){console.error("Error:",C)}},b=async(E,C)=>{try{if(s(null),!l){console.error("Token not found.");return}if(C){const k=await i({instanceName:E,token:l,number:f==null?void 0:f.number});a(k.pairingCode)}else{const k=await i({instanceName:E,token:l});s(k.code)}}catch(k){console.error("Error:",k)}},y=async()=>{s(null),a(""),await h()},w=v.useMemo(()=>{var E,C,k;return f?{contacts:((E=f._count)==null?void 0:E.Contact)||0,chats:((C=f._count)==null?void 0:C.Chat)||0,messages:((k=f._count)==null?void 0:k.Message)||0}:{contacts:0,chats:0,messages:0}},[f]),S=v.useMemo(()=>c==="dark"?"#fff":c==="light"?"#000":"#189d68",[c]);return f?u.jsxs("main",{className:"flex flex-col gap-8",children:[u.jsx("section",{children:u.jsxs(Ja,{children:[u.jsx(Qa,{children:u.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[u.jsx("h2",{className:"break-all text-lg font-semibold",children:f.name}),u.jsx(WP,{status:f.connectionStatus})]})}),u.jsxs(Za,{className:"flex flex-col items-start space-y-6",children:[u.jsx("div",{className:"flex w-full flex-1",children:u.jsx(GP,{token:f.token})}),f.profileName&&u.jsxs("div",{className:"flex flex-1 gap-2",children:[u.jsx(Sg,{children:u.jsx(Cg,{src:f.profilePicUrl,alt:""})}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("strong",{children:f.profileName}),u.jsx("p",{className:"break-all text-sm text-muted-foreground",children:f.ownerJid})]})]}),f.connectionStatus!=="open"&&u.jsxs(iI,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[u.jsx(lI,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),u.jsxs(Tt,{children:[u.jsx(Nt,{onClick:()=>b(f.name,!1),asChild:!0,children:u.jsx(q,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),u.jsxs(xt,{onCloseAutoFocus:y,children:[u.jsx(wt,{children:e("instance.dashboard.button.qrcode.title")}),u.jsx("div",{className:"flex items-center justify-center",children:r&&u.jsx(bY,{value:r,size:256,bgColor:"transparent",fgColor:S,className:"rounded-sm"})})]})]}),f.number&&u.jsxs(Tt,{children:[u.jsx(Nt,{className:"connect-code-button",onClick:()=>b(f.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),u.jsx(xt,{onCloseAutoFocus:y,children:u.jsx(wt,{children:u.jsx(Fi,{children:o?u.jsxs("div",{className:"py-3",children:[u.jsx("p",{className:"text-center",children:u.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),u.jsxs("p",{className:"pairing-code text-center",children:[o.substring(0,4),"-",o.substring(4,8)]})]}):u.jsx(wr,{})})})})]})]})]}),u.jsxs(kg,{className:"flex flex-wrap items-center justify-end gap-3",children:[u.jsx(q,{variant:"outline",className:"refresh-button",size:"icon",onClick:g,children:u.jsx(fj,{size:"20"})}),u.jsx(q,{className:"action-button",variant:"secondary",onClick:()=>m(f.name),children:e("instance.dashboard.button.restart").toUpperCase()}),u.jsx(q,{variant:"destructive",onClick:()=>x(f.name),disabled:f.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),u.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(dj,{size:"20"}),e("instance.dashboard.contacts")]})}),u.jsx(Za,{children:n.format(w.contacts)})]}),u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(J3,{size:"20"}),e("instance.dashboard.chats")]})}),u.jsx(Za,{children:n.format(w.chats)})]}),u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(ug,{size:"20"}),e("instance.dashboard.messages")]})}),u.jsx(Za,{children:n.format(w.messages)})]})]})]}):u.jsx(wr,{})}var CY="Separator",Y1="horizontal",EY=["horizontal","vertical"],uI=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Y1,...s}=e,o=TY(r)?r:Y1,l=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return u.jsx(Ne.div,{"data-orientation":o,...l,...s,ref:t})});uI.displayName=CY;function TY(e){return EY.includes(e)}var cI=uI;const $t=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>u.jsx(cI,{ref:s,decorative:n,orientation:t,className:ge("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));$t.displayName=cI.displayName;const kY=e=>["dify","fetchDify",JSON.stringify(e)],_Y=async({instanceName:e,token:t})=>(await he.get(`/dify/find/${e}`,{headers:{apikey:t}})).data,dI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:kY({instanceName:t,token:n}),queryFn:()=>_Y({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},jY=async({instanceName:e,token:t,data:n})=>(await he.post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,RY=async({instanceName:e,difyId:t,data:n})=>(await he.put(`/dify/update/${t}/${e}`,n)).data,PY=async({instanceName:e,difyId:t})=>(await he.delete(`/dify/delete/${t}/${e}`)).data,MY=async({instanceName:e,token:t,data:n})=>(await he.post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,OY=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Qg(){const e=Ye(MY,{invalidateKeys:[["dify","fetchDefaultSettings"]]}),t=Ye(OY,{invalidateKeys:[["dify","getDify"],["dify","fetchSessions"]]}),n=Ye(PY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),r=Ye(RY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),s=Ye(jY,{invalidateKeys:[["dify","fetchDify"]]});return{setDefaultSettingsDify:e,changeStatusDify:t,deleteDify:n,updateDify:r,createDify:s}}const NY=e=>["dify","fetchDefaultSettings",JSON.stringify(e)],IY=async({instanceName:e,token:t})=>(await he.get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,DY=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:NY({instanceName:t,token:n}),queryFn:()=>IY({instanceName:t,token:n}),enabled:!!t})},AY=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),difyIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean(),timePerChar:_.string()});function FY(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsDify:n}=Qg(),[r,s]=v.useState(!1),{data:o,refetch:a}=dI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:r}),{data:l,refetch:c}=DY({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),i=sn({resolver:on(AY),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{l&&i.reset({expire:l!=null&&l.expire?l.expire.toString():"0",keywordFinish:l.keywordFinish,delayMessage:l.delayMessage?l.delayMessage.toString():"0",unknownMessage:l.unknownMessage,listeningFromMe:l.listeningFromMe,stopBotFromMe:l.stopBotFromMe,keepOpen:l.keepOpen,debounceTime:l.debounceTime?l.debounceTime.toString():"0",ignoreJids:l.ignoreJids,difyIdFallback:l.difyIdFallback,splitMessages:l.splitMessages,timePerChar:l.timePerChar?l.timePerChar.toString():"0"})},[l]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),difyIdFallback:f.difyIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),X.success(e("dify.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){c(),a()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("dify.defaultSettings")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:(o==null?void 0:o.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(G,{name:"expire",label:e("dify.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("dify.form.splitMessages.label"),reverse:!0}),u.jsx(G,{name:"timePerChar",label:e("dify.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("dify.button.save")})})]})})]})]})}/** - * table-core - * - * Copyright (c) TanStack - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function na(e,t){return typeof e=="function"?e(t):e}function Sr(e,t){return n=>{t.setState(r=>({...r,[e]:na(n,r[e])}))}}function Zg(e){return e instanceof Function}function LY(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function fI(e,t){const n=[],r=s=>{s.forEach(o=>{n.push(o);const a=t(o);a!=null&&a.length&&r(a)})};return r(e),n}function De(e,t,n){let r=[],s;return o=>{let a;n.key&&n.debug&&(a=Date.now());const l=e(o);if(!(l.length!==r.length||l.some((d,p)=>r[p]!==d)))return s;r=l;let i;if(n.key&&n.debug&&(i=Date.now()),s=t(...l),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const d=Math.round((Date.now()-a)*100)/100,p=Math.round((Date.now()-i)*100)/100,f=p/16,h=(g,m)=>{for(g=String(g);g.length{var s;return(s=e==null?void 0:e.debugAll)!=null?s:e[t]},key:!1,onChange:r}}function $Y(e,t,n,r){const s=()=>{var a;return(a=o.getValue())!=null?a:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:s,getContext:De(()=>[e,n,t,o],(a,l,c,i)=>({table:a,column:l,row:c,cell:i,getValue:i.getValue,renderValue:i.renderValue}),Ae(e.options,"debugCells"))};return e._features.forEach(a=>{a.createCell==null||a.createCell(o,n,t,e)},{}),o}function BY(e,t,n,r){var s,o;const l={...e._getDefaultColumnDef(),...t},c=l.accessorKey;let i=(s=(o=l.id)!=null?o:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?s:typeof l.header=="string"?l.header:void 0,d;if(l.accessorFn?d=l.accessorFn:c&&(c.includes(".")?d=f=>{let h=f;for(const m of c.split(".")){var g;h=(g=h)==null?void 0:g[m]}return h}:d=f=>f[l.accessorKey]),!i)throw new Error;let p={id:`${String(i)}`,accessorFn:d,parent:r,depth:n,columnDef:l,columns:[],getFlatColumns:De(()=>[!0],()=>{var f;return[p,...(f=p.columns)==null?void 0:f.flatMap(h=>h.getFlatColumns())]},Ae(e.options,"debugColumns")),getLeafColumns:De(()=>[e._getOrderColumnsFn()],f=>{var h;if((h=p.columns)!=null&&h.length){let g=p.columns.flatMap(m=>m.getLeafColumns());return f(g)}return[p]},Ae(e.options,"debugColumns"))};for(const f of e._features)f.createColumn==null||f.createColumn(p,e);return p}const Mn="debugHeaders";function X1(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const a=[],l=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(l),a.push(c)};return l(o),a},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(a=>{a.createHeader==null||a.createHeader(o,e)}),o}const zY={createTable:e=>{e.getHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>{var o,a;const l=(o=r==null?void 0:r.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?o:[],c=(a=s==null?void 0:s.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?a:[],i=n.filter(p=>!(r!=null&&r.includes(p.id))&&!(s!=null&&s.includes(p.id)));return Wf(t,[...l,...i,...c],e)},Ae(e.options,Mn)),e.getCenterHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),Wf(t,n,e,"center")),Ae(e.options,Mn)),e.getLeftHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(l=>l.id===a)).filter(Boolean))!=null?s:[];return Wf(t,o,e,"left")},Ae(e.options,Mn)),e.getRightHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(l=>l.id===a)).filter(Boolean))!=null?s:[];return Wf(t,o,e,"right")},Ae(e.options,Mn)),e.getFooterGroups=De(()=>[e.getHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getLeftFooterGroups=De(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getCenterFooterGroups=De(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getRightFooterGroups=De(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getFlatHeaders=De(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getLeftFlatHeaders=De(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getCenterFlatHeaders=De(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getRightFlatHeaders=De(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getCenterLeafHeaders=De(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Mn)),e.getLeftLeafHeaders=De(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Mn)),e.getRightLeafHeaders=De(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Mn)),e.getLeafHeaders=De(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var s,o,a,l,c,i;return[...(s=(o=t[0])==null?void 0:o.headers)!=null?s:[],...(a=(l=n[0])==null?void 0:l.headers)!=null?a:[],...(c=(i=r[0])==null?void 0:i.headers)!=null?c:[]].map(d=>d.getLeafHeaders()).flat()},Ae(e.options,Mn))}};function Wf(e,t,n,r){var s,o;let a=0;const l=function(f,h){h===void 0&&(h=1),a=Math.max(a,h),f.filter(g=>g.getIsVisible()).forEach(g=>{var m;(m=g.columns)!=null&&m.length&&l(g.columns,h+1)},0)};l(e);let c=[];const i=(f,h)=>{const g={depth:h,id:[r,`${h}`].filter(Boolean).join("_"),headers:[]},m=[];f.forEach(x=>{const b=[...m].reverse()[0],y=x.column.depth===g.depth;let w,S=!1;if(y&&x.column.parent?w=x.column.parent:(w=x.column,S=!0),b&&(b==null?void 0:b.column)===w)b.subHeaders.push(x);else{const E=X1(n,w,{id:[r,h,w.id,x==null?void 0:x.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${m.filter(C=>C.column===w).length}`:void 0,depth:h,index:m.length});E.subHeaders.push(x),m.push(E)}g.headers.push(x),x.headerGroup=g}),c.push(g),h>0&&i(m,h-1)},d=t.map((f,h)=>X1(n,f,{depth:a,index:h}));i(d,a-1),c.reverse();const p=f=>f.filter(g=>g.column.getIsVisible()).map(g=>{let m=0,x=0,b=[0];g.subHeaders&&g.subHeaders.length?(b=[],p(g.subHeaders).forEach(w=>{let{colSpan:S,rowSpan:E}=w;m+=S,b.push(E)})):m=1;const y=Math.min(...b);return x=x+y,g.colSpan=m,g.rowSpan=x,{colSpan:m,rowSpan:x}});return p((s=(o=c[0])==null?void 0:o.headers)!=null?s:[]),c}const Yg=(e,t,n,r,s,o,a)=>{let l={id:t,index:r,original:n,depth:s,parentId:a,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(l._valuesCache.hasOwnProperty(c))return l._valuesCache[c];const i=e.getColumn(c);if(i!=null&&i.accessorFn)return l._valuesCache[c]=i.accessorFn(l.original,r),l._valuesCache[c]},getUniqueValues:c=>{if(l._uniqueValuesCache.hasOwnProperty(c))return l._uniqueValuesCache[c];const i=e.getColumn(c);if(i!=null&&i.accessorFn)return i.columnDef.getUniqueValues?(l._uniqueValuesCache[c]=i.columnDef.getUniqueValues(l.original,r),l._uniqueValuesCache[c]):(l._uniqueValuesCache[c]=[l.getValue(c)],l._uniqueValuesCache[c])},renderValue:c=>{var i;return(i=l.getValue(c))!=null?i:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>fI(l.subRows,c=>c.subRows),getParentRow:()=>l.parentId?e.getRow(l.parentId,!0):void 0,getParentRows:()=>{let c=[],i=l;for(;;){const d=i.getParentRow();if(!d)break;c.push(d),i=d}return c.reverse()},getAllCells:De(()=>[e.getAllLeafColumns()],c=>c.map(i=>$Y(e,l,i,i.id)),Ae(e.options,"debugRows")),_getAllCellsByColumnId:De(()=>[l.getAllCells()],c=>c.reduce((i,d)=>(i[d.column.id]=d,i),{}),Ae(e.options,"debugRows"))};for(let c=0;c{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},pI=(e,t,n)=>{var r;const s=n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(s))};pI.autoRemove=e=>ls(e);const hI=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};hI.autoRemove=e=>ls(e);const gI=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===(n==null?void 0:n.toLowerCase())};gI.autoRemove=e=>ls(e);const mI=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};mI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const vI=(e,t,n)=>!n.some(r=>{var s;return!((s=e.getValue(t))!=null&&s.includes(r))});vI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const yI=(e,t,n)=>n.some(r=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(r)});yI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const bI=(e,t,n)=>e.getValue(t)===n;bI.autoRemove=e=>ls(e);const xI=(e,t,n)=>e.getValue(t)==n;xI.autoRemove=e=>ls(e);const Bw=(e,t,n)=>{let[r,s]=n;const o=e.getValue(t);return o>=r&&o<=s};Bw.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,s=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,a=n===null||Number.isNaN(s)?1/0:s;if(o>a){const l=o;o=a,a=l}return[o,a]};Bw.autoRemove=e=>ls(e)||ls(e[0])&&ls(e[1]);const Xs={includesString:pI,includesStringSensitive:hI,equalsString:gI,arrIncludes:mI,arrIncludesAll:vI,arrIncludesSome:yI,equals:bI,weakEquals:xI,inNumberRange:Bw};function ls(e){return e==null||e===""}const VY={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Sr("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);return typeof r=="string"?Xs.includesString:typeof r=="number"?Xs.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Xs.equals:Array.isArray(r)?Xs.arrIncludes:Xs.weakEquals},e.getFilterFn=()=>{var n,r;return Zg(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:Xs[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,s;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const s=e.getFilterFn(),o=r==null?void 0:r.find(d=>d.id===e.id),a=na(n,o?o.value:void 0);if(eE(s,a,e)){var l;return(l=r==null?void 0:r.filter(d=>d.id!==e.id))!=null?l:[]}const c={id:e.id,value:a};if(o){var i;return(i=r==null?void 0:r.map(d=>d.id===e.id?c:d))!=null?i:[]}return r!=null&&r.length?[...r,c]:[c]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=s=>{var o;return(o=na(t,s))==null?void 0:o.filter(a=>{const l=n.find(c=>c.id===a.id);if(l){const c=l.getFilterFn();if(eE(c,a.value,l))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function eE(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const HY=(e,t,n)=>n.reduce((r,s)=>{const o=s.getValue(e);return r+(typeof o=="number"?o:0)},0),KY=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},qY=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r=o)&&(r=o)}),r},WY=(e,t,n)=>{let r,s;return n.forEach(o=>{const a=o.getValue(e);a!=null&&(r===void 0?a>=a&&(r=s=a):(r>a&&(r=a),s{let n=0,r=0;if(t.forEach(s=>{let o=s.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},JY=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!LY(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,a)=>o-a);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},QY=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),ZY=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,YY=(e,t)=>t.length,mv={sum:HY,min:KY,max:qY,extent:WY,mean:GY,median:JY,unique:QY,uniqueCount:ZY,count:YY},XY={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:Sr("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);if(typeof r=="number")return mv.sum;if(Object.prototype.toString.call(r)==="[object Date]")return mv.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return Zg(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:mv[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var s;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function eX(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(a=>a.id===o)).filter(Boolean),...r]}const tX={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Sr("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=De(n=>[Nc(t,n)],n=>n.findIndex(r=>r.id===e.id),Ae(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Nc(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const s=Nc(t,n);return((r=s[s.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=De(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>s=>{let o=[];if(!(t!=null&&t.length))o=s;else{const a=[...t],l=[...s];for(;l.length&&a.length;){const c=a.shift(),i=l.findIndex(d=>d.id===c);i>-1&&o.push(l.splice(i,1)[0])}o=[...o,...l]}return eX(o,n,r)},Ae(e.options,"debugTable"))}},vv=()=>({left:[],right:[]}),nX={getInitialState:e=>({columnPinning:vv(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Sr("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(s=>s.id).filter(Boolean);t.setColumnPinning(s=>{var o,a;if(n==="right"){var l,c;return{left:((l=s==null?void 0:s.left)!=null?l:[]).filter(p=>!(r!=null&&r.includes(p))),right:[...((c=s==null?void 0:s.right)!=null?c:[]).filter(p=>!(r!=null&&r.includes(p))),...r]}}if(n==="left"){var i,d;return{left:[...((i=s==null?void 0:s.left)!=null?i:[]).filter(p=>!(r!=null&&r.includes(p))),...r],right:((d=s==null?void 0:s.right)!=null?d:[]).filter(p=>!(r!=null&&r.includes(p)))}}return{left:((o=s==null?void 0:s.left)!=null?o:[]).filter(p=>!(r!=null&&r.includes(p))),right:((a=s==null?void 0:s.right)!=null?a:[]).filter(p=>!(r!=null&&r.includes(p)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var s,o,a;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(a=t.options.enableColumnPinning)!=null?a:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(l=>l.id),{left:r,right:s}=t.getState().columnPinning,o=n.some(l=>r==null?void 0:r.includes(l)),a=n.some(l=>s==null?void 0:s.includes(l));return o?"left":a?"right":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();return s?(n=(r=t.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(a=>!o.includes(a.column.id))},Ae(t.options,"debugRows")),e.getLeftVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),Ae(t.options,"debugRows")),e.getRightVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),Ae(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?vv():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:vv())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Ae(e.options,"debugColumns")),e.getRightLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Ae(e.options,"debugColumns")),e.getCenterLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const s=[...n??[],...r??[]];return t.filter(o=>!s.includes(o.id))},Ae(e.options,"debugColumns"))}},Gf={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},yv=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),rX={getDefaultColumnDef:()=>Gf,getInitialState:e=>({columnSizing:{},columnSizingInfo:yv(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Sr("columnSizing",e),onColumnSizingInfoChange:Sr("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,s;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gf.minSize,(r=o??e.columnDef.size)!=null?r:Gf.size),(s=e.columnDef.maxSize)!=null?s:Gf.maxSize)},e.getStart=De(n=>[n,Nc(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),Ae(t.options,"debugColumns")),e.getAfter=De(n=>[n,Nc(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),Ae(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...s}=n;return s})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),s=r==null?void 0:r.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),bv(o)&&o.touches&&o.touches.length>1))return;const a=e.getSize(),l=e?e.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[r.id,r.getSize()]],c=bv(o)?Math.round(o.touches[0].clientX):o.clientX,i={},d=(b,y)=>{typeof y=="number"&&(t.setColumnSizingInfo(w=>{var S,E;const C=t.options.columnResizeDirection==="rtl"?-1:1,k=(y-((S=w==null?void 0:w.startOffset)!=null?S:0))*C,T=Math.max(k/((E=w==null?void 0:w.startSize)!=null?E:0),-.999999);return w.columnSizingStart.forEach(P=>{let[N,U]=P;i[N]=Math.round(Math.max(U+U*T,0)*100)/100}),{...w,deltaOffset:k,deltaPercentage:T}}),(t.options.columnResizeMode==="onChange"||b==="end")&&t.setColumnSizing(w=>({...w,...i})))},p=b=>d("move",b),f=b=>{d("end",b),t.setColumnSizingInfo(y=>({...y,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},h=n||typeof document<"u"?document:null,g={moveHandler:b=>p(b.clientX),upHandler:b=>{h==null||h.removeEventListener("mousemove",g.moveHandler),h==null||h.removeEventListener("mouseup",g.upHandler),f(b.clientX)}},m={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),p(b.touches[0].clientX),!1),upHandler:b=>{var y;h==null||h.removeEventListener("touchmove",m.moveHandler),h==null||h.removeEventListener("touchend",m.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),f((y=b.touches[0])==null?void 0:y.clientX)}},x=sX()?{passive:!1}:!1;bv(o)?(h==null||h.addEventListener("touchmove",m.moveHandler,x),h==null||h.addEventListener("touchend",m.upHandler,x)):(h==null||h.addEventListener("mousemove",g.moveHandler,x),h==null||h.addEventListener("mouseup",g.upHandler,x)),t.setColumnSizingInfo(b=>({...b,startOffset:c,startSize:a,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?yv():(n=e.initialState.columnSizingInfo)!=null?n:yv())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0}}};let Jf=null;function sX(){if(typeof Jf=="boolean")return Jf;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Jf=e,Jf}function bv(e){return e.type==="touchstart"}const oX={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Sr("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const s=e.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=De(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Ae(t.options,"debugRows")),e.getVisibleCells=De(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],Ae(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>De(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),Ae(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Nc(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const aX={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},iX={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Sr("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,s,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>Xs.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return Zg(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:Xs[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},lX={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Sr("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var s,o;e.setExpanded(r?{}:(s=(o=e.initialState)==null?void 0:o.expanded)!=null?s:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const a=o.split(".");r=Math.max(r,a.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[e.id]);let a={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(l=>{a[l]=!0}):a=r,n=(s=n)!=null?s:!o,!o&&n)return{...a,[e.id]:!0};if(o&&!n){const{[e.id]:l,...c}=a;return c}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r!=null&&r[e.id])},e.getCanExpand=()=>{var n,r,s;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((s=e.subRows)!=null&&s.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},Sb=0,Cb=10,xv=()=>({pageIndex:Sb,pageSize:Cb}),uX={getInitialState:e=>({...e,pagination:{...xv(),...e==null?void 0:e.pagination}}),getDefaultOptions:e=>({onPaginationChange:Sr("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const s=o=>na(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(s)},e.resetPagination=r=>{var s;e.setPagination(r?xv():(s=e.initialState.pagination)!=null?s:xv())},e.setPageIndex=r=>{e.setPagination(s=>{let o=na(r,s.pageIndex);const a=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,a)),{...s,pageIndex:o}})},e.resetPageIndex=r=>{var s,o;e.setPageIndex(r?Sb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:Sb)},e.resetPageSize=r=>{var s,o;e.setPageSize(r?Cb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:Cb)},e.setPageSize=r=>{e.setPagination(s=>{const o=Math.max(1,na(r,s.pageSize)),a=s.pageSize*s.pageIndex,l=Math.floor(a/o);return{...s,pageIndex:l,pageSize:o}})},e.setPageCount=r=>e.setPagination(s=>{var o;let a=na(r,(o=e.options.pageCount)!=null?o:-1);return typeof a=="number"&&(a=Math.max(-1,a)),{...s,pageCount:a}}),e.getPageOptions=De(()=>[e.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,a)=>a)),s},Ae(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,s=e.getPageCount();return s===-1?!0:s===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},wv=()=>({top:[],bottom:[]}),cX={getInitialState:e=>({rowPinning:wv(),...e}),getDefaultOptions:e=>({onRowPinningChange:Sr("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,s)=>{const o=r?e.getLeafRows().map(c=>{let{id:i}=c;return i}):[],a=s?e.getParentRows().map(c=>{let{id:i}=c;return i}):[],l=new Set([...a,e.id,...o]);t.setRowPinning(c=>{var i,d;if(n==="bottom"){var p,f;return{top:((p=c==null?void 0:c.top)!=null?p:[]).filter(m=>!(l!=null&&l.has(m))),bottom:[...((f=c==null?void 0:c.bottom)!=null?f:[]).filter(m=>!(l!=null&&l.has(m))),...Array.from(l)]}}if(n==="top"){var h,g;return{top:[...((h=c==null?void 0:c.top)!=null?h:[]).filter(m=>!(l!=null&&l.has(m))),...Array.from(l)],bottom:((g=c==null?void 0:c.bottom)!=null?g:[]).filter(m=>!(l!=null&&l.has(m)))}}return{top:((i=c==null?void 0:c.top)!=null?i:[]).filter(m=>!(l!=null&&l.has(m))),bottom:((d=c==null?void 0:c.bottom)!=null?d:[]).filter(m=>!(l!=null&&l.has(m)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=t.options;return typeof r=="function"?r(e):(n=r??s)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:s}=t.getState().rowPinning,o=n.some(l=>r==null?void 0:r.includes(l)),a=n.some(l=>s==null?void 0:s.includes(l));return o?"top":a?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();if(!s)return-1;const o=(n=s==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(a=>{let{id:l}=a;return l});return(r=o==null?void 0:o.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?wv():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:wv())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var s;return((s=e.options.keepPinnedRows)==null||s?(n??[]).map(a=>{const l=e.getRow(a,!0);return l.getIsAllParentsExpanded()?l:null}):(n??[]).map(a=>t.find(l=>l.id===a))).filter(Boolean).map(a=>({...a,position:r}))},e.getTopRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),Ae(e.options,"debugRows")),e.getBottomRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),Ae(e.options,"debugRows")),e.getCenterRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const s=new Set([...n??[],...r??[]]);return t.filter(o=>!s.has(o.id))},Ae(e.options,"debugRows"))}},dX={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:Sr("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},s=e.getPreGroupedRowModel().flatRows;return t?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),s={...n};return e.getRowModel().rows.forEach(o=>{Eb(s,o.id,r,!0,e)}),s}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=De(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getFilteredSelectedRowModel=De(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getGroupedSelectedRowModel=De(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(s=>!n[s.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const s=e.getIsSelected();t.setRowSelection(o=>{var a;if(n=typeof n<"u"?n:!s,e.getCanSelect()&&s===n)return o;const l={...o};return Eb(l,e.id,n,(a=r==null?void 0:r.selectChildren)!=null?a:!0,t),l})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zw(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var s;n&&e.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},Eb=(e,t,n,r,s)=>{var o;const a=s.getRow(t,!0);n?(a.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),a.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=a.subRows)!=null&&o.length&&a.getCanSelectSubRows()&&a.subRows.forEach(l=>Eb(e,l.id,n,r,s))};function Sv(e,t){const n=e.getState().rowSelection,r=[],s={},o=function(a,l){return a.map(c=>{var i;const d=zw(c,n);if(d&&(r.push(c),s[c.id]=c),(i=c.subRows)!=null&&i.length&&(c={...c,subRows:o(c.subRows)}),d)return c}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:s}}function zw(e,t){var n;return(n=t[e.id])!=null?n:!1}function Tb(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return e.subRows.forEach(a=>{if(!(o&&!s)&&(a.getCanSelect()&&(zw(a,t)?o=!0:s=!1),a.subRows&&a.subRows.length)){const l=Tb(a,t);l==="all"?o=!0:(l==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const kb=/([0-9]+)/gm,fX=(e,t,n)=>wI(Sa(e.getValue(n)).toLowerCase(),Sa(t.getValue(n)).toLowerCase()),pX=(e,t,n)=>wI(Sa(e.getValue(n)),Sa(t.getValue(n))),hX=(e,t,n)=>Uw(Sa(e.getValue(n)).toLowerCase(),Sa(t.getValue(n)).toLowerCase()),gX=(e,t,n)=>Uw(Sa(e.getValue(n)),Sa(t.getValue(n))),mX=(e,t,n)=>{const r=e.getValue(n),s=t.getValue(n);return r>s?1:rUw(e.getValue(n),t.getValue(n));function Uw(e,t){return e===t?0:e>t?1:-1}function Sa(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function wI(e,t){const n=e.split(kb).filter(Boolean),r=t.split(kb).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),a=parseInt(s,10),l=parseInt(o,10),c=[a,l].sort();if(isNaN(c[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(c[1]))return isNaN(a)?-1:1;if(a>l)return 1;if(l>a)return-1}return n.length-r.length}const rc={alphanumeric:fX,alphanumericCaseSensitive:pX,text:hX,textCaseSensitive:gX,datetime:mX,basic:vX},yX={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:Sr("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s==null?void 0:s.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return rc.datetime;if(typeof o=="string"&&(r=!0,o.split(kb).length>1))return rc.alphanumeric}return r?rc.text:rc.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof(n==null?void 0:n.getValue(e.id))=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return Zg(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:rc[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const s=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(a=>{const l=a==null?void 0:a.find(h=>h.id===e.id),c=a==null?void 0:a.findIndex(h=>h.id===e.id);let i=[],d,p=o?n:s==="desc";if(a!=null&&a.length&&e.getCanMultiSort()&&r?l?d="toggle":d="add":a!=null&&a.length&&c!==a.length-1?d="replace":l?d="toggle":d="replace",d==="toggle"&&(o||s||(d="remove")),d==="add"){var f;i=[...a,{id:e.id,desc:p}],i.splice(0,i.length-((f=t.options.maxMultiSortColCount)!=null?f:Number.MAX_SAFE_INTEGER))}else d==="toggle"?i=a.map(h=>h.id===e.id?{...h,desc:p}:h):d==="remove"?i=a.filter(h=>h.id!==e.id):i=[{id:e.id,desc:p}];return i})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,s;const o=e.getFirstSortDir(),a=e.getIsSorted();return a?a!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(s=t.options.enableMultiRemove)!=null)||s)?!1:a==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(s=>s.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},bX=[zY,oX,tX,nX,UY,VY,aX,iX,yX,XY,lX,uX,cX,dX,rX];function xX(e){var t,n;const r=[...bX,...(t=e._features)!=null?t:[]];let s={_features:r};const o=s._features.reduce((f,h)=>Object.assign(f,h.getDefaultOptions==null?void 0:h.getDefaultOptions(s)),{}),a=f=>s.options.mergeOptions?s.options.mergeOptions(o,f):{...o,...f};let c={...{},...(n=e.initialState)!=null?n:{}};s._features.forEach(f=>{var h;c=(h=f.getInitialState==null?void 0:f.getInitialState(c))!=null?h:c});const i=[];let d=!1;const p={_features:r,options:{...o,...e},initialState:c,_queue:f=>{i.push(f),d||(d=!0,Promise.resolve().then(()=>{for(;i.length;)i.shift()();d=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{s.setState(s.initialState)},setOptions:f=>{const h=na(f,s.options);s.options=a(h)},getState:()=>s.options.state,setState:f=>{s.options.onStateChange==null||s.options.onStateChange(f)},_getRowId:(f,h,g)=>{var m;return(m=s.options.getRowId==null?void 0:s.options.getRowId(f,h,g))!=null?m:`${g?[g.id,h].join("."):h}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(f,h)=>{let g=(h?s.getPrePaginationRowModel():s.getRowModel()).rowsById[f];if(!g&&(g=s.getCoreRowModel().rowsById[f],!g))throw new Error;return g},_getDefaultColumnDef:De(()=>[s.options.defaultColumn],f=>{var h;return f=(h=f)!=null?h:{},{header:g=>{const m=g.header.column.columnDef;return m.accessorKey?m.accessorKey:m.accessorFn?m.id:null},cell:g=>{var m,x;return(m=(x=g.renderValue())==null||x.toString==null?void 0:x.toString())!=null?m:null},...s._features.reduce((g,m)=>Object.assign(g,m.getDefaultColumnDef==null?void 0:m.getDefaultColumnDef()),{}),...f}},Ae(e,"debugColumns")),_getColumnDefs:()=>s.options.columns,getAllColumns:De(()=>[s._getColumnDefs()],f=>{const h=function(g,m,x){return x===void 0&&(x=0),g.map(b=>{const y=BY(s,b,x,m),w=b;return y.columns=w.columns?h(w.columns,y,x+1):[],y})};return h(f)},Ae(e,"debugColumns")),getAllFlatColumns:De(()=>[s.getAllColumns()],f=>f.flatMap(h=>h.getFlatColumns()),Ae(e,"debugColumns")),_getAllFlatColumnsById:De(()=>[s.getAllFlatColumns()],f=>f.reduce((h,g)=>(h[g.id]=g,h),{}),Ae(e,"debugColumns")),getAllLeafColumns:De(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(f,h)=>{let g=f.flatMap(m=>m.getLeafColumns());return h(g)},Ae(e,"debugColumns")),getColumn:f=>s._getAllFlatColumnsById()[f]};Object.assign(s,p);for(let f=0;fDe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,a){o===void 0&&(o=0);const l=[];for(let i=0;ie._autoResetPageIndex()))}function SX(e,t,n){return n.options.filterFromLeafRows?CX(e,t,n):EX(e,t,n)}function CX(e,t,n){var r;const s=[],o={},a=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,l=function(c,i){i===void 0&&(i=0);const d=[];for(let f=0;fDe(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,n,r)=>{if(!t.rows.length||!(n!=null&&n.length)&&!r){for(let f=0;f{var h;const g=e.getColumn(f.id);if(!g)return;const m=g.getFilterFn();m&&s.push({id:f.id,filterFn:m,resolvedValue:(h=m.resolveFilterValue==null?void 0:m.resolveFilterValue(f.value))!=null?h:f.value})});const a=(n??[]).map(f=>f.id),l=e.getGlobalFilterFn(),c=e.getAllLeafColumns().filter(f=>f.getCanGlobalFilter());r&&l&&c.length&&(a.push("__global__"),c.forEach(f=>{var h;o.push({id:f.id,filterFn:l,resolvedValue:(h=l.resolveFilterValue==null?void 0:l.resolveFilterValue(r))!=null?h:r})}));let i,d;for(let f=0;f{h.columnFiltersMeta[m]=x})}if(o.length){for(let g=0;g{h.columnFiltersMeta[m]=x})){h.columnFilters.__global__=!0;break}}h.columnFilters.__global__!==!0&&(h.columnFilters.__global__=!1)}}const p=f=>{for(let h=0;he._autoResetPageIndex()))}function kX(){return e=>De(()=>[e.getState().grouping,e.getPreGroupedRowModel()],(t,n)=>{if(!n.rows.length||!t.length)return n.rows.forEach(c=>{c.depth=0,c.parentId=void 0}),n;const r=t.filter(c=>e.getColumn(c)),s=[],o={},a=function(c,i,d){if(i===void 0&&(i=0),i>=r.length)return c.map(g=>(g.depth=i,s.push(g),o[g.id]=g,g.subRows&&(g.subRows=a(g.subRows,i+1,g.id)),g));const p=r[i],f=_X(c,p);return Array.from(f.entries()).map((g,m)=>{let[x,b]=g,y=`${p}:${x}`;y=d?`${d}>${y}`:y;const w=a(b,i+1,y);w.forEach(C=>{C.parentId=y});const S=i?fI(b,C=>C.subRows):b,E=Yg(e,y,S[0].original,m,i,void 0,d);return Object.assign(E,{groupingColumnId:p,groupingValue:x,subRows:w,leafRows:S,getValue:C=>{if(r.includes(C)){if(E._valuesCache.hasOwnProperty(C))return E._valuesCache[C];if(b[0]){var k;E._valuesCache[C]=(k=b[0].getValue(C))!=null?k:void 0}return E._valuesCache[C]}if(E._groupingValuesCache.hasOwnProperty(C))return E._groupingValuesCache[C];const T=e.getColumn(C),P=T==null?void 0:T.getAggregationFn();if(P)return E._groupingValuesCache[C]=P(C,S,b),E._groupingValuesCache[C]}}),w.forEach(C=>{s.push(C),o[C.id]=C}),E})},l=a(n.rows,0);return l.forEach(c=>{s.push(c),o[c.id]=c}),{rows:l,flatRows:s,rowsById:o}},Ae(e.options,"debugTable","getGroupedRowModel",()=>{e._queue(()=>{e._autoResetExpanded(),e._autoResetPageIndex()})}))}function _X(e,t){const n=new Map;return e.reduce((r,s)=>{const o=`${s.getGroupingValue(t)}`,a=r.get(o);return a?a.push(s):r.set(o,[s]),r},n)}function jX(){return e=>De(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,s=[],o=r.filter(c=>{var i;return(i=e.getColumn(c.id))==null?void 0:i.getCanSort()}),a={};o.forEach(c=>{const i=e.getColumn(c.id);i&&(a[c.id]={sortUndefined:i.columnDef.sortUndefined,invertSorting:i.columnDef.invertSorting,sortingFn:i.getSortingFn()})});const l=c=>{const i=c.map(d=>({...d}));return i.sort((d,p)=>{for(let h=0;h{var p;s.push(d),(p=d.subRows)!=null&&p.length&&(d.subRows=l(d.subRows))}),i};return{rows:l(n.rows),flatRows:s,rowsById:n.rowsById}},Ae(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/** - * react-table - * - * Copyright (c) TanStack - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function tE(e,t){return e?RX(e)?v.createElement(e,t):e:null}function RX(e){return PX(e)||typeof e=="function"||MX(e)}function PX(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function MX(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OX(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=v.useState(()=>({current:xX(t)})),[r,s]=v.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:a=>{s(a),e.onStateChange==null||e.onStateChange(a)}})),n.current}const SI=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{className:"relative w-full overflow-auto",children:u.jsx("table",{ref:n,className:ge("w-full caption-bottom text-sm",e),...t})}));SI.displayName="Table";const CI=v.forwardRef(({className:e,...t},n)=>u.jsx("thead",{ref:n,className:ge("[&_tr]:border-b",e),...t}));CI.displayName="TableHeader";const EI=v.forwardRef(({className:e,...t},n)=>u.jsx("tbody",{ref:n,className:ge("[&_tr:last-child]:border-0",e),...t}));EI.displayName="TableBody";const NX=v.forwardRef(({className:e,...t},n)=>u.jsx("tfoot",{ref:n,className:ge("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));NX.displayName="TableFooter";const vc=v.forwardRef(({className:e,...t},n)=>u.jsx("tr",{ref:n,className:ge("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));vc.displayName="TableRow";const TI=v.forwardRef(({className:e,...t},n)=>u.jsx("th",{ref:n,className:ge("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));TI.displayName="TableHead";const Ep=v.forwardRef(({className:e,...t},n)=>u.jsx("td",{ref:n,className:ge("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));Ep.displayName="TableCell";const IX=v.forwardRef(({className:e,...t},n)=>u.jsx("caption",{ref:n,className:ge("mt-4 text-sm text-muted-foreground",e),...t}));IX.displayName="TableCaption";function Nu({columns:e,data:t,isLoading:n,loadingMessage:r,noResultsMessage:s,enableHeaders:o=!0,className:a,highlightedRows:l,...c}){var d;const i=OX({...c,data:t,columns:e,getCoreRowModel:wX(),getFilteredRowModel:TX(),getGroupedRowModel:kX(),getSortedRowModel:jX()});return u.jsx("div",{className:ge("rounded-md border",a),children:u.jsxs(SI,{children:[o&&u.jsx(CI,{children:i.getHeaderGroups().map(p=>u.jsx(vc,{children:p.headers.map(f=>u.jsx(TI,{children:f.isPlaceholder?null:tE(f.column.columnDef.header,f.getContext())},f.id))},p.id))}),u.jsx(EI,{children:n?u.jsx(vc,{children:u.jsx(Ep,{colSpan:e.length,className:"h-24 text-center text-muted-foreground",children:r??"Carregando..."})}):u.jsx(u.Fragment,{children:(d=i.getRowModel().rows)!=null&&d.length?i.getRowModel().rows.map(p=>u.jsx(vc,{"data-state":p.getIsSelected()?"selected":l!=null&&l.includes(p.id)?"highlighted":"",children:p.getVisibleCells().map(f=>u.jsx(Ep,{children:tE(f.column.columnDef.cell,f.getContext())},f.id))},p.id)):u.jsx(vc,{children:u.jsx(Ep,{colSpan:e.length,className:"h-24 text-center",children:s??"Nenhum resultado encontrado!"})})})})]})})}const DX=e=>["dify","fetchSessions",JSON.stringify(e)],AX=async({difyId:e,instanceName:t})=>(await he.get(`/dify/fetchSessions/${e}/${t}`)).data,FX=e=>{const{difyId:t,instanceName:n,...r}=e;return lt({...r,queryKey:DX({difyId:t,instanceName:n}),queryFn:()=>AX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function kI({difyId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusDify:r}=Qg(),[s,o]=v.useState([]),{data:a,refetch:l}=FX({difyId:e,instanceName:n==null?void 0:n.name}),[c,i]=v.useState(!1),[d,p]=v.useState("");function f(){l()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("dify.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("dify.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:c,onOpenChange:i,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("dify.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("dify.sessions.search"),value:d,onChange:m=>p(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Nu,{columns:g,data:a??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("dify.sessions.table.none")})]})]})]})}const LX=_.object({enabled:_.boolean(),description:_.string(),botType:_.string(),apiUrl:_.string(),apiKey:_.string(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function _I({initialData:e,onSubmit:t,handleDelete:n,difyId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(LX),defaultValues:e||{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("dify.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("dify.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.difySettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"botType",label:c("dify.form.botType.label"),options:[{label:c("dify.form.botType.chatBot"),value:"chatBot"},{label:c("dify.form.botType.textGenerator"),value:"textGenerator"},{label:c("dify.form.botType.agent"),value:"agent"},{label:c("dify.form.botType.workflow"),value:"workflow"}]}),u.jsx(G,{name:"apiUrl",label:c("dify.form.apiUrl.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:c("dify.form.apiKey.label"),required:!0,children:u.jsx(K,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("dify.form.triggerType.label"),options:[{label:c("dify.form.triggerType.keyword"),value:"keyword"},{label:c("dify.form.triggerType.all"),value:"all"},{label:c("dify.form.triggerType.advanced"),value:"advanced"},{label:c("dify.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("dify.form.triggerOperator.label"),options:[{label:c("dify.form.triggerOperator.contains"),value:"contains"},{label:c("dify.form.triggerOperator.equals"),value:"equals"},{label:c("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("dify.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("dify.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("dify.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("dify.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("dify.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("dify.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("dify.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("dify.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("dify.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("dify.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("dify.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:c("dify.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:c("dify.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"dify.button.saving":"dify.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(kI,{difyId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"dify.button.saving":"dify.button.update")})]})]})]})})}function $X({resetTable:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createDify:l}=Qg(),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:i.enabled,description:i.description,botType:i.botType,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await l({instanceName:n.name,token:n.token,data:h}),X.success(t("dify.toast.success.create")),a(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("dify.form.title")})}),u.jsx(_I,{onSubmit:c,isModal:!0,isLoading:r})]})]})}const BX=e=>["dify","getDify",JSON.stringify(e)],zX=async({difyId:e,instanceName:t})=>(await he.get(`/dify/fetch/${e}/${t}`)).data,UX=e=>{const{difyId:t,instanceName:n,...r}=e;return lt({...r,queryKey:BX({difyId:t,instanceName:n}),queryFn:()=>zX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function VX({difyId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteDify:l,updateDify:c}=Qg(),{data:i,isLoading:d}=UX({difyId:e,instanceName:r==null?void 0:r.name}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",botType:(i==null?void 0:i.botType)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:(i==null?void 0:i.triggerValue)??"",expire:(i==null?void 0:i.expire)??0,keywordFinish:(i==null?void 0:i.keywordFinish)??"",delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:(i==null?void 0:i.unknownMessage)??"",listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.botType,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,botType:g.botType,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar||0};await c({instanceName:r.name,difyId:e,data:y}),X.success(n("dify.toast.success.update")),t(),s(`/manager/instance/${r.id}/dify/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,difyId:e}),X.success(n("dify.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/dify`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(_I,{initialData:p,onSubmit:f,difyId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function nE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{difyId:r}=So(),{data:s,refetch:o,isLoading:a}=dI({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/dify/${d}`)},i=()=>{o()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(kI,{}),u.jsx(FY,{}),u.jsx($X,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:a?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsxs(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[u.jsx("h4",{className:"text-base",children:d.description||d.id}),u.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):u.jsx(q,{variant:"link",children:e("dify.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(VX,{difyId:r,resetTable:i})})]})]})]})}const HX=e=>["evolutionBot","findEvolutionBot",JSON.stringify(e)],KX=async({instanceName:e,token:t})=>(await he.get(`/evolutionBot/find/${e}`,{headers:{apiKey:t}})).data,jI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:HX({instanceName:t}),queryFn:()=>KX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},qX=e=>["evolutionBot","fetchDefaultSettings",JSON.stringify(e)],WX=async({instanceName:e,token:t})=>{const n=await he.get(`/evolutionBot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},GX=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:qX({instanceName:t}),queryFn:()=>WX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},JX=async({instanceName:e,token:t,data:n})=>(await he.post(`/evolutionBot/create/${e}`,n,{headers:{apikey:t}})).data,QX=async({instanceName:e,token:t,evolutionBotId:n,data:r})=>(await he.put(`/evolutionBot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,ZX=async({instanceName:e,evolutionBotId:t})=>(await he.delete(`/evolutionBot/delete/${t}/${e}`)).data,YX=async({instanceName:e,token:t,data:n})=>(await he.post(`/evolutionBot/settings/${e}`,n,{headers:{apikey:t}})).data,XX=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/evolutionBot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Xg(){const e=Ye(YX,{invalidateKeys:[["evolutionBot","fetchDefaultSettings"]]}),t=Ye(XX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","fetchSessions"]]}),n=Ye(ZX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),r=Ye(QX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),s=Ye(JX,{invalidateKeys:[["evolutionBot","findEvolutionBot"]]});return{setDefaultSettingsEvolutionBot:e,changeStatusEvolutionBot:t,deleteEvolutionBot:n,updateEvolutionBot:r,createEvolutionBot:s}}const eee=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),botIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean(),timePerChar:_.string()});function tee(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{data:s,refetch:o}=GX({instanceName:t==null?void 0:t.name,enabled:n}),{data:a,refetch:l}=jI({instanceName:t==null?void 0:t.name,enabled:n}),{setDefaultSettingsEvolutionBot:c}=Xg(),i=sn({resolver:on(eee),defaultValues:{expire:"0",keywordFinish:e("evolutionBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evolutionBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{s&&i.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback,splitMessages:s.splitMessages,timePerChar:s.timePerChar?s.timePerChar.toString():"0"})},[s]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),botIdFallback:f.botIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await c({instanceName:t.name,token:t.token,data:x}),X.success(e("evolutionBot.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){o(),l()}return u.jsxs(Tt,{open:n,onOpenChange:r,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("evolutionBot.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("evolutionBot.defaultSettings")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"botIdFallback",label:e("evolutionBot.form.botIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(G,{name:"expire",label:e("evolutionBot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("evolutionBot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("evolutionBot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("evolutionBot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("evolutionBot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("evolutionBot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("evolutionBot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("evolutionBot.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:e("evolutionBot.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("evolutionBot.form.ignoreJids.label"),placeholder:e("evolutionBot.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("evolutionBot.button.save")})})]})})]})]})}const nee=e=>["evolutionBot","fetchSessions",JSON.stringify(e)],ree=async({instanceName:e,evolutionBotId:t,token:n})=>(await he.get(`/evolutionBot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,see=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return lt({...s,queryKey:nee({instanceName:t}),queryFn:()=>ree({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function RI({evolutionBotId:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[l,c]=v.useState(""),{data:i,refetch:d}=see({instanceName:n==null?void 0:n.name,evolutionBotId:e,enabled:o}),{changeStatusEvolutionBot:p}=Xg();function f(){d()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await p({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("evolutionBot.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("evolutionBot.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("evolutionBot.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("evolutionBot.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("evolutionBot.sessions.search"),value:l,onChange:m=>c(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Nu,{columns:g,data:i??[],onSortingChange:s,state:{sorting:r,globalFilter:l},onGlobalFilterChange:c,enableGlobalFilter:!0,noResultsMessage:t("evolutionBot.sessions.table.none")})]})]})]})}const oee=_.object({enabled:_.boolean(),description:_.string(),apiUrl:_.string(),apiKey:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function PI({initialData:e,onSubmit:t,handleDelete:n,evolutionBotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(oee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("evolutionBot.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("evolutionBot.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.evolutionBotSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"apiUrl",label:c("evolutionBot.form.apiUrl.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:c("evolutionBot.form.apiKey.label"),children:u.jsx(K,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("evolutionBot.form.triggerType.label"),options:[{label:c("evolutionBot.form.triggerType.keyword"),value:"keyword"},{label:c("evolutionBot.form.triggerType.all"),value:"all"},{label:c("evolutionBot.form.triggerType.advanced"),value:"advanced"},{label:c("evolutionBot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("evolutionBot.form.triggerOperator.label"),options:[{label:c("evolutionBot.form.triggerOperator.contains"),value:"contains"},{label:c("evolutionBot.form.triggerOperator.equals"),value:"equals"},{label:c("evolutionBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("evolutionBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("evolutionBot.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("evolutionBot.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("evolutionBot.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("evolutionBot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("evolutionBot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("evolutionBot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("evolutionBot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("evolutionBot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("evolutionBot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("evolutionBot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:c("evolutionBot.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:c("evolutionBot.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"evolutionBot.button.saving":"evolutionBot.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(RI,{evolutionBotId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"evolutionBot.button.saving":"evolutionBot.button.update")})]})]})]})})}function aee({resetTable:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createEvolutionBot:l}=Xg(),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:i.enabled,description:i.description,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar?i.timePerChar:0};await l({instanceName:n.name,token:n.token,data:h}),X.success(t("evolutionBot.toast.success.create")),a(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("evolutionBot.form.title")})}),u.jsx(PI,{onSubmit:c,isModal:!0,isLoading:r})]})]})}const iee=e=>["evolutionBot","getEvolutionBot",JSON.stringify(e)],lee=async({instanceName:e,token:t,evolutionBotId:n})=>{const r=await he.get(`/evolutionBot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},uee=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return lt({...s,queryKey:iee({instanceName:t}),queryFn:()=>lee({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function cee({evolutionBotId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteEvolutionBot:l,updateEvolutionBot:c}=Xg(),{data:i,isLoading:d}=uee({instanceName:r==null?void 0:r.name,evolutionBotId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:i!=null&&i.timePerChar?i==null?void 0:i.timePerChar:0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar?g.timePerChar:0};await c({instanceName:r.name,evolutionBotId:e,data:y}),X.success(n("evolutionBot.toast.success.update")),t(),s(`/manager/instance/${r.id}/evolutionBot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,evolutionBotId:e}),X.success(n("evolutionBot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/evolutionBot`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir evolutionBot:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(PI,{initialData:p,onSubmit:f,evolutionBotId:e,handleDelete:h,isModal:!1,openDeletionDialog:o,setOpenDeletionDialog:a})})}function rE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{evolutionBotId:r}=So(),{data:s,isLoading:o,refetch:a}=jI({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/evolutionBot/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("evolutionBot.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(RI,{}),u.jsx(tee,{}),u.jsx(aee,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:u.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):u.jsx(q,{variant:"link",children:e("evolutionBot.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(cee,{evolutionBotId:r,resetTable:i})})]})]})]})}const dee=e=>["flowise","findFlowise",JSON.stringify(e)],fee=async({instanceName:e,token:t})=>(await he.get(`/flowise/find/${e}`,{headers:{apiKey:t}})).data,MI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:dee({instanceName:t}),queryFn:()=>fee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},pee=e=>["flowise","fetchDefaultSettings",JSON.stringify(e)],hee=async({instanceName:e,token:t})=>{const n=await he.get(`/flowise/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},gee=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:pee({instanceName:t}),queryFn:()=>hee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},mee=async({instanceName:e,token:t,data:n})=>(await he.post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,vee=async({instanceName:e,flowiseId:t,data:n})=>(await he.put(`/flowise/update/${t}/${e}`,n)).data,yee=async({instanceName:e,flowiseId:t})=>(await he.delete(`/flowise/delete/${t}/${e}`)).data,bee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,xee=async({instanceName:e,token:t,data:n})=>(await he.post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data;function em(){const e=Ye(xee,{invalidateKeys:[["flowise","fetchDefaultSettings"]]}),t=Ye(bee,{invalidateKeys:[["flowise","getFlowise"],["flowise","fetchSessions"]]}),n=Ye(yee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),r=Ye(vee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),s=Ye(mee,{invalidateKeys:[["flowise","findFlowise"]]});return{setDefaultSettingsFlowise:e,changeStatusFlowise:t,deleteFlowise:n,updateFlowise:r,createFlowise:s}}const wee=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),flowiseIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean(),timePerChar:_.string()});function See(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsFlowise:n}=em(),[r,s]=v.useState(!1),{data:o,refetch:a}=gee({instanceName:t==null?void 0:t.name,enabled:r}),{data:l,refetch:c}=MI({instanceName:t==null?void 0:t.name,enabled:r}),i=sn({resolver:on(wee),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{o&&i.reset({expire:o!=null&&o.expire?o.expire.toString():"0",keywordFinish:o.keywordFinish,delayMessage:o.delayMessage?o.delayMessage.toString():"0",unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime?o.debounceTime.toString():"0",ignoreJids:o.ignoreJids,flowiseIdFallback:o.flowiseIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar?o.timePerChar.toString():"0"})},[o]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),flowiseIdFallback:f.flowiseIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),X.success(e("flowise.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){a(),c()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("flowise.defaultSettings")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:(l==null?void 0:l.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(G,{name:"expire",label:e("flowise.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("flowise.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:e("flowise.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const Cee=e=>["flowise","fetchSessions",JSON.stringify(e)],Eee=async({instanceName:e,flowiseId:t,token:n})=>(await he.get(`/flowise/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Tee=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return lt({...s,queryKey:Cee({instanceName:t}),queryFn:()=>Eee({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function OI({flowiseId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusFlowise:r}=em(),[s,o]=v.useState([]),[a,l]=v.useState(!1),[c,i]=v.useState(""),{data:d,refetch:p}=Tee({instanceName:n==null?void 0:n.name,flowiseId:e,enabled:a});function f(){p()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("flowise.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("flowise.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("flowise.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("flowise.sessions.search"),value:c,onChange:m=>i(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Nu,{columns:g,data:d??[],onSortingChange:o,state:{sorting:s,globalFilter:c},onGlobalFilterChange:i,enableGlobalFilter:!0,noResultsMessage:t("flowise.sessions.table.none")})]})]})]})}const kee=_.object({enabled:_.boolean(),description:_.string(),apiUrl:_.string(),apiKey:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function NI({initialData:e,onSubmit:t,handleDelete:n,flowiseId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(kee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("flowise.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("flowise.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.flowiseSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"apiUrl",label:c("flowise.form.apiUrl.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:c("flowise.form.apiKey.label"),children:u.jsx(K,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("flowise.form.triggerType.label"),options:[{label:c("flowise.form.triggerType.keyword"),value:"keyword"},{label:c("flowise.form.triggerType.all"),value:"all"},{label:c("flowise.form.triggerType.advanced"),value:"advanced"},{label:c("flowise.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("flowise.form.triggerOperator.label"),options:[{label:c("flowise.form.triggerOperator.contains"),value:"contains"},{label:c("flowise.form.triggerOperator.equals"),value:"equals"},{label:c("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("flowise.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("flowise.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("flowise.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("flowise.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("flowise.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("flowise.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("flowise.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("flowise.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("flowise.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("flowise.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("flowise.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:c("flowise.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:c("flowise.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"flowise.button.saving":"flowise.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(OI,{flowiseId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"flowise.button.saving":"flowise.button.update")})]})]})]})})}function _ee({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createFlowise:r}=em(),[s,o]=v.useState(!1),[a,l]=v.useState(!1),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:i.enabled,description:i.description,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("flowise.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("flowise.form.title")})}),u.jsx(NI,{onSubmit:c,isModal:!0,isLoading:s})]})]})}const jee=e=>["flowise","getFlowise",JSON.stringify(e)],Ree=async({instanceName:e,token:t,flowiseId:n})=>{const r=await he.get(`/flowise/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Pee=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return lt({...s,queryKey:jee({instanceName:t}),queryFn:()=>Ree({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function Mee({flowiseId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteFlowise:l,updateFlowise:c}=em(),{data:i,isLoading:d}=Pee({instanceName:r==null?void 0:r.name,flowiseId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:i==null?void 0:i.stopBotFromMe,keepOpen:i==null?void 0:i.keepOpen,debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar||0};await c({instanceName:r.name,flowiseId:e,data:y}),X.success(n("flowise.toast.success.update")),t(),s(`/manager/instance/${r.id}/flowise/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,flowiseId:e}),X.success(n("flowise.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/flowise`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(NI,{initialData:p,onSubmit:f,flowiseId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function sE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{flowiseId:r}=So(),{data:s,isLoading:o,refetch:a}=MI({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/flowise/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(OI,{}),u.jsx(See,{}),u.jsx(_ee,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:u.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):u.jsx(q,{variant:"link",children:e("flowise.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(Mee,{flowiseId:r,resetTable:i})})]})]})]})}const Oee=e=>["openai","findOpenai",JSON.stringify(e)],Nee=async({instanceName:e,token:t})=>(await he.get(`/openai/find/${e}`,{headers:{apiKey:t}})).data,II=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Oee({instanceName:t}),queryFn:()=>Nee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Iee=e=>["openai","findOpenaiCreds",JSON.stringify(e)],Dee=async({instanceName:e,token:t})=>(await he.get(`/openai/creds/${e}`,{headers:{apiKey:t}})).data,Vw=e=>{const{instanceName:t,token:n,...r}=e;return lt({staleTime:1e3*60*60*6,...r,queryKey:Iee({instanceName:t}),queryFn:()=>Dee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Aee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,Fee=async({openaiCredsId:e,instanceName:t})=>(await he.delete(`/openai/creds/${e}/${t}`)).data,Lee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,$ee=async({instanceName:e,token:t,openaiId:n,data:r})=>(await he.put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,Bee=async({instanceName:e,token:t,openaiId:n})=>(await he.delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,zee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,Uee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function rf(){const e=Ye(zee,{invalidateKeys:[["openai","fetchDefaultSettings"]]}),t=Ye(Uee,{invalidateKeys:[["openai","getOpenai"],["openai","fetchSessions"]]}),n=Ye(Bee,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),r=Ye($ee,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),s=Ye(Lee,{invalidateKeys:[["openai","findOpenai"]]}),o=Ye(Aee,{invalidateKeys:[["openai","findOpenaiCreds"]]}),a=Ye(Fee,{invalidateKeys:[["openai","findOpenaiCreds"]]});return{setDefaultSettingsOpenai:e,changeStatusOpenai:t,deleteOpenai:n,updateOpenai:r,createOpenai:s,createOpenaiCreds:o,deleteOpenaiCreds:a}}const Vee=_.object({name:_.string(),apiKey:_.string()});function Hee(){const{t:e}=ze(),{instance:t}=nt(),{createOpenaiCreds:n,deleteOpenaiCreds:r}=rf(),[s,o]=v.useState(!1),[a,l]=v.useState([]),{data:c,refetch:i}=Vw({instanceName:t==null?void 0:t.name,enabled:s}),d=sn({resolver:on(Vee),defaultValues:{name:"",apiKey:""}}),p=async m=>{var x,b,y;try{if(!t||!t.name)throw new Error("instance not found.");const w={name:m.name,apiKey:m.apiKey};await n({instanceName:t.name,token:t.token,data:w}),X.success(e("openai.toast.success.credentialsCreate")),f()}catch(w){console.error("Error:",w),X.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}};function f(){d.reset(),i()}const h=async m=>{var x,b,y;if(!(t!=null&&t.name)){X.error("Instance not found.");return}try{await r({openaiCredsId:m,instanceName:t==null?void 0:t.name}),X.success(e("openai.toast.success.credentialsDelete")),i()}catch(w){console.error("Error:",w),X.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}},g=[{accessorKey:"name",header:({column:m})=>u.jsxs(q,{variant:"ghost",onClick:()=>m.toggleSorting(m.getIsSorted()==="asc"),children:[e("openai.credentials.table.name"),u.jsx(_3,{className:"ml-2 h-4 w-4"})]}),cell:({row:m})=>u.jsx("div",{children:m.getValue("name")})},{accessorKey:"apiKey",header:()=>u.jsx("div",{className:"text-right",children:e("openai.credentials.table.apiKey")}),cell:({row:m})=>u.jsxs("div",{children:[`${m.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:e("openai.credentials.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:e("openai.credentials.table.actions.title")}),u.jsx(Pa,{}),u.jsx(ft,{onClick:()=>h(x.id),children:e("openai.credentials.table.actions.delete")})]})]})}}];return u.jsxs(Tt,{open:s,onOpenChange:o,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(H3,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:e("openai.credentials.title")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("openai.credentials.title")})}),u.jsx(Tr,{...d,children:u.jsxs("form",{onSubmit:d.handleSubmit(p),className:"w-full space-y-6",children:[u.jsx("div",{children:u.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[u.jsx(G,{name:"name",label:e("openai.credentials.table.name"),children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:e("openai.credentials.table.apiKey"),children:u.jsx(K,{type:"password"})})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("openai.button.save")})})]})}),u.jsx($t,{}),u.jsx("div",{children:u.jsx(Nu,{columns:g,data:c??[],onSortingChange:l,state:{sorting:a},noResultsMessage:e("openai.credentials.table.none")})})]})]})}const Kee=e=>["openai","fetchDefaultSettings",JSON.stringify(e)],qee=async({instanceName:e,token:t})=>{const n=await he.get(`/openai/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Wee=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Kee({instanceName:t}),queryFn:()=>qee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Gee=_.object({openaiCredsId:_.string(),expire:_.coerce.number(),keywordFinish:_.string(),delayMessage:_.coerce.number().default(0),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.coerce.number(),speechToText:_.boolean(),ignoreJids:_.array(_.string()).default([]),openaiIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function Jee(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsOpenai:n}=rf(),[r,s]=v.useState(!1),{data:o,refetch:a}=Wee({instanceName:t==null?void 0:t.name,enabled:r}),{data:l,refetch:c}=II({instanceName:t==null?void 0:t.name,enabled:r}),{data:i}=Vw({instanceName:t==null?void 0:t.name,enabled:r}),d=sn({resolver:on(Gee),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0,splitMessages:!1,timePerChar:0}});v.useEffect(()=>{o&&d.reset({openaiCredsId:o.openaiCredsId,expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0,speechToText:o.speechToText,ignoreJids:o.ignoreJids,openaiIdFallback:o.openaiIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar??0})},[o]);const p=async h=>{var g,m,x;try{if(!t||!t.name)throw new Error("instance not found.");const b={openaiCredsId:h.openaiCredsId,expire:h.expire,keywordFinish:h.keywordFinish,delayMessage:h.delayMessage,unknownMessage:h.unknownMessage,listeningFromMe:h.listeningFromMe,stopBotFromMe:h.stopBotFromMe,keepOpen:h.keepOpen,debounceTime:h.debounceTime,speechToText:h.speechToText,openaiIdFallback:h.openaiIdFallback||void 0,ignoreJids:h.ignoreJids,splitMessages:h.splitMessages,timePerChar:h.timePerChar};await n({instanceName:t.name,token:t.token,data:b}),X.success(e("openai.toast.defaultSettings.success"))}catch(b){console.error("Error:",b),X.error(`Error: ${(x=(m=(g=b==null?void 0:b.response)==null?void 0:g.data)==null?void 0:m.response)==null?void 0:x.message}`)}};function f(){a(),c()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("openai.defaultSettings")})}),u.jsx(Tr,{...d,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:d.handleSubmit(p),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:(i==null?void 0:i.filter(h=>!!h.id).map(h=>({label:h.name?h.name:h.apiKey.substring(0,15)+"...",value:h.id})))||[]}),u.jsx(Qt,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:(l==null?void 0:l.filter(h=>!!h.id).map(h=>({label:h.description,value:h.id})))??[]}),u.jsx(G,{name:"expire",label:e("openai.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),u.jsx(ke,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("openai.form.splitMessages.label"),reverse:!0}),d.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:e("openai.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const Qee=e=>["openai","getModels",JSON.stringify(e)],Zee=async({instanceName:e,token:t})=>(await he.get(`/openai/getModels/${e}`,{headers:{apiKey:t}})).data,Yee=e=>{const{instanceName:t,token:n,...r}=e;return lt({staleTime:1e3*60*60*6,...r,queryKey:Qee({instanceName:t}),queryFn:()=>Zee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Xee=e=>["openai","fetchSessions",JSON.stringify(e)],ete=async({instanceName:e,openaiId:t,token:n})=>(await he.get(`/openai/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,tte=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return lt({...s,queryKey:Xee({instanceName:t}),queryFn:()=>ete({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function DI({openaiId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusOpenai:r}=rf(),[s,o]=v.useState([]),[a,l]=v.useState(!1),{data:c,refetch:i}=tte({instanceName:n==null?void 0:n.name,openaiId:e,enabled:a}),[d,p]=v.useState("");function f(){i()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("openai.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",size:"icon",children:[u.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("openai.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("openai.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("openai.sessions.search"),value:d,onChange:m=>p(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{size:16})})]}),u.jsx(Nu,{columns:g,data:c??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("openai.sessions.table.none")})]})]})]})}const nte=_.object({enabled:_.boolean(),description:_.string(),openaiCredsId:_.string(),botType:_.string(),assistantId:_.string().optional(),functionUrl:_.string().optional(),model:_.string().optional(),systemMessages:_.string().optional(),assistantMessages:_.string().optional(),userMessages:_.string().optional(),maxTokens:_.coerce.number().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function AI({initialData:e,onSubmit:t,handleDelete:n,openaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{},open:c}){const{t:i}=ze(),{instance:d}=nt(),{data:p}=Vw({instanceName:d==null?void 0:d.name,enabled:c}),{data:f}=Yee({instanceName:d==null?void 0:d.name,enabled:c}),h=sn({resolver:on(nte),defaultValues:e||{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:0,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),g=h.watch("botType"),m=h.watch("triggerType");return u.jsx(Tr,{...h,children:u.jsxs("form",{onSubmit:h.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:i("openai.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:i("openai.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsx(Qt,{name:"openaiCredsId",label:i("openai.form.openaiCredsId.label"),required:!0,options:(p==null?void 0:p.filter(x=>!!x.id).map(x=>({label:x.name?x.name:x.apiKey.substring(0,15)+"...",value:x.id})))??[]}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.openaiSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"botType",label:i("openai.form.botType.label"),required:!0,options:[{label:i("openai.form.botType.assistant"),value:"assistant"},{label:i("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),g==="assistant"&&u.jsxs(u.Fragment,{children:[u.jsx(G,{name:"assistantId",label:i("openai.form.assistantId.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"functionUrl",label:i("openai.form.functionUrl.label"),required:!0,children:u.jsx(K,{})})]}),g==="chatCompletion"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"model",label:i("openai.form.model.label"),required:!0,options:(f==null?void 0:f.map(x=>({label:x.id,value:x.id})))??[]}),u.jsx(G,{name:"systemMessages",label:i("openai.form.systemMessages.label"),children:u.jsx(Ml,{})}),u.jsx(G,{name:"assistantMessages",label:i("openai.form.assistantMessages.label"),children:u.jsx(Ml,{})}),u.jsx(G,{name:"userMessages",label:i("openai.form.userMessages.label"),children:u.jsx(Ml,{})}),u.jsx(G,{name:"maxTokens",label:i("openai.form.maxTokens.label"),children:u.jsx(K,{type:"number"})})]}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:i("openai.form.triggerType.label"),required:!0,options:[{label:i("openai.form.triggerType.keyword"),value:"keyword"},{label:i("openai.form.triggerType.all"),value:"all"},{label:i("openai.form.triggerType.advanced"),value:"advanced"},{label:i("openai.form.triggerType.none"),value:"none"}]}),m==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:i("openai.form.triggerOperator.label"),required:!0,options:[{label:i("openai.form.triggerOperator.contains"),value:"contains"},{label:i("openai.form.triggerOperator.equals"),value:"equals"},{label:i("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:i("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:i("openai.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:i("openai.form.triggerValue.label"),required:!0,children:u.jsx(K,{})})]}),m==="advanced"&&u.jsx(G,{name:"triggerValue",label:i("openai.form.triggerConditions.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:i("openai.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:i("openai.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:i("openai.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:i("openai.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:i("openai.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:i("openai.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:i("openai.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:i("openai.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:i("openai.form.splitMessages.label"),reverse:!0}),h.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:i("openai.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:i(o?"openai.button.saving":"openai.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(DI,{openaiId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:i("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:i("modal.delete.title")}),u.jsx(Fi,{children:i("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:i("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:i("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:i(o?"openai.button.saving":"openai.button.update")})]})]})]})})}function rte({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createOpenai:r}=rf(),[s,o]=v.useState(!1),[a,l]=v.useState(!1),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:i.enabled,description:i.description,openaiCredsId:i.openaiCredsId,botType:i.botType,assistantId:i.assistantId||"",functionUrl:i.functionUrl||"",model:i.model||"",systemMessages:[i.systemMessages||""],assistantMessages:[i.assistantMessages||""],userMessages:[i.userMessages||""],maxTokens:i.maxTokens||0,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("openai.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("openai.form.title")})}),u.jsx(AI,{onSubmit:c,isModal:!0,isLoading:s,open:a})]})]})}const ste=e=>["openai","getOpenai",JSON.stringify(e)],ote=async({instanceName:e,token:t,openaiId:n})=>{const r=await he.get(`/openai/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},ate=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return lt({...s,queryKey:ste({instanceName:t}),queryFn:()=>ote({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ite({openaiId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteOpenai:l,updateOpenai:c}=rf(),{data:i,isLoading:d}=ate({instanceName:r==null?void 0:r.name,openaiId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",openaiCredsId:(i==null?void 0:i.openaiCredsId)??"",botType:(i==null?void 0:i.botType)??"",assistantId:(i==null?void 0:i.assistantId)||"",functionUrl:(i==null?void 0:i.functionUrl)||"",model:(i==null?void 0:i.model)||"",systemMessages:Array.isArray(i==null?void 0:i.systemMessages)?i==null?void 0:i.systemMessages.join(", "):(i==null?void 0:i.systemMessages)||"",assistantMessages:Array.isArray(i==null?void 0:i.assistantMessages)?i==null?void 0:i.assistantMessages.join(", "):(i==null?void 0:i.assistantMessages)||"",userMessages:Array.isArray(i==null?void 0:i.userMessages)?i==null?void 0:i.userMessages.join(", "):(i==null?void 0:i.userMessages)||"",maxTokens:(i==null?void 0:i.maxTokens)||0,triggerType:(i==null?void 0:i.triggerType)||"",triggerOperator:(i==null?void 0:i.triggerOperator)||"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)||0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)||0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:i==null?void 0:i.stopBotFromMe,keepOpen:i==null?void 0:i.keepOpen,debounceTime:(i==null?void 0:i.debounceTime)||0,splitMessages:(i==null?void 0:i.splitMessages)||!1,timePerChar:(i==null?void 0:i.timePerChar)||0}),[i==null?void 0:i.assistantId,i==null?void 0:i.assistantMessages,i==null?void 0:i.botType,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.functionUrl,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.maxTokens,i==null?void 0:i.model,i==null?void 0:i.openaiCredsId,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.systemMessages,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.userMessages,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,openaiCredsId:g.openaiCredsId,botType:g.botType,assistantId:g.assistantId||"",functionUrl:g.functionUrl||"",model:g.model||"",systemMessages:[g.systemMessages||""],assistantMessages:[g.assistantMessages||""],userMessages:[g.userMessages||""],maxTokens:g.maxTokens||0,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar||0};await c({instanceName:r.name,openaiId:e,data:y}),X.success(n("openai.toast.success.update")),t(),s(`/manager/instance/${r.id}/openai/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,openaiId:e}),X.success(n("openai.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/openai`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(AI,{initialData:p,onSubmit:f,openaiId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function oE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{botId:r}=So(),{data:s,isLoading:o,refetch:a}=II({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/openai/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(DI,{}),u.jsx(Jee,{}),u.jsx(Hee,{}),u.jsx(rte,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsxs(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[u.jsx("h4",{className:"text-base",children:d.description||d.id}),u.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):u.jsx(q,{variant:"link",children:e("openai.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(ite,{openaiId:r,resetTable:i})})]})]})]})}const lte=e=>["proxy","fetchProxy",JSON.stringify(e)],ute=async({instanceName:e,token:t})=>(await he.get(`/proxy/find/${e}`,{headers:{apiKey:t}})).data,cte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:lte({instanceName:t,token:n}),queryFn:()=>ute({instanceName:t,token:n}),enabled:!!t})},dte=async({instanceName:e,token:t,data:n})=>(await he.post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data;function fte(){return{createProxy:Ye(dte,{invalidateKeys:[["proxy","fetchProxy"]]})}}const pte=_.object({enabled:_.boolean(),host:_.string(),port:_.string(),protocol:_.string(),username:_.string(),password:_.string()});function hte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createProxy:s}=fte(),{data:o}=cte({instanceName:t==null?void 0:t.name}),a=sn({resolver:on(pte),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,host:o.host,port:o.port,protocol:o.protocol,username:o.username,password:o.password})},[o]);const l=async c=>{var i,d,p;if(t){r(!0);try{const f={enabled:c.enabled,host:c.host,port:c.port,protocol:c.protocol,username:c.username,password:c.password};await s({instanceName:t.name,token:t.token,data:f}),X.success(e("proxy.toast.success"))}catch(f){console.error(e("proxy.toast.error"),f),X.error(`Error : ${(p=(d=(i=f==null?void 0:f.response)==null?void 0:i.data)==null?void 0:d.response)==null?void 0:p.message}`)}finally{r(!1)}}};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),u.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[u.jsx(G,{name:"protocol",label:e("proxy.form.protocol.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"host",label:e("proxy.form.host.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"port",label:e("proxy.form.port.label"),children:u.jsx(K,{type:"number"})})]}),u.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[u.jsx(G,{name:"username",label:e("proxy.form.username.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"password",label:e("proxy.form.password.label"),children:u.jsx(K,{type:"password"})})]}),u.jsx("div",{className:"flex justify-end px-4 pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const gte=e=>["rabbitmq","fetchRabbitmq",JSON.stringify(e)],mte=async({instanceName:e,token:t})=>(await he.get(`/rabbitmq/find/${e}`,{headers:{apiKey:t}})).data,vte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:gte({instanceName:t,token:n}),queryFn:()=>mte({instanceName:t,token:n}),enabled:!!t})},yte=async({instanceName:e,token:t,data:n})=>(await he.post(`/rabbitmq/set/${e}`,{rabbitmq:n},{headers:{apikey:t}})).data;function bte(){return{createRabbitmq:Ye(yte,{invalidateKeys:[["rabbitmq","fetchRabbitmq"]]})}}const xte=_.object({enabled:_.boolean(),events:_.array(_.string())});function wte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createRabbitmq:s}=bte(),{data:o}=vte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(xte),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("rabbitmq.toast.success"))}catch(m){console.error(e("rabbitmq.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const Ste=e=>["instance","fetchSettings",JSON.stringify(e)],Cte=async({instanceName:e,token:t})=>(await he.get(`/settings/find/${e}`,{headers:{apikey:t}})).data,Ete=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ste({instanceName:t,token:n}),queryFn:()=>Cte({instanceName:t,token:n}),enabled:!!t})},Tte=_.object({rejectCall:_.boolean(),msgCall:_.string().optional(),groupsIgnore:_.boolean(),alwaysOnline:_.boolean(),readMessages:_.boolean(),syncFullHistory:_.boolean(),readStatus:_.boolean()});function kte(){const{t:e}=ze(),[t,n]=v.useState(!1),{instance:r}=nt(),{updateSettings:s}=_g(),{data:o,isLoading:a}=Ete({instanceName:r==null?void 0:r.name,token:r==null?void 0:r.token}),l=sn({resolver:on(Tte),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});v.useEffect(()=>{o&&l.reset({rejectCall:o.rejectCall,msgCall:o.msgCall||"",groupsIgnore:o.groupsIgnore,alwaysOnline:o.alwaysOnline,readMessages:o.readMessages,syncFullHistory:o.syncFullHistory,readStatus:o.readStatus})},[l,o]);const c=async p=>{try{if(!r||!r.name)throw new Error("instance not found");n(!0);const f={rejectCall:p.rejectCall,msgCall:p.msgCall,groupsIgnore:p.groupsIgnore,alwaysOnline:p.alwaysOnline,readMessages:p.readMessages,syncFullHistory:p.syncFullHistory,readStatus:p.readStatus};await s({instanceName:r.name,token:r.token,data:f}),X.success(e("settings.toast.success"))}catch(f){console.error(e("settings.toast.success"),f),X.error(e("settings.toast.error"))}finally{n(!1)}},i=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],d=l.watch("rejectCall");return a?u.jsx(wr,{}):u.jsx(u.Fragment,{children:u.jsx(Na,{...l,children:u.jsx("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),u.jsx($t,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[u.jsxs("div",{className:"flex flex-col p-4",children:[u.jsx(ke,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),d&&u.jsx("div",{className:"mr-16 mt-2",children:u.jsx(G,{name:"msgCall",children:u.jsx(Ml,{placeholder:e("settings.form.msgCall.description")})})})]}),i.map(p=>u.jsx("div",{className:"flex p-4",children:u.jsx(ke,{name:p.name,label:p.label,className:"w-full justify-between",helper:p.description})},p.name)),u.jsx("div",{className:"flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:t,children:e(t?"settings.button.saving":"settings.button.save")})})]})]})})})})}const _te=e=>["sqs","fetchSqs",JSON.stringify(e)],jte=async({instanceName:e,token:t})=>(await he.get(`/sqs/find/${e}`,{headers:{apiKey:t}})).data,Rte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:_te({instanceName:t,token:n}),queryFn:()=>jte({instanceName:t,token:n}),enabled:!!t})},Pte=async({instanceName:e,token:t,data:n})=>(await he.post(`/sqs/set/${e}`,{sqs:n},{headers:{apikey:t}})).data;function Mte(){return{createSqs:Ye(Pte,{invalidateKeys:[["sqs","fetchSqs"]]})}}const Ote=_.object({enabled:_.boolean(),events:_.array(_.string())});function Nte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createSqs:s}=Mte(),{data:o}=Rte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(Ote),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("sqs.toast.success"))}catch(m){console.error(e("sqs.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const Ite=e=>["typebot","findTypebot",JSON.stringify(e)],Dte=async({instanceName:e,token:t})=>(await he.get(`/typebot/find/${e}`,{headers:{apiKey:t}})).data,FI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ite({instanceName:t}),queryFn:()=>Dte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Ate=e=>["typebot","fetchDefaultSettings",JSON.stringify(e)],Fte=async({instanceName:e,token:t})=>{const n=await he.get(`/typebot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Lte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ate({instanceName:t}),queryFn:()=>Fte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},$te=async({instanceName:e,token:t,data:n})=>(await he.post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,Bte=async({instanceName:e,token:t,typebotId:n,data:r})=>(await he.put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,zte=async({instanceName:e,typebotId:t})=>(await he.delete(`/typebot/delete/${t}/${e}`)).data,Ute=async({instanceName:e,token:t,data:n})=>(await he.post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,Vte=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function tm(){const e=Ye(Ute,{invalidateKeys:[["typebot","fetchDefaultSettings"]]}),t=Ye(Vte,{invalidateKeys:[["typebot","getTypebot"],["typebot","fetchSessions"]]}),n=Ye(zte,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),r=Ye(Bte,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),s=Ye($te,{invalidateKeys:[["typebot","findTypebot"]]});return{setDefaultSettingsTypebot:e,changeStatusTypebot:t,deleteTypebot:n,updateTypebot:r,createTypebot:s}}const Hte=_.object({expire:_.coerce.number(),keywordFinish:_.string(),delayMessage:_.coerce.number(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.coerce.number()});function Kte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{setDefaultSettingsTypebot:s}=tm(),{data:o,refetch:a}=Lte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),{data:l,refetch:c}=FI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),i=sn({resolver:on(Hte),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});v.useEffect(()=>{o&&i.reset({expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0})},[o]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:f.expire,keywordFinish:f.keywordFinish,delayMessage:f.delayMessage,unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:f.debounceTime};await s({instanceName:t.name,token:t.token,data:x}),X.success(e("typebot.toast.defaultSettings.success"))}catch(x){console.error(e("typebot.toast.defaultSettings.error"),x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){a(),c()}return u.jsxs(Tt,{open:n,onOpenChange:r,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("typebot.modal.defaultSettings.title")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:(l==null?void 0:l.filter(f=>!!f.id).map(f=>({label:f.typebot,value:f.description})))??[]}),u.jsx(G,{name:"expire",label:e("typebot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const qte=e=>["typebot","fetchSessions",JSON.stringify(e)],Wte=async({instanceName:e,typebotId:t,token:n})=>(await he.get(`/typebot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Gte=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return lt({...s,queryKey:qte({instanceName:t}),queryFn:()=>Wte({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function LI({typebotId:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[l,c]=v.useState(""),{changeStatusTypebot:i}=tm(),{data:d,refetch:p}=Gte({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token,typebotId:e});function f(){p()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await i({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("typebot.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:"Actions"}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"})," ",u.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("typebot.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("typebot.sessions.search"),value:l,onChange:m=>c(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{size:16})})]}),u.jsx(Nu,{columns:g,data:d??[],onSortingChange:s,state:{sorting:r,globalFilter:l},onGlobalFilterChange:c,enableGlobalFilter:!0,noResultsMessage:t("typebot.sessions.table.none")})]})]})]})}const Jte=_.object({enabled:_.boolean(),description:_.string(),url:_.string(),typebot:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function $I({initialData:e,onSubmit:t,handleDelete:n,typebotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(Jte),defaultValues:e||{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("typebot.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("typebot.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.typebotSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"url",label:c("typebot.form.url.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"typebot",label:c("typebot.form.typebot.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("typebot.form.triggerType.label"),options:[{label:c("typebot.form.triggerType.keyword"),value:"keyword"},{label:c("typebot.form.triggerType.all"),value:"all"},{label:c("typebot.form.triggerType.advanced"),value:"advanced"},{label:c("typebot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("typebot.form.triggerOperator.label"),options:[{label:c("typebot.form.triggerOperator.contains"),value:"contains"},{label:c("typebot.form.triggerOperator.equals"),value:"equals"},{label:c("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("typebot.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("typebot.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("typebot.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("typebot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("typebot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("typebot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("typebot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("typebot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("typebot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("typebot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("typebot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"typebot.button.saving":"typebot.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(LI,{typebotId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"typebot.button.saving":"typebot.button.update")})]})]})]})})}function Qte({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createTypebot:r}=tm(),[s,o]=v.useState(!1),[a,l]=v.useState(!1),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:i.enabled,description:i.description,url:i.url,typebot:i.typebot||"",triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("typebot.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("typebot.form.title")})}),u.jsx($I,{onSubmit:c,isModal:!0,isLoading:s})]})]})}const Zte=e=>["typebot","getTypebot",JSON.stringify(e)],Yte=async({instanceName:e,token:t,typebotId:n})=>{const r=await he.get(`/typebot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Xte=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return lt({...s,queryKey:Zte({instanceName:t}),queryFn:()=>Yte({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ene({typebotId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteTypebot:l,updateTypebot:c}=tm(),{data:i,isLoading:d}=Xte({instanceName:r==null?void 0:r.name,typebotId:e}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",url:(i==null?void 0:i.url)??"",typebot:(i==null?void 0:i.typebot)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0}),[i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.typebot,i==null?void 0:i.unknownMessage,i==null?void 0:i.url]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,url:g.url,typebot:g.typebot||"",triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,typebotId:e,data:y}),X.success(n("typebot.toast.success.update")),t(),s(`/manager/instance/${r.id}/typebot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,typebotId:e}),X.success(n("typebot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/typebot`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx($I,{initialData:p,onSubmit:f,typebotId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function aE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{typebotId:r}=So(),{data:s,isLoading:o,refetch:a}=FI({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/typebot/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),u.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[u.jsx(LI,{}),u.jsx(Kte,{}),u.jsx(Qte,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:d.description?u.jsxs(u.Fragment,{children:[u.jsx("h4",{className:"text-base",children:d.description}),u.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[d.url," - ",d.typebot]})]}):u.jsxs(u.Fragment,{children:[u.jsx("h4",{className:"text-base",children:d.url}),u.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:d.typebot})]})},d.id)):u.jsx(q,{variant:"link",children:e("typebot.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-black"}),u.jsx(Ur,{children:u.jsx(ene,{typebotId:r,resetTable:i})})]})]})]})}const tne=e=>["webhook","fetchWebhook",JSON.stringify(e)],nne=async({instanceName:e,token:t})=>(await he.get(`/webhook/find/${e}`,{headers:{apiKey:t}})).data,rne=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:tne({instanceName:t,token:n}),queryFn:()=>nne({instanceName:t,token:n}),enabled:!!t})},sne=async({instanceName:e,token:t,data:n})=>(await he.post(`/webhook/set/${e}`,{webhook:n},{headers:{apikey:t}})).data;function one(){return{createWebhook:Ye(sne,{invalidateKeys:[["webhook","fetchWebhook"]]})}}const ane=_.object({enabled:_.boolean(),url:_.string().url("Invalid URL format"),events:_.array(_.string()),base64:_.boolean(),byEvents:_.boolean()});function ine(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createWebhook:s}=one(),{data:o}=rne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(ane),defaultValues:{enabled:!1,url:"",events:[],base64:!1,byEvents:!1}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,url:o.url,events:o.events,base64:o.webhookBase64,byEvents:o.webhookByEvents})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,url:p.url,events:p.events,base64:p.base64,byEvents:p.byEvents};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("webhook.toast.success"))}catch(m){console.error(e("webhook.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),u.jsx(G,{name:"url",label:"URL",children:u.jsx(K,{})}),u.jsx(ke,{name:"byEvents",label:e("webhook.form.byEvents.label"),className:"w-full justify-between",helper:e("webhook.form.byEvents.description")}),u.jsx(ke,{name:"base64",label:e("webhook.form.base64.label"),className:"w-full justify-between",helper:e("webhook.form.base64.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const lne=e=>["websocket","fetchWebsocket",JSON.stringify(e)],une=async({instanceName:e,token:t})=>(await he.get(`/websocket/find/${e}`,{headers:{apiKey:t}})).data,cne=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:lne({instanceName:t,token:n}),queryFn:()=>une({instanceName:t,token:n}),enabled:!!t})},dne=async({instanceName:e,token:t,data:n})=>(await he.post(`/websocket/set/${e}`,{websocket:n},{headers:{apikey:t}})).data;function fne(){return{createWebsocket:Ye(dne,{invalidateKeys:[["websocket","fetchWebsocket"]]})}}const pne=_.object({enabled:_.boolean(),events:_.array(_.string())});function hne(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createWebsocket:s}=fne(),{data:o}=cne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(pne),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("websocket.toast.success"))}catch(m){console.error(e("websocket.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const gne=async({url:e,token:t})=>{try{const{data:n}=await zt.post(`${e}/verify-creds`,{},{headers:{apikey:t}});return P_({facebookAppId:n.facebookAppId,facebookConfigId:n.facebookConfigId,facebookUserToken:n.facebookUserToken}),n}catch{return null}},mne=_.object({serverUrl:_.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:_.string({required_error:"ApiKey is required"})});function vne(){const{t:e}=ze(),t=An(),n=sn({resolver:on(mne),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),r=async s=>{const o=await nj({url:s.serverUrl});if(!o||!o.version){M_(),n.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await gne({token:s.apiKey,url:s.serverUrl})){n.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}P_({version:o.version,clientName:o.clientName,url:s.serverUrl,token:s.apiKey}),t("/manager/")};return u.jsxs("div",{className:"flex min-h-screen flex-col",children:[u.jsx("div",{className:"flex items-center justify-center pt-2",children:u.jsx("img",{className:"h-10",src:"/assets/images/evolution-logo.png",alt:"logo"})}),u.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:u.jsxs(Ja,{className:"b-none w-[350px] shadow-none",children:[u.jsxs(Qa,{children:[u.jsx(jc,{className:"text-center",children:e("login.title")}),u.jsx(JP,{className:"text-center",children:e("login.description")})]}),u.jsx(Na,{...n,children:u.jsxs("form",{onSubmit:n.handleSubmit(r),children:[u.jsx(Za,{children:u.jsxs("div",{className:"grid w-full items-center gap-4",children:[u.jsx(G,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:u.jsx(K,{})}),u.jsx(G,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:u.jsx(K,{type:"password"})})]})}),u.jsx(kg,{className:"flex justify-center",children:u.jsx(q,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),u.jsx(Ax,{})]})}const yne=OL([{path:"/manager/login",element:u.jsx(l$,{children:u.jsx(vne,{})})},{path:"/manager/",element:u.jsx(Gt,{children:u.jsx(SV,{children:u.jsx(GQ,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(SY,{})})})},{path:"/manager/instance/:instanceId/chat",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Q1,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Q1,{})})})},{path:"/manager/instance/:instanceId/settings",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(kte,{})})})},{path:"/manager/instance/:instanceId/openai",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(oE,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(oE,{})})})},{path:"/manager/instance/:instanceId/webhook",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(ine,{})})})},{path:"/manager/instance/:instanceId/websocket",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(hne,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(wte,{})})})},{path:"/manager/instance/:instanceId/sqs",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Nte,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(HZ,{})})})},{path:"/manager/instance/:instanceId/typebot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(aE,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(aE,{})})})},{path:"/manager/instance/:instanceId/dify",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(nE,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(nE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(rE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot/:evolutionBotId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(rE,{})})})},{path:"/manager/instance/:instanceId/flowise",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(sE,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(sE,{})})})},{path:"/manager/instance/:instanceId/proxy",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(hte,{})})})}]),bne={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class jh{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||bne,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[l,c]=a;for(let i=0;i{let[l,c]=a;for(let i=0;i{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},iE=e=>e==null?"":""+e,xne=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},wne=/###/g,lE=e=>e&&e.indexOf("###")>-1?e.replace(wne,"."):e,uE=e=>!e||typeof e=="string",Ic=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=Ic(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],a=t.slice(0,t.length-1),l=Ic(e,a,Object);for(;l.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),l=Ic(e,a,Object),l&&l.obj&&typeof l.obj[`${l.k}.${o}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${o}`]=n},Sne=(e,t,n,r)=>{const{obj:s,k:o}=Ic(e,t,Object);s[o]=s[o]||[],s[o].push(n)},Rh=(e,t)=>{const{obj:n,k:r}=Ic(e,t);if(n)return n[r]},Cne=(e,t,n)=>{const r=Rh(e,n);return r!==void 0?r:Rh(t,n)},BI=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):BI(e[r],t[r],n):e[r]=t[r]);return e},Xi=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ene={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Tne=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>Ene[t]):e;class kne{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const _ne=[" ",",","?","!",";"],jne=new kne(20),Rne=(e,t,n)=>{t=t||"",n=n||"";const r=_ne.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const s=jne.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!s.test(e);if(!o){const a=e.indexOf(n);a>0&&!s.test(e.substring(0,a))&&(o=!0)}return o},_b=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&ce&&e.indexOf("_")>0?e.replace("_","-"):e;class dE extends nm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;t.indexOf(".")>-1?l=t.split("."):(l=[t,n],r&&(Array.isArray(r)?l.push(...r):typeof r=="string"&&o?l.push(...r.split(o)):l.push(r)));const c=Rh(this.data,l);return!c&&!n&&!r&&t.indexOf(".")>-1&&(t=l[0],n=l[1],r=l.slice(2).join(".")),c||!a||typeof r!="string"?c:_b(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let l=[t,n];r&&(l=l.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(l=t.split("."),s=n,n=l[1]),this.addNamespaces(n),cE(this.data,l,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},l=[t,n];t.indexOf(".")>-1&&(l=t.split("."),s=r,r=n,n=l[1]),this.addNamespaces(n);let c=Rh(this.data,l)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?BI(c,r,o):c={...c,...r},cE(this.data,l,c),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var zI={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const fE={};class Mh extends nm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),xne(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Is.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Rne(t,r,s);if(a&&!l){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:o};const i=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(i[0])>-1)&&(o=i.shift()),t=i.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(t[t.length-1],n),c=l[l.length-1],i=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(i&&i.toLowerCase()==="cimode"){if(d){const S=n.nsSeparator||this.options.nsSeparator;return s?{res:`${c}${S}${a}`,usedKey:a,exactUsedKey:a,usedLng:i,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:`${c}${S}${a}`}return s?{res:a,usedKey:a,exactUsedKey:a,usedLng:i,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:a}const p=this.resolve(t,n);let f=p&&p.res;const h=p&&p.usedKey||a,g=p&&p.exactUsedKey||a,m=Object.prototype.toString.apply(f),x=["[object Number]","[object Function]","[object RegExp]"],b=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject;if(y&&f&&(typeof f!="string"&&typeof f!="boolean"&&typeof f!="number")&&x.indexOf(m)<0&&!(typeof b=="string"&&Array.isArray(f))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,f,{...n,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(p.res=S,p.usedParams=this.getUsedParamsDetails(n),p):S}if(o){const S=Array.isArray(f),E=S?[]:{},C=S?g:h;for(const k in f)if(Object.prototype.hasOwnProperty.call(f,k)){const T=`${C}${o}${k}`;E[k]=this.translate(T,{...n,joinArrays:!1,ns:l}),E[k]===T&&(E[k]=f[k])}f=E}}else if(y&&typeof b=="string"&&Array.isArray(f))f=f.join(b),f&&(f=this.extendTranslation(f,t,n,r));else{let S=!1,E=!1;const C=n.count!==void 0&&typeof n.count!="string",k=Mh.hasDefaultValue(n),T=C?this.pluralResolver.getSuffix(i,n.count,n):"",P=n.ordinal&&C?this.pluralResolver.getSuffix(i,n.count,{ordinal:!1}):"",N=C&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),U=N&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${T}`]||n[`defaultValue${P}`]||n.defaultValue;!this.isValidLookup(f)&&k&&(S=!0,f=U),this.isValidLookup(f)||(E=!0,f=a);const Z=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:f,V=k&&U!==f&&this.options.updateMissing;if(E||S||V){if(this.logger.log(V?"updateKey":"missingKey",i,c,a,V?U:f),o){const F=this.resolve(a,{...n,keySeparator:!1});F&&F.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Q=[];const ee=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ee&&ee[0])for(let F=0;F{const de=k&&Y!==f?Y:Z;this.options.missingKeyHandler?this.options.missingKeyHandler(F,c,A,de,V,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(F,c,A,de,V,n),this.emit("missingKey",F,c,A,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?Q.forEach(F=>{const A=this.pluralResolver.getSuffixes(F,n);N&&n[`defaultValue${this.options.pluralSeparator}zero`]&&A.indexOf(`${this.options.pluralSeparator}zero`)<0&&A.push(`${this.options.pluralSeparator}zero`),A.forEach(Y=>{W([F],a+Y,n[`defaultValue${Y}`]||U)})}):W(Q,a,U))}f=this.extendTranslation(f,t,n,p,r),E&&f===a&&this.options.appendNamespaceToMissingKey&&(f=`${c}:${a}`),(E||S)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}:${a}`:a,S?f:void 0):f=this.options.parseMissingKeyHandler(f))}return s?(p.res=f,p.usedParams=this.getUsedParamsDetails(n),p):f}extendTranslation(t,n,r,s,o){var a=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const i=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(i){const f=t.match(this.interpolator.nestingRegexp);d=f&&f.length}let p=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),t=this.interpolator.interpolate(t,p,r.lng||this.language||s.usedLng,r),i){const f=t.match(this.interpolator.nestingRegexp),h=f&&f.length;d1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,a,l;return typeof t=="string"&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(r))return;const i=this.extractFromKey(c,n),d=i.key;s=d;let p=i.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const f=n.count!==void 0&&typeof n.count!="string",h=f&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),g=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);p.forEach(x=>{this.isValidLookup(r)||(l=x,!fE[`${m[0]}-${x}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(l)&&(fE[`${m[0]}-${x}`]=!0,this.logger.warn(`key "${s}" for languages "${m.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(b=>{if(this.isValidLookup(r))return;a=b;const y=[d];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(y,d,b,x,n);else{let S;f&&(S=this.pluralResolver.getSuffix(b,n.count,n));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(y.push(d+S),n.ordinal&&S.indexOf(C)===0&&y.push(d+S.replace(C,this.options.pluralSeparator)),h&&y.push(d+E)),g){const k=`${d}${this.options.contextSeparator}${n.context}`;y.push(k),f&&(y.push(k+S),n.ordinal&&S.indexOf(C)===0&&y.push(k+S.replace(C,this.options.pluralSeparator)),h&&y.push(k+E))}}let w;for(;w=y.pop();)this.isValidLookup(r)||(o=w,r=this.getResource(b,x,w,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:a,usedNS:l}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const Cv=e=>e.charAt(0).toUpperCase()+e.slice(1);class pE{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Is.create("languageUtils")}getScriptPartFromCode(t){if(t=Ph(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Ph(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Cv(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Cv(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=Cv(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(a=>{s.indexOf(a)<0&&o(this.formatLanguageCode(a))}),s}}let Pne=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Mne={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const One=["v1","v2","v3"],Nne=["v4"],hE={zero:0,one:1,two:2,few:3,many:4,other:5},Ine=()=>{const e={};return Pne.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:Mne[t.fc]}})}),e};class Dne{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=Is.create("pluralResolver"),(!this.options.compatibilityJSON||Nne.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=Ine(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=Ph(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const a=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=a,a}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>hE[s]-hE[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!One.includes(this.options.compatibilityJSON)}}const gE=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=Cne(e,t,n);return!o&&s&&typeof n=="string"&&(o=_b(e,n,r),o===void 0&&(o=_b(t,n,r))),o},Ev=e=>e.replace(/\$/g,"$$$$");class Ane{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Is.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:a,suffix:l,suffixEscaped:c,formatSeparator:i,unescapeSuffix:d,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:h,nestingSuffix:g,nestingSuffixEscaped:m,nestingOptionsSeparator:x,maxReplaces:b,alwaysFormat:y}=t.interpolation;this.escape=n!==void 0?n:Tne,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?Xi(o):a||"{{",this.suffix=l?Xi(l):c||"}}",this.formatSeparator=i||",",this.unescapePrefix=d?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?Xi(f):h||Xi("$t("),this.nestingSuffix=g?Xi(g):m||Xi(")"),this.nestingOptionsSeparator=x||",",this.maxReplaces=b||1e3,this.alwaysFormat=y!==void 0?y:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,a,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},i=h=>{if(h.indexOf(this.formatSeparator)<0){const b=gE(n,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(b,void 0,r,{...s,...n,interpolationkey:h}):b}const g=h.split(this.formatSeparator),m=g.shift().trim(),x=g.join(this.formatSeparator).trim();return this.format(gE(n,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),x,r,{...s,...n,interpolationkey:m})};this.resetRegExp();const d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,p=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>Ev(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?Ev(this.escape(h)):Ev(h)}].forEach(h=>{for(l=0;o=h.regex.exec(t);){const g=o[1].trim();if(a=i(g),a===void 0)if(typeof d=="function"){const x=d(t,o,s);a=typeof x=="string"?x:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))a="";else if(p){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${t}`),a="";else typeof a!="string"&&!this.useRawValueToEscape&&(a=iE(a));const m=h.safeValue(a);if(t=t.replace(o[0],m),p?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=o[0].length):h.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,a;const l=(c,i)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const p=c.split(new RegExp(`${d}[ ]*{`));let f=`{${p[1]}`;c=p[0],f=this.interpolate(f,a);const h=f.match(/'/g),g=f.match(/"/g);(h&&h.length%2===0&&!g||g.length%2!==0)&&(f=f.replace(/'/g,'"'));try{a=JSON.parse(f),i&&(a={...i,...a})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${d}${f}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,c};for(;s=this.nestingRegexp.exec(t);){let c=[];a={...r},a=a.replace&&typeof a.replace!="string"?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let i=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const d=s[1].split(this.formatSeparator).map(p=>p.trim());s[1]=d.shift(),c=d,i=!0}if(o=n(l.call(this,s[1].trim(),a),a),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=iE(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),i&&(o=c.reduce((d,p)=>this.format(d,p,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const Fne=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(a=>{if(a){const[l,...c]=a.split(":"),i=c.join(":").trim().replace(/^'+|'+$/g,""),d=l.trim();n[d]||(n[d]=i),i==="false"&&(n[d]=!1),i==="true"&&(n[d]=!0),isNaN(i)||(n[d]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},el=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const a=r+JSON.stringify(o);let l=t[a];return l||(l=e(Ph(r),s),t[a]=l),l(n)}};class Lne{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Is.create("formatter"),this.options=t,this.formats={number:el((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:el((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:el((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:el((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:el((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=el(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(l=>l.indexOf(")")>-1)){const l=o.findIndex(c=>c.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,l)].join(this.formatSeparator)}return o.reduce((l,c)=>{const{formatName:i,formatOptions:d}=Fne(c);if(this.formats[i]){let p=l;try{const f=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},h=f.locale||f.lng||s.locale||s.lng||r;p=this.formats[i](l,h,{...d,...s,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${i}`);return l},t)}}const $ne=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class Bne extends nm{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=Is.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},a={},l={},c={};return t.forEach(i=>{let d=!0;n.forEach(p=>{const f=`${i}|${p}`;!r.reload&&this.store.hasResourceBundle(i,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?a[f]===void 0&&(a[f]=!0):(this.state[f]=1,d=!1,a[f]===void 0&&(a[f]=!0),o[f]===void 0&&(o[f]=!0),c[p]===void 0&&(c[p]=!0)))}),d||(l[i]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(t,n,r){const s=t.split("|"),o=s[0],a=s[1];n&&this.emit("failedLoading",o,a,n),!n&&r&&this.store.addResourceBundle(o,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const l={};this.queue.forEach(c=>{Sne(c.loaded,[o],a),$ne(c,t),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(i=>{l[i]||(l[i]={});const d=c.loaded[i];d.length&&d.forEach(p=>{l[i][p]===void 0&&(l[i][p]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:a});return}this.readingCalls++;const l=(i,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(i&&d&&s{this.read.call(this,t,n,r,s+1,o*2,a)},o);return}a(i,d)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const i=c(t,n);i&&typeof i.then=="function"?i.then(d=>l(null,d)).catch(l):l(null,i)}catch(i){l(i)}return}return c(t,n,l)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(a,l)=>{a&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,a),!a&&l&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,l),this.loaded(t,a,l)})}saveMissing(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},l=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const c={...a,isUpdate:o},i=this.backend.create.bind(this.backend);if(i.length<6)try{let d;i.length===5?d=i(t,n,r,s,c):d=i(t,n,r,s),d&&typeof d.then=="function"?d.then(p=>l(null,p)).catch(l):l(null,d)}catch(d){l(d)}else i(t,n,r,s,l,c)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const mE=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),vE=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),Qf=()=>{},zne=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Pd extends nm{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=vE(t),this.services={},this.logger=Is,this.modules={external:[]},zne(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=mE();this.options={...s,...this.options,...vE(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Is.init(o(this.modules.logger),this.options):Is.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:typeof Intl<"u"&&(d=Lne);const p=new pE(this.options);this.store=new dE(this.options.resources,this.options);const f=this.services;f.logger=Is,f.resourceStore=this.store,f.languageUtils=p,f.pluralResolver=new Dne(p,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(f.formatter=o(d),f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new Ane(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Bne(o(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",function(h){for(var g=arguments.length,m=new Array(g>1?g-1:0),x=1;x1?g-1:0),x=1;x{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Qf),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=function(){return t.store[d](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=function(){return t.store[d](...arguments),t}});const c=sc(),i=()=>{const d=(p,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),r(p,f)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initImmediate?i():setTimeout(i,0),c}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qf;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],a=l=>{if(!l||l==="cimode")return;this.services.languageUtils.toResolveHierarchy(l).forEach(i=>{i!=="cimode"&&o.indexOf(i)<0&&o.push(i)})};s?a(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>a(c)),this.options.preload&&this.options.preload.forEach(l=>a(l)),this.services.backendConnector.load(o,this.options.ns,l=>{!l&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(l)})}else r(null)}reloadResources(t,n,r){const s=sc();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=Qf),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&zI.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=sc();this.emit("languageChanging",t);const o=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},a=(c,i)=>{i?(o(i),this.translator.changeLanguage(i),this.isLanguageChangingTo=void 0,this.emit("languageChanged",i),this.logger.log("languageChanged",i)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(c,function(){return r.t(...arguments)})},l=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const i=typeof c=="string"?c:this.services.languageUtils.getBestMatchFromCodes(c);i&&(this.language||o(i),this.translator.language||this.translator.changeLanguage(i),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(i)),this.loadResources(i,d=>{a(d,i)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?l(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(l):this.services.languageDetector.detect(l):l(t),s}getFixedT(t,n,r){var s=this;const o=function(a,l){let c;if(typeof l!="object"){for(var i=arguments.length,d=new Array(i>2?i-2:0),p=2;p`${c.keyPrefix}${f}${g}`):h=c.keyPrefix?`${c.keyPrefix}${f}${a}`:a,s.t(h,c)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(l,c)=>{const i=this.services.backendConnector.state[`${l}|${c}`];return i===-1||i===0||i===2};if(n.precheck){const l=n.precheck(this,a);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!s||a(o,t)))}loadNamespaces(t,n){const r=sc();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=sc();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(a=>s.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=s.concat(o),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new pE(mE());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Pd(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qf;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new Pd(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(l=>{o[l]=this[l]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new dE(this.store.data,s),o.services.resourceStore=o.store),o.translator=new Mh(o.services,s),o.translator.on("*",function(l){for(var c=arguments.length,i=new Array(c>1?c-1:0),d=1;d:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.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-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * 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-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))}.divide-x>:not([hidden])~:not([hidden]){--tw-divide-x-reverse: 0;border-right-width:calc(1px * var(--tw-divide-x-reverse));border-left-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.self-end{align-self:flex-end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.text-wrap{text-wrap:wrap}.break-all{word-break:break-all}.rounded-3xl{border-radius:1.5rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[--color-border\]{border-color:var(--color-border)}.border-amber-500\/20{border-color:#f59e0b33}.border-black{--tw-border-opacity: 1;border-color:rgb(0 0 0 / var(--tw-border-opacity))}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-emerald-500\/20{border-color:#10b98133}.border-gray-600\/50{border-color:#4b556380}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-red-500\/20{border-color:#ef444433}.border-sky-500\/20{border-color:#0ea5e933}.border-transparent{border-color:transparent}.border-zinc-500\/20{border-color:#71717a33}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-amber-50\/50{background-color:#fffbeb80}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity))}.bg-background{background-color:hsl(var(--background))}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-50\/50{background-color:#ecfdf580}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-primary\/30{background-color:hsl(var(--primary) / .3)}.bg-red-50\/50{background-color:#fef2f280}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sky-50\/50{background-color:#f0f9ff80}.bg-transparent{background-color:transparent}.bg-zinc-50\/50{background-color:#fafafa80}.fill-current{fill:currentColor}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pl-12{padding-left:3rem}.pl-2{padding-left:.5rem}.pl-3{padding-left:.75rem}.pl-8{padding-left:2rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-base{font-size:1rem;line-height:1.5rem}.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-normal{font-weight:400}.font-semibold{font-weight:600}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity))}.text-foreground{color:hsl(var(--foreground))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/80{color:hsl(var(--muted-foreground) / .8)}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity))}.text-rose-600{--tw-text-opacity: 1;color:rgb(225 29 72 / var(--tw-text-opacity))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.text-zinc-900{--tw-text-opacity: 1;color:rgb(24 24 27 / var(--tw-text-opacity))}.underline-offset-4{text-underline-offset:4px}.caret-transparent{caret-color:transparent}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.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)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 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-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--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(0px + 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-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-muted-foreground{--tw-ring-color: hsl(var(--muted-foreground))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.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}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;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))}.after\:bg-border:after{content:var(--tw-content);background-color:hsl(var(--border))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-amber-600\/80:hover{background-color:#d97706cc}.hover\:bg-amber-600\/90:hover{background-color:#d97706e6}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-transparent:hover{background-color:transparent}.hover\:stroke-destructive:hover{stroke:hsl(var(--destructive))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.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-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--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(1px + 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-visible\:ring-2:focus-visible{--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-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-default:disabled{cursor:default}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;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))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;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))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;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))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;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))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;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))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;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))}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-muted[data-state=open],.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-slate-400[data-state=unchecked]{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 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)}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;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))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;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))}.dark\:-rotate-90:is(.dark *){--tw-rotate: -90deg;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))}.dark\:rotate-0:is(.dark *){--tw-rotate: 0deg;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))}.dark\:scale-0:is(.dark *){--tw-scale-x: 0;--tw-scale-y: 0;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))}.dark\:scale-100:is(.dark *){--tw-scale-x: 1;--tw-scale-y: 1;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))}.dark\:border-amber-500\/30:is(.dark *){border-color:#f59e0b4d}.dark\:border-emerald-500\/30:is(.dark *){border-color:#10b9814d}.dark\:border-red-500\/30:is(.dark *){border-color:#ef44444d}.dark\:border-sky-500\/30:is(.dark *){border-color:#0ea5e94d}.dark\:border-zinc-500\/30:is(.dark *){border-color:#71717a4d}.dark\:bg-amber-500\/10:is(.dark *){background-color:#f59e0b1a}.dark\:bg-emerald-500\/10:is(.dark *){background-color:#10b9811a}.dark\:bg-red-500\/10:is(.dark *){background-color:#ef44441a}.dark\:bg-sky-500\/10:is(.dark *){background-color:#0ea5e91a}.dark\:bg-zinc-500\/10:is(.dark *){background-color:#71717a1a}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity))}.dark\:text-emerald-200:is(.dark *){--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}.dark\:text-sky-200:is(.dark *){--tw-text-opacity: 1;color:rgb(186 230 253 / var(--tw-text-opacity))}.dark\:text-zinc-300:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:m-4{margin:1rem}.sm\:inline{display:inline}.sm\:max-h-\[600px\]{max-height:600px}.sm\:max-w-\[650px\]{max-width:650px}.sm\:max-w-\[740px\]{max-width:740px}.sm\:max-w-\[950px\]{max-width:950px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[10rem_1fr_10rem\]{grid-template-columns:10rem 1fr 10rem}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:w-64{width:16rem}.md\:w-full{width:100%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:gap-8{gap:2rem}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>\*\]\:p-4>*{padding:1rem}.\[\&\>\*\]\:px-4>*{padding-left:1rem;padding-right:1rem}.\[\&\>\*\]\:py-2>*{padding-top:.5rem;padding-bottom:.5rem}.\[\&\>div\[style\]\]\:\!block>div[style]{display:block!important}.\[\&\>div\[style\]\]\:h-full>div[style]{height:100%}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;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))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:fill-rose-600>svg{fill:#e11d48}.\[\&\>svg\]\:text-amber-500>svg{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-emerald-600>svg{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-red-600>svg{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-sky-500>svg{--tw-text-opacity: 1;color:rgb(14 165 233 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-zinc-400>svg{--tw-text-opacity: 1;color:rgb(161 161 170 / var(--tw-text-opacity))}.hover\:\[\&\>svg\]\:fill-rose-700>svg:hover{fill:#be123c}.dark\:\[\&\>svg\]\:text-emerald-400\/80>svg:is(.dark *){color:#34d399cc}.dark\:\[\&\>svg\]\:text-red-400\/80>svg:is(.dark *){color:#f87171cc}.dark\:\[\&\>svg\]\:text-zinc-300>svg:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;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))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_strong\]\:text-foreground strong{color:hsl(var(--foreground))}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: #e74c3c;--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient( to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55 );--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width : 480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}}.Toastify__toast{--y: 0;position:relative;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px #0000001a;display:flex;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;flex:1 1 auto;padding:6px;display:flex;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;flex:1}.Toastify__toast-icon{margin-inline-end:10px;width:20px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width : 480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.tabs-chat{background-color:transparent;width:100%;border-radius:0}.chat-item{display:flex;padding:10px;cursor:pointer;background-color:hsl(var(--background))}.chat-item:hover,.chat-item.active{background-color:#2f2f2f}.bubble{border-radius:16px;padding:12px;word-wrap:break-word}.bubble-right .bubble{background-color:#0a0a0a;text-align:right;max-width:100%}.bubble-left .bubble{background-color:#1b1b1b;max-width:100%}.bubble-right{align-self:flex-end;display:flex;justify-content:flex-end;width:80%}.bubble-left{align-self:flex-start;display:flex;justify-content:flex-start;width:80%}.input-message textarea{background-color:#2f2f2f;padding-left:48px}.input-message textarea:focus{outline:none;border:none;box-shadow:none}.message-container{flex:1;overflow-y:auto;max-height:calc(100vh - 110px);padding-top:50px} diff --git a/manager/dist/assets/index-D-oOjDYe.js b/manager/dist/assets/index-D-oOjDYe.js new file mode 100644 index 00000000..25cc0b12 --- /dev/null +++ b/manager/dist/assets/index-D-oOjDYe.js @@ -0,0 +1,381 @@ +var Yw=e=>{throw TypeError(e)};var sD=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var lm=(e,t,n)=>t.has(e)||Yw("Cannot "+n);var N=(e,t,n)=>(lm(e,t,"read from private field"),n?n.call(e):t.get(e)),De=(e,t,n)=>t.has(e)?Yw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),we=(e,t,n,r)=>(lm(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Ye=(e,t,n)=>(lm(e,t,"access private method"),n);var uf=(e,t,n,r)=>({set _(s){we(e,t,s,n)},get _(){return N(e,t,r)}});var Ooe=sD((fo,po)=>{function DE(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();function Rb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var AE={exports:{}},Ig={},FE={exports:{}},it={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var zd=Symbol.for("react.element"),oD=Symbol.for("react.portal"),aD=Symbol.for("react.fragment"),iD=Symbol.for("react.strict_mode"),lD=Symbol.for("react.profiler"),cD=Symbol.for("react.provider"),uD=Symbol.for("react.context"),dD=Symbol.for("react.forward_ref"),fD=Symbol.for("react.suspense"),pD=Symbol.for("react.memo"),gD=Symbol.for("react.lazy"),Xw=Symbol.iterator;function hD(e){return e===null||typeof e!="object"?null:(e=Xw&&e[Xw]||e["@@iterator"],typeof e=="function"?e:null)}var LE={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},$E=Object.assign,BE={};function bc(e,t,n){this.props=e,this.context=t,this.refs=BE,this.updater=n||LE}bc.prototype.isReactComponent={};bc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};bc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function zE(){}zE.prototype=bc.prototype;function Ob(e,t,n){this.props=e,this.context=t,this.refs=BE,this.updater=n||LE}var Ib=Ob.prototype=new zE;Ib.constructor=Ob;$E(Ib,bc.prototype);Ib.isPureReactComponent=!0;var eS=Array.isArray,UE=Object.prototype.hasOwnProperty,Db={current:null},VE={key:!0,ref:!0,__self:!0,__source:!0};function HE(e,t,n){var r,s={},o=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(o=""+t.key),t)UE.call(t,r)&&!VE.hasOwnProperty(r)&&(s[r]=t[r]);var c=arguments.length-2;if(c===1)s.children=n;else if(1{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},rc=typeof window>"u"||"Deno"in globalThis;function Dr(){}function jD(e,t){return typeof e=="function"?e(t):e}function Nv(e){return typeof e=="number"&&e>=0&&e!==1/0}function WE(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Pl(e,t){return typeof e=="function"?e(t):e}function Xr(e,t){return typeof e=="function"?e(t):e}function nS(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Fb(a,t.options))return!1}else if(!zu(t.queryKey,a))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||o&&!o(t))}function rS(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(ki(t.options.mutationKey)!==ki(o))return!1}else if(!zu(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Fb(e,t){return((t==null?void 0:t.queryKeyHashFn)||ki)(e)}function ki(e){return JSON.stringify(e,(t,n)=>_v(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function zu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!zu(e[n],t[n])):!1}function GE(e,t){if(e===t)return e;const n=sS(e)&&sS(t);if(n||_v(e)&&_v(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),a=o.length,c=n?[]:{};let u=0;for(let i=0;i{setTimeout(t,e)})}function Pv(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?GE(e,t):t}function MD(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function ND(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var JE=Symbol();function QE(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===JE?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var ui,Qo,Hl,kE,_D=(kE=class extends xc{constructor(){super();De(this,ui);De(this,Qo);De(this,Hl);we(this,Hl,t=>{if(!rc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){N(this,Qo)||this.setEventListener(N(this,Hl))}onUnsubscribe(){var t;this.hasListeners()||((t=N(this,Qo))==null||t.call(this),we(this,Qo,void 0))}setEventListener(t){var n;we(this,Hl,t),(n=N(this,Qo))==null||n.call(this),we(this,Qo,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){N(this,ui)!==t&&(we(this,ui,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof N(this,ui)=="boolean"?N(this,ui):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ui=new WeakMap,Qo=new WeakMap,Hl=new WeakMap,kE),Lb=new _D,Kl,Zo,ql,jE,PD=(jE=class extends xc{constructor(){super();De(this,Kl,!0);De(this,Zo);De(this,ql);we(this,ql,t=>{if(!rc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){N(this,Zo)||this.setEventListener(N(this,ql))}onUnsubscribe(){var t;this.hasListeners()||((t=N(this,Zo))==null||t.call(this),we(this,Zo,void 0))}setEventListener(t){var n;we(this,ql,t),(n=N(this,Zo))==null||n.call(this),we(this,Zo,t(this.setOnline.bind(this)))}setOnline(t){N(this,Kl)!==t&&(we(this,Kl,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return N(this,Kl)}},Kl=new WeakMap,Zo=new WeakMap,ql=new WeakMap,jE),Tp=new PD;function RD(e){return Math.min(1e3*2**e,3e4)}function ZE(e){return(e??"online")==="online"?Tp.isOnline():!0}var YE=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function um(e){return e instanceof YE}function XE(e){let t=!1,n=0,r=!1,s,o,a;const c=new Promise((b,y)=>{o=b,a=y}),u=b=>{var y;r||(h(new YE(b)),(y=e.abort)==null||y.call(e))},i=()=>{t=!0},d=()=>{t=!1},p=()=>Lb.isFocused()&&(e.networkMode==="always"||Tp.isOnline())&&e.canRun(),f=()=>ZE(e.networkMode)&&e.canRun(),g=b=>{var y;r||(r=!0,(y=e.onSuccess)==null||y.call(e,b),s==null||s(),o(b))},h=b=>{var y;r||(r=!0,(y=e.onError)==null||y.call(e,b),s==null||s(),a(b))},m=()=>new Promise(b=>{var y;s=w=>{(r||p())&&b(w)},(y=e.onPause)==null||y.call(e)}).then(()=>{var b;s=void 0,r||(b=e.onContinue)==null||b.call(e)}),x=()=>{if(r)return;let b;const y=n===0?e.initialPromise:void 0;try{b=y??e.fn()}catch(w){b=Promise.reject(w)}Promise.resolve(b).then(g).catch(w=>{var j;if(r)return;const S=e.retry??(rc?0:3),E=e.retryDelay??RD,C=typeof E=="function"?E(n,w):E,T=S===!0||typeof S=="number"&&np()?void 0:m()).then(()=>{t?h(w):x()})})};return{promise:c,cancel:u,continue:()=>(s==null||s(),c),cancelRetry:i,continueRetry:d,canStart:f,start:()=>(f()?x():m().then(x),c)}}function OD(){let e=[],t=0,n=f=>{f()},r=f=>{f()},s=f=>setTimeout(f,0);const o=f=>{s=f},a=f=>{let g;t++;try{g=f()}finally{t--,t||i()}return g},c=f=>{t?e.push(f):s(()=>{n(f)})},u=f=>(...g)=>{c(()=>{f(...g)})},i=()=>{const f=e;e=[],f.length&&s(()=>{r(()=>{f.forEach(g=>{n(g)})})})};return{batch:a,batchCalls:u,schedule:c,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:o}}var dn=OD(),di,TE,ek=(TE=class{constructor(){De(this,di)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Nv(this.gcTime)&&we(this,di,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(rc?1/0:5*60*1e3))}clearGcTimeout(){N(this,di)&&(clearTimeout(N(this,di)),we(this,di,void 0))}},di=new WeakMap,TE),Wl,Gl,Ir,Dn,Fd,fi,Qr,eo,ME,ID=(ME=class extends ek{constructor(t){super();De(this,Qr);De(this,Wl);De(this,Gl);De(this,Ir);De(this,Dn);De(this,Fd);De(this,fi);we(this,fi,!1),we(this,Fd,t.defaultOptions),this.setOptions(t.options),this.observers=[],we(this,Ir,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,we(this,Wl,DD(this.options)),this.state=t.state??N(this,Wl),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=N(this,Dn))==null?void 0:t.promise}setOptions(t){this.options={...N(this,Fd),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&N(this,Ir).remove(this)}setData(t,n){const r=Pv(this.state.data,t,this.options);return Ye(this,Qr,eo).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Ye(this,Qr,eo).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=N(this,Dn))==null?void 0:r.promise;return(s=N(this,Dn))==null||s.cancel(t),n?n.then(Dr).catch(Dr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(N(this,Wl))}isActive(){return this.observers.some(t=>Xr(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!WE(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=N(this,Dn))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=N(this,Dn))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),N(this,Ir).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(N(this,Dn)&&(N(this,fi)?N(this,Dn).cancel({revert:!0}):N(this,Dn).cancelRetry()),this.scheduleGc()),N(this,Ir).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ye(this,Qr,eo).call(this,{type:"invalidate"})}fetch(t,n){var u,i,d;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(N(this,Dn))return N(this,Dn).continueRetry(),N(this,Dn).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,s=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(we(this,fi,!0),r.signal)})},o=()=>{const p=QE(this.options,n),f={queryKey:this.queryKey,meta:this.meta};return s(f),we(this,fi,!1),this.options.persister?this.options.persister(p,f,this):p(f)},a={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:o};s(a),(u=this.options.behavior)==null||u.onFetch(a,this),we(this,Gl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((i=a.fetchOptions)==null?void 0:i.meta))&&Ye(this,Qr,eo).call(this,{type:"fetch",meta:(d=a.fetchOptions)==null?void 0:d.meta});const c=p=>{var f,g,h,m;um(p)&&p.silent||Ye(this,Qr,eo).call(this,{type:"error",error:p}),um(p)||((g=(f=N(this,Ir).config).onError)==null||g.call(f,p,this),(m=(h=N(this,Ir).config).onSettled)==null||m.call(h,this.state.data,p,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return we(this,Dn,XE({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,g,h,m;if(p===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(x){c(x);return}(g=(f=N(this,Ir).config).onSuccess)==null||g.call(f,p,this),(m=(h=N(this,Ir).config).onSettled)==null||m.call(h,p,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:c,onFail:(p,f)=>{Ye(this,Qr,eo).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Ye(this,Qr,eo).call(this,{type:"pause"})},onContinue:()=>{Ye(this,Qr,eo).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),N(this,Dn).start()}},Wl=new WeakMap,Gl=new WeakMap,Ir=new WeakMap,Dn=new WeakMap,Fd=new WeakMap,fi=new WeakMap,Qr=new WeakSet,eo=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...tk(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=t.error;return um(s)&&s.revert&&N(this,Gl)?{...N(this,Gl),fetchStatus:"idle"}:{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),dn.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),N(this,Ir).notify({query:this,type:"updated",action:t})})},ME);function tk(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ZE(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function DD(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var js,NE,AD=(NE=class extends xc{constructor(t={}){super();De(this,js);this.config=t,we(this,js,new Map)}build(t,n,r){const s=n.queryKey,o=n.queryHash??Fb(s,n);let a=this.get(o);return a||(a=new ID({cache:this,queryKey:s,queryHash:o,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){N(this,js).has(t.queryHash)||(N(this,js).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=N(this,js).get(t.queryHash);n&&(t.destroy(),n===t&&N(this,js).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){dn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return N(this,js).get(t)}getAll(){return[...N(this,js).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>nS(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>nS(t,r)):n}notify(t){dn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){dn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){dn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},js=new WeakMap,NE),Ts,Un,pi,Ms,zo,_E,FD=(_E=class extends ek{constructor(t){super();De(this,Ms);De(this,Ts);De(this,Un);De(this,pi);this.mutationId=t.mutationId,we(this,Un,t.mutationCache),we(this,Ts,[]),this.state=t.state||nk(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){N(this,Ts).includes(t)||(N(this,Ts).push(t),this.clearGcTimeout(),N(this,Un).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){we(this,Ts,N(this,Ts).filter(n=>n!==t)),this.scheduleGc(),N(this,Un).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){N(this,Ts).length||(this.state.status==="pending"?this.scheduleGc():N(this,Un).remove(this))}continue(){var t;return((t=N(this,pi))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,a,c,u,i,d,p,f,g,h,m,x,b,y,w,S,E,C,T;we(this,pi,XE({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(j,_)=>{Ye(this,Ms,zo).call(this,{type:"failed",failureCount:j,error:_})},onPause:()=>{Ye(this,Ms,zo).call(this,{type:"pause"})},onContinue:()=>{Ye(this,Ms,zo).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>N(this,Un).canRun(this)}));const n=this.state.status==="pending",r=!N(this,pi).canStart();try{if(!n){Ye(this,Ms,zo).call(this,{type:"pending",variables:t,isPaused:r}),await((o=(s=N(this,Un).config).onMutate)==null?void 0:o.call(s,t,this));const _=await((c=(a=this.options).onMutate)==null?void 0:c.call(a,t));_!==this.state.context&&Ye(this,Ms,zo).call(this,{type:"pending",context:_,variables:t,isPaused:r})}const j=await N(this,pi).start();return await((i=(u=N(this,Un).config).onSuccess)==null?void 0:i.call(u,j,t,this.state.context,this)),await((p=(d=this.options).onSuccess)==null?void 0:p.call(d,j,t,this.state.context)),await((g=(f=N(this,Un).config).onSettled)==null?void 0:g.call(f,j,null,this.state.variables,this.state.context,this)),await((m=(h=this.options).onSettled)==null?void 0:m.call(h,j,null,t,this.state.context)),Ye(this,Ms,zo).call(this,{type:"success",data:j}),j}catch(j){try{throw await((b=(x=N(this,Un).config).onError)==null?void 0:b.call(x,j,t,this.state.context,this)),await((w=(y=this.options).onError)==null?void 0:w.call(y,j,t,this.state.context)),await((E=(S=N(this,Un).config).onSettled)==null?void 0:E.call(S,void 0,j,this.state.variables,this.state.context,this)),await((T=(C=this.options).onSettled)==null?void 0:T.call(C,void 0,j,t,this.state.context)),j}finally{Ye(this,Ms,zo).call(this,{type:"error",error:j})}}finally{N(this,Un).runNext(this)}}},Ts=new WeakMap,Un=new WeakMap,pi=new WeakMap,Ms=new WeakSet,zo=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),dn.batch(()=>{N(this,Ts).forEach(r=>{r.onMutationUpdate(t)}),N(this,Un).notify({mutation:this,type:"updated",action:t})})},_E);function nk(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var fr,Ld,PE,LD=(PE=class extends xc{constructor(t={}){super();De(this,fr);De(this,Ld);this.config=t,we(this,fr,new Map),we(this,Ld,Date.now())}build(t,n,r){const s=new FD({mutationCache:this,mutationId:++uf(this,Ld)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){const n=ff(t),r=N(this,fr).get(n)??[];r.push(t),N(this,fr).set(n,r),this.notify({type:"added",mutation:t})}remove(t){var r;const n=ff(t);if(N(this,fr).has(n)){const s=(r=N(this,fr).get(n))==null?void 0:r.filter(o=>o!==t);s&&(s.length===0?N(this,fr).delete(n):N(this,fr).set(n,s))}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=(r=N(this,fr).get(ff(t)))==null?void 0:r.find(s=>s.state.status==="pending");return!n||n===t}runNext(t){var r;const n=(r=N(this,fr).get(ff(t)))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}clear(){dn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}getAll(){return[...N(this,fr).values()].flat()}find(t){const n={exact:!0,...t};return this.getAll().find(r=>rS(n,r))}findAll(t={}){return this.getAll().filter(n=>rS(t,n))}notify(t){dn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return dn.batch(()=>Promise.all(t.map(n=>n.continue().catch(Dr))))}},fr=new WeakMap,Ld=new WeakMap,PE);function ff(e){var t;return((t=e.options.scope)==null?void 0:t.id)??String(e.mutationId)}function $D(e){return{onFetch:(t,n)=>{const r=async()=>{var h,m,x,b,y;const s=t.options,o=(x=(m=(h=t.fetchOptions)==null?void 0:h.meta)==null?void 0:m.fetchMore)==null?void 0:x.direction,a=((b=t.state.data)==null?void 0:b.pages)||[],c=((y=t.state.data)==null?void 0:y.pageParams)||[],u={pages:[],pageParams:[]};let i=!1;const d=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?i=!0:t.signal.addEventListener("abort",()=>{i=!0}),t.signal)})},p=QE(t.options,t.fetchOptions),f=async(w,S,E)=>{if(i)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const C={queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};d(C);const T=await p(C),{maxPages:j}=t.options,_=E?ND:MD;return{pages:_(w.pages,T,j),pageParams:_(w.pageParams,S,j)}};let g;if(o&&a.length){const w=o==="backward",S=w?BD:aS,E={pages:a,pageParams:c},C=S(s,E);g=await f(E,C,w)}else{g=await f(u,c[0]??s.initialPageParam);const w=e??a.length;for(let S=1;S{var s,o;return(o=(s=t.options).persister)==null?void 0:o.call(s,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function aS(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function BD(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Qt,Yo,Xo,Jl,Ql,ea,Zl,Yl,RE,zD=(RE=class{constructor(e={}){De(this,Qt);De(this,Yo);De(this,Xo);De(this,Jl);De(this,Ql);De(this,ea);De(this,Zl);De(this,Yl);we(this,Qt,e.queryCache||new AD),we(this,Yo,e.mutationCache||new LD),we(this,Xo,e.defaultOptions||{}),we(this,Jl,new Map),we(this,Ql,new Map),we(this,ea,0)}mount(){uf(this,ea)._++,N(this,ea)===1&&(we(this,Zl,Lb.subscribe(async e=>{e&&(await this.resumePausedMutations(),N(this,Qt).onFocus())})),we(this,Yl,Tp.subscribe(async e=>{e&&(await this.resumePausedMutations(),N(this,Qt).onOnline())})))}unmount(){var e,t;uf(this,ea)._--,N(this,ea)===0&&((e=N(this,Zl))==null||e.call(this),we(this,Zl,void 0),(t=N(this,Yl))==null||t.call(this),we(this,Yl,void 0))}isFetching(e){return N(this,Qt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return N(this,Yo).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=N(this,Qt).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);if(t===void 0)return this.fetchQuery(e);{const n=this.defaultQueryOptions(e),r=N(this,Qt).build(this,n);return e.revalidateIfStale&&r.isStaleByTime(Pl(n.staleTime,r))&&this.prefetchQuery(n),Promise.resolve(t)}}getQueriesData(e){return N(this,Qt).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=N(this,Qt).get(r.queryHash),o=s==null?void 0:s.state.data,a=jD(t,o);if(a!==void 0)return N(this,Qt).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return dn.batch(()=>N(this,Qt).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=N(this,Qt).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=N(this,Qt);dn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=N(this,Qt),r={type:"active",...e};return dn.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=dn.batch(()=>N(this,Qt).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Dr).catch(Dr)}invalidateQueries(e={},t={}){return dn.batch(()=>{if(N(this,Qt).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=dn.batch(()=>N(this,Qt).findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Dr)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Dr)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=N(this,Qt).build(this,t);return n.isStaleByTime(Pl(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Dr).catch(Dr)}fetchInfiniteQuery(e){return e.behavior=$D(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Dr).catch(Dr)}resumePausedMutations(){return Tp.isOnline()?N(this,Yo).resumePausedMutations():Promise.resolve()}getQueryCache(){return N(this,Qt)}getMutationCache(){return N(this,Yo)}getDefaultOptions(){return N(this,Xo)}setDefaultOptions(e){we(this,Xo,e)}setQueryDefaults(e,t){N(this,Jl).set(ki(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...N(this,Jl).values()];let n={};return t.forEach(r=>{zu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){N(this,Ql).set(ki(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...N(this,Ql).values()];let n={};return t.forEach(r=>{zu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...N(this,Xo).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fb(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.enabled!==!0&&t.queryFn===JE&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...N(this,Xo).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){N(this,Qt).clear(),N(this,Yo).clear()}},Qt=new WeakMap,Yo=new WeakMap,Xo=new WeakMap,Jl=new WeakMap,Ql=new WeakMap,ea=new WeakMap,Zl=new WeakMap,Yl=new WeakMap,RE),er,lt,$d,Vn,gi,Xl,Ns,Bd,ec,tc,hi,mi,ta,nc,wt,du,Rv,Ov,Iv,Dv,Av,Fv,Lv,rk,OE,UD=(OE=class extends xc{constructor(t,n){super();De(this,wt);De(this,er);De(this,lt);De(this,$d);De(this,Vn);De(this,gi);De(this,Xl);De(this,Ns);De(this,Bd);De(this,ec);De(this,tc);De(this,hi);De(this,mi);De(this,ta);De(this,nc,new Set);this.options=n,we(this,er,t),we(this,Ns,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(N(this,lt).addObserver(this),iS(N(this,lt),this.options)?Ye(this,wt,du).call(this):this.updateResult(),Ye(this,wt,Dv).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return $v(N(this,lt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return $v(N(this,lt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ye(this,wt,Av).call(this),Ye(this,wt,Fv).call(this),N(this,lt).removeObserver(this)}setOptions(t,n){const r=this.options,s=N(this,lt);if(this.options=N(this,er).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Xr(this.options.enabled,N(this,lt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ye(this,wt,Lv).call(this),N(this,lt).setOptions(this.options),r._defaulted&&!jp(this.options,r)&&N(this,er).getQueryCache().notify({type:"observerOptionsUpdated",query:N(this,lt),observer:this});const o=this.hasListeners();o&&lS(N(this,lt),s,this.options,r)&&Ye(this,wt,du).call(this),this.updateResult(n),o&&(N(this,lt)!==s||Xr(this.options.enabled,N(this,lt))!==Xr(r.enabled,N(this,lt))||Pl(this.options.staleTime,N(this,lt))!==Pl(r.staleTime,N(this,lt)))&&Ye(this,wt,Rv).call(this);const a=Ye(this,wt,Ov).call(this);o&&(N(this,lt)!==s||Xr(this.options.enabled,N(this,lt))!==Xr(r.enabled,N(this,lt))||a!==N(this,ta))&&Ye(this,wt,Iv).call(this,a)}getOptimisticResult(t){const n=N(this,er).getQueryCache().build(N(this,er),t),r=this.createResult(n,t);return HD(this,r)&&(we(this,Vn,r),we(this,Xl,this.options),we(this,gi,N(this,lt).state)),r}getCurrentResult(){return N(this,Vn)}trackResult(t,n){const r={};return Object.keys(t).forEach(s=>{Object.defineProperty(r,s,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(s),n==null||n(s),t[s])})}),r}trackProp(t){N(this,nc).add(t)}getCurrentQuery(){return N(this,lt)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=N(this,er).defaultQueryOptions(t),r=N(this,er).getQueryCache().build(N(this,er),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Ye(this,wt,du).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),N(this,Vn)))}createResult(t,n){var T;const r=N(this,lt),s=this.options,o=N(this,Vn),a=N(this,gi),c=N(this,Xl),i=t!==r?t.state:N(this,$d),{state:d}=t;let p={...d},f=!1,g;if(n._optimisticResults){const j=this.hasListeners(),_=!j&&iS(t,n),O=j&&lS(t,r,n,s);(_||O)&&(p={...p,...tk(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:h,errorUpdatedAt:m,status:x}=p;if(n.select&&p.data!==void 0)if(o&&p.data===(a==null?void 0:a.data)&&n.select===N(this,Bd))g=N(this,ec);else try{we(this,Bd,n.select),g=n.select(p.data),g=Pv(o==null?void 0:o.data,g,n),we(this,ec,g),we(this,Ns,null)}catch(j){we(this,Ns,j)}else g=p.data;if(n.placeholderData!==void 0&&g===void 0&&x==="pending"){let j;if(o!=null&&o.isPlaceholderData&&n.placeholderData===(c==null?void 0:c.placeholderData))j=o.data;else if(j=typeof n.placeholderData=="function"?n.placeholderData((T=N(this,tc))==null?void 0:T.state.data,N(this,tc)):n.placeholderData,n.select&&j!==void 0)try{j=n.select(j),we(this,Ns,null)}catch(_){we(this,Ns,_)}j!==void 0&&(x="success",g=Pv(o==null?void 0:o.data,j,n),f=!0)}N(this,Ns)&&(h=N(this,Ns),g=N(this,ec),m=Date.now(),x="error");const b=p.fetchStatus==="fetching",y=x==="pending",w=x==="error",S=y&&b,E=g!==void 0;return{status:x,fetchStatus:p.fetchStatus,isPending:y,isSuccess:x==="success",isError:w,isInitialLoading:S,isLoading:S,data:g,dataUpdatedAt:p.dataUpdatedAt,error:h,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>i.dataUpdateCount||p.errorUpdateCount>i.errorUpdateCount,isFetching:b,isRefetching:b&&!y,isLoadingError:w&&!E,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:w&&E,isStale:$b(t,n),refetch:this.refetch}}updateResult(t){const n=N(this,Vn),r=this.createResult(N(this,lt),this.options);if(we(this,gi,N(this,lt).state),we(this,Xl,this.options),N(this,gi).data!==void 0&&we(this,tc,N(this,lt)),jp(r,n))return;we(this,Vn,r);const s={},o=()=>{if(!n)return!0;const{notifyOnChangeProps:a}=this.options,c=typeof a=="function"?a():a;if(c==="all"||!c&&!N(this,nc).size)return!0;const u=new Set(c??N(this,nc));return this.options.throwOnError&&u.add("error"),Object.keys(N(this,Vn)).some(i=>{const d=i;return N(this,Vn)[d]!==n[d]&&u.has(d)})};(t==null?void 0:t.listeners)!==!1&&o()&&(s.listeners=!0),Ye(this,wt,rk).call(this,{...s,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ye(this,wt,Dv).call(this)}},er=new WeakMap,lt=new WeakMap,$d=new WeakMap,Vn=new WeakMap,gi=new WeakMap,Xl=new WeakMap,Ns=new WeakMap,Bd=new WeakMap,ec=new WeakMap,tc=new WeakMap,hi=new WeakMap,mi=new WeakMap,ta=new WeakMap,nc=new WeakMap,wt=new WeakSet,du=function(t){Ye(this,wt,Lv).call(this);let n=N(this,lt).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Dr)),n},Rv=function(){Ye(this,wt,Av).call(this);const t=Pl(this.options.staleTime,N(this,lt));if(rc||N(this,Vn).isStale||!Nv(t))return;const r=WE(N(this,Vn).dataUpdatedAt,t)+1;we(this,hi,setTimeout(()=>{N(this,Vn).isStale||this.updateResult()},r))},Ov=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(N(this,lt)):this.options.refetchInterval)??!1},Iv=function(t){Ye(this,wt,Fv).call(this),we(this,ta,t),!(rc||Xr(this.options.enabled,N(this,lt))===!1||!Nv(N(this,ta))||N(this,ta)===0)&&we(this,mi,setInterval(()=>{(this.options.refetchIntervalInBackground||Lb.isFocused())&&Ye(this,wt,du).call(this)},N(this,ta)))},Dv=function(){Ye(this,wt,Rv).call(this),Ye(this,wt,Iv).call(this,Ye(this,wt,Ov).call(this))},Av=function(){N(this,hi)&&(clearTimeout(N(this,hi)),we(this,hi,void 0))},Fv=function(){N(this,mi)&&(clearInterval(N(this,mi)),we(this,mi,void 0))},Lv=function(){const t=N(this,er).getQueryCache().build(N(this,er),this.options);if(t===N(this,lt))return;const n=N(this,lt);we(this,lt,t),we(this,$d,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},rk=function(t){dn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(N(this,Vn))}),N(this,er).getQueryCache().notify({query:N(this,lt),type:"observerResultsUpdated"})})},OE);function VD(e,t){return Xr(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function iS(e,t){return VD(e,t)||e.state.data!==void 0&&$v(e,t,t.refetchOnMount)}function $v(e,t,n){if(Xr(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&$b(e,t)}return!1}function lS(e,t,n,r){return(e!==t||Xr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&$b(e,n)}function $b(e,t){return Xr(t.enabled,e)!==!1&&e.isStaleByTime(Pl(t.staleTime,e))}function HD(e,t){return!jp(e.getCurrentResult(),t)}var na,ra,tr,ao,mo,ep,Bv,IE,KD=(IE=class extends xc{constructor(n,r){super();De(this,mo);De(this,na);De(this,ra);De(this,tr);De(this,ao);we(this,na,n),this.setOptions(r),this.bindMethods(),Ye(this,mo,ep).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var s;const r=this.options;this.options=N(this,na).defaultMutationOptions(n),jp(this.options,r)||N(this,na).getMutationCache().notify({type:"observerOptionsUpdated",mutation:N(this,tr),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&ki(r.mutationKey)!==ki(this.options.mutationKey)?this.reset():((s=N(this,tr))==null?void 0:s.state.status)==="pending"&&N(this,tr).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=N(this,tr))==null||n.removeObserver(this)}onMutationUpdate(n){Ye(this,mo,ep).call(this),Ye(this,mo,Bv).call(this,n)}getCurrentResult(){return N(this,ra)}reset(){var n;(n=N(this,tr))==null||n.removeObserver(this),we(this,tr,void 0),Ye(this,mo,ep).call(this),Ye(this,mo,Bv).call(this)}mutate(n,r){var s;return we(this,ao,r),(s=N(this,tr))==null||s.removeObserver(this),we(this,tr,N(this,na).getMutationCache().build(N(this,na),this.options)),N(this,tr).addObserver(this),N(this,tr).execute(n)}},na=new WeakMap,ra=new WeakMap,tr=new WeakMap,ao=new WeakMap,mo=new WeakSet,ep=function(){var r;const n=((r=N(this,tr))==null?void 0:r.state)??nk();we(this,ra,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Bv=function(n){dn.batch(()=>{var r,s,o,a,c,u,i,d;if(N(this,ao)&&this.hasListeners()){const p=N(this,ra).variables,f=N(this,ra).context;(n==null?void 0:n.type)==="success"?((s=(r=N(this,ao)).onSuccess)==null||s.call(r,n.data,p,f),(a=(o=N(this,ao)).onSettled)==null||a.call(o,n.data,null,p,f)):(n==null?void 0:n.type)==="error"&&((u=(c=N(this,ao)).onError)==null||u.call(c,n.error,p,f),(d=(i=N(this,ao)).onSettled)==null||d.call(i,void 0,n.error,p,f))}this.listeners.forEach(p=>{p(N(this,ra))})})},IE),sk=v.createContext(void 0),Bb=e=>{const t=v.useContext(sk);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},qD=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),l.jsx(sk.Provider,{value:e,children:t})),ok=v.createContext(!1),WD=()=>v.useContext(ok);ok.Provider;function GD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var JD=v.createContext(GD()),QD=()=>v.useContext(JD);function ak(e,t){return typeof e=="function"?e(...t):!!e}function ZD(){}var YD=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},XD=e=>{v.useEffect(()=>{e.clearReset()},[e])},eA=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&ak(n,[e.error,r]),tA=e=>{e.suspense&&(typeof e.staleTime!="number"&&(e.staleTime=1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},nA=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,rA=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function sA(e,t,n){var i,d,p,f;const r=Bb(),s=WD(),o=QD(),a=r.defaultQueryOptions(e);(d=(i=r.getDefaultOptions().queries)==null?void 0:i._experimental_beforeQuery)==null||d.call(i,a),a._optimisticResults=s?"isRestoring":"optimistic",tA(a),YD(a,o),XD(o);const[c]=v.useState(()=>new t(r,a)),u=c.getOptimisticResult(a);if(v.useSyncExternalStore(v.useCallback(g=>{const h=s?()=>{}:c.subscribe(dn.batchCalls(g));return c.updateResult(),h},[c,s]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),v.useEffect(()=>{c.setOptions(a,{listeners:!1})},[a,c]),nA(a,u))throw rA(a,c,o);if(eA({result:u,errorResetBoundary:o,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash)}))throw u.error;return(f=(p=r.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,a,u),a.notifyOnChangeProps?u:c.trackResult(u)}function qe(e,t){return sA(e,UD)}function oA(e,t){const n=Bb(),[r]=v.useState(()=>new KD(n,e));v.useEffect(()=>{r.setOptions(e)},[r,e]);const s=v.useSyncExternalStore(v.useCallback(a=>r.subscribe(dn.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=v.useCallback((a,c)=>{r.mutate(a,c).catch(ZD)},[r]);if(s.error&&ak(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:o,mutateAsync:s.mutate}}var zv={},ik={exports:{}},jr={},lk={exports:{}},ck={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(e){function t(L,A){var X=L.length;L.push(A);e:for(;0>>1,H=L[fe];if(0>>1;fes(le,X))oes(Q,le)?(L[fe]=Q,L[oe]=X,fe=oe):(L[fe]=le,L[ne]=X,fe=ne);else if(oes(Q,X))L[fe]=Q,L[oe]=X,fe=oe;else break e}}return A}function s(L,A){var X=L.sortIndex-A.sortIndex;return X!==0?X:L.id-A.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,c=a.now();e.unstable_now=function(){return a.now()-c}}var u=[],i=[],d=1,p=null,f=3,g=!1,h=!1,m=!1,x=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(L){for(var A=n(i);A!==null;){if(A.callback===null)r(i);else if(A.startTime<=L)r(i),A.sortIndex=A.expirationTime,t(u,A);else break;A=n(i)}}function S(L){if(m=!1,w(L),!h)if(n(u)!==null)h=!0,ee(E);else{var A=n(i);A!==null&&J(S,A.startTime-L)}}function E(L,A){h=!1,m&&(m=!1,b(j),j=-1),g=!0;var X=f;try{for(w(A),p=n(u);p!==null&&(!(p.expirationTime>A)||L&&!K());){var fe=p.callback;if(typeof fe=="function"){p.callback=null,f=p.priorityLevel;var H=fe(p.expirationTime<=A);A=e.unstable_now(),typeof H=="function"?p.callback=H:p===n(u)&&r(u),w(A)}else r(u);p=n(u)}if(p!==null)var se=!0;else{var ne=n(i);ne!==null&&J(S,ne.startTime-A),se=!1}return se}finally{p=null,f=X,g=!1}}var C=!1,T=null,j=-1,_=5,O=-1;function K(){return!(e.unstable_now()-O<_)}function I(){if(T!==null){var L=e.unstable_now();O=L;var A=!0;try{A=T(!0,L)}finally{A?Y():(C=!1,T=null)}}else C=!1}var Y;if(typeof y=="function")Y=function(){y(I)};else if(typeof MessageChannel<"u"){var q=new MessageChannel,Z=q.port2;q.port1.onmessage=I,Y=function(){Z.postMessage(null)}}else Y=function(){x(I,0)};function ee(L){T=L,C||(C=!0,Y())}function J(L,A){j=x(function(){L(e.unstable_now())},A)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(L){L.callback=null},e.unstable_continueExecution=function(){h||g||(h=!0,ee(E))},e.unstable_forceFrameRate=function(L){0>L||125fe?(L.sortIndex=X,t(i,L),n(u)===null&&L===n(i)&&(m?(b(j),j=-1):m=!0,J(S,X-fe))):(L.sortIndex=H,t(u,L),h||g||(h=!0,ee(E))),L},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(L){var A=f;return function(){var X=f;f=A;try{return L.apply(this,arguments)}finally{f=X}}}})(ck);lk.exports=ck;var aA=lk.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var iA=v,Cr=aA;function te(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Uv=Object.prototype.hasOwnProperty,lA=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,cS={},uS={};function cA(e){return Uv.call(uS,e)?!0:Uv.call(cS,e)?!1:lA.test(e)?uS[e]=!0:(cS[e]=!0,!1)}function uA(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function dA(e,t,n,r){if(t===null||typeof t>"u"||uA(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Zn(e,t,n,r,s,o,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=a}var jn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){jn[e]=new Zn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];jn[t]=new Zn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){jn[e]=new Zn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){jn[e]=new Zn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){jn[e]=new Zn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){jn[e]=new Zn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){jn[e]=new Zn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){jn[e]=new Zn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){jn[e]=new Zn(e,5,!1,e.toLowerCase(),null,!1,!1)});var zb=/[\-:]([a-z])/g;function Ub(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(zb,Ub);jn[t]=new Zn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(zb,Ub);jn[t]=new Zn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(zb,Ub);jn[t]=new Zn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){jn[e]=new Zn(e,1,!1,e.toLowerCase(),null,!1,!1)});jn.xlinkHref=new Zn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){jn[e]=new Zn(e,1,!1,e.toLowerCase(),null,!0,!0)});function Vb(e,t,n,r){var s=jn.hasOwnProperty(t)?jn[t]:null;(s!==null?s.type!==0:r||!(2c||s[a]!==o[c]){var u=` +`+s[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=c);break}}}finally{fm=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?fu(e):""}function fA(e){switch(e.tag){case 5:return fu(e.type);case 16:return fu("Lazy");case 13:return fu("Suspense");case 19:return fu("SuspenseList");case 0:case 2:case 15:return e=pm(e.type,!1),e;case 11:return e=pm(e.type.render,!1),e;case 1:return e=pm(e.type,!0),e;default:return""}}function qv(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ml:return"Fragment";case hl:return"Portal";case Vv:return"Profiler";case Hb:return"StrictMode";case Hv:return"Suspense";case Kv:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case fk:return(e.displayName||"Context")+".Consumer";case dk:return(e._context.displayName||"Context")+".Provider";case Kb:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case qb:return t=e.displayName||null,t!==null?t:qv(e.type)||"Memo";case Ho:t=e._payload,e=e._init;try{return qv(e(t))}catch{}}return null}function pA(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return qv(t);case 8:return t===Hb?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ma(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function gk(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function gA(e){var t=gk(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function gf(e){e._valueTracker||(e._valueTracker=gA(e))}function hk(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=gk(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Mp(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Wv(e,t){var n=t.checked;return Gt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function fS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ma(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function mk(e,t){t=t.checked,t!=null&&Vb(e,"checked",t,!1)}function Gv(e,t){mk(e,t);var n=ma(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Jv(e,t.type,n):t.hasOwnProperty("defaultValue")&&Jv(e,t.type,ma(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function pS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Jv(e,t,n){(t!=="number"||Mp(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var pu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=hf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Vu(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},hA=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){hA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function xk(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function wk(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=xk(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var mA=Gt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Yv(e,t){if(t){if(mA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(te(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(te(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(te(61))}if(t.style!=null&&typeof t.style!="object")throw Error(te(62))}}function Xv(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ey=null;function Wb(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ty=null,Ol=null,Il=null;function mS(e){if(e=Hd(e)){if(typeof ty!="function")throw Error(te(280));var t=e.stateNode;t&&(t=Bg(t),ty(e.stateNode,e.type,t))}}function Sk(e){Ol?Il?Il.push(e):Il=[e]:Ol=e}function Ck(){if(Ol){var e=Ol,t=Il;if(Il=Ol=null,mS(e),t)for(e=0;e>>=0,e===0?32:31-(TA(e)/MA|0)|0}var mf=64,vf=4194304;function gu(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Rp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,a=n&268435455;if(a!==0){var c=a&~s;c!==0?r=gu(c):(o&=a,o!==0&&(r=gu(o)))}else a=n&~s,a!==0?r=gu(a):o!==0&&(r=gu(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,o=t&-t,s>=o||s===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ud(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ss(t),e[t]=n}function RA(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=ju),kS=" ",jS=!1;function Vk(e,t){switch(e){case"keyup":return aF.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var vl=!1;function lF(e,t){switch(e){case"compositionend":return Hk(t);case"keypress":return t.which!==32?null:(jS=!0,kS);case"textInput":return e=t.data,e===kS&&jS?null:e;default:return null}}function cF(e,t){if(vl)return e==="compositionend"||!tx&&Vk(e,t)?(e=zk(),np=Yb=sa=null,vl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=_S(n)}}function Gk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Gk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Jk(){for(var e=window,t=Mp();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Mp(e.document)}return t}function nx(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function yF(e){var t=Jk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Gk(n.ownerDocument.documentElement,n)){if(r!==null&&nx(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=PS(n,o);var a=PS(n,r);s&&a&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,yl=null,iy=null,Mu=null,ly=!1;function RS(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ly||yl==null||yl!==Mp(r)||(r=yl,"selectionStart"in r&&nx(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Mu&&Ju(Mu,r)||(Mu=r,r=Dp(iy,"onSelect"),0wl||(e.current=gy[wl],gy[wl]=null,wl--)}function Nt(e,t){wl++,gy[wl]=e.current,e.current=t}var va={},Ln=Na(va),or=Na(!1),ji=va;function oc(e,t){var n=e.type.contextTypes;if(!n)return va;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in n)s[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function ar(e){return e=e.childContextTypes,e!=null}function Fp(){At(or),At(Ln)}function $S(e,t,n){if(Ln.current!==va)throw Error(te(168));Nt(Ln,t),Nt(or,n)}function sj(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(te(108,pA(e)||"Unknown",s));return Gt({},n,r)}function Lp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||va,ji=Ln.current,Nt(Ln,e),Nt(or,or.current),!0}function BS(e,t,n){var r=e.stateNode;if(!r)throw Error(te(169));n?(e=sj(e,t,ji),r.__reactInternalMemoizedMergedChildContext=e,At(or),At(Ln),Nt(Ln,e)):At(or),Nt(or,n)}var oo=null,zg=!1,Tm=!1;function oj(e){oo===null?oo=[e]:oo.push(e)}function _F(e){zg=!0,oj(e)}function _a(){if(!Tm&&oo!==null){Tm=!0;var e=0,t=Ct;try{var n=oo;for(Ct=1;e>=a,s-=a,lo=1<<32-ss(t)+s|n<j?(_=T,T=null):_=T.sibling;var O=f(b,T,w[j],S);if(O===null){T===null&&(T=_);break}e&&T&&O.alternate===null&&t(b,T),y=o(O,y,j),C===null?E=O:C.sibling=O,C=O,T=_}if(j===w.length)return n(b,T),$t&&Ja(b,j),E;if(T===null){for(;jj?(_=T,T=null):_=T.sibling;var K=f(b,T,O.value,S);if(K===null){T===null&&(T=_);break}e&&T&&K.alternate===null&&t(b,T),y=o(K,y,j),C===null?E=K:C.sibling=K,C=K,T=_}if(O.done)return n(b,T),$t&&Ja(b,j),E;if(T===null){for(;!O.done;j++,O=w.next())O=p(b,O.value,S),O!==null&&(y=o(O,y,j),C===null?E=O:C.sibling=O,C=O);return $t&&Ja(b,j),E}for(T=r(b,T);!O.done;j++,O=w.next())O=g(T,b,j,O.value,S),O!==null&&(e&&O.alternate!==null&&T.delete(O.key===null?j:O.key),y=o(O,y,j),C===null?E=O:C.sibling=O,C=O);return e&&T.forEach(function(I){return t(b,I)}),$t&&Ja(b,j),E}function x(b,y,w,S){if(typeof w=="object"&&w!==null&&w.type===ml&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case pf:e:{for(var E=w.key,C=y;C!==null;){if(C.key===E){if(E=w.type,E===ml){if(C.tag===7){n(b,C.sibling),y=s(C,w.props.children),y.return=b,b=y;break e}}else if(C.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Ho&&VS(E)===C.type){n(b,C.sibling),y=s(C,w.props),y.ref=Gc(b,C,w),y.return=b,b=y;break e}n(b,C);break}else t(b,C);C=C.sibling}w.type===ml?(y=yi(w.props.children,b.mode,S,w.key),y.return=b,b=y):(S=up(w.type,w.key,w.props,null,b.mode,S),S.ref=Gc(b,y,w),S.return=b,b=S)}return a(b);case hl:e:{for(C=w.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){n(b,y.sibling),y=s(y,w.children||[]),y.return=b,b=y;break e}else{n(b,y);break}else t(b,y);y=y.sibling}y=Dm(w,b.mode,S),y.return=b,b=y}return a(b);case Ho:return C=w._init,x(b,y,C(w._payload),S)}if(pu(w))return h(b,y,w,S);if(Vc(w))return m(b,y,w,S);Ef(b,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(n(b,y.sibling),y=s(y,w),y.return=b,b=y):(n(b,y),y=Im(w,b.mode,S),y.return=b,b=y),a(b)):n(b,y)}return x}var ic=cj(!0),uj=cj(!1),zp=Na(null),Up=null,El=null,ax=null;function ix(){ax=El=Up=null}function lx(e){var t=zp.current;At(zp),e._currentValue=t}function vy(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Al(e,t){Up=e,ax=El=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(sr=!0),e.firstContext=null)}function Hr(e){var t=e._currentValue;if(ax!==e)if(e={context:e,memoizedValue:t,next:null},El===null){if(Up===null)throw Error(te(308));El=e,Up.dependencies={lanes:0,firstContext:e}}else El=El.next=e;return t}var ei=null;function cx(e){ei===null?ei=[e]:ei.push(e)}function dj(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,cx(t)):(n.next=s.next,s.next=n),t.interleaved=n,bo(e,r)}function bo(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Ko=!1;function ux(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function fj(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function go(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function fa(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,gt&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,bo(e,n)}return s=r.interleaved,s===null?(t.next=t,cx(r)):(t.next=s.next,s.next=t),r.interleaved=t,bo(e,n)}function sp(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Jb(e,n)}}function HS(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?s=o=a:o=o.next=a,n=n.next}while(n!==null);o===null?s=o=t:o=o.next=t}else s=o=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Vp(e,t,n,r){var s=e.updateQueue;Ko=!1;var o=s.firstBaseUpdate,a=s.lastBaseUpdate,c=s.shared.pending;if(c!==null){s.shared.pending=null;var u=c,i=u.next;u.next=null,a===null?o=i:a.next=i,a=u;var d=e.alternate;d!==null&&(d=d.updateQueue,c=d.lastBaseUpdate,c!==a&&(c===null?d.firstBaseUpdate=i:c.next=i,d.lastBaseUpdate=u))}if(o!==null){var p=s.baseState;a=0,d=i=u=null,c=o;do{var f=c.lane,g=c.eventTime;if((r&f)===f){d!==null&&(d=d.next={eventTime:g,lane:0,tag:c.tag,payload:c.payload,callback:c.callback,next:null});e:{var h=e,m=c;switch(f=t,g=n,m.tag){case 1:if(h=m.payload,typeof h=="function"){p=h.call(g,p,f);break e}p=h;break e;case 3:h.flags=h.flags&-65537|128;case 0:if(h=m.payload,f=typeof h=="function"?h.call(g,p,f):h,f==null)break e;p=Gt({},p,f);break e;case 2:Ko=!0}}c.callback!==null&&c.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[c]:f.push(c))}else g={eventTime:g,lane:f,tag:c.tag,payload:c.payload,callback:c.callback,next:null},d===null?(i=d=g,u=p):d=d.next=g,a|=f;if(c=c.next,c===null){if(c=s.shared.pending,c===null)break;f=c,c=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(d===null&&(u=p),s.baseState=u,s.firstBaseUpdate=i,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do a|=s.lane,s=s.next;while(s!==t)}else o===null&&(s.shared.lanes=0);Ni|=a,e.lanes=a,e.memoizedState=p}}function KS(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Nm.transition;Nm.transition={};try{e(!1),t()}finally{Ct=n,Nm.transition=r}}function Nj(){return Kr().memoizedState}function IF(e,t,n){var r=ga(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},_j(e))Pj(t,n);else if(n=dj(e,t,n,r),n!==null){var s=Gn();os(n,e,r,s),Rj(n,t,r)}}function DF(e,t,n){var r=ga(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(_j(e))Pj(t,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var a=t.lastRenderedState,c=o(a,n);if(s.hasEagerState=!0,s.eagerState=c,ds(c,a)){var u=t.interleaved;u===null?(s.next=s,cx(t)):(s.next=u.next,u.next=s),t.interleaved=s;return}}catch{}finally{}n=dj(e,t,s,r),n!==null&&(s=Gn(),os(n,e,r,s),Rj(n,t,r))}}function _j(e){var t=e.alternate;return e===Wt||t!==null&&t===Wt}function Pj(e,t){Nu=Kp=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Rj(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Jb(e,n)}}var qp={readContext:Hr,useCallback:Pn,useContext:Pn,useEffect:Pn,useImperativeHandle:Pn,useInsertionEffect:Pn,useLayoutEffect:Pn,useMemo:Pn,useReducer:Pn,useRef:Pn,useState:Pn,useDebugValue:Pn,useDeferredValue:Pn,useTransition:Pn,useMutableSource:Pn,useSyncExternalStore:Pn,useId:Pn,unstable_isNewReconciler:!1},AF={readContext:Hr,useCallback:function(e,t){return ks().memoizedState=[e,t===void 0?null:t],e},useContext:Hr,useEffect:WS,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ap(4194308,4,Ej.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ap(4194308,4,e,t)},useInsertionEffect:function(e,t){return ap(4,2,e,t)},useMemo:function(e,t){var n=ks();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ks();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=IF.bind(null,Wt,e),[r.memoizedState,e]},useRef:function(e){var t=ks();return e={current:e},t.memoizedState=e},useState:qS,useDebugValue:yx,useDeferredValue:function(e){return ks().memoizedState=e},useTransition:function(){var e=qS(!1),t=e[0];return e=OF.bind(null,e[1]),ks().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Wt,s=ks();if($t){if(n===void 0)throw Error(te(407));n=n()}else{if(n=t(),yn===null)throw Error(te(349));Mi&30||mj(r,t,n)}s.memoizedState=n;var o={value:n,getSnapshot:t};return s.queue=o,WS(yj.bind(null,r,o,e),[e]),r.flags|=2048,rd(9,vj.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=ks(),t=yn.identifierPrefix;if($t){var n=co,r=lo;n=(r&~(1<<32-ss(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=td++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[_s]=t,e[Yu]=r,Uj(e,t,!1,!1),t.stateNode=e;e:{switch(a=Xv(n,r),n){case"dialog":It("cancel",e),It("close",e),s=r;break;case"iframe":case"object":case"embed":It("load",e),s=r;break;case"video":case"audio":for(s=0;suc&&(t.flags|=128,r=!0,Jc(o,!1),t.lanes=4194304)}else{if(!r)if(e=Hp(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Jc(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!$t)return Rn(t),null}else 2*en()-o.renderingStartTime>uc&&n!==1073741824&&(t.flags|=128,r=!0,Jc(o,!1),t.lanes=4194304);o.isBackwards?(a.sibling=t.child,t.child=a):(n=o.last,n!==null?n.sibling=a:t.child=a,o.last=a)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=en(),t.sibling=null,n=qt.current,Nt(qt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Ex(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?gr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(te(156,t.tag))}function HF(e,t){switch(sx(t),t.tag){case 1:return ar(t.type)&&Fp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return lc(),At(or),At(Ln),px(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return fx(t),null;case 13:if(At(qt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(te(340));ac()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(qt),null;case 4:return lc(),null;case 10:return lx(t.type._context),null;case 22:case 23:return Ex(),null;case 24:return null;default:return null}}var jf=!1,An=!1,KF=typeof WeakSet=="function"?WeakSet:Set,Se=null;function kl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Zt(e,t,r)}else n.current=null}function jy(e,t,n){try{n()}catch(r){Zt(e,t,r)}}var s0=!1;function qF(e,t){if(cy=Op,e=Jk(),nx(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var a=0,c=-1,u=-1,i=0,d=0,p=e,f=null;t:for(;;){for(var g;p!==n||s!==0&&p.nodeType!==3||(c=a+s),p!==o||r!==0&&p.nodeType!==3||(u=a+r),p.nodeType===3&&(a+=p.nodeValue.length),(g=p.firstChild)!==null;)f=p,p=g;for(;;){if(p===e)break t;if(f===n&&++i===s&&(c=a),f===o&&++d===r&&(u=a),(g=p.nextSibling)!==null)break;p=f,f=p.parentNode}p=g}n=c===-1||u===-1?null:{start:c,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(uy={focusedElem:e,selectionRange:n},Op=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var h=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var m=h.memoizedProps,x=h.memoizedState,b=t.stateNode,y=b.getSnapshotBeforeUpdate(t.elementType===t.type?m:Jr(t.type,m),x);b.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(te(163))}}catch(S){Zt(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return h=s0,s0=!1,h}function _u(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&jy(t,n,o)}s=s.next}while(s!==r)}}function Hg(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ty(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Kj(e){var t=e.alternate;t!==null&&(e.alternate=null,Kj(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[_s],delete t[Yu],delete t[py],delete t[MF],delete t[NF])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function qj(e){return e.tag===5||e.tag===3||e.tag===4}function o0(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||qj(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function My(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ap));else if(r!==4&&(e=e.child,e!==null))for(My(e,t,n),e=e.sibling;e!==null;)My(e,t,n),e=e.sibling}function Ny(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ny(e,t,n),e=e.sibling;e!==null;)Ny(e,t,n),e=e.sibling}var Cn=null,Zr=!1;function Ao(e,t,n){for(n=n.child;n!==null;)Wj(e,t,n),n=n.sibling}function Wj(e,t,n){if($s&&typeof $s.onCommitFiberUnmount=="function")try{$s.onCommitFiberUnmount(Ag,n)}catch{}switch(n.tag){case 5:An||kl(n,t);case 6:var r=Cn,s=Zr;Cn=null,Ao(e,t,n),Cn=r,Zr=s,Cn!==null&&(Zr?(e=Cn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Cn.removeChild(n.stateNode));break;case 18:Cn!==null&&(Zr?(e=Cn,n=n.stateNode,e.nodeType===8?jm(e.parentNode,n):e.nodeType===1&&jm(e,n),Wu(e)):jm(Cn,n.stateNode));break;case 4:r=Cn,s=Zr,Cn=n.stateNode.containerInfo,Zr=!0,Ao(e,t,n),Cn=r,Zr=s;break;case 0:case 11:case 14:case 15:if(!An&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&jy(n,t,a),s=s.next}while(s!==r)}Ao(e,t,n);break;case 1:if(!An&&(kl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(c){Zt(n,t,c)}Ao(e,t,n);break;case 21:Ao(e,t,n);break;case 22:n.mode&1?(An=(r=An)||n.memoizedState!==null,Ao(e,t,n),An=r):Ao(e,t,n);break;default:Ao(e,t,n)}}function a0(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new KF),t.forEach(function(r){var s=t2.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Gr(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=a),r&=~o}if(r=s,r=en()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*GF(r/1960))-r,10e?16:e,oa===null)var r=!1;else{if(e=oa,oa=null,Jp=0,gt&6)throw Error(te(331));var s=gt;for(gt|=4,Se=e.current;Se!==null;){var o=Se,a=o.child;if(Se.flags&16){var c=o.deletions;if(c!==null){for(var u=0;uen()-Sx?vi(e,0):wx|=n),ir(e,t)}function tT(e,t){t===0&&(e.mode&1?(t=vf,vf<<=1,!(vf&130023424)&&(vf=4194304)):t=1);var n=Gn();e=bo(e,t),e!==null&&(Ud(e,t,n),ir(e,n))}function e2(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),tT(e,n)}function t2(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(te(314))}r!==null&&r.delete(t),tT(e,n)}var nT;nT=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||or.current)sr=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return sr=!1,UF(e,t,n);sr=!!(e.flags&131072)}else sr=!1,$t&&t.flags&1048576&&aj(t,Bp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ip(e,t),e=t.pendingProps;var s=oc(t,Ln.current);Al(t,n),s=hx(null,t,r,e,s,n);var o=mx();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ar(r)?(o=!0,Lp(t)):o=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ux(t),s.updater=Vg,t.stateNode=s,s._reactInternals=t,by(t,r,e,n),t=Sy(null,t,r,!0,o,n)):(t.tag=0,$t&&o&&rx(t),Kn(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ip(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=r2(r),e=Jr(r,e),s){case 0:t=wy(null,t,r,e,n);break e;case 1:t=t0(null,t,r,e,n);break e;case 11:t=XS(null,t,r,e,n);break e;case 14:t=e0(null,t,r,Jr(r.type,e),n);break e}throw Error(te(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Jr(r,s),wy(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Jr(r,s),t0(e,t,r,s,n);case 3:e:{if($j(t),e===null)throw Error(te(387));r=t.pendingProps,o=t.memoizedState,s=o.element,fj(e,t),Vp(t,r,null,n);var a=t.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){s=cc(Error(te(423)),t),t=n0(e,t,r,n,s);break e}else if(r!==s){s=cc(Error(te(424)),t),t=n0(e,t,r,n,s);break e}else for(yr=da(t.stateNode.containerInfo.firstChild),xr=t,$t=!0,es=null,n=uj(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ac(),r===s){t=xo(e,t,n);break e}Kn(e,t,r,n)}t=t.child}return t;case 5:return pj(t),e===null&&my(t),r=t.type,s=t.pendingProps,o=e!==null?e.memoizedProps:null,a=s.children,dy(r,s)?a=null:o!==null&&dy(r,o)&&(t.flags|=32),Lj(e,t),Kn(e,t,a,n),t.child;case 6:return e===null&&my(t),null;case 13:return Bj(e,t,n);case 4:return dx(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ic(t,null,r,n):Kn(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Jr(r,s),XS(e,t,r,s,n);case 7:return Kn(e,t,t.pendingProps,n),t.child;case 8:return Kn(e,t,t.pendingProps.children,n),t.child;case 12:return Kn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,o=t.memoizedProps,a=s.value,Nt(zp,r._currentValue),r._currentValue=a,o!==null)if(ds(o.value,a)){if(o.children===s.children&&!or.current){t=xo(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var c=o.dependencies;if(c!==null){a=o.child;for(var u=c.firstContext;u!==null;){if(u.context===r){if(o.tag===1){u=go(-1,n&-n),u.tag=2;var i=o.updateQueue;if(i!==null){i=i.shared;var d=i.pending;d===null?u.next=u:(u.next=d.next,d.next=u),i.pending=u}}o.lanes|=n,u=o.alternate,u!==null&&(u.lanes|=n),vy(o.return,n,t),c.lanes|=n;break}u=u.next}}else if(o.tag===10)a=o.type===t.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(te(341));a.lanes|=n,c=a.alternate,c!==null&&(c.lanes|=n),vy(a,n,t),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===t){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}Kn(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Al(t,n),s=Hr(s),r=r(s),t.flags|=1,Kn(e,t,r,n),t.child;case 14:return r=t.type,s=Jr(r,t.pendingProps),s=Jr(r.type,s),e0(e,t,r,s,n);case 15:return Aj(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Jr(r,s),ip(e,t),t.tag=1,ar(r)?(e=!0,Lp(t)):e=!1,Al(t,n),Oj(t,r,s),by(t,r,s,n),Sy(null,t,r,!0,e,n);case 19:return zj(e,t,n);case 22:return Fj(e,t,n)}throw Error(te(156,t.tag))};function rT(e,t){return _k(e,t)}function n2(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function $r(e,t,n,r){return new n2(e,t,n,r)}function jx(e){return e=e.prototype,!(!e||!e.isReactComponent)}function r2(e){if(typeof e=="function")return jx(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Kb)return 11;if(e===qb)return 14}return 2}function ha(e,t){var n=e.alternate;return n===null?(n=$r(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function up(e,t,n,r,s,o){var a=2;if(r=e,typeof e=="function")jx(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case ml:return yi(n.children,s,o,t);case Hb:a=8,s|=8;break;case Vv:return e=$r(12,n,t,s|2),e.elementType=Vv,e.lanes=o,e;case Hv:return e=$r(13,n,t,s),e.elementType=Hv,e.lanes=o,e;case Kv:return e=$r(19,n,t,s),e.elementType=Kv,e.lanes=o,e;case pk:return qg(n,s,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case dk:a=10;break e;case fk:a=9;break e;case Kb:a=11;break e;case qb:a=14;break e;case Ho:a=16,r=null;break e}throw Error(te(130,e==null?e:typeof e,""))}return t=$r(a,n,t,s),t.elementType=e,t.type=r,t.lanes=o,t}function yi(e,t,n,r){return e=$r(7,e,r,t),e.lanes=n,e}function qg(e,t,n,r){return e=$r(22,e,r,t),e.elementType=pk,e.lanes=n,e.stateNode={isHidden:!1},e}function Im(e,t,n){return e=$r(6,e,null,t),e.lanes=n,e}function Dm(e,t,n){return t=$r(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function s2(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=hm(0),this.expirationTimes=hm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=hm(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Tx(e,t,n,r,s,o,a,c,u){return e=new s2(e,t,n,c,u),t===1?(t=1,o===!0&&(t|=8)):t=0,o=$r(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ux(o),e}function o2(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(iT)}catch(e){console.error(e)}}iT(),ik.exports=jr;var Pa=ik.exports;const lT=Rb(Pa),u2=DE({__proto__:null,default:lT},[Pa]);var g0=Pa;zv.createRoot=g0.createRoot,zv.hydrateRoot=g0.hydrateRoot;const d2=(...e)=>{console!=null&&console.warn&&(bi(e[0])&&(e[0]=`react-i18next:: ${e[0]}`),console.warn(...e))},h0={},Iy=(...e)=>{bi(e[0])&&h0[e[0]]||(bi(e[0])&&(h0[e[0]]=new Date),d2(...e))},cT=(e,t)=>()=>{if(e.isInitialized)t();else{const n=()=>{setTimeout(()=>{e.off("initialized",n)},0),t()};e.on("initialized",n)}},m0=(e,t,n)=>{e.loadNamespaces(t,cT(e,n))},v0=(e,t,n,r)=>{bi(n)&&(n=[n]),n.forEach(s=>{e.options.ns.indexOf(s)<0&&e.options.ns.push(s)}),e.loadLanguages(t,cT(e,r))},f2=(e,t,n={})=>!t.languages||!t.languages.length?(Iy("i18n.languages were undefined or empty",t.languages),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(r,s)=>{var o;if(((o=n.bindI18n)==null?void 0:o.indexOf("languageChanging"))>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!s(r.isLanguageChangingTo,e))return!1}}),bi=e=>typeof e=="string",p2=e=>typeof e=="object"&&e!==null,g2=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,h2={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},m2=e=>h2[e],v2=e=>e.replace(g2,m2);let Dy={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:v2};const y2=(e={})=>{Dy={...Dy,...e}},b2=()=>Dy;let uT;const x2=e=>{uT=e},w2=()=>uT,S2={type:"3rdParty",init(e){y2(e.options.react),x2(e)}},dT=v.createContext();class C2{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(n=>{var r;(r=this.usedNamespaces)[n]??(r[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const E2=(e,t)=>{const n=v.useRef();return v.useEffect(()=>{n.current=e},[e,t]),n.current},fT=(e,t,n,r)=>e.getFixedT(t,n,r),k2=(e,t,n,r)=>v.useCallback(fT(e,t,n,r),[e,t,n,r]),Te=(e,t={})=>{var S,E,C,T;const{i18n:n}=t,{i18n:r,defaultNS:s}=v.useContext(dT)||{},o=n||r||w2();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new C2),!o){Iy("You will need to pass in an i18next instance by using initReactI18next");const j=(O,K)=>bi(K)?K:p2(K)&&bi(K.defaultValue)?K.defaultValue:Array.isArray(O)?O[O.length-1]:O,_=[j,{},!1];return _.t=j,_.i18n={},_.ready=!1,_}(S=o.options.react)!=null&&S.wait&&Iy("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const a={...b2(),...o.options.react,...t},{useSuspense:c,keyPrefix:u}=a;let i=s||((E=o.options)==null?void 0:E.defaultNS);i=bi(i)?[i]:i||["translation"],(T=(C=o.reportNamespaces).addUsedNamespaces)==null||T.call(C,i);const d=(o.isInitialized||o.initializedStoreOnce)&&i.every(j=>f2(j,o,a)),p=k2(o,t.lng||null,a.nsMode==="fallback"?i:i[0],u),f=()=>p,g=()=>fT(o,t.lng||null,a.nsMode==="fallback"?i:i[0],u),[h,m]=v.useState(f);let x=i.join();t.lng&&(x=`${t.lng}${x}`);const b=E2(x),y=v.useRef(!0);v.useEffect(()=>{const{bindI18n:j,bindI18nStore:_}=a;y.current=!0,!d&&!c&&(t.lng?v0(o,t.lng,i,()=>{y.current&&m(g)}):m0(o,i,()=>{y.current&&m(g)})),d&&b&&b!==x&&y.current&&m(g);const O=()=>{y.current&&m(g)};return j&&(o==null||o.on(j,O)),_&&(o==null||o.store.on(_,O)),()=>{y.current=!1,o&&(j==null||j.split(" ").forEach(K=>o.off(K,O))),_&&o&&_.split(" ").forEach(K=>o.store.off(K,O))}},[o,x]),v.useEffect(()=>{y.current&&d&&m(f)},[o,u,d]);const w=[h,o,d];if(w.t=h,w.i18n=o,w.ready=d,d||!d&&!c)return w;throw new Promise(j=>{t.lng?v0(o,t.lng,i,()=>j()):m0(o,i,()=>j())})};function j2({i18n:e,defaultNS:t,children:n}){const r=v.useMemo(()=>({i18n:e,defaultNS:t}),[e,t]);return v.createElement(dT.Provider,{value:r},n)}/** + * @remix-run/router v1.18.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Kt(){return Kt=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function dc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function M2(){return Math.random().toString(36).substr(2,8)}function b0(e,t){return{usr:e.state,key:e.key,idx:t}}function od(e,t,n,r){return n===void 0&&(n=null),Kt({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Ra(t):t,{state:n,key:t&&t.key||r||M2()})}function Pi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Ra(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function N2(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,a=s.history,c=rn.Pop,u=null,i=d();i==null&&(i=0,a.replaceState(Kt({},a.state,{idx:i}),""));function d(){return(a.state||{idx:null}).idx}function p(){c=rn.Pop;let x=d(),b=x==null?null:x-i;i=x,u&&u({action:c,location:m.location,delta:b})}function f(x,b){c=rn.Push;let y=od(m.location,x,b);i=d()+1;let w=b0(y,i),S=m.createHref(y);try{a.pushState(w,"",S)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;s.location.assign(S)}o&&u&&u({action:c,location:m.location,delta:1})}function g(x,b){c=rn.Replace;let y=od(m.location,x,b);i=d();let w=b0(y,i),S=m.createHref(y);a.replaceState(w,"",S),o&&u&&u({action:c,location:m.location,delta:0})}function h(x){let b=s.location.origin!=="null"?s.location.origin:s.location.href,y=typeof x=="string"?x:Pi(x);return y=y.replace(/ $/,"%20"),et(b,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,b)}let m={get action(){return c},get location(){return e(s,a)},listen(x){if(u)throw new Error("A history only accepts one active listener");return s.addEventListener(y0,p),u=x,()=>{s.removeEventListener(y0,p),u=null}},createHref(x){return t(s,x)},createURL:h,encodeLocation(x){let b=h(x);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:f,replace:g,go(x){return a.go(x)}};return m}var Mt;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Mt||(Mt={}));const _2=new Set(["lazy","caseSensitive","path","id","index","children"]);function P2(e){return e.index===!0}function ad(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((s,o)=>{let a=[...n,String(o)],c=typeof s.id=="string"?s.id:a.join("-");if(et(s.index!==!0||!s.children,"Cannot specify children on an index route"),et(!r[c],'Found a route id collision on id "'+c+`". Route id's must be globally unique within Data Router usages`),P2(s)){let u=Kt({},s,t(s),{id:c});return r[c]=u,u}else{let u=Kt({},s,t(s),{id:c,children:void 0});return r[c]=u,s.children&&(u.children=ad(s.children,t,a,r)),u}})}function Ya(e,t,n){return n===void 0&&(n="/"),dp(e,t,n,!1)}function dp(e,t,n,r){let s=typeof t=="string"?Ra(t):t,o=Cc(s.pathname||"/",n);if(o==null)return null;let a=pT(e);O2(a);let c=null;for(let u=0;c==null&&u{let u={relativePath:c===void 0?o.path||"":c,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};u.relativePath.startsWith("/")&&(et(u.relativePath.startsWith(r),'Absolute route path "'+u.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),u.relativePath=u.relativePath.slice(r.length));let i=ho([r,u.relativePath]),d=n.concat(u);o.children&&o.children.length>0&&(et(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+i+'".')),pT(o.children,t,d,i)),!(o.path==null&&!o.index)&&t.push({path:i,score:B2(i,o.index),routesMeta:d})};return e.forEach((o,a)=>{var c;if(o.path===""||!((c=o.path)!=null&&c.includes("?")))s(o,a);else for(let u of gT(o.path))s(o,a,u)}),t}function gT(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let a=gT(r.join("/")),c=[];return c.push(...a.map(u=>u===""?o:[o,u].join("/"))),s&&c.push(...a),c.map(u=>e.startsWith("/")&&u===""?"/":u)}function O2(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:z2(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const I2=/^:[\w-]+$/,D2=3,A2=2,F2=1,L2=10,$2=-2,x0=e=>e==="*";function B2(e,t){let n=e.split("/"),r=n.length;return n.some(x0)&&(r+=$2),t&&(r+=A2),n.filter(s=>!x0(s)).reduce((s,o)=>s+(I2.test(o)?D2:o===""?F2:L2),r)}function z2(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function U2(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,s={},o="/",a=[];for(let c=0;c{let{paramName:f,isOptional:g}=d;if(f==="*"){let m=c[p]||"";a=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const h=c[p];return g&&!h?i[f]=void 0:i[f]=(h||"").replace(/%2F/g,"/"),i},{}),pathname:o,pathnameBase:a,pattern:e}}function V2(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),dc(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,u)=>(r.push({paramName:c,isOptional:u!=null}),u?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function H2(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return dc(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Cc(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function K2(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Ra(e):e;return{pathname:n?n.startsWith("/")?n:q2(n,t):t,search:G2(r),hash:J2(s)}}function q2(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Am(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function hT(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Zg(e,t){let n=hT(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Yg(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=Ra(e):(s=Kt({},e),et(!s.pathname||!s.pathname.includes("?"),Am("?","pathname","search",s)),et(!s.pathname||!s.pathname.includes("#"),Am("#","pathname","hash",s)),et(!s.search||!s.search.includes("#"),Am("#","search","hash",s)));let o=e===""||s.pathname==="",a=o?"/":s.pathname,c;if(a==null)c=n;else{let p=t.length-1;if(!r&&a.startsWith("..")){let f=a.split("/");for(;f[0]==="..";)f.shift(),p-=1;s.pathname=f.join("/")}c=p>=0?t[p]:"/"}let u=K2(s,c),i=a&&a!=="/"&&a.endsWith("/"),d=(o||a===".")&&n.endsWith("/");return!u.pathname.endsWith("/")&&(i||d)&&(u.pathname+="/"),u}const ho=e=>e.join("/").replace(/\/\/+/g,"/"),W2=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),G2=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,J2=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class Px{constructor(t,n,r,s){s===void 0&&(s=!1),this.status=t,this.statusText=n||"",this.internal=s,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Xg(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const mT=["post","put","patch","delete"],Q2=new Set(mT),Z2=["get",...mT],Y2=new Set(Z2),X2=new Set([301,302,303,307,308]),eL=new Set([307,308]),Fm={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},tL={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Zc={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},Rx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nL=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),vT="remix-router-transitions";function rL(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;et(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let s;if(e.mapRouteProperties)s=e.mapRouteProperties;else if(e.detectErrorBoundary){let P=e.detectErrorBoundary;s=R=>({hasErrorBoundary:P(R)})}else s=nL;let o={},a=ad(e.routes,s,void 0,o),c,u=e.basename||"/",i=e.unstable_dataStrategy||lL,d=e.unstable_patchRoutesOnMiss,p=Kt({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),f=null,g=new Set,h=null,m=null,x=null,b=e.hydrationData!=null,y=Ya(a,e.history.location,u),w=null;if(y==null&&!d){let P=Hn(404,{pathname:e.history.location.pathname}),{matches:R,route:B}=P0(a);y=R,w={[B.id]:P}}y&&d&&!e.hydrationData&&im(y,a,e.history.location.pathname).active&&(y=null);let S;if(!y)S=!1,y=[];else if(y.some(P=>P.route.lazy))S=!1;else if(!y.some(P=>P.route.loader))S=!0;else if(p.v7_partialHydration){let P=e.hydrationData?e.hydrationData.loaderData:null,R=e.hydrationData?e.hydrationData.errors:null,B=W=>W.route.loader?typeof W.route.loader=="function"&&W.route.loader.hydrate===!0?!1:P&&P[W.route.id]!==void 0||R&&R[W.route.id]!==void 0:!0;if(R){let W=y.findIndex(be=>R[be.route.id]!==void 0);S=y.slice(0,W+1).every(B)}else S=y.every(B)}else S=e.hydrationData!=null;let E,C={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,navigation:Fm,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||w,fetchers:new Map,blockers:new Map},T=rn.Pop,j=!1,_,O=!1,K=new Map,I=null,Y=!1,q=!1,Z=[],ee=[],J=new Map,L=0,A=-1,X=new Map,fe=new Set,H=new Map,se=new Map,ne=new Set,le=new Map,oe=new Map,Q=new Map,Ee=!1;function Pe(){if(f=e.history.listen(P=>{let{action:R,location:B,delta:W}=P;if(Ee){Ee=!1;return}dc(oe.size===0||W!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let be=Io({currentLocation:C.location,nextLocation:B,historyAction:R});if(be&&W!=null){Ee=!0,e.history.go(W*-1),xs(be,{state:"blocked",location:B,proceed(){xs(be,{state:"proceeding",proceed:void 0,reset:void 0,location:B}),e.history.go(W)},reset(){let Me=new Map(C.blockers);Me.set(be,Zc),ve({blockers:Me})}});return}return Xt(R,B)}),n){wL(t,K);let P=()=>SL(t,K);t.addEventListener("pagehide",P),I=()=>t.removeEventListener("pagehide",P)}return C.initialized||Xt(rn.Pop,C.location,{initialHydration:!0}),E}function Be(){f&&f(),I&&I(),g.clear(),_&&_.abort(),C.fetchers.forEach((P,R)=>bs(R)),C.blockers.forEach((P,R)=>_n(R))}function Re(P){return g.add(P),()=>g.delete(P)}function ve(P,R){R===void 0&&(R={}),C=Kt({},C,P);let B=[],W=[];p.v7_fetcherPersist&&C.fetchers.forEach((be,Me)=>{be.state==="idle"&&(ne.has(Me)?W.push(Me):B.push(Me))}),[...g].forEach(be=>be(C,{deletedFetchers:W,unstable_viewTransitionOpts:R.viewTransitionOpts,unstable_flushSync:R.flushSync===!0})),p.v7_fetcherPersist&&(B.forEach(be=>C.fetchers.delete(be)),W.forEach(be=>bs(be)))}function ot(P,R,B){var W,be;let{flushSync:Me}=B===void 0?{}:B,ze=C.actionData!=null&&C.navigation.formMethod!=null&&Yr(C.navigation.formMethod)&&C.navigation.state==="loading"&&((W=P.state)==null?void 0:W._isRedirect)!==!0,pe;R.actionData?Object.keys(R.actionData).length>0?pe=R.actionData:pe=null:ze?pe=C.actionData:pe=null;let Je=R.loaderData?N0(C.loaderData,R.loaderData,R.matches||[],R.errors):C.loaderData,_e=C.blockers;_e.size>0&&(_e=new Map(_e),_e.forEach((St,kt)=>_e.set(kt,Zc)));let Oe=j===!0||C.navigation.formMethod!=null&&Yr(C.navigation.formMethod)&&((be=P.state)==null?void 0:be._isRedirect)!==!0;c&&(a=c,c=void 0),Y||T===rn.Pop||(T===rn.Push?e.history.push(P,P.state):T===rn.Replace&&e.history.replace(P,P.state));let Et;if(T===rn.Pop){let St=K.get(C.location.pathname);St&&St.has(P.pathname)?Et={currentLocation:C.location,nextLocation:P}:K.has(P.pathname)&&(Et={currentLocation:P,nextLocation:C.location})}else if(O){let St=K.get(C.location.pathname);St?St.add(P.pathname):(St=new Set([P.pathname]),K.set(C.location.pathname,St)),Et={currentLocation:C.location,nextLocation:P}}ve(Kt({},R,{actionData:pe,loaderData:Je,historyAction:T,location:P,initialized:!0,navigation:Fm,revalidation:"idle",restoreScrollPosition:Qw(P,R.matches||C.matches),preventScrollReset:Oe,blockers:_e}),{viewTransitionOpts:Et,flushSync:Me===!0}),T=rn.Pop,j=!1,O=!1,Y=!1,q=!1,Z=[],ee=[]}async function Vt(P,R){if(typeof P=="number"){e.history.go(P);return}let B=Ay(C.location,C.matches,u,p.v7_prependBasename,P,p.v7_relativeSplatPath,R==null?void 0:R.fromRouteId,R==null?void 0:R.relative),{path:W,submission:be,error:Me}=S0(p.v7_normalizeFormMethod,!1,B,R),ze=C.location,pe=od(C.location,W,R&&R.state);pe=Kt({},pe,e.history.encodeLocation(pe));let Je=R&&R.replace!=null?R.replace:void 0,_e=rn.Push;Je===!0?_e=rn.Replace:Je===!1||be!=null&&Yr(be.formMethod)&&be.formAction===C.location.pathname+C.location.search&&(_e=rn.Replace);let Oe=R&&"preventScrollReset"in R?R.preventScrollReset===!0:void 0,Et=(R&&R.unstable_flushSync)===!0,St=Io({currentLocation:ze,nextLocation:pe,historyAction:_e});if(St){xs(St,{state:"blocked",location:pe,proceed(){xs(St,{state:"proceeding",proceed:void 0,reset:void 0,location:pe}),Vt(P,R)},reset(){let kt=new Map(C.blockers);kt.set(St,Zc),ve({blockers:kt})}});return}return await Xt(_e,pe,{submission:be,pendingError:Me,preventScrollReset:Oe,replace:R&&R.replace,enableViewTransition:R&&R.unstable_viewTransition,flushSync:Et})}function tn(){if(hn(),ve({revalidation:"loading"}),C.navigation.state!=="submitting"){if(C.navigation.state==="idle"){Xt(C.historyAction,C.location,{startUninterruptedRevalidation:!0});return}Xt(T||C.historyAction,C.navigation.location,{overrideNavigation:C.navigation})}}async function Xt(P,R,B){_&&_.abort(),_=null,T=P,Y=(B&&B.startUninterruptedRevalidation)===!0,eD(C.location,C.matches),j=(B&&B.preventScrollReset)===!0,O=(B&&B.enableViewTransition)===!0;let W=c||a,be=B&&B.overrideNavigation,Me=Ya(W,R,u),ze=(B&&B.flushSync)===!0,pe=im(Me,W,R.pathname);if(pe.active&&pe.matches&&(Me=pe.matches),!Me){let{error:bt,notFoundMatches:xn,route:nn}=Bc(R.pathname);ot(R,{matches:xn,loaderData:{},errors:{[nn.id]:bt}},{flushSync:ze});return}if(C.initialized&&!q&&gL(C.location,R)&&!(B&&B.submission&&Yr(B.submission.formMethod))){ot(R,{matches:Me},{flushSync:ze});return}_=new AbortController;let Je=nl(e.history,R,_.signal,B&&B.submission),_e;if(B&&B.pendingError)_e=[Tl(Me).route.id,{type:Mt.error,error:B.pendingError}];else if(B&&B.submission&&Yr(B.submission.formMethod)){let bt=await ln(Je,R,B.submission,Me,pe.active,{replace:B.replace,flushSync:ze});if(bt.shortCircuited)return;if(bt.pendingActionResult){let[xn,nn]=bt.pendingActionResult;if(mr(nn)&&Xg(nn.error)&&nn.error.status===404){_=null,ot(R,{matches:bt.matches,loaderData:{},errors:{[xn]:nn.error}});return}}Me=bt.matches||Me,_e=bt.pendingActionResult,be=Lm(R,B.submission),ze=!1,pe.active=!1,Je=nl(e.history,Je.url,Je.signal)}let{shortCircuited:Oe,matches:Et,loaderData:St,errors:kt}=await M(Je,R,Me,pe.active,be,B&&B.submission,B&&B.fetcherSubmission,B&&B.replace,B&&B.initialHydration===!0,ze,_e);Oe||(_=null,ot(R,Kt({matches:Et||Me},_0(_e),{loaderData:St,errors:kt})))}async function ln(P,R,B,W,be,Me){Me===void 0&&(Me={}),hn();let ze=bL(R,B);if(ve({navigation:ze},{flushSync:Me.flushSync===!0}),be){let _e=await of(W,R.pathname,P.signal);if(_e.type==="aborted")return{shortCircuited:!0};if(_e.type==="error"){let{boundaryId:Oe,error:Et}=Zi(R.pathname,_e);return{matches:_e.partialMatches,pendingActionResult:[Oe,{type:Mt.error,error:Et}]}}else if(_e.matches)W=_e.matches;else{let{notFoundMatches:Oe,error:Et,route:St}=Bc(R.pathname);return{matches:Oe,pendingActionResult:[St.id,{type:Mt.error,error:Et}]}}}let pe,Je=mu(W,R);if(!Je.route.action&&!Je.route.lazy)pe={type:Mt.error,error:Hn(405,{method:P.method,pathname:R.pathname,routeId:Je.route.id})};else if(pe=(await rt("action",P,[Je],W))[0],P.signal.aborted)return{shortCircuited:!0};if(ri(pe)){let _e;return Me&&Me.replace!=null?_e=Me.replace:_e=j0(pe.response.headers.get("Location"),new URL(P.url),u)===C.location.pathname+C.location.search,await ke(P,pe,{submission:B,replace:_e}),{shortCircuited:!0}}if(ni(pe))throw Hn(400,{type:"defer-action"});if(mr(pe)){let _e=Tl(W,Je.route.id);return(Me&&Me.replace)!==!0&&(T=rn.Push),{matches:W,pendingActionResult:[_e.route.id,pe]}}return{matches:W,pendingActionResult:[Je.route.id,pe]}}async function M(P,R,B,W,be,Me,ze,pe,Je,_e,Oe){let Et=be||Lm(R,Me),St=Me||ze||I0(Et),kt=!Y&&(!p.v7_partialHydration||!Je);if(W){if(kt){let Jt=D(Oe);ve(Kt({navigation:Et},Jt!==void 0?{actionData:Jt}:{}),{flushSync:_e})}let Ze=await of(B,R.pathname,P.signal);if(Ze.type==="aborted")return{shortCircuited:!0};if(Ze.type==="error"){let{boundaryId:Jt,error:ur}=Zi(R.pathname,Ze);return{matches:Ze.partialMatches,loaderData:{},errors:{[Jt]:ur}}}else if(Ze.matches)B=Ze.matches;else{let{error:Jt,notFoundMatches:ur,route:Ft}=Bc(R.pathname);return{matches:ur,loaderData:{},errors:{[Ft.id]:Jt}}}}let bt=c||a,[xn,nn]=C0(e.history,C,B,St,R,p.v7_partialHydration&&Je===!0,p.v7_skipActionErrorRevalidation,q,Z,ee,ne,H,fe,bt,u,Oe);if(ws(Ze=>!(B&&B.some(Jt=>Jt.route.id===Ze))||xn&&xn.some(Jt=>Jt.route.id===Ze)),A=++L,xn.length===0&&nn.length===0){let Ze=He();return ot(R,Kt({matches:B,loaderData:{},errors:Oe&&mr(Oe[1])?{[Oe[0]]:Oe[1].error}:null},_0(Oe),Ze?{fetchers:new Map(C.fetchers)}:{}),{flushSync:_e}),{shortCircuited:!0}}if(kt){let Ze={};if(!W){Ze.navigation=Et;let Jt=D(Oe);Jt!==void 0&&(Ze.actionData=Jt)}nn.length>0&&(Ze.fetchers=V(nn)),ve(Ze,{flushSync:_e})}nn.forEach(Ze=>{J.has(Ze.key)&&zn(Ze.key),Ze.controller&&J.set(Ze.key,Ze.controller)});let Uc=()=>nn.forEach(Ze=>zn(Ze.key));_&&_.signal.addEventListener("abort",Uc);let{loaderResults:Do,fetcherResults:Yi}=await Pt(C.matches,B,xn,nn,P);if(P.signal.aborted)return{shortCircuited:!0};_&&_.signal.removeEventListener("abort",Uc),nn.forEach(Ze=>J.delete(Ze.key));let Xi=R0([...Do,...Yi]);if(Xi){if(Xi.idx>=xn.length){let Ze=nn[Xi.idx-xn.length].key;fe.add(Ze)}return await ke(P,Xi.result,{replace:pe}),{shortCircuited:!0}}let{loaderData:el,errors:Ss}=M0(C,B,xn,Do,Oe,nn,Yi,le);le.forEach((Ze,Jt)=>{Ze.subscribe(ur=>{(ur||Ze.done)&&le.delete(Jt)})}),p.v7_partialHydration&&Je&&C.errors&&Object.entries(C.errors).filter(Ze=>{let[Jt]=Ze;return!xn.some(ur=>ur.route.id===Jt)}).forEach(Ze=>{let[Jt,ur]=Ze;Ss=Object.assign(Ss||{},{[Jt]:ur})});let af=He(),lf=Tt(A),cf=af||lf||nn.length>0;return Kt({matches:B,loaderData:el,errors:Ss},cf?{fetchers:new Map(C.fetchers)}:{})}function D(P){if(P&&!mr(P[1]))return{[P[0]]:P[1].data};if(C.actionData)return Object.keys(C.actionData).length===0?null:C.actionData}function V(P){return P.forEach(R=>{let B=C.fetchers.get(R.key),W=Yc(void 0,B?B.data:void 0);C.fetchers.set(R.key,W)}),new Map(C.fetchers)}function he(P,R,B,W){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");J.has(P)&&zn(P);let be=(W&&W.unstable_flushSync)===!0,Me=c||a,ze=Ay(C.location,C.matches,u,p.v7_prependBasename,B,p.v7_relativeSplatPath,R,W==null?void 0:W.relative),pe=Ya(Me,ze,u),Je=im(pe,Me,ze);if(Je.active&&Je.matches&&(pe=Je.matches),!pe){mn(P,R,Hn(404,{pathname:ze}),{flushSync:be});return}let{path:_e,submission:Oe,error:Et}=S0(p.v7_normalizeFormMethod,!0,ze,W);if(Et){mn(P,R,Et,{flushSync:be});return}let St=mu(pe,_e);if(j=(W&&W.preventScrollReset)===!0,Oe&&Yr(Oe.formMethod)){ce(P,R,_e,St,pe,Je.active,be,Oe);return}H.set(P,{routeId:R,path:_e}),ae(P,R,_e,St,pe,Je.active,be,Oe)}async function ce(P,R,B,W,be,Me,ze,pe){hn(),H.delete(P);function Je(Ft){if(!Ft.route.action&&!Ft.route.lazy){let Qs=Hn(405,{method:pe.formMethod,pathname:B,routeId:R});return mn(P,R,Qs,{flushSync:ze}),!0}return!1}if(!Me&&Je(W))return;let _e=C.fetchers.get(P);bn(P,xL(pe,_e),{flushSync:ze});let Oe=new AbortController,Et=nl(e.history,B,Oe.signal,pe);if(Me){let Ft=await of(be,B,Et.signal);if(Ft.type==="aborted")return;if(Ft.type==="error"){let{error:Qs}=Zi(B,Ft);mn(P,R,Qs,{flushSync:ze});return}else if(Ft.matches){if(be=Ft.matches,W=mu(be,B),Je(W))return}else{mn(P,R,Hn(404,{pathname:B}),{flushSync:ze});return}}J.set(P,Oe);let St=L,bt=(await rt("action",Et,[W],be))[0];if(Et.signal.aborted){J.get(P)===Oe&&J.delete(P);return}if(p.v7_fetcherPersist&&ne.has(P)){if(ri(bt)||mr(bt)){bn(P,Uo(void 0));return}}else{if(ri(bt))if(J.delete(P),A>St){bn(P,Uo(void 0));return}else return fe.add(P),bn(P,Yc(pe)),ke(Et,bt,{fetcherSubmission:pe});if(mr(bt)){mn(P,R,bt.error);return}}if(ni(bt))throw Hn(400,{type:"defer-action"});let xn=C.navigation.location||C.location,nn=nl(e.history,xn,Oe.signal),Uc=c||a,Do=C.navigation.state!=="idle"?Ya(Uc,C.navigation.location,u):C.matches;et(Do,"Didn't find any matches after fetcher action");let Yi=++L;X.set(P,Yi);let Xi=Yc(pe,bt.data);C.fetchers.set(P,Xi);let[el,Ss]=C0(e.history,C,Do,pe,xn,!1,p.v7_skipActionErrorRevalidation,q,Z,ee,ne,H,fe,Uc,u,[W.route.id,bt]);Ss.filter(Ft=>Ft.key!==P).forEach(Ft=>{let Qs=Ft.key,Zw=C.fetchers.get(Qs),rD=Yc(void 0,Zw?Zw.data:void 0);C.fetchers.set(Qs,rD),J.has(Qs)&&zn(Qs),Ft.controller&&J.set(Qs,Ft.controller)}),ve({fetchers:new Map(C.fetchers)});let af=()=>Ss.forEach(Ft=>zn(Ft.key));Oe.signal.addEventListener("abort",af);let{loaderResults:lf,fetcherResults:cf}=await Pt(C.matches,Do,el,Ss,nn);if(Oe.signal.aborted)return;Oe.signal.removeEventListener("abort",af),X.delete(P),J.delete(P),Ss.forEach(Ft=>J.delete(Ft.key));let Ze=R0([...lf,...cf]);if(Ze){if(Ze.idx>=el.length){let Ft=Ss[Ze.idx-el.length].key;fe.add(Ft)}return ke(nn,Ze.result)}let{loaderData:Jt,errors:ur}=M0(C,C.matches,el,lf,void 0,Ss,cf,le);if(C.fetchers.has(P)){let Ft=Uo(bt.data);C.fetchers.set(P,Ft)}Tt(Yi),C.navigation.state==="loading"&&Yi>A?(et(T,"Expected pending action"),_&&_.abort(),ot(C.navigation.location,{matches:Do,loaderData:Jt,errors:ur,fetchers:new Map(C.fetchers)})):(ve({errors:ur,loaderData:N0(C.loaderData,Jt,Do,ur),fetchers:new Map(C.fetchers)}),q=!1)}async function ae(P,R,B,W,be,Me,ze,pe){let Je=C.fetchers.get(P);bn(P,Yc(pe,Je?Je.data:void 0),{flushSync:ze});let _e=new AbortController,Oe=nl(e.history,B,_e.signal);if(Me){let bt=await of(be,B,Oe.signal);if(bt.type==="aborted")return;if(bt.type==="error"){let{error:xn}=Zi(B,bt);mn(P,R,xn,{flushSync:ze});return}else if(bt.matches)be=bt.matches,W=mu(be,B);else{mn(P,R,Hn(404,{pathname:B}),{flushSync:ze});return}}J.set(P,_e);let Et=L,kt=(await rt("loader",Oe,[W],be))[0];if(ni(kt)&&(kt=await ST(kt,Oe.signal,!0)||kt),J.get(P)===_e&&J.delete(P),!Oe.signal.aborted){if(ne.has(P)){bn(P,Uo(void 0));return}if(ri(kt))if(A>Et){bn(P,Uo(void 0));return}else{fe.add(P),await ke(Oe,kt);return}if(mr(kt)){mn(P,R,kt.error);return}et(!ni(kt),"Unhandled fetcher deferred data"),bn(P,Uo(kt.data))}}async function ke(P,R,B){let{submission:W,fetcherSubmission:be,replace:Me}=B===void 0?{}:B;R.response.headers.has("X-Remix-Revalidate")&&(q=!0);let ze=R.response.headers.get("Location");et(ze,"Expected a Location header on the redirect Response"),ze=j0(ze,new URL(P.url),u);let pe=od(C.location,ze,{_isRedirect:!0});if(n){let kt=!1;if(R.response.headers.has("X-Remix-Reload-Document"))kt=!0;else if(Rx.test(ze)){const bt=e.history.createURL(ze);kt=bt.origin!==t.location.origin||Cc(bt.pathname,u)==null}if(kt){Me?t.location.replace(ze):t.location.assign(ze);return}}_=null;let Je=Me===!0?rn.Replace:rn.Push,{formMethod:_e,formAction:Oe,formEncType:Et}=C.navigation;!W&&!be&&_e&&Oe&&Et&&(W=I0(C.navigation));let St=W||be;if(eL.has(R.response.status)&&St&&Yr(St.formMethod))await Xt(Je,pe,{submission:Kt({},St,{formAction:ze}),preventScrollReset:j});else{let kt=Lm(pe,W);await Xt(Je,pe,{overrideNavigation:kt,fetcherSubmission:be,preventScrollReset:j})}}async function rt(P,R,B,W){try{let be=await cL(i,P,R,B,W,o,s);return await Promise.all(be.map((Me,ze)=>{if(mL(Me)){let pe=Me.result;return{type:Mt.redirect,response:fL(pe,R,B[ze].route.id,W,u,p.v7_relativeSplatPath)}}return dL(Me)}))}catch(be){return B.map(()=>({type:Mt.error,error:be}))}}async function Pt(P,R,B,W,be){let[Me,...ze]=await Promise.all([B.length?rt("loader",be,B,R):[],...W.map(pe=>{if(pe.matches&&pe.match&&pe.controller){let Je=nl(e.history,pe.path,pe.controller.signal);return rt("loader",Je,[pe.match],pe.matches).then(_e=>_e[0])}else return Promise.resolve({type:Mt.error,error:Hn(404,{pathname:pe.path})})})]);return await Promise.all([O0(P,B,Me,Me.map(()=>be.signal),!1,C.loaderData),O0(P,W.map(pe=>pe.match),ze,W.map(pe=>pe.controller?pe.controller.signal:null),!0)]),{loaderResults:Me,fetcherResults:ze}}function hn(){q=!0,Z.push(...ws()),H.forEach((P,R)=>{J.has(R)&&(ee.push(R),zn(R))})}function bn(P,R,B){B===void 0&&(B={}),C.fetchers.set(P,R),ve({fetchers:new Map(C.fetchers)},{flushSync:(B&&B.flushSync)===!0})}function mn(P,R,B,W){W===void 0&&(W={});let be=Tl(C.matches,R);bs(P),ve({errors:{[be.route.id]:B},fetchers:new Map(C.fetchers)},{flushSync:(W&&W.flushSync)===!0})}function Oo(P){return p.v7_fetcherPersist&&(se.set(P,(se.get(P)||0)+1),ne.has(P)&&ne.delete(P)),C.fetchers.get(P)||tL}function bs(P){let R=C.fetchers.get(P);J.has(P)&&!(R&&R.state==="loading"&&X.has(P))&&zn(P),H.delete(P),X.delete(P),fe.delete(P),ne.delete(P),C.fetchers.delete(P)}function qa(P){if(p.v7_fetcherPersist){let R=(se.get(P)||0)-1;R<=0?(se.delete(P),ne.add(P)):se.set(P,R)}else bs(P);ve({fetchers:new Map(C.fetchers)})}function zn(P){let R=J.get(P);et(R,"Expected fetch controller: "+P),R.abort(),J.delete(P)}function ue(P){for(let R of P){let B=Oo(R),W=Uo(B.data);C.fetchers.set(R,W)}}function He(){let P=[],R=!1;for(let B of fe){let W=C.fetchers.get(B);et(W,"Expected fetcher: "+B),W.state==="loading"&&(fe.delete(B),P.push(B),R=!0)}return ue(P),R}function Tt(P){let R=[];for(let[B,W]of X)if(W0}function vt(P,R){let B=C.blockers.get(P)||Zc;return oe.get(P)!==R&&oe.set(P,R),B}function _n(P){C.blockers.delete(P),oe.delete(P)}function xs(P,R){let B=C.blockers.get(P)||Zc;et(B.state==="unblocked"&&R.state==="blocked"||B.state==="blocked"&&R.state==="blocked"||B.state==="blocked"&&R.state==="proceeding"||B.state==="blocked"&&R.state==="unblocked"||B.state==="proceeding"&&R.state==="unblocked","Invalid blocker state transition: "+B.state+" -> "+R.state);let W=new Map(C.blockers);W.set(P,R),ve({blockers:W})}function Io(P){let{currentLocation:R,nextLocation:B,historyAction:W}=P;if(oe.size===0)return;oe.size>1&&dc(!1,"A router only supports one blocker at a time");let be=Array.from(oe.entries()),[Me,ze]=be[be.length-1],pe=C.blockers.get(Me);if(!(pe&&pe.state==="proceeding")&&ze({currentLocation:R,nextLocation:B,historyAction:W}))return Me}function Bc(P){let R=Hn(404,{pathname:P}),B=c||a,{matches:W,route:be}=P0(B);return ws(),{notFoundMatches:W,route:be,error:R}}function Zi(P,R){return{boundaryId:Tl(R.partialMatches).route.id,error:Hn(400,{type:"route-discovery",pathname:P,message:R.error!=null&&"message"in R.error?R.error:String(R.error)})}}function ws(P){let R=[];return le.forEach((B,W)=>{(!P||P(W))&&(B.cancel(),R.push(W),le.delete(W))}),R}function zc(P,R,B){if(h=P,x=R,m=B||null,!b&&C.navigation===Fm){b=!0;let W=Qw(C.location,C.matches);W!=null&&ve({restoreScrollPosition:W})}return()=>{h=null,x=null,m=null}}function Jw(P,R){return m&&m(P,R.map(W=>R2(W,C.loaderData)))||P.key}function eD(P,R){if(h&&x){let B=Jw(P,R);h[B]=x()}}function Qw(P,R){if(h){let B=Jw(P,R),W=h[B];if(typeof W=="number")return W}return null}function im(P,R,B){if(d)if(P){let W=P[P.length-1].route;if(W.path&&(W.path==="*"||W.path.endsWith("/*")))return{active:!0,matches:dp(R,B,u,!0)}}else return{active:!0,matches:dp(R,B,u,!0)||[]};return{active:!1,matches:null}}async function of(P,R,B){let W=P,be=W.length>0?W[W.length-1].route:null;for(;;){let Me=c==null,ze=c||a;try{await iL(d,R,W,ze,o,s,Q,B)}catch(Oe){return{type:"error",error:Oe,partialMatches:W}}finally{Me&&(a=[...a])}if(B.aborted)return{type:"aborted"};let pe=Ya(ze,R,u),Je=!1;if(pe){let Oe=pe[pe.length-1].route;if(Oe.index)return{type:"success",matches:pe};if(Oe.path&&Oe.path.length>0)if(Oe.path==="*")Je=!0;else return{type:"success",matches:pe}}let _e=dp(ze,R,u,!0);if(!_e||W.map(Oe=>Oe.route.id).join("-")===_e.map(Oe=>Oe.route.id).join("-"))return{type:"success",matches:Je?pe:null};if(W=_e,be=W[W.length-1].route,be.path==="*")return{type:"success",matches:W}}}function tD(P){o={},c=ad(P,s,void 0,o)}function nD(P,R){let B=c==null;bT(P,R,c||a,o,s),B&&(a=[...a],ve({}))}return E={get basename(){return u},get future(){return p},get state(){return C},get routes(){return a},get window(){return t},initialize:Pe,subscribe:Re,enableScrollRestoration:zc,navigate:Vt,fetch:he,revalidate:tn,createHref:P=>e.history.createHref(P),encodeLocation:P=>e.history.encodeLocation(P),getFetcher:Oo,deleteFetcher:qa,dispose:Be,getBlocker:vt,deleteBlocker:_n,patchRoutes:nD,_internalFetchControllers:J,_internalActiveDeferreds:le,_internalSetRoutes:tD},E}function sL(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Ay(e,t,n,r,s,o,a,c){let u,i;if(a){u=[];for(let p of t)if(u.push(p),p.route.id===a){i=p;break}}else u=t,i=t[t.length-1];let d=Yg(s||".",Zg(u,o),Cc(e.pathname,n)||e.pathname,c==="path");return s==null&&(d.search=e.search,d.hash=e.hash),(s==null||s===""||s===".")&&i&&i.route.index&&!Ox(d.search)&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(d.pathname=d.pathname==="/"?n:ho([n,d.pathname])),Pi(d)}function S0(e,t,n,r){if(!r||!sL(r))return{path:n};if(r.formMethod&&!yL(r.formMethod))return{path:n,error:Hn(405,{method:r.formMethod})};let s=()=>({path:n,error:Hn(400,{type:"invalid-body"})}),o=r.formMethod||"get",a=e?o.toUpperCase():o.toLowerCase(),c=xT(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Yr(a))return s();let f=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((g,h)=>{let[m,x]=h;return""+g+m+"="+x+` +`},""):String(r.body);return{path:n,submission:{formMethod:a,formAction:c,formEncType:r.formEncType,formData:void 0,json:void 0,text:f}}}else if(r.formEncType==="application/json"){if(!Yr(a))return s();try{let f=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:a,formAction:c,formEncType:r.formEncType,formData:void 0,json:f,text:void 0}}}catch{return s()}}}et(typeof FormData=="function","FormData is not available in this environment");let u,i;if(r.formData)u=Fy(r.formData),i=r.formData;else if(r.body instanceof FormData)u=Fy(r.body),i=r.body;else if(r.body instanceof URLSearchParams)u=r.body,i=T0(u);else if(r.body==null)u=new URLSearchParams,i=new FormData;else try{u=new URLSearchParams(r.body),i=T0(u)}catch{return s()}let d={formMethod:a,formAction:c,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(Yr(d.formMethod))return{path:n,submission:d};let p=Ra(n);return t&&p.search&&Ox(p.search)&&u.append("index",""),p.search="?"+u,{path:Pi(p),submission:d}}function oL(e,t){let n=e;if(t){let r=e.findIndex(s=>s.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function C0(e,t,n,r,s,o,a,c,u,i,d,p,f,g,h,m){let x=m?mr(m[1])?m[1].error:m[1].data:void 0,b=e.createURL(t.location),y=e.createURL(s),w=m&&mr(m[1])?m[0]:void 0,S=w?oL(n,w):n,E=m?m[1].statusCode:void 0,C=a&&E&&E>=400,T=S.filter((_,O)=>{let{route:K}=_;if(K.lazy)return!0;if(K.loader==null)return!1;if(o)return typeof K.loader!="function"||K.loader.hydrate?!0:t.loaderData[K.id]===void 0&&(!t.errors||t.errors[K.id]===void 0);if(aL(t.loaderData,t.matches[O],_)||u.some(q=>q===_.route.id))return!0;let I=t.matches[O],Y=_;return E0(_,Kt({currentUrl:b,currentParams:I.params,nextUrl:y,nextParams:Y.params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:c||b.pathname+b.search===y.pathname+y.search||b.search!==y.search||yT(I,Y)}))}),j=[];return p.forEach((_,O)=>{if(o||!n.some(Z=>Z.route.id===_.routeId)||d.has(O))return;let K=Ya(g,_.path,h);if(!K){j.push({key:O,routeId:_.routeId,path:_.path,matches:null,match:null,controller:null});return}let I=t.fetchers.get(O),Y=mu(K,_.path),q=!1;f.has(O)?q=!1:i.includes(O)?q=!0:I&&I.state!=="idle"&&I.data===void 0?q=c:q=E0(Y,Kt({currentUrl:b,currentParams:t.matches[t.matches.length-1].params,nextUrl:y,nextParams:n[n.length-1].params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:c})),q&&j.push({key:O,routeId:_.routeId,path:_.path,matches:K,match:Y,controller:new AbortController})}),[T,j]}function aL(e,t,n){let r=!t||n.route.id!==t.route.id,s=e[n.route.id]===void 0;return r||s}function yT(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function E0(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function iL(e,t,n,r,s,o,a,c){let u=[t,...n.map(i=>i.route.id)].join("-");try{let i=a.get(u);i||(i=e({path:t,matches:n,patch:(d,p)=>{c.aborted||bT(d,p,r,s,o)}}),a.set(u,i)),i&&hL(i)&&await i}finally{a.delete(u)}}function bT(e,t,n,r,s){if(e){var o;let a=r[e];et(a,"No route found to patch children into: routeId = "+e);let c=ad(t,s,[e,"patch",String(((o=a.children)==null?void 0:o.length)||"0")],r);a.children?a.children.push(...c):a.children=c}else{let a=ad(t,s,["patch",String(n.length||"0")],r);n.push(...a)}}async function k0(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let s=n[e.id];et(s,"No route found in manifest");let o={};for(let a in r){let u=s[a]!==void 0&&a!=="hasErrorBoundary";dc(!u,'Route "'+s.id+'" has a static property "'+a+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+a+'" will be ignored.')),!u&&!_2.has(a)&&(o[a]=r[a])}Object.assign(s,o),Object.assign(s,Kt({},t(s),{lazy:void 0}))}function lL(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function cL(e,t,n,r,s,o,a,c){let u=r.reduce((p,f)=>p.add(f.route.id),new Set),i=new Set,d=await e({matches:s.map(p=>{let f=u.has(p.route.id);return Kt({},p,{shouldLoad:f,resolve:h=>(i.add(p.route.id),f?uL(t,n,p,o,a,h,c):Promise.resolve({type:Mt.data,result:void 0}))})}),request:n,params:s[0].params,context:c});return s.forEach(p=>et(i.has(p.route.id),'`match.resolve()` was not called for route id "'+p.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),d.filter((p,f)=>u.has(s[f].route.id))}async function uL(e,t,n,r,s,o,a){let c,u,i=d=>{let p,f=new Promise((m,x)=>p=x);u=()=>p(),t.signal.addEventListener("abort",u);let g=m=>typeof d!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):d({request:t,params:n.params,context:a},...m!==void 0?[m]:[]),h;return o?h=o(m=>g(m)):h=(async()=>{try{return{type:"data",result:await g()}}catch(m){return{type:"error",result:m}}})(),Promise.race([h,f])};try{let d=n.route[e];if(n.route.lazy)if(d){let p,[f]=await Promise.all([i(d).catch(g=>{p=g}),k0(n.route,s,r)]);if(p!==void 0)throw p;c=f}else if(await k0(n.route,s,r),d=n.route[e],d)c=await i(d);else if(e==="action"){let p=new URL(t.url),f=p.pathname+p.search;throw Hn(405,{method:t.method,pathname:f,routeId:n.route.id})}else return{type:Mt.data,result:void 0};else if(d)c=await i(d);else{let p=new URL(t.url),f=p.pathname+p.search;throw Hn(404,{pathname:f})}et(c.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(d){return{type:Mt.error,result:d}}finally{u&&t.signal.removeEventListener("abort",u)}return c}async function dL(e){let{result:t,type:n,status:r}=e;if(wT(t)){let a;try{let c=t.headers.get("Content-Type");c&&/\bapplication\/json\b/.test(c)?t.body==null?a=null:a=await t.json():a=await t.text()}catch(c){return{type:Mt.error,error:c}}return n===Mt.error?{type:Mt.error,error:new Px(t.status,t.statusText,a),statusCode:t.status,headers:t.headers}:{type:Mt.data,data:a,statusCode:t.status,headers:t.headers}}if(n===Mt.error)return{type:Mt.error,error:t,statusCode:Xg(t)?t.status:r};if(vL(t)){var s,o;return{type:Mt.deferred,deferredData:t,statusCode:(s=t.init)==null?void 0:s.status,headers:((o=t.init)==null?void 0:o.headers)&&new Headers(t.init.headers)}}return{type:Mt.data,data:t,statusCode:r}}function fL(e,t,n,r,s,o){let a=e.headers.get("Location");if(et(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!Rx.test(a)){let c=r.slice(0,r.findIndex(u=>u.route.id===n)+1);a=Ay(new URL(t.url),c,s,!0,a,o),e.headers.set("Location",a)}return e}function j0(e,t,n){if(Rx.test(e)){let r=e,s=r.startsWith("//")?new URL(t.protocol+r):new URL(r),o=Cc(s.pathname,n)!=null;if(s.origin===t.origin&&o)return s.pathname+s.search+s.hash}return e}function nl(e,t,n,r){let s=e.createURL(xT(t)).toString(),o={signal:n};if(r&&Yr(r.formMethod)){let{formMethod:a,formEncType:c}=r;o.method=a.toUpperCase(),c==="application/json"?(o.headers=new Headers({"Content-Type":c}),o.body=JSON.stringify(r.json)):c==="text/plain"?o.body=r.text:c==="application/x-www-form-urlencoded"&&r.formData?o.body=Fy(r.formData):o.body=r.formData}return new Request(s,o)}function Fy(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function T0(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function pL(e,t,n,r,s,o){let a={},c=null,u,i=!1,d={},p=r&&mr(r[1])?r[1].error:void 0;return n.forEach((f,g)=>{let h=t[g].route.id;if(et(!ri(f),"Cannot handle redirect results in processLoaderData"),mr(f)){let m=f.error;p!==void 0&&(m=p,p=void 0),c=c||{};{let x=Tl(e,h);c[x.route.id]==null&&(c[x.route.id]=m)}a[h]=void 0,i||(i=!0,u=Xg(f.error)?f.error.status:500),f.headers&&(d[h]=f.headers)}else ni(f)?(s.set(h,f.deferredData),a[h]=f.deferredData.data,f.statusCode!=null&&f.statusCode!==200&&!i&&(u=f.statusCode),f.headers&&(d[h]=f.headers)):(a[h]=f.data,f.statusCode&&f.statusCode!==200&&!i&&(u=f.statusCode),f.headers&&(d[h]=f.headers))}),p!==void 0&&r&&(c={[r[0]]:p},a[r[0]]=void 0),{loaderData:a,errors:c,statusCode:u||200,loaderHeaders:d}}function M0(e,t,n,r,s,o,a,c){let{loaderData:u,errors:i}=pL(t,n,r,s,c);for(let d=0;dr.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function P0(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Hn(e,t){let{pathname:n,routeId:r,method:s,type:o,message:a}=t===void 0?{}:t,c="Unknown Server Error",u="Unknown @remix-run/router error";return e===400?(c="Bad Request",o==="route-discovery"?u='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error: +`+a):s&&n&&r?u="You made a "+s+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":o==="defer-action"?u="defer() is not supported in actions":o==="invalid-body"&&(u="Unable to encode submission body")):e===403?(c="Forbidden",u='Route "'+r+'" does not match URL "'+n+'"'):e===404?(c="Not Found",u='No route matches URL "'+n+'"'):e===405&&(c="Method Not Allowed",s&&n&&r?u="You made a "+s.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":s&&(u='Invalid request method "'+s.toUpperCase()+'"')),new Px(e||500,c,new Error(u),!0)}function R0(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(ri(n))return{result:n,idx:t}}}function xT(e){let t=typeof e=="string"?Ra(e):e;return Pi(Kt({},t,{hash:""}))}function gL(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function hL(e){return typeof e=="object"&&e!=null&&"then"in e}function mL(e){return wT(e.result)&&X2.has(e.result.status)}function ni(e){return e.type===Mt.deferred}function mr(e){return e.type===Mt.error}function ri(e){return(e&&e.type)===Mt.redirect}function vL(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function wT(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function yL(e){return Y2.has(e.toLowerCase())}function Yr(e){return Q2.has(e.toLowerCase())}async function O0(e,t,n,r,s,o){for(let a=0;ap.route.id===u.route.id),d=i!=null&&!yT(i,u)&&(o&&o[u.route.id])!==void 0;if(ni(c)&&(s||d)){let p=r[a];et(p,"Expected an AbortSignal for revalidating fetcher deferred result"),await ST(c,p,s).then(f=>{f&&(n[a]=f||n[a])})}}}async function ST(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:Mt.data,data:e.deferredData.unwrappedData}}catch(s){return{type:Mt.error,error:s}}return{type:Mt.data,data:e.deferredData.data}}}function Ox(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function mu(e,t){let n=typeof t=="string"?Ra(t).search:t.search;if(e[e.length-1].route.index&&Ox(n||""))return e[e.length-1];let r=hT(e);return r[r.length-1]}function I0(e){let{formMethod:t,formAction:n,formEncType:r,text:s,formData:o,json:a}=e;if(!(!t||!n||!r)){if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:s};if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:o,json:void 0,text:void 0};if(a!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:a,text:void 0}}}function Lm(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function bL(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Yc(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function xL(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Uo(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function wL(e,t){try{let n=e.sessionStorage.getItem(vT);if(n){let r=JSON.parse(n);for(let[s,o]of Object.entries(r||{}))o&&Array.isArray(o)&&t.set(s,new Set(o||[]))}}catch{}}function SL(e,t){if(t.size>0){let n={};for(let[r,s]of t)n[r]=[...s];try{e.sessionStorage.setItem(vT,JSON.stringify(n))}catch(r){dc(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** + * React Router v6.25.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Yp(){return Yp=Object.assign?Object.assign.bind():function(e){for(var t=1;t{c.current=!0}),v.useCallback(function(i,d){if(d===void 0&&(d={}),!c.current)return;if(typeof i=="number"){r.go(i);return}let p=Yg(i,JSON.parse(a),o,d.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:ho([t,p.pathname])),(d.replace?r.replace:r.push)(p,d.state,d)},[t,r,a,o,e])}function gs(){let{matches:e}=v.useContext(jo),t=e[e.length-1];return t?t.params:{}}function jT(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=v.useContext(Oa),{matches:s}=v.useContext(jo),{pathname:o}=kc(),a=JSON.stringify(Zg(s,r.v7_relativeSplatPath));return v.useMemo(()=>Yg(e,JSON.parse(a),o,n==="path"),[e,a,o,n])}function kL(e,t,n,r){Ec()||et(!1);let{navigator:s}=v.useContext(Oa),{matches:o}=v.useContext(jo),a=o[o.length-1],c=a?a.params:{};a&&a.pathname;let u=a?a.pathnameBase:"/";a&&a.route;let i=kc(),d;d=i;let p=d.pathname||"/",f=p;if(u!=="/"){let m=u.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(m.length).join("/")}let g=Ya(e,{pathname:f});return _L(g&&g.map(m=>Object.assign({},m,{params:Object.assign({},c,m.params),pathname:ho([u,s.encodeLocation?s.encodeLocation(m.pathname).pathname:m.pathname]),pathnameBase:m.pathnameBase==="/"?u:ho([u,s.encodeLocation?s.encodeLocation(m.pathnameBase).pathname:m.pathnameBase])})),o,n,r)}function jL(){let e=IL(),t=Xg(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),n?v.createElement("pre",{style:s},n):null,null)}const TL=v.createElement(jL,null);class ML extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?v.createElement(jo.Provider,{value:this.props.routeContext},v.createElement(ET.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function NL(e){let{routeContext:t,match:n,children:r}=e,s=v.useContext(eh);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),v.createElement(jo.Provider,{value:t},r)}function _L(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if((o=n)!=null&&o.errors)e=n.matches;else return null}let a=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let d=a.findIndex(p=>p.route.id&&(c==null?void 0:c[p.route.id])!==void 0);d>=0||et(!1),a=a.slice(0,Math.min(a.length,d+1))}let u=!1,i=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?a=a.slice(0,i+1):a=[a[0]];break}}}return a.reduceRight((d,p,f)=>{let g,h=!1,m=null,x=null;n&&(g=c&&p.route.id?c[p.route.id]:void 0,m=p.route.errorElement||TL,u&&(i<0&&f===0?(AL("route-fallback"),h=!0,x=null):i===f&&(h=!0,x=p.route.hydrateFallbackElement||null)));let b=t.concat(a.slice(0,f+1)),y=()=>{let w;return g?w=m:h?w=x:p.route.Component?w=v.createElement(p.route.Component,null):p.route.element?w=p.route.element:w=d,v.createElement(NL,{match:p,routeContext:{outlet:d,matches:b,isDataRoute:n!=null},children:w})};return n&&(p.route.ErrorBoundary||p.route.errorElement||f===0)?v.createElement(ML,{location:n.location,revalidation:n.revalidation,component:m,error:g,children:y(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):y()},null)}var TT=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(TT||{}),Xp=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Xp||{});function PL(e){let t=v.useContext(eh);return t||et(!1),t}function RL(e){let t=v.useContext(CT);return t||et(!1),t}function OL(e){let t=v.useContext(jo);return t||et(!1),t}function MT(e){let t=OL(),n=t.matches[t.matches.length-1];return n.route.id||et(!1),n.route.id}function IL(){var e;let t=v.useContext(ET),n=RL(Xp.UseRouteError),r=MT(Xp.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function DL(){let{router:e}=PL(TT.UseNavigateStable),t=MT(Xp.UseNavigateStable),n=v.useRef(!1);return kT(()=>{n.current=!0}),v.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Yp({fromRouteId:t},o)))},[e,t])}const D0={};function AL(e,t,n){D0[e]||(D0[e]=!0)}function NT(e){let{to:t,replace:n,state:r,relative:s}=e;Ec()||et(!1);let{future:o,static:a}=v.useContext(Oa),{matches:c}=v.useContext(jo),{pathname:u}=kc(),i=an(),d=Yg(t,Zg(c,o.v7_relativeSplatPath),u,s==="path"),p=JSON.stringify(d);return v.useEffect(()=>i(JSON.parse(p),{replace:n,state:r,relative:s}),[i,p,s,n,r]),null}function FL(e){let{basename:t="/",children:n=null,location:r,navigationType:s=rn.Pop,navigator:o,static:a=!1,future:c}=e;Ec()&&et(!1);let u=t.replace(/^\/*/,"/"),i=v.useMemo(()=>({basename:u,navigator:o,static:a,future:Yp({v7_relativeSplatPath:!1},c)}),[u,c,o,a]);typeof r=="string"&&(r=Ra(r));let{pathname:d="/",search:p="",hash:f="",state:g=null,key:h="default"}=r,m=v.useMemo(()=>{let x=Cc(d,u);return x==null?null:{location:{pathname:x,search:p,hash:f,state:g,key:h},navigationType:s}},[u,d,p,f,g,h,s]);return m==null?null:v.createElement(Oa.Provider,{value:i},v.createElement(Ix.Provider,{children:n,value:m}))}new Promise(()=>{});function LL(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:v.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:v.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:v.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** + * React Router DOM v6.25.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function id(){return id=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function BL(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function zL(e,t){return e.button===0&&(!t||t==="_self")&&!BL(e)}const UL=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],VL="6";try{window.__reactRouterVersion=VL}catch{}function HL(e,t){return rL({basename:void 0,future:id({},void 0,{v7_prependBasename:!0}),history:T2({window:void 0}),hydrationData:KL(),routes:e,mapRouteProperties:LL,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function KL(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=id({},t,{errors:qL(t.errors)})),t}function qL(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,s]of t)if(s&&s.__type==="RouteErrorResponse")n[r]=new Px(s.status,s.statusText,s.data,s.internal===!0);else if(s&&s.__type==="Error"){if(s.__subType){let o=window[s.__subType];if(typeof o=="function")try{let a=new o(s.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let o=new Error(s.message);o.stack="",n[r]=o}}else n[r]=s;return n}const WL=v.createContext({isTransitioning:!1}),GL=v.createContext(new Map),JL="startTransition",A0=Dg[JL],QL="flushSync",F0=u2[QL];function ZL(e){A0?A0(e):e()}function Xc(e){F0?F0(e):e()}class YL{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function XL(e){let{fallbackElement:t,router:n,future:r}=e,[s,o]=v.useState(n.state),[a,c]=v.useState(),[u,i]=v.useState({isTransitioning:!1}),[d,p]=v.useState(),[f,g]=v.useState(),[h,m]=v.useState(),x=v.useRef(new Map),{v7_startTransition:b}=r||{},y=v.useCallback(j=>{b?ZL(j):j()},[b]),w=v.useCallback((j,_)=>{let{deletedFetchers:O,unstable_flushSync:K,unstable_viewTransitionOpts:I}=_;O.forEach(q=>x.current.delete(q)),j.fetchers.forEach((q,Z)=>{q.data!==void 0&&x.current.set(Z,q.data)});let Y=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!I||Y){K?Xc(()=>o(j)):y(()=>o(j));return}if(K){Xc(()=>{f&&(d&&d.resolve(),f.skipTransition()),i({isTransitioning:!0,flushSync:!0,currentLocation:I.currentLocation,nextLocation:I.nextLocation})});let q=n.window.document.startViewTransition(()=>{Xc(()=>o(j))});q.finished.finally(()=>{Xc(()=>{p(void 0),g(void 0),c(void 0),i({isTransitioning:!1})})}),Xc(()=>g(q));return}f?(d&&d.resolve(),f.skipTransition(),m({state:j,currentLocation:I.currentLocation,nextLocation:I.nextLocation})):(c(j),i({isTransitioning:!0,flushSync:!1,currentLocation:I.currentLocation,nextLocation:I.nextLocation}))},[n.window,f,d,x,y]);v.useLayoutEffect(()=>n.subscribe(w),[n,w]),v.useEffect(()=>{u.isTransitioning&&!u.flushSync&&p(new YL)},[u]),v.useEffect(()=>{if(d&&a&&n.window){let j=a,_=d.promise,O=n.window.document.startViewTransition(async()=>{y(()=>o(j)),await _});O.finished.finally(()=>{p(void 0),g(void 0),c(void 0),i({isTransitioning:!1})}),g(O)}},[y,a,d,n.window]),v.useEffect(()=>{d&&a&&s.location.key===a.location.key&&d.resolve()},[d,f,s.location,a]),v.useEffect(()=>{!u.isTransitioning&&h&&(c(h.state),i({isTransitioning:!0,flushSync:!1,currentLocation:h.currentLocation,nextLocation:h.nextLocation}),m(void 0))},[u.isTransitioning,h]),v.useEffect(()=>{},[]);let S=v.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:j=>n.navigate(j),push:(j,_,O)=>n.navigate(j,{state:_,preventScrollReset:O==null?void 0:O.preventScrollReset}),replace:(j,_,O)=>n.navigate(j,{replace:!0,state:_,preventScrollReset:O==null?void 0:O.preventScrollReset})}),[n]),E=n.basename||"/",C=v.useMemo(()=>({router:n,navigator:S,static:!1,basename:E}),[n,S,E]),T=v.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return v.createElement(v.Fragment,null,v.createElement(eh.Provider,{value:C},v.createElement(CT.Provider,{value:s},v.createElement(GL.Provider,{value:x.current},v.createElement(WL.Provider,{value:u},v.createElement(FL,{basename:E,location:s.location,navigationType:s.historyAction,navigator:S,future:T},s.initialized||n.future.v7_partialHydration?v.createElement(e$,{routes:n.routes,future:n.future,state:s}):t))))),null)}const e$=v.memo(t$);function t$(e){let{routes:t,future:n,state:r}=e;return kL(t,void 0,r,n)}const n$=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",r$=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ld=v.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:o,replace:a,state:c,target:u,to:i,preventScrollReset:d,unstable_viewTransition:p}=t,f=$L(t,UL),{basename:g}=v.useContext(Oa),h,m=!1;if(typeof i=="string"&&r$.test(i)&&(h=i,n$))try{let w=new URL(window.location.href),S=i.startsWith("//")?new URL(w.protocol+i):new URL(i),E=Cc(S.pathname,g);S.origin===w.origin&&E!=null?i=E+S.search+S.hash:m=!0}catch{}let x=CL(i,{relative:s}),b=s$(i,{replace:a,state:c,target:u,preventScrollReset:d,relative:s,unstable_viewTransition:p});function y(w){r&&r(w),w.defaultPrevented||b(w)}return v.createElement("a",id({},f,{href:h||x,onClick:m||o?r:y,ref:n,target:u}))});var L0;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(L0||(L0={}));var $0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})($0||($0={}));function s$(e,t){let{target:n,replace:r,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:c}=t===void 0?{}:t,u=an(),i=kc(),d=jT(e,{relative:a});return v.useCallback(p=>{if(zL(p,n)){p.preventDefault();let f=r!==void 0?r:Pi(i)===Pi(d);u(e,{replace:f,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:c})}},[i,u,d,r,s,n,e,o,a,c])}function _T(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;ttypeof e=="number"&&!isNaN(e),xi=e=>typeof e=="string",br=e=>typeof e=="function",fp=e=>xi(e)||br(e)?e:null,Ly=e=>v.isValidElement(e)||xi(e)||br(e)||cd(e);function o$(e,t,n){n===void 0&&(n=300);const{scrollHeight:r,style:s}=e;requestAnimationFrame(()=>{s.minHeight="initial",s.height=r+"px",s.transition=`all ${n}ms`,requestAnimationFrame(()=>{s.height="0",s.padding="0",s.margin="0",setTimeout(t,n)})})}function th(e){let{enter:t,exit:n,appendPosition:r=!1,collapse:s=!0,collapseDuration:o=300}=e;return function(a){let{children:c,position:u,preventExitTransition:i,done:d,nodeRef:p,isIn:f,playToast:g}=a;const h=r?`${t}--${u}`:t,m=r?`${n}--${u}`:n,x=v.useRef(0);return v.useLayoutEffect(()=>{const b=p.current,y=h.split(" "),w=S=>{S.target===p.current&&(g(),b.removeEventListener("animationend",w),b.removeEventListener("animationcancel",w),x.current===0&&S.type!=="animationcancel"&&b.classList.remove(...y))};b.classList.add(...y),b.addEventListener("animationend",w),b.addEventListener("animationcancel",w)},[]),v.useEffect(()=>{const b=p.current,y=()=>{b.removeEventListener("animationend",y),s?o$(b,d,o):d()};f||(i?y():(x.current=1,b.className+=` ${m}`,b.addEventListener("animationend",y)))},[f]),je.createElement(je.Fragment,null,c)}}function B0(e,t){return e!=null?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const Wn=new Map;let ud=[];const $y=new Set,a$=e=>$y.forEach(t=>t(e)),PT=()=>Wn.size>0;function RT(e,t){var n;if(t)return!((n=Wn.get(t))==null||!n.isToastActive(e));let r=!1;return Wn.forEach(s=>{s.isToastActive(e)&&(r=!0)}),r}function OT(e,t){Ly(e)&&(PT()||ud.push({content:e,options:t}),Wn.forEach(n=>{n.buildToast(e,t)}))}function z0(e,t){Wn.forEach(n=>{t!=null&&t!=null&&t.containerId?(t==null?void 0:t.containerId)===n.id&&n.toggle(e,t==null?void 0:t.id):n.toggle(e,t==null?void 0:t.id)})}function i$(e){const{subscribe:t,getSnapshot:n,setProps:r}=v.useRef(function(o){const a=o.containerId||1;return{subscribe(c){const u=function(d,p,f){let g=1,h=0,m=[],x=[],b=[],y=p;const w=new Map,S=new Set,E=()=>{b=Array.from(w.values()),S.forEach(j=>j())},C=j=>{x=j==null?[]:x.filter(_=>_!==j),E()},T=j=>{const{toastId:_,onOpen:O,updateId:K,children:I}=j.props,Y=K==null;j.staleId&&w.delete(j.staleId),w.set(_,j),x=[...x,j.props.toastId].filter(q=>q!==j.staleId),E(),f(B0(j,Y?"added":"updated")),Y&&br(O)&&O(v.isValidElement(I)&&I.props)};return{id:d,props:y,observe:j=>(S.add(j),()=>S.delete(j)),toggle:(j,_)=>{w.forEach(O=>{_!=null&&_!==O.props.toastId||br(O.toggle)&&O.toggle(j)})},removeToast:C,toasts:w,clearQueue:()=>{h-=m.length,m=[]},buildToast:(j,_)=>{if((H=>{let{containerId:se,toastId:ne,updateId:le}=H;const oe=se?se!==d:d!==1,Q=w.has(ne)&&le==null;return oe||Q})(_))return;const{toastId:O,updateId:K,data:I,staleId:Y,delay:q}=_,Z=()=>{C(O)},ee=K==null;ee&&h++;const J={...y,style:y.toastStyle,key:g++,...Object.fromEntries(Object.entries(_).filter(H=>{let[se,ne]=H;return ne!=null})),toastId:O,updateId:K,data:I,closeToast:Z,isIn:!1,className:fp(_.className||y.toastClassName),bodyClassName:fp(_.bodyClassName||y.bodyClassName),progressClassName:fp(_.progressClassName||y.progressClassName),autoClose:!_.isLoading&&(L=_.autoClose,A=y.autoClose,L===!1||cd(L)&&L>0?L:A),deleteToast(){const H=w.get(O),{onClose:se,children:ne}=H.props;br(se)&&se(v.isValidElement(ne)&&ne.props),f(B0(H,"removed")),w.delete(O),h--,h<0&&(h=0),m.length>0?T(m.shift()):E()}};var L,A;J.closeButton=y.closeButton,_.closeButton===!1||Ly(_.closeButton)?J.closeButton=_.closeButton:_.closeButton===!0&&(J.closeButton=!Ly(y.closeButton)||y.closeButton);let X=j;v.isValidElement(j)&&!xi(j.type)?X=v.cloneElement(j,{closeToast:Z,toastProps:J,data:I}):br(j)&&(X=j({closeToast:Z,toastProps:J,data:I}));const fe={content:X,props:J,staleId:Y};y.limit&&y.limit>0&&h>y.limit&&ee?m.push(fe):cd(q)?setTimeout(()=>{T(fe)},q):T(fe)},setProps(j){y=j},setToggle:(j,_)=>{w.get(j).toggle=_},isToastActive:j=>x.some(_=>_===j),getSnapshot:()=>y.newestOnTop?b.reverse():b}}(a,o,a$);Wn.set(a,u);const i=u.observe(c);return ud.forEach(d=>OT(d.content,d.options)),ud=[],()=>{i(),Wn.delete(a)}},setProps(c){var u;(u=Wn.get(a))==null||u.setProps(c)},getSnapshot(){var c;return(c=Wn.get(a))==null?void 0:c.getSnapshot()}}}(e)).current;r(e);const s=v.useSyncExternalStore(t,n,n);return{getToastToRender:function(o){if(!s)return[];const a=new Map;return s.forEach(c=>{const{position:u}=c.props;a.has(u)||a.set(u,[]),a.get(u).push(c)}),Array.from(a,c=>o(c[0],c[1]))},isToastActive:RT,count:s==null?void 0:s.length}}function l$(e){const[t,n]=v.useState(!1),[r,s]=v.useState(!1),o=v.useRef(null),a=v.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:c,pauseOnHover:u,closeToast:i,onClick:d,closeOnClick:p}=e;var f,g;function h(){n(!0)}function m(){n(!1)}function x(w){const S=o.current;a.canDrag&&S&&(a.didMove=!0,t&&m(),a.delta=e.draggableDirection==="x"?w.clientX-a.start:w.clientY-a.start,a.start!==w.clientX&&(a.canCloseOnClick=!1),S.style.transform=`translate3d(${e.draggableDirection==="x"?`${a.delta}px, var(--y)`:`0, calc(${a.delta}px + var(--y))`},0)`,S.style.opacity=""+(1-Math.abs(a.delta/a.removalDistance)))}function b(){document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",b);const w=o.current;if(a.canDrag&&a.didMove&&w){if(a.canDrag=!1,Math.abs(a.delta)>a.removalDistance)return s(!0),e.closeToast(),void e.collapseAll();w.style.transition="transform 0.2s, opacity 0.2s",w.style.removeProperty("transform"),w.style.removeProperty("opacity")}}(g=Wn.get((f={id:e.toastId,containerId:e.containerId,fn:n}).containerId||1))==null||g.setToggle(f.id,f.fn),v.useEffect(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||m(),window.addEventListener("focus",h),window.addEventListener("blur",m),()=>{window.removeEventListener("focus",h),window.removeEventListener("blur",m)}},[e.pauseOnFocusLoss]);const y={onPointerDown:function(w){if(e.draggable===!0||e.draggable===w.pointerType){a.didMove=!1,document.addEventListener("pointermove",x),document.addEventListener("pointerup",b);const S=o.current;a.canCloseOnClick=!0,a.canDrag=!0,S.style.transition="none",e.draggableDirection==="x"?(a.start=w.clientX,a.removalDistance=S.offsetWidth*(e.draggablePercent/100)):(a.start=w.clientY,a.removalDistance=S.offsetHeight*(e.draggablePercent===80?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(w){const{top:S,bottom:E,left:C,right:T}=o.current.getBoundingClientRect();w.nativeEvent.type!=="touchend"&&e.pauseOnHover&&w.clientX>=C&&w.clientX<=T&&w.clientY>=S&&w.clientY<=E?m():h()}};return c&&u&&(y.onMouseEnter=m,e.stacked||(y.onMouseLeave=h)),p&&(y.onClick=w=>{d&&d(w),a.canCloseOnClick&&i()}),{playToast:h,pauseToast:m,isRunning:t,preventExitTransition:r,toastRef:o,eventHandlers:y}}function c$(e){let{delay:t,isRunning:n,closeToast:r,type:s="default",hide:o,className:a,style:c,controlledProgress:u,progress:i,rtl:d,isIn:p,theme:f}=e;const g=o||u&&i===0,h={...c,animationDuration:`${t}ms`,animationPlayState:n?"running":"paused"};u&&(h.transform=`scaleX(${i})`);const m=uo("Toastify__progress-bar",u?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${f}`,`Toastify__progress-bar--${s}`,{"Toastify__progress-bar--rtl":d}),x=br(a)?a({rtl:d,type:s,defaultClassName:m}):uo(m,a),b={[u&&i>=1?"onTransitionEnd":"onAnimationEnd"]:u&&i<1?null:()=>{p&&r()}};return je.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":g},je.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${f} Toastify__progress-bar--${s}`}),je.createElement("div",{role:"progressbar","aria-hidden":g?"true":"false","aria-label":"notification timer",className:x,style:h,...b}))}let u$=1;const IT=()=>""+u$++;function d$(e){return e&&(xi(e.toastId)||cd(e.toastId))?e.toastId:IT()}function Ou(e,t){return OT(e,t),t.toastId}function eg(e,t){return{...t,type:t&&t.type||e,toastId:d$(t)}}function Nf(e){return(t,n)=>Ou(t,eg(e,n))}function G(e,t){return Ou(e,eg("default",t))}G.loading=(e,t)=>Ou(e,eg("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),G.promise=function(e,t,n){let r,{pending:s,error:o,success:a}=t;s&&(r=xi(s)?G.loading(s,n):G.loading(s.render,{...n,...s}));const c={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},u=(d,p,f)=>{if(p==null)return void G.dismiss(r);const g={type:d,...c,...n,data:f},h=xi(p)?{render:p}:p;return r?G.update(r,{...g,...h}):G(h.render,{...g,...h}),f},i=br(e)?e():e;return i.then(d=>u("success",a,d)).catch(d=>u("error",o,d)),i},G.success=Nf("success"),G.info=Nf("info"),G.error=Nf("error"),G.warning=Nf("warning"),G.warn=G.warning,G.dark=(e,t)=>Ou(e,eg("default",{theme:"dark",...t})),G.dismiss=function(e){(function(t){var n;if(PT()){if(t==null||xi(n=t)||cd(n))Wn.forEach(r=>{r.removeToast(t)});else if(t&&("containerId"in t||"id"in t)){const r=Wn.get(t.containerId);r?r.removeToast(t.id):Wn.forEach(s=>{s.removeToast(t.id)})}}else ud=ud.filter(r=>t!=null&&r.options.toastId!==t)})(e)},G.clearWaitingQueue=function(e){e===void 0&&(e={}),Wn.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},G.isActive=RT,G.update=function(e,t){t===void 0&&(t={});const n=((r,s)=>{var o;let{containerId:a}=s;return(o=Wn.get(a||1))==null?void 0:o.toasts.get(r)})(e,t);if(n){const{props:r,content:s}=n,o={delay:100,...r,...t,toastId:t.toastId||e,updateId:IT()};o.toastId!==e&&(o.staleId=e);const a=o.render||s;delete o.render,Ou(a,o)}},G.done=e=>{G.update(e,{progress:1})},G.onChange=function(e){return $y.add(e),()=>{$y.delete(e)}},G.play=e=>z0(!0,e),G.pause=e=>z0(!1,e);const f$=typeof window<"u"?v.useLayoutEffect:v.useEffect,_f=e=>{let{theme:t,type:n,isLoading:r,...s}=e;return je.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:t==="colored"?"currentColor":`var(--toastify-icon-color-${n})`,...s})},$m={info:function(e){return je.createElement(_f,{...e},je.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(e){return je.createElement(_f,{...e},je.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(e){return je.createElement(_f,{...e},je.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(e){return je.createElement(_f,{...e},je.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return je.createElement("div",{className:"Toastify__spinner"})}},p$=e=>{const{isRunning:t,preventExitTransition:n,toastRef:r,eventHandlers:s,playToast:o}=l$(e),{closeButton:a,children:c,autoClose:u,onClick:i,type:d,hideProgressBar:p,closeToast:f,transition:g,position:h,className:m,style:x,bodyClassName:b,bodyStyle:y,progressClassName:w,progressStyle:S,updateId:E,role:C,progress:T,rtl:j,toastId:_,deleteToast:O,isIn:K,isLoading:I,closeOnClick:Y,theme:q}=e,Z=uo("Toastify__toast",`Toastify__toast-theme--${q}`,`Toastify__toast--${d}`,{"Toastify__toast--rtl":j},{"Toastify__toast--close-on-click":Y}),ee=br(m)?m({rtl:j,position:h,type:d,defaultClassName:Z}):uo(Z,m),J=function(fe){let{theme:H,type:se,isLoading:ne,icon:le}=fe,oe=null;const Q={theme:H,type:se};return le===!1||(br(le)?oe=le({...Q,isLoading:ne}):v.isValidElement(le)?oe=v.cloneElement(le,Q):ne?oe=$m.spinner():(Ee=>Ee in $m)(se)&&(oe=$m[se](Q))),oe}(e),L=!!T||!u,A={closeToast:f,type:d,theme:q};let X=null;return a===!1||(X=br(a)?a(A):v.isValidElement(a)?v.cloneElement(a,A):function(fe){let{closeToast:H,theme:se,ariaLabel:ne="close"}=fe;return je.createElement("button",{className:`Toastify__close-button Toastify__close-button--${se}`,type:"button",onClick:le=>{le.stopPropagation(),H(le)},"aria-label":ne},je.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},je.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(A)),je.createElement(g,{isIn:K,done:O,position:h,preventExitTransition:n,nodeRef:r,playToast:o},je.createElement("div",{id:_,onClick:i,"data-in":K,className:ee,...s,style:x,ref:r},je.createElement("div",{...K&&{role:C},className:br(b)?b({type:d}):uo("Toastify__toast-body",b),style:y},J!=null&&je.createElement("div",{className:uo("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!I})},J),je.createElement("div",null,c)),X,je.createElement(c$,{...E&&!L?{key:`pb-${E}`}:{},rtl:j,theme:q,delay:u,isRunning:t,isIn:K,closeToast:f,hide:p,type:d,style:S,className:w,controlledProgress:L,progress:T||0})))},nh=function(e,t){return t===void 0&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},g$=th(nh("bounce",!0));th(nh("slide",!0));th(nh("zoom"));th(nh("flip"));const h$={position:"top-right",transition:g$,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function m$(e){let t={...h$,...e};const n=e.stacked,[r,s]=v.useState(!0),o=v.useRef(null),{getToastToRender:a,isToastActive:c,count:u}=i$(t),{className:i,style:d,rtl:p,containerId:f}=t;function g(m){const x=uo("Toastify__toast-container",`Toastify__toast-container--${m}`,{"Toastify__toast-container--rtl":p});return br(i)?i({position:m,rtl:p,defaultClassName:x}):uo(x,fp(i))}function h(){n&&(s(!0),G.play())}return f$(()=>{if(n){var m;const x=o.current.querySelectorAll('[data-in="true"]'),b=12,y=(m=t.position)==null?void 0:m.includes("top");let w=0,S=0;Array.from(x).reverse().forEach((E,C)=>{const T=E;T.classList.add("Toastify__toast--stacked"),C>0&&(T.dataset.collapsed=`${r}`),T.dataset.pos||(T.dataset.pos=y?"top":"bot");const j=w*(r?.2:1)+(r?0:b*C);T.style.setProperty("--y",`${y?j:-1*j}px`),T.style.setProperty("--g",`${b}`),T.style.setProperty("--s",""+(1-(r?S:0))),w+=T.offsetHeight,S+=.025})}},[r,u,n]),je.createElement("div",{ref:o,className:"Toastify",id:f,onMouseEnter:()=>{n&&(s(!1),G.pause())},onMouseLeave:h},a((m,x)=>{const b=x.length?{...d}:{...d,pointerEvents:"none"};return je.createElement("div",{className:g(m),style:b,key:`container-${m}`},x.map(y=>{let{content:w,props:S}=y;return je.createElement(p$,{...S,stacked:n,collapseAll:h,isIn:c(S.toastId,S.containerId),style:S.style,key:`toast-${S.key}`},w)}))}))}const v$={theme:"system",setTheme:()=>null},DT=v.createContext(v$);function y$({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const[s,o]=v.useState(()=>localStorage.getItem(n)||t);v.useEffect(()=>{const c=window.document.documentElement;if(c.classList.remove("light","dark"),s==="system"){const u=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";c.classList.add(u);return}c.classList.add(s)},[s]);const a={theme:s,setTheme:c=>{localStorage.setItem(n,c),o(c)}};return l.jsx(DT.Provider,{...r,value:a,children:e})}const Dx=()=>{const e=v.useContext(DT);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e};let Bm=!1;const b$=new zD({defaultOptions:{queries:{staleTime:1e3*60*5,retry(e){return e>=3?(Bm===!1&&(Bm=!0,G.error("The application is taking longer than expected to load, please try again in a few minutes.",{onClose:()=>{Bm=!1}})),!1):!0}}}});var Fn=(e=>(e.API_URL="apiUrl",e.TOKEN="token",e.INSTANCE_ID="instanceId",e.INSTANCE_NAME="instanceName",e.INSTANCE_TOKEN="instanceToken",e.VERSION="version",e.FACEBOOK_APP_ID="facebookAppId",e.FACEBOOK_CONFIG_ID="facebookConfigId",e.FACEBOOK_USER_TOKEN="facebookUserToken",e.CLIENT_NAME="clientName",e))(Fn||{});const AT=async e=>{if(e.url){const t=e.url.endsWith("/")?e.url.slice(0,-1):e.url;localStorage.setItem("apiUrl",t)}e.token&&localStorage.setItem("token",e.token),e.version&&localStorage.setItem("version",e.version),e.facebookAppId&&localStorage.setItem("facebookAppId",e.facebookAppId),e.facebookConfigId&&localStorage.setItem("facebookConfigId",e.facebookConfigId),e.facebookUserToken&&localStorage.setItem("facebookUserToken",e.facebookUserToken),e.clientName&&localStorage.setItem("clientName",e.clientName)},FT=()=>{localStorage.removeItem("apiUrl"),localStorage.removeItem("token"),localStorage.removeItem("version"),localStorage.removeItem("facebookAppId"),localStorage.removeItem("facebookConfigId"),localStorage.removeItem("facebookUserToken"),localStorage.removeItem("clientName")},zr=e=>localStorage.getItem(e),Rt=({children:e})=>{const t=zr(Fn.API_URL),n=zr(Fn.TOKEN),r=zr(Fn.VERSION);return!t||!n||!r?l.jsx(NT,{to:"/manager/login"}):e},x$=({children:e})=>{const t=zr(Fn.API_URL),n=zr(Fn.TOKEN),r=zr(Fn.VERSION);return t&&n&&r?l.jsx(NT,{to:"/"}):e};function LT(e,t){return function(){return e.apply(t,arguments)}}const{toString:w$}=Object.prototype,{getPrototypeOf:Ax}=Object,rh=(e=>t=>{const n=w$.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),hs=e=>(e=e.toLowerCase(),t=>rh(t)===e),sh=e=>t=>typeof t===e,{isArray:jc}=Array,dd=sh("undefined");function S$(e){return e!==null&&!dd(e)&&e.constructor!==null&&!dd(e.constructor)&&Ur(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const $T=hs("ArrayBuffer");function C$(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&$T(e.buffer),t}const E$=sh("string"),Ur=sh("function"),BT=sh("number"),oh=e=>e!==null&&typeof e=="object",k$=e=>e===!0||e===!1,pp=e=>{if(rh(e)!=="object")return!1;const t=Ax(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},j$=hs("Date"),T$=hs("File"),M$=hs("Blob"),N$=hs("FileList"),_$=e=>oh(e)&&Ur(e.pipe),P$=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Ur(e.append)&&((t=rh(e))==="formdata"||t==="object"&&Ur(e.toString)&&e.toString()==="[object FormData]"))},R$=hs("URLSearchParams"),[O$,I$,D$,A$]=["ReadableStream","Request","Response","Headers"].map(hs),F$=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function qd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),jc(e))for(r=0,s=e.length;r0;)if(s=n[r],t===s.toLowerCase())return s;return null}const UT=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,VT=e=>!dd(e)&&e!==UT;function By(){const{caseless:e}=VT(this)&&this||{},t={},n=(r,s)=>{const o=e&&zT(t,s)||s;pp(t[o])&&pp(r)?t[o]=By(t[o],r):pp(r)?t[o]=By({},r):jc(r)?t[o]=r.slice():t[o]=r};for(let r=0,s=arguments.length;r(qd(t,(s,o)=>{n&&Ur(s)?e[o]=LT(s,n):e[o]=s},{allOwnKeys:r}),e),$$=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),B$=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},z$=(e,t,n,r)=>{let s,o,a;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)a=s[o],(!r||r(a,e,t))&&!c[a]&&(t[a]=e[a],c[a]=!0);e=n!==!1&&Ax(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},U$=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},V$=e=>{if(!e)return null;if(jc(e))return e;let t=e.length;if(!BT(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},H$=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ax(Uint8Array)),K$=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},q$=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},W$=hs("HTMLFormElement"),G$=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),U0=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),J$=hs("RegExp"),HT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};qd(n,(s,o)=>{let a;(a=t(s,o,e))!==!1&&(r[o]=a||s)}),Object.defineProperties(e,r)},Q$=e=>{HT(e,(t,n)=>{if(Ur(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Ur(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Z$=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return jc(e)?r(e):r(String(e).split(t)),n},Y$=()=>{},X$=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,zm="abcdefghijklmnopqrstuvwxyz",V0="0123456789",KT={DIGIT:V0,ALPHA:zm,ALPHA_DIGIT:zm+zm.toUpperCase()+V0},e4=(e=16,t=KT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function t4(e){return!!(e&&Ur(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const n4=e=>{const t=new Array(10),n=(r,s)=>{if(oh(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[s]=r;const o=jc(r)?[]:{};return qd(r,(a,c)=>{const u=n(a,s+1);!dd(u)&&(o[c]=u)}),t[s]=void 0,o}}return r};return n(e,0)},r4=hs("AsyncFunction"),s4=e=>e&&(oh(e)||Ur(e))&&Ur(e.then)&&Ur(e.catch),U={isArray:jc,isArrayBuffer:$T,isBuffer:S$,isFormData:P$,isArrayBufferView:C$,isString:E$,isNumber:BT,isBoolean:k$,isObject:oh,isPlainObject:pp,isReadableStream:O$,isRequest:I$,isResponse:D$,isHeaders:A$,isUndefined:dd,isDate:j$,isFile:T$,isBlob:M$,isRegExp:J$,isFunction:Ur,isStream:_$,isURLSearchParams:R$,isTypedArray:H$,isFileList:N$,forEach:qd,merge:By,extend:L$,trim:F$,stripBOM:$$,inherits:B$,toFlatObject:z$,kindOf:rh,kindOfTest:hs,endsWith:U$,toArray:V$,forEachEntry:K$,matchAll:q$,isHTMLForm:W$,hasOwnProperty:U0,hasOwnProp:U0,reduceDescriptors:HT,freezeMethods:Q$,toObjectSet:Z$,toCamelCase:G$,noop:Y$,toFiniteNumber:X$,findKey:zT,global:UT,isContextDefined:VT,ALPHABET:KT,generateString:e4,isSpecCompliantForm:t4,toJSONObject:n4,isAsyncFn:r4,isThenable:s4};function We(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s)}U.inherits(We,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:U.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const qT=We.prototype,WT={};["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(e=>{WT[e]={value:e}});Object.defineProperties(We,WT);Object.defineProperty(qT,"isAxiosError",{value:!0});We.from=(e,t,n,r,s,o)=>{const a=Object.create(qT);return U.toFlatObject(e,a,function(u){return u!==Error.prototype},c=>c!=="isAxiosError"),We.call(a,e.message,t,n,r,s),a.cause=e,a.name=e.name,o&&Object.assign(a,o),a};const o4=null;function zy(e){return U.isPlainObject(e)||U.isArray(e)}function GT(e){return U.endsWith(e,"[]")?e.slice(0,-2):e}function H0(e,t,n){return e?e.concat(t).map(function(s,o){return s=GT(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function a4(e){return U.isArray(e)&&!e.some(zy)}const i4=U.toFlatObject(U,{},null,function(t){return/^is[A-Z]/.test(t)});function ah(e,t,n){if(!U.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=U.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,x){return!U.isUndefined(x[m])});const r=n.metaTokens,s=n.visitor||d,o=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&U.isSpecCompliantForm(t);if(!U.isFunction(s))throw new TypeError("visitor must be a function");function i(h){if(h===null)return"";if(U.isDate(h))return h.toISOString();if(!u&&U.isBlob(h))throw new We("Blob is not supported. Use a Buffer instead.");return U.isArrayBuffer(h)||U.isTypedArray(h)?u&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function d(h,m,x){let b=h;if(h&&!x&&typeof h=="object"){if(U.endsWith(m,"{}"))m=r?m:m.slice(0,-2),h=JSON.stringify(h);else if(U.isArray(h)&&a4(h)||(U.isFileList(h)||U.endsWith(m,"[]"))&&(b=U.toArray(h)))return m=GT(m),b.forEach(function(w,S){!(U.isUndefined(w)||w===null)&&t.append(a===!0?H0([m],S,o):a===null?m:m+"[]",i(w))}),!1}return zy(h)?!0:(t.append(H0(x,m,o),i(h)),!1)}const p=[],f=Object.assign(i4,{defaultVisitor:d,convertValue:i,isVisitable:zy});function g(h,m){if(!U.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+m.join("."));p.push(h),U.forEach(h,function(b,y){(!(U.isUndefined(b)||b===null)&&s.call(t,b,U.isString(y)?y.trim():y,m,f))===!0&&g(b,m?m.concat(y):[y])}),p.pop()}}if(!U.isObject(e))throw new TypeError("data must be an object");return g(e),t}function K0(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Fx(e,t){this._pairs=[],e&&ah(e,this,t)}const JT=Fx.prototype;JT.append=function(t,n){this._pairs.push([t,n])};JT.toString=function(t){const n=t?function(r){return t.call(this,r,K0)}:K0;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function l4(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function QT(e,t,n){if(!t)return e;const r=n&&n.encode||l4,s=n&&n.serialize;let o;if(s?o=s(t,n):o=U.isURLSearchParams(t)?t.toString():new Fx(t,n).toString(r),o){const a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class q0{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){U.forEach(this.handlers,function(r){r!==null&&t(r)})}}const ZT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},c4=typeof URLSearchParams<"u"?URLSearchParams:Fx,u4=typeof FormData<"u"?FormData:null,d4=typeof Blob<"u"?Blob:null,f4={isBrowser:!0,classes:{URLSearchParams:c4,FormData:u4,Blob:d4},protocols:["http","https","file","blob","url","data"]},Lx=typeof window<"u"&&typeof document<"u",p4=(e=>Lx&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),g4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",h4=Lx&&window.location.href||"http://localhost",m4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Lx,hasStandardBrowserEnv:p4,hasStandardBrowserWebWorkerEnv:g4,origin:h4},Symbol.toStringTag,{value:"Module"})),as={...m4,...f4};function v4(e,t){return ah(e,new as.classes.URLSearchParams,Object.assign({visitor:function(n,r,s,o){return as.isNode&&U.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}function y4(e){return U.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function b4(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r=n.length;return a=!a&&U.isArray(s)?s.length:a,u?(U.hasOwnProp(s,a)?s[a]=[s[a],r]:s[a]=r,!c):((!s[a]||!U.isObject(s[a]))&&(s[a]=[]),t(n,r,s[a],o)&&U.isArray(s[a])&&(s[a]=b4(s[a])),!c)}if(U.isFormData(e)&&U.isFunction(e.entries)){const n={};return U.forEachEntry(e,(r,s)=>{t(y4(r),s,n,0)}),n}return null}function x4(e,t,n){if(U.isString(e))try{return(t||JSON.parse)(e),U.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Wd={transitional:ZT,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=U.isObject(t);if(o&&U.isHTMLForm(t)&&(t=new FormData(t)),U.isFormData(t))return s?JSON.stringify(YT(t)):t;if(U.isArrayBuffer(t)||U.isBuffer(t)||U.isStream(t)||U.isFile(t)||U.isBlob(t)||U.isReadableStream(t))return t;if(U.isArrayBufferView(t))return t.buffer;if(U.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return v4(t,this.formSerializer).toString();if((c=U.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return ah(c?{"files[]":t}:t,u&&new u,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),x4(t)):t}],transformResponse:[function(t){const n=this.transitional||Wd.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(U.isResponse(t)||U.isReadableStream(t))return t;if(t&&U.isString(t)&&(r&&!this.responseType||s)){const a=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t)}catch(c){if(a)throw c.name==="SyntaxError"?We.from(c,We.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:as.classes.FormData,Blob:as.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};U.forEach(["delete","get","head","post","put","patch"],e=>{Wd.headers[e]={}});const w4=U.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"]),S4=e=>{const t={};let n,r,s;return e&&e.split(` +`).forEach(function(a){s=a.indexOf(":"),n=a.substring(0,s).trim().toLowerCase(),r=a.substring(s+1).trim(),!(!n||t[n]&&w4[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},W0=Symbol("internals");function eu(e){return e&&String(e).trim().toLowerCase()}function gp(e){return e===!1||e==null?e:U.isArray(e)?e.map(gp):String(e)}function C4(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const E4=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Um(e,t,n,r,s){if(U.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!U.isString(t)){if(U.isString(r))return t.indexOf(r)!==-1;if(U.isRegExp(r))return r.test(t)}}function k4(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function j4(e,t){const n=U.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,a){return this[r].call(this,t,s,o,a)},configurable:!0})})}let lr=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(c,u,i){const d=eu(u);if(!d)throw new Error("header name must be a non-empty string");const p=U.findKey(s,d);(!p||s[p]===void 0||i===!0||i===void 0&&s[p]!==!1)&&(s[p||u]=gp(c))}const a=(c,u)=>U.forEach(c,(i,d)=>o(i,d,u));if(U.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if(U.isString(t)&&(t=t.trim())&&!E4(t))a(S4(t),n);else if(U.isHeaders(t))for(const[c,u]of t.entries())o(u,c,r);else t!=null&&o(n,t,r);return this}get(t,n){if(t=eu(t),t){const r=U.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return C4(s);if(U.isFunction(n))return n.call(this,s,r);if(U.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=eu(t),t){const r=U.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Um(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(a){if(a=eu(a),a){const c=U.findKey(r,a);c&&(!n||Um(r,r[c],c,n))&&(delete r[c],s=!0)}}return U.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||Um(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return U.forEach(this,(s,o)=>{const a=U.findKey(r,o);if(a){n[a]=gp(s),delete n[o];return}const c=t?k4(o):String(o).trim();c!==o&&delete n[o],n[c]=gp(s),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return U.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&U.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[W0]=this[W0]={accessors:{}}).accessors,s=this.prototype;function o(a){const c=eu(a);r[c]||(j4(s,a),r[c]=!0)}return U.isArray(t)?t.forEach(o):o(t),this}};lr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);U.reduceDescriptors(lr.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});U.freezeMethods(lr);function Vm(e,t){const n=this||Wd,r=t||n,s=lr.from(r.headers);let o=r.data;return U.forEach(e,function(c){o=c.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function XT(e){return!!(e&&e.__CANCEL__)}function Tc(e,t,n){We.call(this,e??"canceled",We.ERR_CANCELED,t,n),this.name="CanceledError"}U.inherits(Tc,We,{__CANCEL__:!0});function eM(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new We("Request failed with status code "+n.status,[We.ERR_BAD_REQUEST,We.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function T4(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function M4(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,a;return t=t!==void 0?t:1e3,function(u){const i=Date.now(),d=r[o];a||(a=i),n[s]=u,r[s]=i;let p=o,f=0;for(;p!==s;)f+=n[p++],p=p%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),i-ar)return s&&(clearTimeout(s),s=null),n=c,e.apply(null,arguments);s||(s=setTimeout(()=>(s=null,n=Date.now(),e.apply(null,arguments)),r-(c-n)))}}const tg=(e,t,n=3)=>{let r=0;const s=M4(50,250);return N4(o=>{const a=o.loaded,c=o.lengthComputable?o.total:void 0,u=a-r,i=s(u),d=a<=c;r=a;const p={loaded:a,total:c,progress:c?a/c:void 0,bytes:u,rate:i||void 0,estimated:i&&c&&d?(c-a)/i:void 0,event:o,lengthComputable:c!=null};p[t?"download":"upload"]=!0,e(p)},n)},_4=as.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function s(o){let a=o;return t&&(n.setAttribute("href",a),a=n.href),n.setAttribute("href",a),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=s(window.location.href),function(a){const c=U.isString(a)?s(a):a;return c.protocol===r.protocol&&c.host===r.host}}():function(){return function(){return!0}}(),P4=as.hasStandardBrowserEnv?{write(e,t,n,r,s,o){const a=[e+"="+encodeURIComponent(t)];U.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),U.isString(r)&&a.push("path="+r),U.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function R4(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function O4(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function tM(e,t){return e&&!R4(t)?O4(e,t):t}const G0=e=>e instanceof lr?{...e}:e;function Ri(e,t){t=t||{};const n={};function r(i,d,p){return U.isPlainObject(i)&&U.isPlainObject(d)?U.merge.call({caseless:p},i,d):U.isPlainObject(d)?U.merge({},d):U.isArray(d)?d.slice():d}function s(i,d,p){if(U.isUndefined(d)){if(!U.isUndefined(i))return r(void 0,i,p)}else return r(i,d,p)}function o(i,d){if(!U.isUndefined(d))return r(void 0,d)}function a(i,d){if(U.isUndefined(d)){if(!U.isUndefined(i))return r(void 0,i)}else return r(void 0,d)}function c(i,d,p){if(p in t)return r(i,d);if(p in e)return r(void 0,i)}const u={url:o,method:o,data:o,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:c,headers:(i,d)=>s(G0(i),G0(d),!0)};return U.forEach(Object.keys(Object.assign({},e,t)),function(d){const p=u[d]||s,f=p(e[d],t[d],d);U.isUndefined(f)&&p!==c||(n[d]=f)}),n}const nM=e=>{const t=Ri({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;t.headers=a=lr.from(a),t.url=QT(tM(t.baseURL,t.url),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let u;if(U.isFormData(n)){if(as.hasStandardBrowserEnv||as.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if((u=a.getContentType())!==!1){const[i,...d]=u?u.split(";").map(p=>p.trim()).filter(Boolean):[];a.setContentType([i||"multipart/form-data",...d].join("; "))}}if(as.hasStandardBrowserEnv&&(r&&U.isFunction(r)&&(r=r(t)),r||r!==!1&&_4(t.url))){const i=s&&o&&P4.read(o);i&&a.set(s,i)}return t},I4=typeof XMLHttpRequest<"u",D4=I4&&function(e){return new Promise(function(n,r){const s=nM(e);let o=s.data;const a=lr.from(s.headers).normalize();let{responseType:c}=s,u;function i(){s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let d=new XMLHttpRequest;d.open(s.method.toUpperCase(),s.url,!0),d.timeout=s.timeout;function p(){if(!d)return;const g=lr.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),m={data:!c||c==="text"||c==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:g,config:e,request:d};eM(function(b){n(b),i()},function(b){r(b),i()},m),d=null}"onloadend"in d?d.onloadend=p:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(p)},d.onabort=function(){d&&(r(new We("Request aborted",We.ECONNABORTED,s,d)),d=null)},d.onerror=function(){r(new We("Network Error",We.ERR_NETWORK,s,d)),d=null},d.ontimeout=function(){let h=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const m=s.transitional||ZT;s.timeoutErrorMessage&&(h=s.timeoutErrorMessage),r(new We(h,m.clarifyTimeoutError?We.ETIMEDOUT:We.ECONNABORTED,s,d)),d=null},o===void 0&&a.setContentType(null),"setRequestHeader"in d&&U.forEach(a.toJSON(),function(h,m){d.setRequestHeader(m,h)}),U.isUndefined(s.withCredentials)||(d.withCredentials=!!s.withCredentials),c&&c!=="json"&&(d.responseType=s.responseType),typeof s.onDownloadProgress=="function"&&d.addEventListener("progress",tg(s.onDownloadProgress,!0)),typeof s.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",tg(s.onUploadProgress)),(s.cancelToken||s.signal)&&(u=g=>{d&&(r(!g||g.type?new Tc(null,e,d):g),d.abort(),d=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const f=T4(s.url);if(f&&as.protocols.indexOf(f)===-1){r(new We("Unsupported protocol "+f+":",We.ERR_BAD_REQUEST,e));return}d.send(o||null)})},A4=(e,t)=>{let n=new AbortController,r;const s=function(u){if(!r){r=!0,a();const i=u instanceof Error?u:this.reason;n.abort(i instanceof We?i:new Tc(i instanceof Error?i.message:i))}};let o=t&&setTimeout(()=>{s(new We(`timeout ${t} of ms exceeded`,We.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(u=>{u&&(u.removeEventListener?u.removeEventListener("abort",s):u.unsubscribe(s))}),e=null)};e.forEach(u=>u&&u.addEventListener&&u.addEventListener("abort",s));const{signal:c}=n;return c.unsubscribe=a,[c,()=>{o&&clearTimeout(o),o=null}]},F4=function*(e,t){let n=e.byteLength;if(!t||n{const o=L4(e,t,s);let a=0;return new ReadableStream({type:"bytes",async pull(c){const{done:u,value:i}=await o.next();if(u){c.close(),r();return}let d=i.byteLength;n&&n(a+=d),c.enqueue(new Uint8Array(i))},cancel(c){return r(c),o.return()}},{highWaterMark:2})},Q0=(e,t)=>{const n=e!=null;return r=>setTimeout(()=>t({lengthComputable:n,total:e,loaded:r}))},ih=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",rM=ih&&typeof ReadableStream=="function",Uy=ih&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),$4=rM&&(()=>{let e=!1;const t=new Request(as.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})(),Z0=64*1024,Vy=rM&&!!(()=>{try{return U.isReadableStream(new Response("").body)}catch{}})(),ng={stream:Vy&&(e=>e.body)};ih&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!ng[t]&&(ng[t]=U.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new We(`Response type '${t}' is not supported`,We.ERR_NOT_SUPPORT,r)})})})(new Response);const B4=async e=>{if(e==null)return 0;if(U.isBlob(e))return e.size;if(U.isSpecCompliantForm(e))return(await new Request(e).arrayBuffer()).byteLength;if(U.isArrayBufferView(e))return e.byteLength;if(U.isURLSearchParams(e)&&(e=e+""),U.isString(e))return(await Uy(e)).byteLength},z4=async(e,t)=>{const n=U.toFiniteNumber(e.getContentLength());return n??B4(t)},U4=ih&&(async e=>{let{url:t,method:n,data:r,signal:s,cancelToken:o,timeout:a,onDownloadProgress:c,onUploadProgress:u,responseType:i,headers:d,withCredentials:p="same-origin",fetchOptions:f}=nM(e);i=i?(i+"").toLowerCase():"text";let[g,h]=s||o||a?A4([s,o],a):[],m,x;const b=()=>{!m&&setTimeout(()=>{g&&g.unsubscribe()}),m=!0};let y;try{if(u&&$4&&n!=="get"&&n!=="head"&&(y=await z4(d,r))!==0){let C=new Request(t,{method:"POST",body:r,duplex:"half"}),T;U.isFormData(r)&&(T=C.headers.get("content-type"))&&d.setContentType(T),C.body&&(r=J0(C.body,Z0,Q0(y,tg(u)),null,Uy))}U.isString(p)||(p=p?"cors":"omit"),x=new Request(t,{...f,signal:g,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:r,duplex:"half",withCredentials:p});let w=await fetch(x);const S=Vy&&(i==="stream"||i==="response");if(Vy&&(c||S)){const C={};["status","statusText","headers"].forEach(j=>{C[j]=w[j]});const T=U.toFiniteNumber(w.headers.get("content-length"));w=new Response(J0(w.body,Z0,c&&Q0(T,tg(c,!0)),S&&b,Uy),C)}i=i||"text";let E=await ng[U.findKey(ng,i)||"text"](w,e);return!S&&b(),h&&h(),await new Promise((C,T)=>{eM(C,T,{data:E,headers:lr.from(w.headers),status:w.status,statusText:w.statusText,config:e,request:x})})}catch(w){throw b(),w&&w.name==="TypeError"&&/fetch/i.test(w.message)?Object.assign(new We("Network Error",We.ERR_NETWORK,e,x),{cause:w.cause||w}):We.from(w,w&&w.code,e,x)}}),Hy={http:o4,xhr:D4,fetch:U4};U.forEach(Hy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Y0=e=>`- ${e}`,V4=e=>U.isFunction(e)||e===null||e===!1,sM={getAdapter:e=>{e=U.isArray(e)?e:[e];const{length:t}=e;let n,r;const s={};for(let o=0;o`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build"));let a=t?o.length>1?`since : +`+o.map(Y0).join(` +`):" "+Y0(o[0]):"as no adapter specified";throw new We("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return r},adapters:Hy};function Hm(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Tc(null,e)}function X0(e){return Hm(e),e.headers=lr.from(e.headers),e.data=Vm.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),sM.getAdapter(e.adapter||Wd.adapter)(e).then(function(r){return Hm(e),r.data=Vm.call(e,e.transformResponse,r),r.headers=lr.from(r.headers),r},function(r){return XT(r)||(Hm(e),r&&r.response&&(r.response.data=Vm.call(e,e.transformResponse,r.response),r.response.headers=lr.from(r.response.headers))),Promise.reject(r)})}const oM="1.7.2",$x={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{$x[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const eC={};$x.transitional=function(t,n,r){function s(o,a){return"[Axios v"+oM+"] Transitional option '"+o+"'"+a+(r?". "+r:"")}return(o,a,c)=>{if(t===!1)throw new We(s(a," has been removed"+(n?" in "+n:"")),We.ERR_DEPRECATED);return n&&!eC[a]&&(eC[a]=!0,console.warn(s(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,a,c):!0}};function H4(e,t,n){if(typeof e!="object")throw new We("options must be an object",We.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],a=t[o];if(a){const c=e[o],u=c===void 0||a(c,o,e);if(u!==!0)throw new We("option "+o+" must be "+u,We.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new We("Unknown option "+o,We.ERR_BAD_OPTION)}}const Ky={assertOptions:H4,validators:$x},Fo=Ky.validators;let wi=class{constructor(t){this.defaults=t,this.interceptors={request:new q0,response:new q0}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Ri(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Ky.assertOptions(r,{silentJSONParsing:Fo.transitional(Fo.boolean),forcedJSONParsing:Fo.transitional(Fo.boolean),clarifyTimeoutError:Fo.transitional(Fo.boolean)},!1),s!=null&&(U.isFunction(s)?n.paramsSerializer={serialize:s}:Ky.assertOptions(s,{encode:Fo.function,serialize:Fo.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=o&&U.merge(o.common,o[n.method]);o&&U.forEach(["delete","get","head","post","put","patch","common"],h=>{delete o[h]}),n.headers=lr.concat(a,o);const c=[];let u=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(u=u&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const i=[];this.interceptors.response.forEach(function(m){i.push(m.fulfilled,m.rejected)});let d,p=0,f;if(!u){const h=[X0.bind(this),void 0];for(h.unshift.apply(h,c),h.push.apply(h,i),f=h.length,d=Promise.resolve(n);p{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const a=new Promise(c=>{r.subscribe(c),o=c}).then(s);return a.cancel=function(){r.unsubscribe(o)},a},t(function(o,a,c){r.reason||(r.reason=new Tc(o,a,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new aM(function(s){t=s}),cancel:t}}};function q4(e){return function(n){return e.apply(null,n)}}function W4(e){return U.isObject(e)&&e.isAxiosError===!0}const qy={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(qy).forEach(([e,t])=>{qy[t]=e});function iM(e){const t=new wi(e),n=LT(wi.prototype.request,t);return U.extend(n,wi.prototype,t,{allOwnKeys:!0}),U.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return iM(Ri(e,s))},n}const Bt=iM(Wd);Bt.Axios=wi;Bt.CanceledError=Tc;Bt.CancelToken=K4;Bt.isCancel=XT;Bt.VERSION=oM;Bt.toFormData=ah;Bt.AxiosError=We;Bt.Cancel=Bt.CanceledError;Bt.all=function(t){return Promise.all(t)};Bt.spread=q4;Bt.isAxiosError=W4;Bt.mergeConfig=Ri;Bt.AxiosHeaders=lr;Bt.formToJSON=e=>YT(U.isHTMLForm(e)?new FormData(e):e);Bt.getAdapter=sM.getAdapter;Bt.HttpStatusCode=qy;Bt.default=Bt;const{Axios:Loe,AxiosError:$oe,CanceledError:Boe,isCancel:zoe,CancelToken:Uoe,VERSION:Voe,all:Hoe,Cancel:Koe,isAxiosError:G4,spread:qoe,toFormData:Woe,AxiosHeaders:Goe,HttpStatusCode:Joe,formToJSON:Qoe,getAdapter:Zoe,mergeConfig:Yoe}=Bt,J4=e=>["auth","verifyServer",JSON.stringify(e)],lM=async({url:e})=>(await Bt.get(`${e}/`)).data,Q4=e=>{const{url:t,...n}=e;return qe({...n,queryKey:J4({url:t}),queryFn:()=>lM({url:t}),enabled:!!t})};function Z4(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function lh(...e){return t=>e.forEach(n=>Z4(n,t))}function ct(...e){return v.useCallback(lh(...e),e)}var wo=v.forwardRef((e,t)=>{const{children:n,...r}=e,s=v.Children.toArray(n),o=s.find(X4);if(o){const a=o.props.children,c=s.map(u=>u===o?v.Children.count(a)>1?v.Children.only(null):v.isValidElement(a)?a.props.children:null:u);return l.jsx(Wy,{...r,ref:t,children:v.isValidElement(a)?v.cloneElement(a,void 0,c):null})}return l.jsx(Wy,{...r,ref:t,children:n})});wo.displayName="Slot";var Wy=v.forwardRef((e,t)=>{const{children:n,...r}=e;if(v.isValidElement(n)){const s=tB(n);return v.cloneElement(n,{...eB(r,n.props),ref:t?lh(t,s):s})}return v.Children.count(n)>1?v.Children.only(null):null});Wy.displayName="SlotClone";var Y4=({children:e})=>l.jsx(l.Fragment,{children:e});function X4(e){return v.isValidElement(e)&&e.type===Y4}function eB(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...c)=>{o(...c),s(...c)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function tB(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function cM(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;ttypeof e=="boolean"?"".concat(e):e===0?"0":e,nC=nB,ch=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return nC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:s,defaultVariants:o}=t,a=Object.keys(s).map(i=>{const d=n==null?void 0:n[i],p=o==null?void 0:o[i];if(d===null)return null;const f=tC(d)||tC(p);return s[i][f]}),c=n&&Object.entries(n).reduce((i,d)=>{let[p,f]=d;return f===void 0||(i[p]=f),i},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((i,d)=>{let{class:p,className:f,...g}=d;return Object.entries(g).every(h=>{let[m,x]=h;return Array.isArray(x)?x.includes({...o,...c}[m]):{...o,...c}[m]===x})?[...i,p,f]:i},[]);return nC(e,a,u,n==null?void 0:n.class,n==null?void 0:n.className)},Bx="-";function rB(e){const t=oB(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;function s(a){const c=a.split(Bx);return c[0]===""&&c.length!==1&&c.shift(),uM(c,t)||sB(a)}function o(a,c){const u=n[a]||[];return c&&r[a]?[...u,...r[a]]:u}return{getClassGroupId:s,getConflictingClassGroupIds:o}}function uM(e,t){var a;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?uM(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Bx);return(a=t.validators.find(({validator:c})=>c(o)))==null?void 0:a.classGroupId}const rC=/^\[(.+)\]$/;function sB(e){if(rC.test(e)){const t=rC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function oB(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return iB(Object.entries(e.classGroups),n).forEach(([o,a])=>{Gy(a,r,o,t)}),r}function Gy(e,t,n,r){e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:sC(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(aB(s)){Gy(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,a])=>{Gy(a,sC(t,o),n,r)})})}function sC(e,t){let n=e;return t.split(Bx).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function aB(e){return e.isThemeGetter}function iB(e,t){return t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,c])=>[t+a,c])):o);return[n,s]}):e}function lB(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function s(o,a){n.set(o,a),t++,t>e&&(t=0,r=n,n=new Map)}return{get(o){let a=n.get(o);if(a!==void 0)return a;if((a=r.get(o))!==void 0)return s(o,a),a},set(o,a){n.has(o)?n.set(o,a):s(o,a)}}}const dM="!";function cB(e){const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length;function a(c){const u=[];let i=0,d=0,p;for(let x=0;xd?p-d:void 0;return{modifiers:u,hasImportantModifier:g,baseClassName:h,maybePostfixModifierPosition:m}}return n?function(u){return n({className:u,parseClassName:a})}:a}function uB(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function dB(e){return{cache:lB(e.cacheSize),parseClassName:cB(e),...rB(e)}}const fB=/\s+/;function pB(e,t){const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=new Set;return e.trim().split(fB).map(a=>{const{modifiers:c,hasImportantModifier:u,baseClassName:i,maybePostfixModifierPosition:d}=n(a);let p=!!d,f=r(p?i.substring(0,d):i);if(!f){if(!p)return{isTailwindClass:!1,originalClassName:a};if(f=r(i),!f)return{isTailwindClass:!1,originalClassName:a};p=!1}const g=uB(c).join(":");return{isTailwindClass:!0,modifierId:u?g+dM:g,classGroupId:f,originalClassName:a,hasPostfixModifier:p}}).reverse().filter(a=>{if(!a.isTailwindClass)return!0;const{modifierId:c,classGroupId:u,hasPostfixModifier:i}=a,d=c+u;return o.has(d)?!1:(o.add(d),s(u,i).forEach(p=>o.add(c+p)),!0)}).reverse().map(a=>a.originalClassName).join(" ")}function gB(){let e=0,t,n,r="";for(;ep(d),e());return n=dB(i),r=n.cache.get,s=n.cache.set,o=c,c(u)}function c(u){const i=r(u);if(i)return i;const d=pB(u,n);return s(u,d),d}return function(){return o(gB.apply(null,arguments))}}function Ot(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const pM=/^\[(?:([a-z-]+):)?(.+)\]$/i,mB=/^\d+\/\d+$/,vB=new Set(["px","full","screen"]),yB=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,bB=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,xB=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,wB=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,SB=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function Zs(e){return si(e)||vB.has(e)||mB.test(e)}function Lo(e){return Mc(e,"length",_B)}function si(e){return!!e&&!Number.isNaN(Number(e))}function Pf(e){return Mc(e,"number",si)}function tu(e){return!!e&&Number.isInteger(Number(e))}function CB(e){return e.endsWith("%")&&si(e.slice(0,-1))}function Qe(e){return pM.test(e)}function $o(e){return yB.test(e)}const EB=new Set(["length","size","percentage"]);function kB(e){return Mc(e,EB,gM)}function jB(e){return Mc(e,"position",gM)}const TB=new Set(["image","url"]);function MB(e){return Mc(e,TB,RB)}function NB(e){return Mc(e,"",PB)}function nu(){return!0}function Mc(e,t,n){const r=pM.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function _B(e){return bB.test(e)&&!xB.test(e)}function gM(){return!1}function PB(e){return wB.test(e)}function RB(e){return SB.test(e)}function OB(){const e=Ot("colors"),t=Ot("spacing"),n=Ot("blur"),r=Ot("brightness"),s=Ot("borderColor"),o=Ot("borderRadius"),a=Ot("borderSpacing"),c=Ot("borderWidth"),u=Ot("contrast"),i=Ot("grayscale"),d=Ot("hueRotate"),p=Ot("invert"),f=Ot("gap"),g=Ot("gradientColorStops"),h=Ot("gradientColorStopPositions"),m=Ot("inset"),x=Ot("margin"),b=Ot("opacity"),y=Ot("padding"),w=Ot("saturate"),S=Ot("scale"),E=Ot("sepia"),C=Ot("skew"),T=Ot("space"),j=Ot("translate"),_=()=>["auto","contain","none"],O=()=>["auto","hidden","clip","visible","scroll"],K=()=>["auto",Qe,t],I=()=>[Qe,t],Y=()=>["",Zs,Lo],q=()=>["auto",si,Qe],Z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ee=()=>["solid","dashed","dotted","double","none"],J=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],L=()=>["start","end","center","between","around","evenly","stretch"],A=()=>["","0",Qe],X=()=>["auto","avoid","all","avoid-page","page","left","right","column"],fe=()=>[si,Pf],H=()=>[si,Qe];return{cacheSize:500,separator:":",theme:{colors:[nu],spacing:[Zs,Lo],blur:["none","",$o,Qe],brightness:fe(),borderColor:[e],borderRadius:["none","","full",$o,Qe],borderSpacing:I(),borderWidth:Y(),contrast:fe(),grayscale:A(),hueRotate:H(),invert:A(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[CB,Lo],inset:K(),margin:K(),opacity:fe(),padding:I(),saturate:fe(),scale:fe(),sepia:A(),skew:H(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",Qe]}],container:["container"],columns:[{columns:[$o]}],"break-after":[{"break-after":X()}],"break-before":[{"break-before":X()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...Z(),Qe]}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[m]}],"inset-x":[{"inset-x":[m]}],"inset-y":[{"inset-y":[m]}],start:[{start:[m]}],end:[{end:[m]}],top:[{top:[m]}],right:[{right:[m]}],bottom:[{bottom:[m]}],left:[{left:[m]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",tu,Qe]}],basis:[{basis:K()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Qe]}],grow:[{grow:A()}],shrink:[{shrink:A()}],order:[{order:["first","last","none",tu,Qe]}],"grid-cols":[{"grid-cols":[nu]}],"col-start-end":[{col:["auto",{span:["full",tu,Qe]},Qe]}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":[nu]}],"row-start-end":[{row:["auto",{span:[tu,Qe]},Qe]}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Qe]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Qe]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...L()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...L(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...L(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[T]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[T]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Qe,t]}],"min-w":[{"min-w":[Qe,t,"min","max","fit"]}],"max-w":[{"max-w":[Qe,t,"none","full","min","max","fit","prose",{screen:[$o]},$o]}],h:[{h:[Qe,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Qe,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Qe,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Qe,t,"auto","min","max","fit"]}],"font-size":[{text:["base",$o,Lo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Pf]}],"font-family":[{font:[nu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Qe]}],"line-clamp":[{"line-clamp":["none",si,Pf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Zs,Qe]}],"list-image":[{"list-image":["none",Qe]}],"list-style-type":[{list:["none","disc","decimal",Qe]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ee(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Zs,Lo]}],"underline-offset":[{"underline-offset":["auto",Zs,Qe]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Qe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Qe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Z(),jB]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",kB]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},MB]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[h]}],"gradient-via-pos":[{via:[h]}],"gradient-to-pos":[{to:[h]}],"gradient-from":[{from:[g]}],"gradient-via":[{via:[g]}],"gradient-to":[{to:[g]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[c]}],"border-w-x":[{"border-x":[c]}],"border-w-y":[{"border-y":[c]}],"border-w-s":[{"border-s":[c]}],"border-w-e":[{"border-e":[c]}],"border-w-t":[{"border-t":[c]}],"border-w-r":[{"border-r":[c]}],"border-w-b":[{"border-b":[c]}],"border-w-l":[{"border-l":[c]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...ee(),"hidden"]}],"divide-x":[{"divide-x":[c]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[c]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:ee()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...ee()]}],"outline-offset":[{"outline-offset":[Zs,Qe]}],"outline-w":[{outline:[Zs,Lo]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[Zs,Lo]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",$o,NB]}],"shadow-color":[{shadow:[nu]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...J(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":J()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",$o,Qe]}],grayscale:[{grayscale:[i]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[p]}],saturate:[{saturate:[w]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[i]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Qe]}],duration:[{duration:H()}],ease:[{ease:["linear","in","out","in-out",Qe]}],delay:[{delay:H()}],animate:[{animate:["none","spin","ping","pulse","bounce",Qe]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[tu,Qe]}],"translate-x":[{"translate-x":[j]}],"translate-y":[{"translate-y":[j]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Qe]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Qe]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Qe]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[Zs,Lo,Pf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const IB=hB(OB);function me(...e){return IB(uo(e))}const DB=ch("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",warning:"bg-amber-600 shadow-sm hover:bg-amber-600/90 data-active:bg-amber-600/90 text-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),z=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...s},o)=>{const a=r?wo:"button";return l.jsx(a,{className:me(DB({variant:t,size:n,className:e})),ref:o,...s})});z.displayName="Button";function zx(){const{t:e}=Te(),t=zr(Fn.API_URL),{data:n}=Q4({url:t}),r=v.useMemo(()=>n==null?void 0:n.clientName,[n]),s=v.useMemo(()=>n==null?void 0:n.version,[n]),o=[{name:"Discord",url:"https://evolution-api.com/discord"},{name:"Postman",url:"https://evolution-api.com/postman"},{name:"GitHub",url:"https://github.com/EvolutionAPI/evolution-api"},{name:"Docs",url:"https://doc.evolution-api.com"}];return l.jsxs("footer",{className:"flex w-full flex-col items-center justify-between p-6 text-xs text-secondary-foreground sm:flex-row",children:[l.jsxs("div",{className:"flex items-center space-x-3 divide-x",children:[r&&r!==""&&l.jsxs("span",{children:[e("footer.clientName"),": ",l.jsx("strong",{children:r})]}),s&&s!==""&&l.jsxs("span",{className:"pl-3",children:[e("footer.version"),": ",l.jsx("strong",{children:s})]})]}),l.jsx("div",{className:"flex gap-2",children:o.map(a=>l.jsx(z,{variant:"link",asChild:!0,size:"sm",className:"text-xs",children:l.jsx("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:a.name})},a.url))})]})}/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const AB=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),hM=(...e)=>e.filter((t,n,r)=>!!t&&r.indexOf(t)===n).join(" ");/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var FB={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const LB=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:o,iconNode:a,...c},u)=>v.createElement("svg",{ref:u,...FB,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:hM("lucide",s),...c},[...a.map(([i,d])=>v.createElement(i,d)),...Array.isArray(o)?o:[o]]));/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const nt=(e,t)=>{const n=v.forwardRef(({className:r,...s},o)=>v.createElement(LB,{ref:o,iconNode:t,className:hM(`lucide-${AB(e)}`,r),...s}));return n.displayName=`${e}`,n};/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $B=nt("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const BB=nt("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mM=nt("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const uh=nt("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zB=nt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const UB=nt("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const VB=nt("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const HB=nt("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ui=nt("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{width:"6",height:"6",x:"9",y:"9",key:"1wrtvo"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vM=nt("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const KB=nt("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const To=nt("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qB=nt("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vi=nt("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const WB=nt("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ia=nt("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const GB=nt("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const JB=nt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const QB=nt("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ZB=nt("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const YB=nt("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const XB=nt("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const e3=nt("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const t3=nt("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hi=nt("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const n3=nt("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dh=nt("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const r3=nt("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const s3=nt("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ki=nt("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qi=nt("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ws=nt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const rg=nt("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wi=nt("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const o3=nt("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const a3=nt("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const i3=nt("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const l3=nt("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yM=nt("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),ie=Bt.create({timeout:3e4});ie.interceptors.request.use(async e=>{const t=zr(Fn.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=zr(Fn.INSTANCE_TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const Gd=Bt.create({timeout:3e4});Gd.interceptors.request.use(async e=>{const t=zr(Fn.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=zr(Fn.TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const c3=e=>["instance","fetchInstance",JSON.stringify(e)],u3=async({instanceId:e})=>{const t=await Gd.get("/instance/fetchInstances",{params:{instanceId:e}});return Array.isArray(t.data)?t.data[0]:t.data},bM=e=>{const{instanceId:t,...n}=e;return qe({...n,queryKey:c3({instanceId:t}),queryFn:()=>u3({instanceId:t}),enabled:!!t})};function Ce(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function d3(e,t){const n=v.createContext(t);function r(o){const{children:a,...c}=o,u=v.useMemo(()=>c,Object.values(c));return l.jsx(n.Provider,{value:u,children:a})}function s(o){const a=v.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function qr(e,t=[]){let n=[];function r(o,a){const c=v.createContext(a),u=n.length;n=[...n,a];function i(p){const{scope:f,children:g,...h}=p,m=(f==null?void 0:f[e][u])||c,x=v.useMemo(()=>h,Object.values(h));return l.jsx(m.Provider,{value:x,children:g})}function d(p,f){const g=(f==null?void 0:f[e][u])||c,h=v.useContext(g);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${o}\``)}return i.displayName=o+"Provider",[i,d]}const s=()=>{const o=n.map(a=>v.createContext(a));return function(c){const u=(c==null?void 0:c[e])||o;return v.useMemo(()=>({[`__scope${e}`]:{...c,[e]:u}}),[c,u])}};return s.scopeName=e,[r,f3(s,...t)]}function f3(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const a=r.reduce((c,{useScope:u,scopeName:i})=>{const p=u(o)[`__scope${i}`];return{...c,...p}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function on(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function ya({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,s]=p3({defaultProp:t,onChange:n}),o=e!==void 0,a=o?e:r,c=on(n),u=v.useCallback(i=>{if(o){const p=typeof i=="function"?i(e):i;p!==e&&c(p)}else s(i)},[o,e,s,c]);return[a,u]}function p3({defaultProp:e,onChange:t}){const n=v.useState(e),[r]=n,s=v.useRef(r),o=on(t);return v.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),n}var g3=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ie=g3.reduce((e,t)=>{const n=v.forwardRef((r,s)=>{const{asChild:o,...a}=r,c=o?wo:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(c,{...a,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function xM(e,t){e&&Pa.flushSync(()=>e.dispatchEvent(t))}function Ux(e){const t=e+"CollectionProvider",[n,r]=qr(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=g=>{const{scope:h,children:m}=g,x=je.useRef(null),b=je.useRef(new Map).current;return l.jsx(s,{scope:h,itemMap:b,collectionRef:x,children:m})};a.displayName=t;const c=e+"CollectionSlot",u=je.forwardRef((g,h)=>{const{scope:m,children:x}=g,b=o(c,m),y=ct(h,b.collectionRef);return l.jsx(wo,{ref:y,children:x})});u.displayName=c;const i=e+"CollectionItemSlot",d="data-radix-collection-item",p=je.forwardRef((g,h)=>{const{scope:m,children:x,...b}=g,y=je.useRef(null),w=ct(h,y),S=o(i,m);return je.useEffect(()=>(S.itemMap.set(y,{ref:y,...b}),()=>void S.itemMap.delete(y))),l.jsx(wo,{[d]:"",ref:w,children:x})});p.displayName=i;function f(g){const h=o(e+"CollectionConsumer",g);return je.useCallback(()=>{const x=h.collectionRef.current;if(!x)return[];const b=Array.from(x.querySelectorAll(`[${d}]`));return Array.from(h.itemMap.values()).sort((S,E)=>b.indexOf(S.ref.current)-b.indexOf(E.ref.current))},[h.collectionRef,h.itemMap])}return[{Provider:a,Slot:u,ItemSlot:p},f,r]}var h3=v.createContext(void 0);function Jd(e){const t=v.useContext(h3);return e||t||"ltr"}function m3(e,t=globalThis==null?void 0:globalThis.document){const n=on(e);v.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var v3="DismissableLayer",Jy="dismissableLayer.update",y3="dismissableLayer.pointerDownOutside",b3="dismissableLayer.focusOutside",oC,wM=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),fh=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:a,onDismiss:c,...u}=e,i=v.useContext(wM),[d,p]=v.useState(null),f=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,g]=v.useState({}),h=ct(t,T=>p(T)),m=Array.from(i.layers),[x]=[...i.layersWithOutsidePointerEventsDisabled].slice(-1),b=m.indexOf(x),y=d?m.indexOf(d):-1,w=i.layersWithOutsidePointerEventsDisabled.size>0,S=y>=b,E=S3(T=>{const j=T.target,_=[...i.branches].some(O=>O.contains(j));!S||_||(s==null||s(T),a==null||a(T),T.defaultPrevented||c==null||c())},f),C=C3(T=>{const j=T.target;[...i.branches].some(O=>O.contains(j))||(o==null||o(T),a==null||a(T),T.defaultPrevented||c==null||c())},f);return m3(T=>{y===i.layers.size-1&&(r==null||r(T),!T.defaultPrevented&&c&&(T.preventDefault(),c()))},f),v.useEffect(()=>{if(d)return n&&(i.layersWithOutsidePointerEventsDisabled.size===0&&(oC=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),i.layersWithOutsidePointerEventsDisabled.add(d)),i.layers.add(d),aC(),()=>{n&&i.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=oC)}},[d,f,n,i]),v.useEffect(()=>()=>{d&&(i.layers.delete(d),i.layersWithOutsidePointerEventsDisabled.delete(d),aC())},[d,i]),v.useEffect(()=>{const T=()=>g({});return document.addEventListener(Jy,T),()=>document.removeEventListener(Jy,T)},[]),l.jsx(Ie.div,{...u,ref:h,style:{pointerEvents:w?S?"auto":"none":void 0,...e.style},onFocusCapture:Ce(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Ce(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Ce(e.onPointerDownCapture,E.onPointerDownCapture)})});fh.displayName=v3;var x3="DismissableLayerBranch",w3=v.forwardRef((e,t)=>{const n=v.useContext(wM),r=v.useRef(null),s=ct(t,r);return v.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),l.jsx(Ie.div,{...e,ref:s})});w3.displayName=x3;function S3(e,t=globalThis==null?void 0:globalThis.document){const n=on(e),r=v.useRef(!1),s=v.useRef(()=>{});return v.useEffect(()=>{const o=c=>{if(c.target&&!r.current){let u=function(){SM(y3,n,i,{discrete:!0})};const i={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=u,t.addEventListener("click",s.current,{once:!0})):u()}else t.removeEventListener("click",s.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",o),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function C3(e,t=globalThis==null?void 0:globalThis.document){const n=on(e),r=v.useRef(!1);return v.useEffect(()=>{const s=o=>{o.target&&!r.current&&SM(b3,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function aC(){const e=new CustomEvent(Jy);document.dispatchEvent(e)}function SM(e,t,n,{discrete:r}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?xM(s,o):s.dispatchEvent(o)}var Km=0;function Vx(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??iC()),document.body.insertAdjacentElement("beforeend",e[1]??iC()),Km++,()=>{Km===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Km--}},[])}function iC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var qm="focusScope.autoFocusOnMount",Wm="focusScope.autoFocusOnUnmount",lC={bubbles:!1,cancelable:!0},E3="FocusScope",ph=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[c,u]=v.useState(null),i=on(s),d=on(o),p=v.useRef(null),f=ct(t,m=>u(m)),g=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(w){if(g.paused||!c)return;const S=w.target;c.contains(S)?p.current=S:Vo(p.current,{select:!0})},x=function(w){if(g.paused||!c)return;const S=w.relatedTarget;S!==null&&(c.contains(S)||Vo(p.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const E of w)E.removedNodes.length>0&&Vo(c)};document.addEventListener("focusin",m),document.addEventListener("focusout",x);const y=new MutationObserver(b);return c&&y.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",x),y.disconnect()}}},[r,c,g.paused]),v.useEffect(()=>{if(c){uC.add(g);const m=document.activeElement;if(!c.contains(m)){const b=new CustomEvent(qm,lC);c.addEventListener(qm,i),c.dispatchEvent(b),b.defaultPrevented||(k3(_3(CM(c)),{select:!0}),document.activeElement===m&&Vo(c))}return()=>{c.removeEventListener(qm,i),setTimeout(()=>{const b=new CustomEvent(Wm,lC);c.addEventListener(Wm,d),c.dispatchEvent(b),b.defaultPrevented||Vo(m??document.body,{select:!0}),c.removeEventListener(Wm,d),uC.remove(g)},0)}}},[c,i,d,g]);const h=v.useCallback(m=>{if(!n&&!r||g.paused)return;const x=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,b=document.activeElement;if(x&&b){const y=m.currentTarget,[w,S]=j3(y);w&&S?!m.shiftKey&&b===S?(m.preventDefault(),n&&Vo(w,{select:!0})):m.shiftKey&&b===w&&(m.preventDefault(),n&&Vo(S,{select:!0})):b===y&&m.preventDefault()}},[n,r,g.paused]);return l.jsx(Ie.div,{tabIndex:-1,...a,ref:f,onKeyDown:h})});ph.displayName=E3;function k3(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Vo(r,{select:t}),document.activeElement!==n)return}function j3(e){const t=CM(e),n=cC(t,e),r=cC(t.reverse(),e);return[n,r]}function CM(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function cC(e,t){for(const n of e)if(!T3(n,{upTo:t}))return n}function T3(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function M3(e){return e instanceof HTMLInputElement&&"select"in e}function Vo(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&M3(e)&&t&&e.select()}}var uC=N3();function N3(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=dC(e,t),e.unshift(t)},remove(t){var n;e=dC(e,t),(n=e[0])==null||n.resume()}}}function dC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function _3(e){return e.filter(t=>t.tagName!=="A")}var pn=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},P3=Dg.useId||(()=>{}),R3=0;function is(e){const[t,n]=v.useState(P3());return pn(()=>{n(r=>r??String(R3++))},[e]),t?`radix-${t}`:""}const O3=["top","right","bottom","left"],Ds=Math.min,vr=Math.max,sg=Math.round,Rf=Math.floor,ba=e=>({x:e,y:e}),I3={left:"right",right:"left",bottom:"top",top:"bottom"},D3={start:"end",end:"start"};function Qy(e,t,n){return vr(e,Ds(t,n))}function So(e,t){return typeof e=="function"?e(t):e}function Co(e){return e.split("-")[0]}function Nc(e){return e.split("-")[1]}function Hx(e){return e==="x"?"y":"x"}function Kx(e){return e==="y"?"height":"width"}function xa(e){return["top","bottom"].includes(Co(e))?"y":"x"}function qx(e){return Hx(xa(e))}function A3(e,t,n){n===void 0&&(n=!1);const r=Nc(e),s=qx(e),o=Kx(s);let a=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=og(a)),[a,og(a)]}function F3(e){const t=og(e);return[Zy(e),t,Zy(t)]}function Zy(e){return e.replace(/start|end/g,t=>D3[t])}function L3(e,t,n){const r=["left","right"],s=["right","left"],o=["top","bottom"],a=["bottom","top"];switch(e){case"top":case"bottom":return n?t?s:r:t?r:s;case"left":case"right":return t?o:a;default:return[]}}function $3(e,t,n,r){const s=Nc(e);let o=L3(Co(e),n==="start",r);return s&&(o=o.map(a=>a+"-"+s),t&&(o=o.concat(o.map(Zy)))),o}function og(e){return e.replace(/left|right|bottom|top/g,t=>I3[t])}function B3(e){return{top:0,right:0,bottom:0,left:0,...e}}function EM(e){return typeof e!="number"?B3(e):{top:e,right:e,bottom:e,left:e}}function ag(e){const{x:t,y:n,width:r,height:s}=e;return{width:r,height:s,top:n,left:t,right:t+r,bottom:n+s,x:t,y:n}}function fC(e,t,n){let{reference:r,floating:s}=e;const o=xa(t),a=qx(t),c=Kx(a),u=Co(t),i=o==="y",d=r.x+r.width/2-s.width/2,p=r.y+r.height/2-s.height/2,f=r[c]/2-s[c]/2;let g;switch(u){case"top":g={x:d,y:r.y-s.height};break;case"bottom":g={x:d,y:r.y+r.height};break;case"right":g={x:r.x+r.width,y:p};break;case"left":g={x:r.x-s.width,y:p};break;default:g={x:r.x,y:r.y}}switch(Nc(t)){case"start":g[a]-=f*(n&&i?-1:1);break;case"end":g[a]+=f*(n&&i?-1:1);break}return g}const z3=async(e,t,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:o=[],platform:a}=n,c=o.filter(Boolean),u=await(a.isRTL==null?void 0:a.isRTL(t));let i=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:d,y:p}=fC(i,r,u),f=r,g={},h=0;for(let m=0;m({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:o,platform:a,elements:c,middlewareData:u}=t,{element:i,padding:d=0}=So(e,t)||{};if(i==null)return{};const p=EM(d),f={x:n,y:r},g=qx(s),h=Kx(g),m=await a.getDimensions(i),x=g==="y",b=x?"top":"left",y=x?"bottom":"right",w=x?"clientHeight":"clientWidth",S=o.reference[h]+o.reference[g]-f[g]-o.floating[h],E=f[g]-o.reference[g],C=await(a.getOffsetParent==null?void 0:a.getOffsetParent(i));let T=C?C[w]:0;(!T||!await(a.isElement==null?void 0:a.isElement(C)))&&(T=c.floating[w]||o.floating[h]);const j=S/2-E/2,_=T/2-m[h]/2-1,O=Ds(p[b],_),K=Ds(p[y],_),I=O,Y=T-m[h]-K,q=T/2-m[h]/2+j,Z=Qy(I,q,Y),ee=!u.arrow&&Nc(s)!=null&&q!==Z&&o.reference[h]/2-(qq<=0)){var K,I;const q=(((K=o.flip)==null?void 0:K.index)||0)+1,Z=T[q];if(Z)return{data:{index:q,overflows:O},reset:{placement:Z}};let ee=(I=O.filter(J=>J.overflows[0]<=0).sort((J,L)=>J.overflows[1]-L.overflows[1])[0])==null?void 0:I.placement;if(!ee)switch(g){case"bestFit":{var Y;const J=(Y=O.filter(L=>{if(C){const A=xa(L.placement);return A===y||A==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(A=>A>0).reduce((A,X)=>A+X,0)]).sort((L,A)=>L[1]-A[1])[0])==null?void 0:Y[0];J&&(ee=J);break}case"initialPlacement":ee=c;break}if(s!==ee)return{reset:{placement:ee}}}return{}}}};function pC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function gC(e){return O3.some(t=>e[t]>=0)}const H3=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...s}=So(e,t);switch(r){case"referenceHidden":{const o=await fd(t,{...s,elementContext:"reference"}),a=pC(o,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:gC(a)}}}case"escaped":{const o=await fd(t,{...s,altBoundary:!0}),a=pC(o,n.floating);return{data:{escapedOffsets:a,escaped:gC(a)}}}default:return{}}}}};async function K3(e,t){const{placement:n,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),a=Co(n),c=Nc(n),u=xa(n)==="y",i=["left","top"].includes(a)?-1:1,d=o&&u?-1:1,p=So(t,e);let{mainAxis:f,crossAxis:g,alignmentAxis:h}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return c&&typeof h=="number"&&(g=c==="end"?h*-1:h),u?{x:g*d,y:f*i}:{x:f*i,y:g*d}}const q3=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:s,y:o,placement:a,middlewareData:c}=t,u=await K3(t,e);return a===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:s+u.x,y:o+u.y,data:{...u,placement:a}}}}},W3=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:s}=t,{mainAxis:o=!0,crossAxis:a=!1,limiter:c={fn:x=>{let{x:b,y}=x;return{x:b,y}}},...u}=So(e,t),i={x:n,y:r},d=await fd(t,u),p=xa(Co(s)),f=Hx(p);let g=i[f],h=i[p];if(o){const x=f==="y"?"top":"left",b=f==="y"?"bottom":"right",y=g+d[x],w=g-d[b];g=Qy(y,g,w)}if(a){const x=p==="y"?"top":"left",b=p==="y"?"bottom":"right",y=h+d[x],w=h-d[b];h=Qy(y,h,w)}const m=c.fn({...t,[f]:g,[p]:h});return{...m,data:{x:m.x-n,y:m.y-r}}}}},G3=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:s,rects:o,middlewareData:a}=t,{offset:c=0,mainAxis:u=!0,crossAxis:i=!0}=So(e,t),d={x:n,y:r},p=xa(s),f=Hx(p);let g=d[f],h=d[p];const m=So(c,t),x=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(u){const w=f==="y"?"height":"width",S=o.reference[f]-o.floating[w]+x.mainAxis,E=o.reference[f]+o.reference[w]-x.mainAxis;gE&&(g=E)}if(i){var b,y;const w=f==="y"?"width":"height",S=["top","left"].includes(Co(s)),E=o.reference[p]-o.floating[w]+(S&&((b=a.offset)==null?void 0:b[p])||0)+(S?0:x.crossAxis),C=o.reference[p]+o.reference[w]+(S?0:((y=a.offset)==null?void 0:y[p])||0)-(S?x.crossAxis:0);hC&&(h=C)}return{[f]:g,[p]:h}}}},J3=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:s,elements:o}=t,{apply:a=()=>{},...c}=So(e,t),u=await fd(t,c),i=Co(n),d=Nc(n),p=xa(n)==="y",{width:f,height:g}=r.floating;let h,m;i==="top"||i==="bottom"?(h=i,m=d===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(m=i,h=d==="end"?"top":"bottom");const x=g-u.top-u.bottom,b=f-u.left-u.right,y=Ds(g-u[h],x),w=Ds(f-u[m],b),S=!t.middlewareData.shift;let E=y,C=w;if(p?C=d||S?Ds(w,b):b:E=d||S?Ds(y,x):x,S&&!d){const j=vr(u.left,0),_=vr(u.right,0),O=vr(u.top,0),K=vr(u.bottom,0);p?C=f-2*(j!==0||_!==0?j+_:vr(u.left,u.right)):E=g-2*(O!==0||K!==0?O+K:vr(u.top,u.bottom))}await a({...t,availableWidth:C,availableHeight:E});const T=await s.getDimensions(o.floating);return f!==T.width||g!==T.height?{reset:{rects:!0}}:{}}}};function _c(e){return kM(e)?(e.nodeName||"").toLowerCase():"#document"}function wr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mo(e){var t;return(t=(kM(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function kM(e){return e instanceof Node||e instanceof wr(e).Node}function Us(e){return e instanceof Element||e instanceof wr(e).Element}function Vs(e){return e instanceof HTMLElement||e instanceof wr(e).HTMLElement}function hC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof wr(e).ShadowRoot}function Qd(e){const{overflow:t,overflowX:n,overflowY:r,display:s}=fs(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(s)}function Q3(e){return["table","td","th"].includes(_c(e))}function gh(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function Wx(e){const t=Gx(),n=fs(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function Z3(e){let t=wa(e);for(;Vs(t)&&!fc(t);){if(gh(t))return null;if(Wx(t))return t;t=wa(t)}return null}function Gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function fc(e){return["html","body","#document"].includes(_c(e))}function fs(e){return wr(e).getComputedStyle(e)}function hh(e){return Us(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function wa(e){if(_c(e)==="html")return e;const t=e.assignedSlot||e.parentNode||hC(e)&&e.host||Mo(e);return hC(t)?t.host:t}function jM(e){const t=wa(e);return fc(t)?e.ownerDocument?e.ownerDocument.body:e.body:Vs(t)&&Qd(t)?t:jM(t)}function pd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const s=jM(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),a=wr(s);return o?t.concat(a,a.visualViewport||[],Qd(s)?s:[],a.frameElement&&n?pd(a.frameElement):[]):t.concat(s,pd(s,[],n))}function TM(e){const t=fs(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=Vs(e),o=s?e.offsetWidth:n,a=s?e.offsetHeight:r,c=sg(n)!==o||sg(r)!==a;return c&&(n=o,r=a),{width:n,height:r,$:c}}function Jx(e){return Us(e)?e:e.contextElement}function Ll(e){const t=Jx(e);if(!Vs(t))return ba(1);const n=t.getBoundingClientRect(),{width:r,height:s,$:o}=TM(t);let a=(o?sg(n.width):n.width)/r,c=(o?sg(n.height):n.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!c||!Number.isFinite(c))&&(c=1),{x:a,y:c}}const Y3=ba(0);function MM(e){const t=wr(e);return!Gx()||!t.visualViewport?Y3:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function X3(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==wr(e)?!1:t}function Oi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const s=e.getBoundingClientRect(),o=Jx(e);let a=ba(1);t&&(r?Us(r)&&(a=Ll(r)):a=Ll(e));const c=X3(o,n,r)?MM(o):ba(0);let u=(s.left+c.x)/a.x,i=(s.top+c.y)/a.y,d=s.width/a.x,p=s.height/a.y;if(o){const f=wr(o),g=r&&Us(r)?wr(r):r;let h=f,m=h.frameElement;for(;m&&r&&g!==h;){const x=Ll(m),b=m.getBoundingClientRect(),y=fs(m),w=b.left+(m.clientLeft+parseFloat(y.paddingLeft))*x.x,S=b.top+(m.clientTop+parseFloat(y.paddingTop))*x.y;u*=x.x,i*=x.y,d*=x.x,p*=x.y,u+=w,i+=S,h=wr(m),m=h.frameElement}}return ag({width:d,height:p,x:u,y:i})}function ez(e){let{elements:t,rect:n,offsetParent:r,strategy:s}=e;const o=s==="fixed",a=Mo(r),c=t?gh(t.floating):!1;if(r===a||c&&o)return n;let u={scrollLeft:0,scrollTop:0},i=ba(1);const d=ba(0),p=Vs(r);if((p||!p&&!o)&&((_c(r)!=="body"||Qd(a))&&(u=hh(r)),Vs(r))){const f=Oi(r);i=Ll(r),d.x=f.x+r.clientLeft,d.y=f.y+r.clientTop}return{width:n.width*i.x,height:n.height*i.y,x:n.x*i.x-u.scrollLeft*i.x+d.x,y:n.y*i.y-u.scrollTop*i.y+d.y}}function tz(e){return Array.from(e.getClientRects())}function NM(e){return Oi(Mo(e)).left+hh(e).scrollLeft}function nz(e){const t=Mo(e),n=hh(e),r=e.ownerDocument.body,s=vr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=vr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+NM(e);const c=-n.scrollTop;return fs(r).direction==="rtl"&&(a+=vr(t.clientWidth,r.clientWidth)-s),{width:s,height:o,x:a,y:c}}function rz(e,t){const n=wr(e),r=Mo(e),s=n.visualViewport;let o=r.clientWidth,a=r.clientHeight,c=0,u=0;if(s){o=s.width,a=s.height;const i=Gx();(!i||i&&t==="fixed")&&(c=s.offsetLeft,u=s.offsetTop)}return{width:o,height:a,x:c,y:u}}function sz(e,t){const n=Oi(e,!0,t==="fixed"),r=n.top+e.clientTop,s=n.left+e.clientLeft,o=Vs(e)?Ll(e):ba(1),a=e.clientWidth*o.x,c=e.clientHeight*o.y,u=s*o.x,i=r*o.y;return{width:a,height:c,x:u,y:i}}function mC(e,t,n){let r;if(t==="viewport")r=rz(e,n);else if(t==="document")r=nz(Mo(e));else if(Us(t))r=sz(t,n);else{const s=MM(e);r={...t,x:t.x-s.x,y:t.y-s.y}}return ag(r)}function _M(e,t){const n=wa(e);return n===t||!Us(n)||fc(n)?!1:fs(n).position==="fixed"||_M(n,t)}function oz(e,t){const n=t.get(e);if(n)return n;let r=pd(e,[],!1).filter(c=>Us(c)&&_c(c)!=="body"),s=null;const o=fs(e).position==="fixed";let a=o?wa(e):e;for(;Us(a)&&!fc(a);){const c=fs(a),u=Wx(a);!u&&c.position==="fixed"&&(s=null),(o?!u&&!s:!u&&c.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||Qd(a)&&!u&&_M(e,a))?r=r.filter(d=>d!==a):s=c,a=wa(a)}return t.set(e,r),r}function az(e){let{element:t,boundary:n,rootBoundary:r,strategy:s}=e;const a=[...n==="clippingAncestors"?gh(t)?[]:oz(t,this._c):[].concat(n),r],c=a[0],u=a.reduce((i,d)=>{const p=mC(t,d,s);return i.top=vr(p.top,i.top),i.right=Ds(p.right,i.right),i.bottom=Ds(p.bottom,i.bottom),i.left=vr(p.left,i.left),i},mC(t,c,s));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function iz(e){const{width:t,height:n}=TM(e);return{width:t,height:n}}function lz(e,t,n){const r=Vs(t),s=Mo(t),o=n==="fixed",a=Oi(e,!0,o,t);let c={scrollLeft:0,scrollTop:0};const u=ba(0);if(r||!r&&!o)if((_c(t)!=="body"||Qd(s))&&(c=hh(t)),r){const p=Oi(t,!0,o,t);u.x=p.x+t.clientLeft,u.y=p.y+t.clientTop}else s&&(u.x=NM(s));const i=a.left+c.scrollLeft-u.x,d=a.top+c.scrollTop-u.y;return{x:i,y:d,width:a.width,height:a.height}}function Gm(e){return fs(e).position==="static"}function vC(e,t){return!Vs(e)||fs(e).position==="fixed"?null:t?t(e):e.offsetParent}function PM(e,t){const n=wr(e);if(gh(e))return n;if(!Vs(e)){let s=wa(e);for(;s&&!fc(s);){if(Us(s)&&!Gm(s))return s;s=wa(s)}return n}let r=vC(e,t);for(;r&&Q3(r)&&Gm(r);)r=vC(r,t);return r&&fc(r)&&Gm(r)&&!Wx(r)?n:r||Z3(e)||n}const cz=async function(e){const t=this.getOffsetParent||PM,n=this.getDimensions,r=await n(e.floating);return{reference:lz(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function uz(e){return fs(e).direction==="rtl"}const dz={convertOffsetParentRelativeRectToViewportRelativeRect:ez,getDocumentElement:Mo,getClippingRect:az,getOffsetParent:PM,getElementRects:cz,getClientRects:tz,getDimensions:iz,getScale:Ll,isElement:Us,isRTL:uz};function fz(e,t){let n=null,r;const s=Mo(e);function o(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function a(c,u){c===void 0&&(c=!1),u===void 0&&(u=1),o();const{left:i,top:d,width:p,height:f}=e.getBoundingClientRect();if(c||t(),!p||!f)return;const g=Rf(d),h=Rf(s.clientWidth-(i+p)),m=Rf(s.clientHeight-(d+f)),x=Rf(i),y={rootMargin:-g+"px "+-h+"px "+-m+"px "+-x+"px",threshold:vr(0,Ds(1,u))||1};let w=!0;function S(E){const C=E[0].intersectionRatio;if(C!==u){if(!w)return a();C?a(!1,C):r=setTimeout(()=>{a(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(S,{...y,root:s.ownerDocument})}catch{n=new IntersectionObserver(S,y)}n.observe(e)}return a(!0),o}function pz(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,i=Jx(e),d=s||o?[...i?pd(i):[],...pd(t)]:[];d.forEach(b=>{s&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=i&&c?fz(i,n):null;let f=-1,g=null;a&&(g=new ResizeObserver(b=>{let[y]=b;y&&y.target===i&&g&&(g.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var w;(w=g)==null||w.observe(t)})),n()}),i&&!u&&g.observe(i),g.observe(t));let h,m=u?Oi(e):null;u&&x();function x(){const b=Oi(e);m&&(b.x!==m.x||b.y!==m.y||b.width!==m.width||b.height!==m.height)&&n(),m=b,h=requestAnimationFrame(x)}return n(),()=>{var b;d.forEach(y=>{s&&y.removeEventListener("scroll",n),o&&y.removeEventListener("resize",n)}),p==null||p(),(b=g)==null||b.disconnect(),g=null,u&&cancelAnimationFrame(h)}}const gz=q3,hz=W3,mz=V3,vz=J3,yz=H3,yC=U3,bz=G3,xz=(e,t,n)=>{const r=new Map,s={platform:dz,...n},o={...s.platform,_c:r};return z3(e,t,{...s,platform:o})};var hp=typeof document<"u"?v.useLayoutEffect:v.useEffect;function ig(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!ig(e[r],t[r]))return!1;return!0}if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,s[r]))return!1;for(r=n;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!ig(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function RM(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function bC(e,t){const n=RM(e);return Math.round(t*n)/n}function xC(e){const t=v.useRef(e);return hp(()=>{t.current=e}),t}function wz(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:a}={},transform:c=!0,whileElementsMounted:u,open:i}=e,[d,p]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,g]=v.useState(r);ig(f,r)||g(r);const[h,m]=v.useState(null),[x,b]=v.useState(null),y=v.useCallback(J=>{J!==C.current&&(C.current=J,m(J))},[]),w=v.useCallback(J=>{J!==T.current&&(T.current=J,b(J))},[]),S=o||h,E=a||x,C=v.useRef(null),T=v.useRef(null),j=v.useRef(d),_=u!=null,O=xC(u),K=xC(s),I=v.useCallback(()=>{if(!C.current||!T.current)return;const J={placement:t,strategy:n,middleware:f};K.current&&(J.platform=K.current),xz(C.current,T.current,J).then(L=>{const A={...L,isPositioned:!0};Y.current&&!ig(j.current,A)&&(j.current=A,Pa.flushSync(()=>{p(A)}))})},[f,t,n,K]);hp(()=>{i===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,p(J=>({...J,isPositioned:!1})))},[i]);const Y=v.useRef(!1);hp(()=>(Y.current=!0,()=>{Y.current=!1}),[]),hp(()=>{if(S&&(C.current=S),E&&(T.current=E),S&&E){if(O.current)return O.current(S,E,I);I()}},[S,E,I,O,_]);const q=v.useMemo(()=>({reference:C,floating:T,setReference:y,setFloating:w}),[y,w]),Z=v.useMemo(()=>({reference:S,floating:E}),[S,E]),ee=v.useMemo(()=>{const J={position:n,left:0,top:0};if(!Z.floating)return J;const L=bC(Z.floating,d.x),A=bC(Z.floating,d.y);return c?{...J,transform:"translate("+L+"px, "+A+"px)",...RM(Z.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:L,top:A}},[n,c,Z.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:I,refs:q,elements:Z,floatingStyles:ee}),[d,I,q,Z,ee])}const Sz=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:s}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?yC({element:r.current,padding:s}).fn(n):{}:r?yC({element:r,padding:s}).fn(n):{}}}},Cz=(e,t)=>({...gz(e),options:[e,t]}),Ez=(e,t)=>({...hz(e),options:[e,t]}),kz=(e,t)=>({...bz(e),options:[e,t]}),jz=(e,t)=>({...mz(e),options:[e,t]}),Tz=(e,t)=>({...vz(e),options:[e,t]}),Mz=(e,t)=>({...yz(e),options:[e,t]}),Nz=(e,t)=>({...Sz(e),options:[e,t]});var _z="Arrow",OM=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...o}=e;return l.jsx(Ie.svg,{...o,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:l.jsx("polygon",{points:"0,0 30,0 15,10"})})});OM.displayName=_z;var Pz=OM;function IM(e){const[t,n]=v.useState(void 0);return pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let a,c;if("borderBoxSize"in o){const u=o.borderBoxSize,i=Array.isArray(u)?u[0]:u;a=i.inlineSize,c=i.blockSize}else a=e.offsetWidth,c=e.offsetHeight;n({width:a,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Qx="Popper",[DM,mh]=qr(Qx),[Rz,AM]=DM(Qx),FM=e=>{const{__scopePopper:t,children:n}=e,[r,s]=v.useState(null);return l.jsx(Rz,{scope:t,anchor:r,onAnchorChange:s,children:n})};FM.displayName=Qx;var LM="PopperAnchor",$M=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,o=AM(LM,n),a=v.useRef(null),c=ct(t,a);return v.useEffect(()=>{o.onAnchorChange((r==null?void 0:r.current)||a.current)}),r?null:l.jsx(Ie.div,{...s,ref:c})});$M.displayName=LM;var Zx="PopperContent",[Oz,Iz]=DM(Zx),BM=v.forwardRef((e,t)=>{var Q,Ee,Pe,Be,Re,ve;const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:c=0,avoidCollisions:u=!0,collisionBoundary:i=[],collisionPadding:d=0,sticky:p="partial",hideWhenDetached:f=!1,updatePositionStrategy:g="optimized",onPlaced:h,...m}=e,x=AM(Zx,n),[b,y]=v.useState(null),w=ct(t,ot=>y(ot)),[S,E]=v.useState(null),C=IM(S),T=(C==null?void 0:C.width)??0,j=(C==null?void 0:C.height)??0,_=r+(o!=="center"?"-"+o:""),O=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},K=Array.isArray(i)?i:[i],I=K.length>0,Y={padding:O,boundary:K.filter(Az),altBoundary:I},{refs:q,floatingStyles:Z,placement:ee,isPositioned:J,middlewareData:L}=wz({strategy:"fixed",placement:_,whileElementsMounted:(...ot)=>pz(...ot,{animationFrame:g==="always"}),elements:{reference:x.anchor},middleware:[Cz({mainAxis:s+j,alignmentAxis:a}),u&&Ez({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?kz():void 0,...Y}),u&&jz({...Y}),Tz({...Y,apply:({elements:ot,rects:Vt,availableWidth:tn,availableHeight:Xt})=>{const{width:ln,height:M}=Vt.reference,D=ot.floating.style;D.setProperty("--radix-popper-available-width",`${tn}px`),D.setProperty("--radix-popper-available-height",`${Xt}px`),D.setProperty("--radix-popper-anchor-width",`${ln}px`),D.setProperty("--radix-popper-anchor-height",`${M}px`)}}),S&&Nz({element:S,padding:c}),Fz({arrowWidth:T,arrowHeight:j}),f&&Mz({strategy:"referenceHidden",...Y})]}),[A,X]=VM(ee),fe=on(h);pn(()=>{J&&(fe==null||fe())},[J,fe]);const H=(Q=L.arrow)==null?void 0:Q.x,se=(Ee=L.arrow)==null?void 0:Ee.y,ne=((Pe=L.arrow)==null?void 0:Pe.centerOffset)!==0,[le,oe]=v.useState();return pn(()=>{b&&oe(window.getComputedStyle(b).zIndex)},[b]),l.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...Z,transform:J?Z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:le,"--radix-popper-transform-origin":[(Be=L.transformOrigin)==null?void 0:Be.x,(Re=L.transformOrigin)==null?void 0:Re.y].join(" "),...((ve=L.hide)==null?void 0:ve.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:l.jsx(Oz,{scope:n,placedSide:A,onArrowChange:E,arrowX:H,arrowY:se,shouldHideArrow:ne,children:l.jsx(Ie.div,{"data-side":A,"data-align":X,...m,ref:w,style:{...m.style,animation:J?void 0:"none"}})})})});BM.displayName=Zx;var zM="PopperArrow",Dz={top:"bottom",right:"left",bottom:"top",left:"right"},UM=v.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,o=Iz(zM,r),a=Dz[o.placedSide];return l.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:l.jsx(Pz,{...s,ref:n,style:{...s.style,display:"block"}})})});UM.displayName=zM;function Az(e){return e!==null}var Fz=e=>({name:"transformOrigin",options:e,fn(t){var x,b,y;const{placement:n,rects:r,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,c=a?0:e.arrowWidth,u=a?0:e.arrowHeight,[i,d]=VM(n),p={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+c/2,g=(((y=s.arrow)==null?void 0:y.y)??0)+u/2;let h="",m="";return i==="bottom"?(h=a?p:`${f}px`,m=`${-u}px`):i==="top"?(h=a?p:`${f}px`,m=`${r.floating.height+u}px`):i==="right"?(h=`${-u}px`,m=a?p:`${g}px`):i==="left"&&(h=`${r.floating.width+u}px`,m=a?p:`${g}px`),{data:{x:h,y:m}}}});function VM(e){const[t,n="center"]=e.split("-");return[t,n]}var HM=FM,KM=$M,qM=BM,WM=UM,Lz="Portal",vh=v.forwardRef((e,t)=>{var c;const{container:n,...r}=e,[s,o]=v.useState(!1);pn(()=>o(!0),[]);const a=n||s&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return a?lT.createPortal(l.jsx(Ie.div,{...r,ref:t}),a):null});vh.displayName=Lz;function $z(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var cr=e=>{const{present:t,children:n}=e,r=Bz(t),s=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),o=ct(r.ref,zz(s));return typeof n=="function"||r.isPresent?v.cloneElement(s,{ref:o}):null};cr.displayName="Presence";function Bz(e){const[t,n]=v.useState(),r=v.useRef({}),s=v.useRef(e),o=v.useRef("none"),a=e?"mounted":"unmounted",[c,u]=$z(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const i=Of(r.current);o.current=c==="mounted"?i:"none"},[c]),pn(()=>{const i=r.current,d=s.current;if(d!==e){const f=o.current,g=Of(i);e?u("MOUNT"):g==="none"||(i==null?void 0:i.display)==="none"?u("UNMOUNT"):u(d&&f!==g?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,u]),pn(()=>{if(t){const i=p=>{const g=Of(r.current).includes(p.animationName);p.target===t&&g&&Pa.flushSync(()=>u("ANIMATION_END"))},d=p=>{p.target===t&&(o.current=Of(r.current))};return t.addEventListener("animationstart",d),t.addEventListener("animationcancel",i),t.addEventListener("animationend",i),()=>{t.removeEventListener("animationstart",d),t.removeEventListener("animationcancel",i),t.removeEventListener("animationend",i)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:v.useCallback(i=>{i&&(r.current=getComputedStyle(i)),n(i)},[])}}function Of(e){return(e==null?void 0:e.animationName)||"none"}function zz(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Jm="rovingFocusGroup.onEntryFocus",Uz={bubbles:!1,cancelable:!0},yh="RovingFocusGroup",[Yy,GM,Vz]=Ux(yh),[Hz,bh]=qr(yh,[Vz]),[Kz,qz]=Hz(yh),JM=v.forwardRef((e,t)=>l.jsx(Yy.Provider,{scope:e.__scopeRovingFocusGroup,children:l.jsx(Yy.Slot,{scope:e.__scopeRovingFocusGroup,children:l.jsx(Wz,{...e,ref:t})})}));JM.displayName=yh;var Wz=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:o,currentTabStopId:a,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:u,onEntryFocus:i,preventScrollOnEntryFocus:d=!1,...p}=e,f=v.useRef(null),g=ct(t,f),h=Jd(o),[m=null,x]=ya({prop:a,defaultProp:c,onChange:u}),[b,y]=v.useState(!1),w=on(i),S=GM(n),E=v.useRef(!1),[C,T]=v.useState(0);return v.useEffect(()=>{const j=f.current;if(j)return j.addEventListener(Jm,w),()=>j.removeEventListener(Jm,w)},[w]),l.jsx(Kz,{scope:n,orientation:r,dir:h,loop:s,currentTabStopId:m,onItemFocus:v.useCallback(j=>x(j),[x]),onItemShiftTab:v.useCallback(()=>y(!0),[]),onFocusableItemAdd:v.useCallback(()=>T(j=>j+1),[]),onFocusableItemRemove:v.useCallback(()=>T(j=>j-1),[]),children:l.jsx(Ie.div,{tabIndex:b||C===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:Ce(e.onMouseDown,()=>{E.current=!0}),onFocus:Ce(e.onFocus,j=>{const _=!E.current;if(j.target===j.currentTarget&&_&&!b){const O=new CustomEvent(Jm,Uz);if(j.currentTarget.dispatchEvent(O),!O.defaultPrevented){const K=S().filter(ee=>ee.focusable),I=K.find(ee=>ee.active),Y=K.find(ee=>ee.id===m),Z=[I,Y,...K].filter(Boolean).map(ee=>ee.ref.current);YM(Z,d)}}E.current=!1}),onBlur:Ce(e.onBlur,()=>y(!1))})})}),QM="RovingFocusGroupItem",ZM=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:o,...a}=e,c=is(),u=o||c,i=qz(QM,n),d=i.currentTabStopId===u,p=GM(n),{onFocusableItemAdd:f,onFocusableItemRemove:g}=i;return v.useEffect(()=>{if(r)return f(),()=>g()},[r,f,g]),l.jsx(Yy.ItemSlot,{scope:n,id:u,focusable:r,active:s,children:l.jsx(Ie.span,{tabIndex:d?0:-1,"data-orientation":i.orientation,...a,ref:t,onMouseDown:Ce(e.onMouseDown,h=>{r?i.onItemFocus(u):h.preventDefault()}),onFocus:Ce(e.onFocus,()=>i.onItemFocus(u)),onKeyDown:Ce(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){i.onItemShiftTab();return}if(h.target!==h.currentTarget)return;const m=Qz(h,i.orientation,i.dir);if(m!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let b=p().filter(y=>y.focusable).map(y=>y.ref.current);if(m==="last")b.reverse();else if(m==="prev"||m==="next"){m==="prev"&&b.reverse();const y=b.indexOf(h.currentTarget);b=i.loop?Zz(b,y+1):b.slice(y+1)}setTimeout(()=>YM(b))}})})})});ZM.displayName=QM;var Gz={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Jz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Qz(e,t,n){const r=Jz(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Gz[r]}function YM(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Zz(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var XM=JM,eN=ZM,Yz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},rl=new WeakMap,If=new WeakMap,Df={},Qm=0,tN=function(e){return e&&(e.host||tN(e.parentNode))},Xz=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=tN(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},eU=function(e,t,n,r){var s=Xz(t,Array.isArray(e)?e:[e]);Df[n]||(Df[n]=new WeakMap);var o=Df[n],a=[],c=new Set,u=new Set(s),i=function(p){!p||c.has(p)||(c.add(p),i(p.parentNode))};s.forEach(i);var d=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(f){if(c.has(f))d(f);else try{var g=f.getAttribute(r),h=g!==null&&g!=="false",m=(rl.get(f)||0)+1,x=(o.get(f)||0)+1;rl.set(f,m),o.set(f,x),a.push(f),m===1&&h&&If.set(f,!0),x===1&&f.setAttribute(n,"true"),h||f.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",f,b)}})};return d(t),c.clear(),Qm++,function(){a.forEach(function(p){var f=rl.get(p)-1,g=o.get(p)-1;rl.set(p,f),o.set(p,g),f||(If.has(p)||p.removeAttribute(r),If.delete(p)),g||p.removeAttribute(n)}),Qm--,Qm||(rl=new WeakMap,rl=new WeakMap,If=new WeakMap,Df={})}},Yx=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=Yz(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),eU(r,s,n,"aria-hidden")):function(){return null}},Ps=function(){return Ps=Object.assign||function(t){for(var n,r=1,s=arguments.length;r"u")return vU;var t=yU(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},xU=oN(),$l="data-scroll-locked",wU=function(e,t,n,r){var s=e.left,o=e.top,a=e.right,c=e.gap;return n===void 0&&(n="margin"),` + .`.concat(nU,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(c,"px ").concat(r,`; + } + body[`).concat($l,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(s,`px; + padding-top: `).concat(o,`px; + padding-right: `).concat(a,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(c,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(mp,` { + right: `).concat(c,"px ").concat(r,`; + } + + .`).concat(vp,` { + margin-right: `).concat(c,"px ").concat(r,`; + } + + .`).concat(mp," .").concat(mp,` { + right: 0 `).concat(r,`; + } + + .`).concat(vp," .").concat(vp,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat($l,`] { + `).concat(rU,": ").concat(c,`px; + } +`)},SC=function(){var e=parseInt(document.body.getAttribute($l)||"0",10);return isFinite(e)?e:0},SU=function(){v.useEffect(function(){return document.body.setAttribute($l,(SC()+1).toString()),function(){var e=SC()-1;e<=0?document.body.removeAttribute($l):document.body.setAttribute($l,e.toString())}},[])},CU=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;SU();var o=v.useMemo(function(){return bU(s)},[s]);return v.createElement(xU,{styles:wU(o,!t,s,n?"":"!important")})},Xy=!1;if(typeof window<"u")try{var Af=Object.defineProperty({},"passive",{get:function(){return Xy=!0,!0}});window.addEventListener("test",Af,Af),window.removeEventListener("test",Af,Af)}catch{Xy=!1}var sl=Xy?{passive:!1}:!1,EU=function(e){return e.tagName==="TEXTAREA"},aN=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!EU(e)&&n[t]==="visible")},kU=function(e){return aN(e,"overflowY")},jU=function(e){return aN(e,"overflowX")},CC=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=iN(e,r);if(s){var o=lN(e,r),a=o[1],c=o[2];if(a>c)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},TU=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},MU=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iN=function(e,t){return e==="v"?kU(t):jU(t)},lN=function(e,t){return e==="v"?TU(t):MU(t)},NU=function(e,t){return e==="h"&&t==="rtl"?-1:1},_U=function(e,t,n,r,s){var o=NU(e,window.getComputedStyle(t).direction),a=o*r,c=n.target,u=t.contains(c),i=!1,d=a>0,p=0,f=0;do{var g=lN(e,c),h=g[0],m=g[1],x=g[2],b=m-x-o*h;(h||b)&&iN(e,c)&&(p+=b,f+=h),c instanceof ShadowRoot?c=c.host:c=c.parentNode}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(d&&(Math.abs(p)<1||!s)||!d&&(Math.abs(f)<1||!s))&&(i=!0),i},Ff=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},EC=function(e){return[e.deltaX,e.deltaY]},kC=function(e){return e&&"current"in e?e.current:e},PU=function(e,t){return e[0]===t[0]&&e[1]===t[1]},RU=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},OU=0,ol=[];function IU(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),s=v.useState(OU++)[0],o=v.useState(oN)[0],a=v.useRef(e);v.useEffect(function(){a.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var m=tU([e.lockRef.current],(e.shards||[]).map(kC),!0).filter(Boolean);return m.forEach(function(x){return x.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),m.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var c=v.useCallback(function(m,x){if("touches"in m&&m.touches.length===2)return!a.current.allowPinchZoom;var b=Ff(m),y=n.current,w="deltaX"in m?m.deltaX:y[0]-b[0],S="deltaY"in m?m.deltaY:y[1]-b[1],E,C=m.target,T=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&T==="h"&&C.type==="range")return!1;var j=CC(T,C);if(!j)return!0;if(j?E=T:(E=T==="v"?"h":"v",j=CC(T,C)),!j)return!1;if(!r.current&&"changedTouches"in m&&(w||S)&&(r.current=E),!E)return!0;var _=r.current||E;return _U(_,x,m,_==="h"?w:S,!0)},[]),u=v.useCallback(function(m){var x=m;if(!(!ol.length||ol[ol.length-1]!==o)){var b="deltaY"in x?EC(x):Ff(x),y=t.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&PU(E.delta,b)})[0];if(y&&y.should){x.cancelable&&x.preventDefault();return}if(!y){var w=(a.current.shards||[]).map(kC).filter(Boolean).filter(function(E){return E.contains(x.target)}),S=w.length>0?c(x,w[0]):!a.current.noIsolation;S&&x.cancelable&&x.preventDefault()}}},[]),i=v.useCallback(function(m,x,b,y){var w={name:m,delta:x,target:b,should:y,shadowParent:DU(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),d=v.useCallback(function(m){n.current=Ff(m),r.current=void 0},[]),p=v.useCallback(function(m){i(m.type,EC(m),m.target,c(m,e.lockRef.current))},[]),f=v.useCallback(function(m){i(m.type,Ff(m),m.target,c(m,e.lockRef.current))},[]);v.useEffect(function(){return ol.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",u,sl),document.addEventListener("touchmove",u,sl),document.addEventListener("touchstart",d,sl),function(){ol=ol.filter(function(m){return m!==o}),document.removeEventListener("wheel",u,sl),document.removeEventListener("touchmove",u,sl),document.removeEventListener("touchstart",d,sl)}},[]);var g=e.removeScrollBar,h=e.inert;return v.createElement(v.Fragment,null,h?v.createElement(o,{styles:RU(s)}):null,g?v.createElement(CU,{gapMode:e.gapMode}):null)}function DU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const AU=uU(sN,IU);var wh=v.forwardRef(function(e,t){return v.createElement(xh,Ps({},e,{ref:t,sideCar:AU}))});wh.classNames=xh.classNames;var eb=["Enter"," "],FU=["ArrowDown","PageUp","Home"],cN=["ArrowUp","PageDown","End"],LU=[...FU,...cN],$U={ltr:[...eb,"ArrowRight"],rtl:[...eb,"ArrowLeft"]},BU={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Zd="Menu",[gd,zU,UU]=Ux(Zd),[Gi,uN]=qr(Zd,[UU,mh,bh]),Sh=mh(),dN=bh(),[VU,Ji]=Gi(Zd),[HU,Yd]=Gi(Zd),fN=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:s,onOpenChange:o,modal:a=!0}=e,c=Sh(t),[u,i]=v.useState(null),d=v.useRef(!1),p=on(o),f=Jd(s);return v.useEffect(()=>{const g=()=>{d.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>d.current=!1;return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),l.jsx(HM,{...c,children:l.jsx(VU,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:i,children:l.jsx(HU,{scope:t,onClose:v.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:d,dir:f,modal:a,children:r})})})};fN.displayName=Zd;var KU="MenuAnchor",Xx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=Sh(n);return l.jsx(KM,{...s,...r,ref:t})});Xx.displayName=KU;var ew="MenuPortal",[qU,pN]=Gi(ew,{forceMount:void 0}),gN=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:s}=e,o=Ji(ew,t);return l.jsx(qU,{scope:t,forceMount:n,children:l.jsx(cr,{present:n||o.open,children:l.jsx(vh,{asChild:!0,container:s,children:r})})})};gN.displayName=ew;var Vr="MenuContent",[WU,tw]=Gi(Vr),hN=v.forwardRef((e,t)=>{const n=pN(Vr,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Ji(Vr,e.__scopeMenu),a=Yd(Vr,e.__scopeMenu);return l.jsx(gd.Provider,{scope:e.__scopeMenu,children:l.jsx(cr,{present:r||o.open,children:l.jsx(gd.Slot,{scope:e.__scopeMenu,children:a.modal?l.jsx(GU,{...s,ref:t}):l.jsx(JU,{...s,ref:t})})})})}),GU=v.forwardRef((e,t)=>{const n=Ji(Vr,e.__scopeMenu),r=v.useRef(null),s=ct(t,r);return v.useEffect(()=>{const o=r.current;if(o)return Yx(o)},[]),l.jsx(nw,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ce(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),JU=v.forwardRef((e,t)=>{const n=Ji(Vr,e.__scopeMenu);return l.jsx(nw,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),nw=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:i,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:g,disableOutsideScroll:h,...m}=e,x=Ji(Vr,n),b=Yd(Vr,n),y=Sh(n),w=dN(n),S=zU(n),[E,C]=v.useState(null),T=v.useRef(null),j=ct(t,T,x.onContentChange),_=v.useRef(0),O=v.useRef(""),K=v.useRef(0),I=v.useRef(null),Y=v.useRef("right"),q=v.useRef(0),Z=h?wh:v.Fragment,ee=h?{as:wo,allowPinchZoom:!0}:void 0,J=A=>{var Q,Ee;const X=O.current+A,fe=S().filter(Pe=>!Pe.disabled),H=document.activeElement,se=(Q=fe.find(Pe=>Pe.ref.current===H))==null?void 0:Q.textValue,ne=fe.map(Pe=>Pe.textValue),le=i5(ne,X,se),oe=(Ee=fe.find(Pe=>Pe.textValue===le))==null?void 0:Ee.ref.current;(function Pe(Be){O.current=Be,window.clearTimeout(_.current),Be!==""&&(_.current=window.setTimeout(()=>Pe(""),1e3))})(X),oe&&setTimeout(()=>oe.focus())};v.useEffect(()=>()=>window.clearTimeout(_.current),[]),Vx();const L=v.useCallback(A=>{var fe,H;return Y.current===((fe=I.current)==null?void 0:fe.side)&&c5(A,(H=I.current)==null?void 0:H.area)},[]);return l.jsx(WU,{scope:n,searchRef:O,onItemEnter:v.useCallback(A=>{L(A)&&A.preventDefault()},[L]),onItemLeave:v.useCallback(A=>{var X;L(A)||((X=T.current)==null||X.focus(),C(null))},[L]),onTriggerLeave:v.useCallback(A=>{L(A)&&A.preventDefault()},[L]),pointerGraceTimerRef:K,onPointerGraceIntentChange:v.useCallback(A=>{I.current=A},[]),children:l.jsx(Z,{...ee,children:l.jsx(ph,{asChild:!0,trapped:s,onMountAutoFocus:Ce(o,A=>{var X;A.preventDefault(),(X=T.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:l.jsx(fh,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:i,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:g,children:l.jsx(XM,{asChild:!0,...w,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:C,onEntryFocus:Ce(u,A=>{b.isUsingKeyboardRef.current||A.preventDefault()}),preventScrollOnEntryFocus:!0,children:l.jsx(qM,{role:"menu","aria-orientation":"vertical","data-state":PN(x.open),"data-radix-menu-content":"",dir:b.dir,...y,...m,ref:j,style:{outline:"none",...m.style},onKeyDown:Ce(m.onKeyDown,A=>{const fe=A.target.closest("[data-radix-menu-content]")===A.currentTarget,H=A.ctrlKey||A.altKey||A.metaKey,se=A.key.length===1;fe&&(A.key==="Tab"&&A.preventDefault(),!H&&se&&J(A.key));const ne=T.current;if(A.target!==ne||!LU.includes(A.key))return;A.preventDefault();const oe=S().filter(Q=>!Q.disabled).map(Q=>Q.ref.current);cN.includes(A.key)&&oe.reverse(),o5(oe)}),onBlur:Ce(e.onBlur,A=>{A.currentTarget.contains(A.target)||(window.clearTimeout(_.current),O.current="")}),onPointerMove:Ce(e.onPointerMove,hd(A=>{const X=A.target,fe=q.current!==A.clientX;if(A.currentTarget.contains(X)&&fe){const H=A.clientX>q.current?"right":"left";Y.current=H,q.current=A.clientX}}))})})})})})})});hN.displayName=Vr;var QU="MenuGroup",rw=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(Ie.div,{role:"group",...r,ref:t})});rw.displayName=QU;var ZU="MenuLabel",mN=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(Ie.div,{...r,ref:t})});mN.displayName=ZU;var lg="MenuItem",jC="menu.itemSelect",Ch=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...s}=e,o=v.useRef(null),a=Yd(lg,e.__scopeMenu),c=tw(lg,e.__scopeMenu),u=ct(t,o),i=v.useRef(!1),d=()=>{const p=o.current;if(!n&&p){const f=new CustomEvent(jC,{bubbles:!0,cancelable:!0});p.addEventListener(jC,g=>r==null?void 0:r(g),{once:!0}),xM(p,f),f.defaultPrevented?i.current=!1:a.onClose()}};return l.jsx(vN,{...s,ref:u,disabled:n,onClick:Ce(e.onClick,d),onPointerDown:p=>{var f;(f=e.onPointerDown)==null||f.call(e,p),i.current=!0},onPointerUp:Ce(e.onPointerUp,p=>{var f;i.current||(f=p.currentTarget)==null||f.click()}),onKeyDown:Ce(e.onKeyDown,p=>{const f=c.searchRef.current!=="";n||f&&p.key===" "||eb.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});Ch.displayName=lg;var vN=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...o}=e,a=tw(lg,n),c=dN(n),u=v.useRef(null),i=ct(t,u),[d,p]=v.useState(!1),[f,g]=v.useState("");return v.useEffect(()=>{const h=u.current;h&&g((h.textContent??"").trim())},[o.children]),l.jsx(gd.ItemSlot,{scope:n,disabled:r,textValue:s??f,children:l.jsx(eN,{asChild:!0,...c,focusable:!r,children:l.jsx(Ie.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:i,onPointerMove:Ce(e.onPointerMove,hd(h=>{r?a.onItemLeave(h):(a.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ce(e.onPointerLeave,hd(h=>a.onItemLeave(h))),onFocus:Ce(e.onFocus,()=>p(!0)),onBlur:Ce(e.onBlur,()=>p(!1))})})})}),YU="MenuCheckboxItem",yN=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...s}=e;return l.jsx(CN,{scope:e.__scopeMenu,checked:n,children:l.jsx(Ch,{role:"menuitemcheckbox","aria-checked":cg(n)?"mixed":n,...s,ref:t,"data-state":ow(n),onSelect:Ce(s.onSelect,()=>r==null?void 0:r(cg(n)?!0:!n),{checkForDefaultPrevented:!1})})})});yN.displayName=YU;var bN="MenuRadioGroup",[XU,e5]=Gi(bN,{value:void 0,onValueChange:()=>{}}),xN=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...s}=e,o=on(r);return l.jsx(XU,{scope:e.__scopeMenu,value:n,onValueChange:o,children:l.jsx(rw,{...s,ref:t})})});xN.displayName=bN;var wN="MenuRadioItem",SN=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=e5(wN,e.__scopeMenu),o=n===s.value;return l.jsx(CN,{scope:e.__scopeMenu,checked:o,children:l.jsx(Ch,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":ow(o),onSelect:Ce(r.onSelect,()=>{var a;return(a=s.onValueChange)==null?void 0:a.call(s,n)},{checkForDefaultPrevented:!1})})})});SN.displayName=wN;var sw="MenuItemIndicator",[CN,t5]=Gi(sw,{checked:!1}),EN=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...s}=e,o=t5(sw,n);return l.jsx(cr,{present:r||cg(o.checked)||o.checked===!0,children:l.jsx(Ie.span,{...s,ref:t,"data-state":ow(o.checked)})})});EN.displayName=sw;var n5="MenuSeparator",kN=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(Ie.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});kN.displayName=n5;var r5="MenuArrow",jN=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=Sh(n);return l.jsx(WM,{...s,...r,ref:t})});jN.displayName=r5;var s5="MenuSub",[Xoe,TN]=Gi(s5),vu="MenuSubTrigger",MN=v.forwardRef((e,t)=>{const n=Ji(vu,e.__scopeMenu),r=Yd(vu,e.__scopeMenu),s=TN(vu,e.__scopeMenu),o=tw(vu,e.__scopeMenu),a=v.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=o,i={__scopeMenu:e.__scopeMenu},d=v.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return v.useEffect(()=>d,[d]),v.useEffect(()=>{const p=c.current;return()=>{window.clearTimeout(p),u(null)}},[c,u]),l.jsx(Xx,{asChild:!0,...i,children:l.jsx(vN,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":PN(n.open),...e,ref:lh(t,s.onTriggerChange),onClick:p=>{var f;(f=e.onClick)==null||f.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ce(e.onPointerMove,hd(p=>{o.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(o.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:Ce(e.onPointerLeave,hd(p=>{var g,h;d();const f=(g=n.content)==null?void 0:g.getBoundingClientRect();if(f){const m=(h=n.content)==null?void 0:h.dataset.side,x=m==="right",b=x?-5:5,y=f[x?"left":"right"],w=f[x?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+b,y:p.clientY},{x:y,y:f.top},{x:w,y:f.top},{x:w,y:f.bottom},{x:y,y:f.bottom}],side:m}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Ce(e.onKeyDown,p=>{var g;const f=o.searchRef.current!=="";e.disabled||f&&p.key===" "||$U[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});MN.displayName=vu;var NN="MenuSubContent",_N=v.forwardRef((e,t)=>{const n=pN(Vr,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Ji(Vr,e.__scopeMenu),a=Yd(Vr,e.__scopeMenu),c=TN(NN,e.__scopeMenu),u=v.useRef(null),i=ct(t,u);return l.jsx(gd.Provider,{scope:e.__scopeMenu,children:l.jsx(cr,{present:r||o.open,children:l.jsx(gd.Slot,{scope:e.__scopeMenu,children:l.jsx(nw,{id:c.contentId,"aria-labelledby":c.triggerId,...s,ref:i,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var p;a.isUsingKeyboardRef.current&&((p=u.current)==null||p.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:Ce(e.onFocusOutside,d=>{d.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Ce(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:Ce(e.onKeyDown,d=>{var g;const p=d.currentTarget.contains(d.target),f=BU[a.dir].includes(d.key);p&&f&&(o.onOpenChange(!1),(g=c.trigger)==null||g.focus(),d.preventDefault())})})})})})});_N.displayName=NN;function PN(e){return e?"open":"closed"}function cg(e){return e==="indeterminate"}function ow(e){return cg(e)?"indeterminate":e?"checked":"unchecked"}function o5(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function a5(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function i5(e,t,n){const s=t.length>1&&Array.from(t).every(i=>i===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=a5(e,Math.max(o,0));s.length===1&&(a=a.filter(i=>i!==n));const u=a.find(i=>i.toLowerCase().startsWith(s.toLowerCase()));return u!==n?u:void 0}function l5(e,t){const{x:n,y:r}=e;let s=!1;for(let o=0,a=t.length-1;or!=d>r&&n<(i-c)*(r-u)/(d-u)+c&&(s=!s)}return s}function c5(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return l5(n,t)}function hd(e){return t=>t.pointerType==="mouse"?e(t):void 0}var u5=fN,d5=Xx,f5=gN,p5=hN,g5=rw,h5=mN,m5=Ch,v5=yN,y5=xN,b5=SN,x5=EN,w5=kN,S5=jN,C5=MN,E5=_N,aw="DropdownMenu",[k5,eae]=qr(aw,[uN]),Yn=uN(),[j5,RN]=k5(aw),iw=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:s,defaultOpen:o,onOpenChange:a,modal:c=!0}=e,u=Yn(t),i=v.useRef(null),[d=!1,p]=ya({prop:s,defaultProp:o,onChange:a});return l.jsx(j5,{scope:t,triggerId:is(),triggerRef:i,contentId:is(),open:d,onOpenChange:p,onOpenToggle:v.useCallback(()=>p(f=>!f),[p]),modal:c,children:l.jsx(u5,{...u,open:d,onOpenChange:p,dir:r,modal:c,children:n})})};iw.displayName=aw;var ON="DropdownMenuTrigger",lw=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=e,o=RN(ON,n),a=Yn(n);return l.jsx(d5,{asChild:!0,...a,children:l.jsx(Ie.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:lh(t,o.triggerRef),onPointerDown:Ce(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(o.onOpenToggle(),o.open||c.preventDefault())}),onKeyDown:Ce(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&o.onOpenToggle(),c.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});lw.displayName=ON;var T5="DropdownMenuPortal",IN=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Yn(t);return l.jsx(f5,{...r,...n})};IN.displayName=T5;var DN="DropdownMenuContent",AN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=RN(DN,n),o=Yn(n),a=v.useRef(!1);return l.jsx(p5,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:t,onCloseAutoFocus:Ce(e.onCloseAutoFocus,c=>{var u;a.current||(u=s.triggerRef.current)==null||u.focus(),a.current=!1,c.preventDefault()}),onInteractOutside:Ce(e.onInteractOutside,c=>{const u=c.detail.originalEvent,i=u.button===0&&u.ctrlKey===!0,d=u.button===2||i;(!s.modal||d)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});AN.displayName=DN;var M5="DropdownMenuGroup",N5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(g5,{...s,...r,ref:t})});N5.displayName=M5;var _5="DropdownMenuLabel",FN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(h5,{...s,...r,ref:t})});FN.displayName=_5;var P5="DropdownMenuItem",LN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(m5,{...s,...r,ref:t})});LN.displayName=P5;var R5="DropdownMenuCheckboxItem",$N=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(v5,{...s,...r,ref:t})});$N.displayName=R5;var O5="DropdownMenuRadioGroup",I5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(y5,{...s,...r,ref:t})});I5.displayName=O5;var D5="DropdownMenuRadioItem",BN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(b5,{...s,...r,ref:t})});BN.displayName=D5;var A5="DropdownMenuItemIndicator",zN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(x5,{...s,...r,ref:t})});zN.displayName=A5;var F5="DropdownMenuSeparator",UN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(w5,{...s,...r,ref:t})});UN.displayName=F5;var L5="DropdownMenuArrow",$5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(S5,{...s,...r,ref:t})});$5.displayName=L5;var B5="DropdownMenuSubTrigger",VN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(C5,{...s,...r,ref:t})});VN.displayName=B5;var z5="DropdownMenuSubContent",HN=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Yn(n);return l.jsx(E5,{...s,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});HN.displayName=z5;var U5=iw,V5=lw,H5=IN,KN=AN,qN=FN,WN=LN,GN=$N,JN=BN,QN=zN,Da=UN,ZN=VN,YN=HN;const ms=U5,vs=V5,K5=v.forwardRef(({className:e,inset:t,children:n,...r},s)=>l.jsxs(ZN,{ref:s,className:me("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,l.jsx(zB,{className:"ml-auto h-4 w-4"})]}));K5.displayName=ZN.displayName;const q5=v.forwardRef(({className:e,...t},n)=>l.jsx(YN,{ref:n,className:me("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));q5.displayName=YN.displayName;const Mr=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>l.jsx(H5,{children:l.jsx(KN,{ref:r,sideOffset:t,className:me("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));Mr.displayName=KN.displayName;const tt=v.forwardRef(({className:e,inset:t,...n},r)=>l.jsx(WN,{ref:r,className:me("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));tt.displayName=WN.displayName;const XN=v.forwardRef(({className:e,children:t,checked:n,...r},s)=>l.jsxs(GN,{ref:s,className:me("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[l.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:l.jsx(QN,{children:l.jsx(mM,{className:"h-4 w-4"})})}),t]}));XN.displayName=GN.displayName;const W5=v.forwardRef(({className:e,children:t,...n},r)=>l.jsxs(JN,{ref:r,className:me("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[l.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:l.jsx(QN,{children:l.jsx(KB,{className:"h-2 w-2 fill-current"})})}),t]}));W5.displayName=JN.displayName;const No=v.forwardRef(({className:e,inset:t,...n},r)=>l.jsx(qN,{ref:r,className:me("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));No.displayName=qN.displayName;const Gs=v.forwardRef(({className:e,...t},n)=>l.jsx(Da,{ref:n,className:me("-mx-1 my-1 h-px bg-muted",e),...t}));Gs.displayName=Da.displayName;function G5(){const{t:e,i18n:t}=Te(),n=r=>{t.changeLanguage(r),localStorage.setItem("i18nextLng",r),window.location.reload()};return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"outline",size:"icon",children:[l.jsx(XB,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all"}),l.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(tt,{className:t.language==="pt-BR"?"font-bold":"",onClick:()=>n("pt-BR"),children:e("header.language.portuguese")}),l.jsx(tt,{className:t.language==="en-US"?"font-bold":"",onClick:()=>n("en-US"),children:e("header.language.english")}),l.jsx(tt,{className:t.language==="es-ES"?"font-bold":"",onClick:()=>n("es-ES"),children:e("header.language.spanish")}),l.jsx(tt,{className:t.language==="fr-FR"?"font-bold":"",onClick:()=>n("fr-FR"),children:e("header.language.french")})]})]})}function J5(){const{t:e}=Te(),{setTheme:t}=Dx();return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"outline",size:"icon",children:[l.jsx(a3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),l.jsx(r3,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),l.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(tt,{onClick:()=>t("light"),children:e("header.theme.light")}),l.jsx(tt,{onClick:()=>t("dark"),children:e("header.theme.dark")}),l.jsx(tt,{onClick:()=>t("system"),children:e("header.theme.system")})]})]})}var cw="Avatar",[Q5,tae]=qr(cw),[Z5,e_]=Q5(cw),t_=v.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[s,o]=v.useState("idle");return l.jsx(Z5,{scope:n,imageLoadingStatus:s,onImageLoadingStatusChange:o,children:l.jsx(Ie.span,{...r,ref:t})})});t_.displayName=cw;var n_="AvatarImage",r_=v.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:s=()=>{},...o}=e,a=e_(n_,n),c=Y5(r),u=on(i=>{s(i),a.onImageLoadingStatusChange(i)});return pn(()=>{c!=="idle"&&u(c)},[c,u]),c==="loaded"?l.jsx(Ie.img,{...o,ref:t,src:r}):null});r_.displayName=n_;var s_="AvatarFallback",o_=v.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...s}=e,o=e_(s_,n),[a,c]=v.useState(r===void 0);return v.useEffect(()=>{if(r!==void 0){const u=window.setTimeout(()=>c(!0),r);return()=>window.clearTimeout(u)}},[r]),a&&o.imageLoadingStatus!=="loaded"?l.jsx(Ie.span,{...s,ref:t}):null});o_.displayName=s_;function Y5(e){const[t,n]=v.useState("idle");return pn(()=>{if(!e){n("error");return}let r=!0;const s=new window.Image,o=a=>()=>{r&&n(a)};return n("loading"),s.onload=o("loaded"),s.onerror=o("error"),s.src=e,()=>{r=!1}},[e]),t}var a_=t_,i_=r_,l_=o_;const Eh=v.forwardRef(({className:e,...t},n)=>l.jsx(a_,{ref:n,className:me("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Eh.displayName=a_.displayName;const kh=v.forwardRef(({className:e,...t},n)=>l.jsx(i_,{ref:n,className:me("aspect-square h-full w-full",e),...t}));kh.displayName=i_.displayName;const X5=v.forwardRef(({className:e,...t},n)=>l.jsx(l_,{ref:n,className:me("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));X5.displayName=l_.displayName;var uw="Dialog",[c_,nae]=qr(uw),[eV,ys]=c_(uw),u_=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:a=!0}=e,c=v.useRef(null),u=v.useRef(null),[i=!1,d]=ya({prop:r,defaultProp:s,onChange:o});return l.jsx(eV,{scope:t,triggerRef:c,contentRef:u,contentId:is(),titleId:is(),descriptionId:is(),open:i,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(p=>!p),[d]),modal:a,children:n})};u_.displayName=uw;var d_="DialogTrigger",f_=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=ys(d_,n),o=ct(t,s.triggerRef);return l.jsx(Ie.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":pw(s.open),...r,ref:o,onClick:Ce(e.onClick,s.onOpenToggle)})});f_.displayName=d_;var dw="DialogPortal",[tV,p_]=c_(dw,{forceMount:void 0}),g_=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:s}=e,o=ys(dw,t);return l.jsx(tV,{scope:t,forceMount:n,children:v.Children.map(r,a=>l.jsx(cr,{present:n||o.open,children:l.jsx(vh,{asChild:!0,container:s,children:a})}))})};g_.displayName=dw;var ug="DialogOverlay",h_=v.forwardRef((e,t)=>{const n=p_(ug,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=ys(ug,e.__scopeDialog);return o.modal?l.jsx(cr,{present:r||o.open,children:l.jsx(nV,{...s,ref:t})}):null});h_.displayName=ug;var nV=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=ys(ug,n);return l.jsx(wh,{as:wo,allowPinchZoom:!0,shards:[s.contentRef],children:l.jsx(Ie.div,{"data-state":pw(s.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Ii="DialogContent",m_=v.forwardRef((e,t)=>{const n=p_(Ii,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=ys(Ii,e.__scopeDialog);return l.jsx(cr,{present:r||o.open,children:o.modal?l.jsx(rV,{...s,ref:t}):l.jsx(sV,{...s,ref:t})})});m_.displayName=Ii;var rV=v.forwardRef((e,t)=>{const n=ys(Ii,e.__scopeDialog),r=v.useRef(null),s=ct(t,n.contentRef,r);return v.useEffect(()=>{const o=r.current;if(o)return Yx(o)},[]),l.jsx(v_,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ce(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ce(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,c=a.button===0&&a.ctrlKey===!0;(a.button===2||c)&&o.preventDefault()}),onFocusOutside:Ce(e.onFocusOutside,o=>o.preventDefault())})}),sV=v.forwardRef((e,t)=>{const n=ys(Ii,e.__scopeDialog),r=v.useRef(!1),s=v.useRef(!1);return l.jsx(v_,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var a,c;(a=e.onCloseAutoFocus)==null||a.call(e,o),o.defaultPrevented||(r.current||(c=n.triggerRef.current)==null||c.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var u,i;(u=e.onInteractOutside)==null||u.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=o.target;((i=n.triggerRef.current)==null?void 0:i.contains(a))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),v_=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...a}=e,c=ys(Ii,n),u=v.useRef(null),i=ct(t,u);return Vx(),l.jsxs(l.Fragment,{children:[l.jsx(ph,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:l.jsx(fh,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":pw(c.open),...a,ref:i,onDismiss:()=>c.onOpenChange(!1)})}),l.jsxs(l.Fragment,{children:[l.jsx(oV,{titleId:c.titleId}),l.jsx(iV,{contentRef:u,descriptionId:c.descriptionId})]})]})}),fw="DialogTitle",y_=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=ys(fw,n);return l.jsx(Ie.h2,{id:s.titleId,...r,ref:t})});y_.displayName=fw;var b_="DialogDescription",x_=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=ys(b_,n);return l.jsx(Ie.p,{id:s.descriptionId,...r,ref:t})});x_.displayName=b_;var w_="DialogClose",S_=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=ys(w_,n);return l.jsx(Ie.button,{type:"button",...r,ref:t,onClick:Ce(e.onClick,()=>s.onOpenChange(!1))})});S_.displayName=w_;function pw(e){return e?"open":"closed"}var C_="DialogTitleWarning",[rae,E_]=d3(C_,{contentName:Ii,titleName:fw,docsSlug:"dialog"}),oV=({titleId:e})=>{const t=E_(C_),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return v.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},aV="DialogDescriptionWarning",iV=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${E_(aV).contentName}}.`;return v.useEffect(()=>{var o;const s=(o=e.current)==null?void 0:o.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},lV=u_,cV=f_,uV=g_,k_=h_,j_=m_,T_=y_,M_=x_,N_=S_;const pt=lV,mt=cV,dV=uV,__=N_,P_=v.forwardRef(({className:e,...t},n)=>l.jsx(k_,{ref:n,className:me("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));P_.displayName=k_.displayName;const ut=v.forwardRef(({className:e,children:t,closeBtn:n=!0,...r},s)=>l.jsx(dV,{children:l.jsx(P_,{className:"fixed inset-0 grid place-items-center overflow-y-auto",children:l.jsxs(j_,{ref:s,className:me("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:m-4 sm:rounded-lg md:w-full",e),...r,children:[t,n&&l.jsxs(N_,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[l.jsx(l3,{className:"h-4 w-4"}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})})}));ut.displayName=j_.displayName;const dt=({className:e,...t})=>l.jsx("div",{className:me("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});dt.displayName="DialogHeader";const _t=({className:e,...t})=>l.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});_t.displayName="DialogFooter";const yt=v.forwardRef(({className:e,...t},n)=>l.jsx(T_,{ref:n,className:me("text-lg font-semibold leading-none tracking-tight",e),...t}));yt.displayName=T_.displayName;const _o=v.forwardRef(({className:e,...t},n)=>l.jsx(M_,{ref:n,className:me("text-sm text-muted-foreground",e),...t}));_o.displayName=M_.displayName;function R_({instanceId:e}){const[t,n]=v.useState(!1),r=an(),{theme:s}=Dx(),o=()=>{FT(),r("/manager/login")},a=()=>{r("/manager/")},{data:c}=bM({instanceId:e});return l.jsxs("header",{className:"flex items-center justify-between px-4 py-2",children:[l.jsx(ld,{to:"/manager",onClick:a,className:"flex h-8 items-center gap-4",children:l.jsx("img",{src:s==="dark"?"https://evolution-api.com/files/evo/evolution-logo-white.svg":"https://evolution-api.com/files/evo/evolution-logo.svg",alt:"Logo",className:"h-full"})}),l.jsxs("div",{className:"flex items-center gap-4",children:[e&&l.jsx(Eh,{className:"h-8 w-8",children:l.jsx(kh,{src:(c==null?void 0:c.profilePicUrl)||"/assets/images/evolution-logo.png",alt:c==null?void 0:c.name})}),l.jsx(G5,{}),l.jsx(J5,{}),l.jsx(z,{onClick:()=>n(!0),variant:"destructive",size:"icon",children:l.jsx(WB,{size:"18"})})]}),t&&l.jsx(pt,{onOpenChange:n,open:t,children:l.jsxs(ut,{children:[l.jsx(__,{}),l.jsx(dt,{children:"Deseja realmente sair?"}),l.jsx(_t,{children:l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx(z,{onClick:()=>n(!1),size:"sm",variant:"outline",children:"Cancelar"}),l.jsx(z,{onClick:o,variant:"destructive",children:"Sair"})]})})]})})]})}const O_=v.createContext(null),Ve=()=>{const e=v.useContext(O_);if(!e)throw new Error("useInstance must be used within an InstanceProvider");return e},fV=({children:e})=>{const t=gs(),[n,r]=v.useState(null),{data:s,refetch:o}=bM({instanceId:n});return v.useEffect(()=>{t.instanceId?r(t.instanceId):r(null)},[t]),l.jsx(O_.Provider,{value:{instance:s??null,reloadInstance:async()=>{await o()}},children:e})};var gw="Collapsible",[pV,sae]=qr(gw),[gV,hw]=pV(gw),I_=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:a,...c}=e,[u=!1,i]=ya({prop:r,defaultProp:s,onChange:a});return l.jsx(gV,{scope:n,disabled:o,contentId:is(),open:u,onOpenToggle:v.useCallback(()=>i(d=>!d),[i]),children:l.jsx(Ie.div,{"data-state":vw(u),"data-disabled":o?"":void 0,...c,ref:t})})});I_.displayName=gw;var D_="CollapsibleTrigger",A_=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=hw(D_,n);return l.jsx(Ie.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":vw(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Ce(e.onClick,s.onOpenToggle)})});A_.displayName=D_;var mw="CollapsibleContent",F_=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=hw(mw,e.__scopeCollapsible);return l.jsx(cr,{present:n||s.open,children:({present:o})=>l.jsx(hV,{...r,ref:t,present:o})})});F_.displayName=mw;var hV=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,a=hw(mw,n),[c,u]=v.useState(r),i=v.useRef(null),d=ct(t,i),p=v.useRef(0),f=p.current,g=v.useRef(0),h=g.current,m=a.open||c,x=v.useRef(m),b=v.useRef();return v.useEffect(()=>{const y=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(y)},[]),pn(()=>{const y=i.current;if(y){b.current=b.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const w=y.getBoundingClientRect();p.current=w.height,g.current=w.width,x.current||(y.style.transitionDuration=b.current.transitionDuration,y.style.animationName=b.current.animationName),u(r)}},[a.open,r]),l.jsx(Ie.div,{"data-state":vw(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...o,ref:d,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":h?`${h}px`:void 0,...e.style},children:m&&s})});function vw(e){return e?"open":"closed"}var mV=I_;const vV=mV,yV=A_,bV=F_;function xV(){const{t:e}=Te(),t=v.useMemo(()=>[{id:"dashboard",title:e("sidebar.dashboard"),icon:e3,path:"dashboard"},{navLabel:!0,title:e("sidebar.configurations"),icon:To,children:[{id:"settings",title:e("sidebar.settings"),path:"settings"},{id:"proxy",title:e("sidebar.proxy"),path:"proxy"}]},{title:e("sidebar.events"),icon:YB,children:[{id:"webhook",title:e("sidebar.webhook"),path:"webhook"},{id:"websocket",title:e("sidebar.websocket"),path:"websocket"},{id:"rabbitmq",title:e("sidebar.rabbitmq"),path:"rabbitmq"},{id:"sqs",title:e("sidebar.sqs"),path:"sqs"}]},{title:e("sidebar.integrations"),icon:yM,children:[{id:"evoai",title:e("sidebar.evoai"),path:"evoai"},{id:"n8n",title:e("sidebar.n8n"),path:"n8n"},{id:"evolutionBot",title:e("sidebar.evolutionBot"),path:"evolutionBot"},{id:"chatwoot",title:e("sidebar.chatwoot"),path:"chatwoot"},{id:"typebot",title:e("sidebar.typebot"),path:"typebot"},{id:"openai",title:e("sidebar.openai"),path:"openai"},{id:"dify",title:e("sidebar.dify"),path:"dify"},{id:"flowise",title:e("sidebar.flowise"),path:"flowise"}]},{id:"documentation",title:e("sidebar.documentation"),icon:QB,link:"https://doc.evolution-api.com",divider:!0},{id:"postman",title:e("sidebar.postman"),icon:HB,link:"https://evolution-api.com/postman"},{id:"discord",title:e("sidebar.discord"),icon:dh,link:"https://evolution-api.com/discord"},{id:"support-premium",title:e("sidebar.supportPremium"),icon:t3,link:"https://evolution-api.com/suporte-pro"}],[e]),n=an(),{pathname:r}=kc(),{instance:s}=Ve(),o=c=>{!c||!s||(c.path&&n(`/manager/instance/${s.id}/${c.path}`),c.link&&window.open(c.link,"_blank"))},a=v.useMemo(()=>t.map(c=>{var u;return{...c,children:"children"in c?(u=c.children)==null?void 0:u.map(i=>({...i,isActive:"path"in i?r.includes(i.path):!1})):void 0,isActive:"path"in c&&c.path?r.includes(c.path):!1}}).map(c=>{var u;return{...c,isActive:c.isActive||"children"in c&&((u=c.children)==null?void 0:u.some(i=>i.isActive))}}),[t,r]);return l.jsx("ul",{className:"flex h-full w-full flex-col gap-2 border-r border-border px-2",children:a.map(c=>l.jsx("li",{className:"divider"in c?"mt-auto":void 0,children:c.children?l.jsxs(vV,{defaultOpen:c.isActive,children:[l.jsx(yV,{asChild:!0,children:l.jsxs(z,{className:me("flex w-full items-center justify-start gap-2"),variant:c.isActive?"secondary":"link",children:[c.icon&&l.jsx(c.icon,{size:"15"}),l.jsx("span",{children:c.title}),l.jsx(uh,{size:"15",className:"ml-auto"})]})}),l.jsx(bV,{children:l.jsx("ul",{className:"my-4 ml-6 flex flex-col gap-2 text-sm",children:c.children.map(u=>l.jsx("li",{children:l.jsx("button",{onClick:()=>o(u),className:me(u.isActive?"text-foreground":"text-muted-foreground"),children:l.jsx("span",{className:"nav-label",children:u.title})})},u.id))})})]}):l.jsxs(z,{className:me("relative flex w-full items-center justify-start gap-2",c.isActive&&"pointer-events-none"),variant:c.isActive?"secondary":"link",children:["link"in c&&l.jsx("a",{href:c.link,target:"_blank",rel:"noreferrer",className:"absolute inset-0 h-full w-full"}),"path"in c&&l.jsx(ld,{to:`/manager/instance/${s==null?void 0:s.id}/${c.path}`,className:"absolute inset-0 h-full w-full"}),c.icon&&l.jsx(c.icon,{size:"15"}),l.jsx("span",{children:c.title})]})},c.title))})}function tb(e,[t,n]){return Math.min(n,Math.max(t,e))}function wV(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var yw="ScrollArea",[L_,oae]=qr(yw),[SV,Wr]=L_(yw),$_=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...a}=e,[c,u]=v.useState(null),[i,d]=v.useState(null),[p,f]=v.useState(null),[g,h]=v.useState(null),[m,x]=v.useState(null),[b,y]=v.useState(0),[w,S]=v.useState(0),[E,C]=v.useState(!1),[T,j]=v.useState(!1),_=ct(t,K=>u(K)),O=Jd(s);return l.jsx(SV,{scope:n,type:r,dir:O,scrollHideDelay:o,scrollArea:c,viewport:i,onViewportChange:d,content:p,onContentChange:f,scrollbarX:g,onScrollbarXChange:h,scrollbarXEnabled:E,onScrollbarXEnabledChange:C,scrollbarY:m,onScrollbarYChange:x,scrollbarYEnabled:T,onScrollbarYEnabledChange:j,onCornerWidthChange:y,onCornerHeightChange:S,children:l.jsx(Ie.div,{dir:O,...a,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":w+"px",...e.style}})})});$_.displayName=yw;var B_="ScrollAreaViewport",z_=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,a=Wr(B_,n),c=v.useRef(null),u=ct(t,c,a.onViewportChange);return l.jsxs(l.Fragment,{children:[l.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),l.jsx(Ie.div,{"data-radix-scroll-area-viewport":"",...o,ref:u,style:{overflowX:a.scrollbarXEnabled?"scroll":"hidden",overflowY:a.scrollbarYEnabled?"scroll":"hidden",...e.style},children:l.jsx("div",{ref:a.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});z_.displayName=B_;var Js="ScrollAreaScrollbar",bw=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Wr(Js,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:a}=s,c=e.orientation==="horizontal";return v.useEffect(()=>(c?o(!0):a(!0),()=>{c?o(!1):a(!1)}),[c,o,a]),s.type==="hover"?l.jsx(CV,{...r,ref:t,forceMount:n}):s.type==="scroll"?l.jsx(EV,{...r,ref:t,forceMount:n}):s.type==="auto"?l.jsx(U_,{...r,ref:t,forceMount:n}):s.type==="always"?l.jsx(xw,{...r,ref:t}):null});bw.displayName=Js;var CV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Wr(Js,e.__scopeScrollArea),[o,a]=v.useState(!1);return v.useEffect(()=>{const c=s.scrollArea;let u=0;if(c){const i=()=>{window.clearTimeout(u),a(!0)},d=()=>{u=window.setTimeout(()=>a(!1),s.scrollHideDelay)};return c.addEventListener("pointerenter",i),c.addEventListener("pointerleave",d),()=>{window.clearTimeout(u),c.removeEventListener("pointerenter",i),c.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),l.jsx(cr,{present:n||o,children:l.jsx(U_,{"data-state":o?"visible":"hidden",...r,ref:t})})}),EV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Wr(Js,e.__scopeScrollArea),o=e.orientation==="horizontal",a=Th(()=>u("SCROLL_END"),100),[c,u]=wV("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(c==="idle"){const i=window.setTimeout(()=>u("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(i)}},[c,s.scrollHideDelay,u]),v.useEffect(()=>{const i=s.viewport,d=o?"scrollLeft":"scrollTop";if(i){let p=i[d];const f=()=>{const g=i[d];p!==g&&(u("SCROLL"),a()),p=g};return i.addEventListener("scroll",f),()=>i.removeEventListener("scroll",f)}},[s.viewport,o,u,a]),l.jsx(cr,{present:n||c!=="hidden",children:l.jsx(xw,{"data-state":c==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ce(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:Ce(e.onPointerLeave,()=>u("POINTER_LEAVE"))})})}),U_=v.forwardRef((e,t)=>{const n=Wr(Js,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,a]=v.useState(!1),c=e.orientation==="horizontal",u=Th(()=>{if(n.viewport){const i=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,s=Wr(Js,e.__scopeScrollArea),o=v.useRef(null),a=v.useRef(0),[c,u]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),i=W_(c.viewport,c.content),d={...r,sizes:c,onSizesChange:u,hasThumb:i>0&&i<1,onThumbChange:f=>o.current=f,onThumbPointerUp:()=>a.current=0,onThumbPointerDown:f=>a.current=f};function p(f,g){return _V(f,a.current,c,g)}return n==="horizontal"?l.jsx(kV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollLeft,g=TC(f,c,s.dir);o.current.style.transform=`translate3d(${g}px, 0, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollLeft=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollLeft=p(f,s.dir))}}):n==="vertical"?l.jsx(jV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollTop,g=TC(f,c);o.current.style.transform=`translate3d(0, ${g}px, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollTop=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollTop=p(f))}}):null}),kV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Wr(Js,e.__scopeScrollArea),[a,c]=v.useState(),u=v.useRef(null),i=ct(t,u,o.onScrollbarXChange);return v.useEffect(()=>{u.current&&c(getComputedStyle(u.current))},[u]),l.jsx(H_,{"data-orientation":"horizontal",...s,ref:i,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":jh(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollLeft+d.deltaX;e.onWheelScroll(f),J_(f,p)&&d.preventDefault()}},onResize:()=>{u.current&&o.viewport&&a&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:fg(a.paddingLeft),paddingEnd:fg(a.paddingRight)}})}})}),jV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Wr(Js,e.__scopeScrollArea),[a,c]=v.useState(),u=v.useRef(null),i=ct(t,u,o.onScrollbarYChange);return v.useEffect(()=>{u.current&&c(getComputedStyle(u.current))},[u]),l.jsx(H_,{"data-orientation":"vertical",...s,ref:i,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":jh(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollTop+d.deltaY;e.onWheelScroll(f),J_(f,p)&&d.preventDefault()}},onResize:()=>{u.current&&o.viewport&&a&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:fg(a.paddingTop),paddingEnd:fg(a.paddingBottom)}})}})}),[TV,V_]=L_(Js),H_=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:a,onThumbPointerDown:c,onThumbPositionChange:u,onDragScroll:i,onWheelScroll:d,onResize:p,...f}=e,g=Wr(Js,n),[h,m]=v.useState(null),x=ct(t,_=>m(_)),b=v.useRef(null),y=v.useRef(""),w=g.viewport,S=r.content-r.viewport,E=on(d),C=on(u),T=Th(p,10);function j(_){if(b.current){const O=_.clientX-b.current.left,K=_.clientY-b.current.top;i({x:O,y:K})}}return v.useEffect(()=>{const _=O=>{const K=O.target;(h==null?void 0:h.contains(K))&&E(O,S)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[w,h,S,E]),v.useEffect(C,[r,C]),pc(h,T),pc(g.content,T),l.jsx(TV,{scope:n,scrollbar:h,hasThumb:s,onThumbChange:on(o),onThumbPointerUp:on(a),onThumbPositionChange:C,onThumbPointerDown:on(c),children:l.jsx(Ie.div,{...f,ref:x,style:{position:"absolute",...f.style},onPointerDown:Ce(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),b.current=h.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",g.viewport&&(g.viewport.style.scrollBehavior="auto"),j(_))}),onPointerMove:Ce(e.onPointerMove,j),onPointerUp:Ce(e.onPointerUp,_=>{const O=_.target;O.hasPointerCapture(_.pointerId)&&O.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=y.current,g.viewport&&(g.viewport.style.scrollBehavior=""),b.current=null})})})}),dg="ScrollAreaThumb",K_=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=V_(dg,e.__scopeScrollArea);return l.jsx(cr,{present:n||s.hasThumb,children:l.jsx(MV,{ref:t,...r})})}),MV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=Wr(dg,n),a=V_(dg,n),{onThumbPositionChange:c}=a,u=ct(t,p=>a.onThumbChange(p)),i=v.useRef(),d=Th(()=>{i.current&&(i.current(),i.current=void 0)},100);return v.useEffect(()=>{const p=o.viewport;if(p){const f=()=>{if(d(),!i.current){const g=PV(p,c);i.current=g,c()}};return c(),p.addEventListener("scroll",f),()=>p.removeEventListener("scroll",f)}},[o.viewport,d,c]),l.jsx(Ie.div,{"data-state":a.hasThumb?"visible":"hidden",...s,ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ce(e.onPointerDownCapture,p=>{const g=p.target.getBoundingClientRect(),h=p.clientX-g.left,m=p.clientY-g.top;a.onThumbPointerDown({x:h,y:m})}),onPointerUp:Ce(e.onPointerUp,a.onThumbPointerUp)})});K_.displayName=dg;var ww="ScrollAreaCorner",q_=v.forwardRef((e,t)=>{const n=Wr(ww,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l.jsx(NV,{...e,ref:t}):null});q_.displayName=ww;var NV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=Wr(ww,n),[o,a]=v.useState(0),[c,u]=v.useState(0),i=!!(o&&c);return pc(s.scrollbarX,()=>{var p;const d=((p=s.scrollbarX)==null?void 0:p.offsetHeight)||0;s.onCornerHeightChange(d),u(d)}),pc(s.scrollbarY,()=>{var p;const d=((p=s.scrollbarY)==null?void 0:p.offsetWidth)||0;s.onCornerWidthChange(d),a(d)}),i?l.jsx(Ie.div,{...r,ref:t,style:{width:o,height:c,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function fg(e){return e?parseInt(e,10):0}function W_(e,t){const n=e/t;return isNaN(n)?0:n}function jh(e){const t=W_(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function _V(e,t,n,r="ltr"){const s=jh(n),o=s/2,a=t||o,c=s-a,u=n.scrollbar.paddingStart+a,i=n.scrollbar.size-n.scrollbar.paddingEnd-c,d=n.content-n.viewport,p=r==="ltr"?[0,d]:[d*-1,0];return G_([u,i],p)(e)}function TC(e,t,n="ltr"){const r=jh(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,a=t.content-t.viewport,c=o-r,u=n==="ltr"?[0,a]:[a*-1,0],i=tb(e,u);return G_([0,a],[0,c])(i)}function G_(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function J_(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function s(){const o={left:e.scrollLeft,top:e.scrollTop},a=n.left!==o.left,c=n.top!==o.top;(a||c)&&t(),n=o,r=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(r)};function Th(e,t){const n=on(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function pc(e,t){const n=on(t);pn(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var Q_=$_,RV=z_,OV=q_;const nb=v.forwardRef(({className:e,children:t,...n},r)=>l.jsxs(Q_,{ref:r,className:me("relative overflow-hidden",e),...n,children:[l.jsx(RV,{className:"h-full w-full rounded-[inherit] [&>div[style]]:!block [&>div[style]]:h-full",children:t}),l.jsx(Z_,{}),l.jsx(OV,{})]}));nb.displayName=Q_.displayName;const Z_=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>l.jsx(bw,{ref:r,orientation:t,className:me("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 border-t border-t-transparent p-[1px]",e),...n,children:l.jsx(K_,{className:me("relative rounded-full bg-border",t==="vertical"&&"flex-1")})}));Z_.displayName=bw.displayName;function Lt({children:e}){const{instanceId:t}=gs();return l.jsx(fV,{children:l.jsxs("div",{className:"flex h-screen flex-col",children:[l.jsx(R_,{instanceId:t}),l.jsxs("div",{className:"flex min-h-[calc(100vh_-_56px)] flex-1 flex-col md:flex-row",children:[l.jsx(nb,{className:"mr-2 py-6 md:w-64",children:l.jsx("div",{className:"flex h-full",children:l.jsx(xV,{})})}),l.jsx(nb,{className:"w-full",children:l.jsxs("div",{className:"flex h-full flex-col",children:[l.jsx("div",{className:"my-6 flex flex-1 flex-col gap-2 pl-2 pr-4",children:e}),l.jsx(zx,{})]})})]})]})})}function IV({children:e}){return l.jsxs("div",{className:"flex h-full min-h-screen flex-col",children:[l.jsx(R_,{}),l.jsx("main",{className:"flex-1",children:e}),l.jsx(zx,{})]})}const DV=ch("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",warning:"border-transparent bg-amber-600 text-amber-100 hover:bg-amber-600/80"}},defaultVariants:{variant:"default"}});function Lf({className:e,variant:t,...n}){return l.jsx("div",{className:me(DV({variant:t}),e),...n})}function Y_({status:e}){const{t}=Te();return e?e==="open"?l.jsx(Lf,{children:t("status.open")}):e==="connecting"?l.jsx(Lf,{variant:"warning",children:t("status.connecting")}):e==="close"||e==="closed"?l.jsx(Lf,{variant:"destructive",children:t("status.closed")}):l.jsx(Lf,{variant:"secondary",children:e}):null}const AV=e=>{navigator.clipboard.writeText(e),G.success("Copiado para a área de transferência")};function X_({token:e,className:t}){const[n,r]=v.useState(!1);return l.jsxs("div",{className:me("flex items-center gap-3 truncate rounded-sm bg-primary/20 px-2 py-1",t),children:[l.jsx("pre",{className:"block truncate text-xs",children:n?e:e==null?void 0:e.replace(/\w/g,"*")}),l.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{AV(e)},children:l.jsx(qB,{size:"15"})}),l.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{r(s=>!s)},children:n?l.jsx(GB,{size:"15"}):l.jsx(JB,{size:"15"})})]})}const oi=v.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:me("flex flex-col rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));oi.displayName="Card";const ai=v.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:me("flex flex-col space-y-1.5 p-6",e),...t}));ai.displayName="CardHeader";const Iu=v.forwardRef(({className:e,...t},n)=>l.jsx("h3",{ref:n,className:me("text-2xl font-semibold leading-none tracking-tight",e),...t}));Iu.displayName="CardTitle";const eP=v.forwardRef(({className:e,...t},n)=>l.jsx("p",{ref:n,className:me("text-sm text-muted-foreground",e),...t}));eP.displayName="CardDescription";const ii=v.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:me("p-6 pt-0",e),...t}));ii.displayName="CardContent";const Mh=v.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:me("flex items-center p-6 pt-0",e),...t}));Mh.displayName="CardFooter";const tP="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",F=v.forwardRef(({className:e,type:t,...n},r)=>l.jsx("input",{type:t,className:me(tP,e),ref:r,...n}));F.displayName="Input";const FV=["instance","fetchInstances"],LV=async()=>(await Gd.get("/instance/fetchInstances")).data,$V=e=>qe({...e,queryKey:FV,queryFn:()=>LV()});function Le(e,t){const n=Bb(),r=oA({mutationFn:e});return(s,o)=>r.mutateAsync(s,{onSuccess:async(a,c,u)=>{var i;t!=null&&t.invalidateKeys&&await Promise.all(t.invalidateKeys.map(d=>n.invalidateQueries({queryKey:d}))),(i=o==null?void 0:o.onSuccess)==null||i.call(o,a,c,u)},onError(a,c,u){var i;(i=o==null?void 0:o.onError)==null||i.call(o,a,c,u)},onSettled(a,c,u,i){var d;(d=o==null?void 0:o.onSettled)==null||d.call(o,a,c,u,i)}})}const BV=async e=>(await Gd.post("/instance/create",e)).data,zV=async e=>(await ie.post(`/instance/restart/${e}`)).data,UV=async e=>(await ie.delete(`/instance/logout/${e}`)).data,VV=async e=>(await Gd.delete(`/instance/delete/${e}`)).data,HV=async({instanceName:e,token:t,number:n})=>(await ie.get(`/instance/connect/${e}`,{headers:{apikey:t},params:{number:n}})).data,KV=async({instanceName:e,token:t,data:n})=>(await ie.post(`/settings/set/${e}`,n,{headers:{apikey:t}})).data;function Nh(){const e=Le(HV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),t=Le(KV,{invalidateKeys:[["instance","fetchSettings"]]}),n=Le(VV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),r=Le(UV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),s=Le(zV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),o=Le(BV,{invalidateKeys:[["instance","fetchInstances"]]});return{connect:e,updateSettings:t,deleteInstance:n,logout:r,restart:s,createInstance:o}}var Xd=e=>e.type==="checkbox",Ml=e=>e instanceof Date,qn=e=>e==null;const nP=e=>typeof e=="object";var gn=e=>!qn(e)&&!Array.isArray(e)&&nP(e)&&!Ml(e),rP=e=>gn(e)&&e.target?Xd(e.target)?e.target.checked:e.target.value:e,qV=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,sP=(e,t)=>e.has(qV(t)),WV=e=>{const t=e.constructor&&e.constructor.prototype;return gn(t)&&t.hasOwnProperty("isPrototypeOf")},Sw=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Xn(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Sw&&(e instanceof Blob||e instanceof FileList))&&(n||gn(e)))if(t=n?[]:{},!n&&!WV(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=Xn(e[r]));else return e;return t}var _h=e=>Array.isArray(e)?e.filter(Boolean):[],Yt=e=>e===void 0,de=(e,t,n)=>{if(!t||!gn(e))return n;const r=_h(t.split(/[,[\].]+?/)).reduce((s,o)=>qn(s)?s:s[o],e);return Yt(r)||r===e?Yt(e[t])?n:e[t]:r},Rs=e=>typeof e=="boolean",Cw=e=>/^\w*$/.test(e),oP=e=>_h(e.replace(/["|']|\]/g,"").split(/\.|\[/)),xt=(e,t,n)=>{let r=-1;const s=Cw(t)?[t]:oP(t),o=s.length,a=o-1;for(;++rje.useContext(aP),Mn=e=>{const{children:t,...n}=e;return je.createElement(aP.Provider,{value:n},t)};var iP=(e,t,n,r=!0)=>{const s={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(s,o,{get:()=>{const a=o;return t._proxyFormState[a]!==ts.all&&(t._proxyFormState[a]=!r||ts.all),n&&(n[a]=!0),e[a]}});return s},pr=e=>gn(e)&&!Object.keys(e).length,lP=(e,t,n,r)=>{n(e);const{name:s,...o}=e;return pr(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(a=>t[a]===(!r||ts.all))},Du=e=>Array.isArray(e)?e:[e],cP=(e,t,n)=>!e||!t||e===t||Du(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Ew(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function GV(e){const t=Ph(),{control:n=t.control,disabled:r,name:s,exact:o}=e||{},[a,c]=je.useState(n._formState),u=je.useRef(!0),i=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),d=je.useRef(s);return d.current=s,Ew({disabled:r,next:p=>u.current&&cP(d.current,p.name,o)&&lP(p,i.current,n._updateFormState)&&c({...n._formState,...p}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,i.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),iP(a,n,i.current,!1)}var As=e=>typeof e=="string",uP=(e,t,n,r,s)=>As(e)?(r&&t.watch.add(e),de(n,e,s)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),de(n,o))):(r&&(t.watchAll=!0),n);function JV(e){const t=Ph(),{control:n=t.control,name:r,defaultValue:s,disabled:o,exact:a}=e||{},c=je.useRef(r);c.current=r,Ew({disabled:o,subject:n._subjects.values,next:d=>{cP(c.current,d.name,a)&&i(Xn(uP(c.current,n._names,d.values||n._formValues,!1,s)))}});const[u,i]=je.useState(n._getWatch(r,s));return je.useEffect(()=>n._removeUnmounted()),u}function QV(e){const t=Ph(),{name:n,disabled:r,control:s=t.control,shouldUnregister:o}=e,a=sP(s._names.array,n),c=JV({control:s,name:n,defaultValue:de(s._formValues,n,de(s._defaultValues,n,e.defaultValue)),exact:!0}),u=GV({control:s,name:n}),i=je.useRef(s.register(n,{...e.rules,value:c,...Rs(e.disabled)?{disabled:e.disabled}:{}}));return je.useEffect(()=>{const d=s._options.shouldUnregister||o,p=(f,g)=>{const h=de(s._fields,f);h&&h._f&&(h._f.mount=g)};if(p(n,!0),d){const f=Xn(de(s._options.defaultValues,n));xt(s._defaultValues,n,f),Yt(de(s._formValues,n))&&xt(s._formValues,n,f)}return()=>{(a?d&&!s._state.action:d)?s.unregister(n):p(n,!1)}},[n,s,a,o]),je.useEffect(()=>{de(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:de(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:c,...Rs(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:je.useCallback(d=>i.current.onChange({target:{value:rP(d),name:n},type:pg.CHANGE}),[n]),onBlur:je.useCallback(()=>i.current.onBlur({target:{value:de(s._formValues,n),name:n},type:pg.BLUR}),[n,s]),ref:d=>{const p=de(s._fields,n);p&&d&&(p._f.ref={focus:()=>d.focus(),select:()=>d.select(),setCustomValidity:f=>d.setCustomValidity(f),reportValidity:()=>d.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!de(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!de(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!de(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!de(u.validatingFields,n)},error:{enumerable:!0,get:()=>de(u.errors,n)}})}}const ZV=e=>e.render(QV(e));var dP=(e,t,n,r,s)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:s||!0}}:{},MC=e=>({isOnSubmit:!e||e===ts.onSubmit,isOnBlur:e===ts.onBlur,isOnChange:e===ts.onChange,isOnAll:e===ts.all,isOnTouch:e===ts.onTouched}),NC=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Au=(e,t,n,r)=>{for(const s of n||Object.keys(e)){const o=de(e,s);if(o){const{_f:a,...c}=o;if(a){if(a.refs&&a.refs[0]&&t(a.refs[0],s)&&!r)break;if(a.ref&&t(a.ref,a.name)&&!r)break;Au(c,t)}else gn(c)&&Au(c,t)}}};var YV=(e,t,n)=>{const r=Du(de(e,n));return xt(r,"root",t[n]),xt(e,n,r),e},kw=e=>e.type==="file",aa=e=>typeof e=="function",gg=e=>{if(!Sw)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},yp=e=>As(e),jw=e=>e.type==="radio",hg=e=>e instanceof RegExp;const _C={value:!1,isValid:!1},PC={value:!0,isValid:!0};var fP=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Yt(e[0].attributes.value)?Yt(e[0].value)||e[0].value===""?PC:{value:e[0].value,isValid:!0}:PC:_C}return _C};const RC={isValid:!1,value:null};var pP=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,RC):RC;function OC(e,t,n="validate"){if(yp(e)||Array.isArray(e)&&e.every(yp)||Rs(e)&&!e)return{type:n,message:yp(e)?e:"",ref:t}}var al=e=>gn(e)&&!hg(e)?e:{value:e,message:""},IC=async(e,t,n,r,s)=>{const{ref:o,refs:a,required:c,maxLength:u,minLength:i,min:d,max:p,pattern:f,validate:g,name:h,valueAsNumber:m,mount:x,disabled:b}=e._f,y=de(t,h);if(!x||b)return{};const w=a?a[0]:o,S=I=>{r&&w.reportValidity&&(w.setCustomValidity(Rs(I)?"":I||""),w.reportValidity())},E={},C=jw(o),T=Xd(o),j=C||T,_=(m||kw(o))&&Yt(o.value)&&Yt(y)||gg(o)&&o.value===""||y===""||Array.isArray(y)&&!y.length,O=dP.bind(null,h,n,E),K=(I,Y,q,Z=Ys.maxLength,ee=Ys.minLength)=>{const J=I?Y:q;E[h]={type:I?Z:ee,message:J,ref:o,...O(I?Z:ee,J)}};if(s?!Array.isArray(y)||!y.length:c&&(!j&&(_||qn(y))||Rs(y)&&!y||T&&!fP(a).isValid||C&&!pP(a).isValid)){const{value:I,message:Y}=yp(c)?{value:!!c,message:c}:al(c);if(I&&(E[h]={type:Ys.required,message:Y,ref:w,...O(Ys.required,Y)},!n))return S(Y),E}if(!_&&(!qn(d)||!qn(p))){let I,Y;const q=al(p),Z=al(d);if(!qn(y)&&!isNaN(y)){const ee=o.valueAsNumber||y&&+y;qn(q.value)||(I=ee>q.value),qn(Z.value)||(Y=eenew Date(new Date().toDateString()+" "+X),L=o.type=="time",A=o.type=="week";As(q.value)&&y&&(I=L?J(y)>J(q.value):A?y>q.value:ee>new Date(q.value)),As(Z.value)&&y&&(Y=L?J(y)+I.value,Z=!qn(Y.value)&&y.length<+Y.value;if((q||Z)&&(K(q,I.message,Y.message),!n))return S(E[h].message),E}if(f&&!_&&As(y)){const{value:I,message:Y}=al(f);if(hg(I)&&!y.match(I)&&(E[h]={type:Ys.pattern,message:Y,ref:o,...O(Ys.pattern,Y)},!n))return S(Y),E}if(g){if(aa(g)){const I=await g(y,t),Y=OC(I,w);if(Y&&(E[h]={...Y,...O(Ys.validate,Y.message)},!n))return S(Y.message),E}else if(gn(g)){let I={};for(const Y in g){if(!pr(I)&&!n)break;const q=OC(await g[Y](y,t),w,Y);q&&(I={...q,...O(Y,q.message)},S(q.message),n&&(E[h]=I))}if(!pr(I)&&(E[h]={ref:w,...I},!n))return E}}return S(!0),E};function XV(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{let e=[];return{get observers(){return e},next:s=>{for(const o of e)o.next&&o.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(o=>o!==s)}}),unsubscribe:()=>{e=[]}}},mg=e=>qn(e)||!nP(e);function li(e,t){if(mg(e)||mg(t))return e===t;if(Ml(e)&&Ml(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n){const o=e[s];if(!r.includes(s))return!1;if(s!=="ref"){const a=t[s];if(Ml(o)&&Ml(a)||gn(o)&&gn(a)||Array.isArray(o)&&Array.isArray(a)?!li(o,a):o!==a)return!1}}return!0}var gP=e=>e.type==="select-multiple",t8=e=>jw(e)||Xd(e),tv=e=>gg(e)&&e.isConnected,hP=e=>{for(const t in e)if(aa(e[t]))return!0;return!1};function vg(e,t={}){const n=Array.isArray(e);if(gn(e)||n)for(const r in e)Array.isArray(e[r])||gn(e[r])&&!hP(e[r])?(t[r]=Array.isArray(e[r])?[]:{},vg(e[r],t[r])):qn(e[r])||(t[r]=!0);return t}function mP(e,t,n){const r=Array.isArray(e);if(gn(e)||r)for(const s in e)Array.isArray(e[s])||gn(e[s])&&!hP(e[s])?Yt(t)||mg(n[s])?n[s]=Array.isArray(e[s])?vg(e[s],[]):{...vg(e[s])}:mP(e[s],qn(t)?{}:t[s],n[s]):n[s]=!li(e[s],t[s]);return n}var $f=(e,t)=>mP(e,t,vg(t)),vP=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Yt(e)?e:t?e===""?NaN:e&&+e:n&&As(e)?new Date(e):r?r(e):e;function nv(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return kw(t)?t.files:jw(t)?pP(e.refs).value:gP(t)?[...t.selectedOptions].map(({value:n})=>n):Xd(t)?fP(e.refs).value:vP(Yt(t.value)?e.ref.value:t.value,e)}var n8=(e,t,n,r)=>{const s={};for(const o of e){const a=de(t,o);a&&xt(s,o,a._f)}return{criteriaMode:n,names:[...e],fields:s,shouldUseNativeValidation:r}},ru=e=>Yt(e)?e:hg(e)?e.source:gn(e)?hg(e.value)?e.value.source:e.value:e,r8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function DC(e,t,n){const r=de(e,n);if(r||Cw(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const o=s.join("."),a=de(t,o),c=de(e,o);if(a&&!Array.isArray(a)&&n!==o)return{name:n};if(c&&c.type)return{name:o,error:c};s.pop()}return{name:n}}var s8=(e,t,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(t||e):(n?r.isOnBlur:s.isOnBlur)?!e:(n?r.isOnChange:s.isOnChange)?e:!0,o8=(e,t)=>!_h(de(e,t)).length&&cn(e,t);const a8={mode:ts.onSubmit,reValidateMode:ts.onChange,shouldFocusError:!0};function i8(e={}){let t={...a8,...e},n={submitCount:0,isDirty:!1,isLoading:aa(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},s=gn(t.defaultValues)||gn(t.values)?Xn(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Xn(s),a={action:!1,mount:!1,watch:!1},c={mount:new Set,unMount:new Set,array:new Set,watch:new Set},u,i=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},p={values:ev(),array:ev(),state:ev()},f=MC(t.mode),g=MC(t.reValidateMode),h=t.criteriaMode===ts.all,m=M=>D=>{clearTimeout(i),i=setTimeout(M,D)},x=async M=>{if(d.isValid||M){const D=t.resolver?pr((await j()).errors):await O(r,!0);D!==n.isValid&&p.state.next({isValid:D})}},b=(M,D)=>{(d.isValidating||d.validatingFields)&&((M||Array.from(c.mount)).forEach(V=>{V&&(D?xt(n.validatingFields,V,D):cn(n.validatingFields,V))}),p.state.next({validatingFields:n.validatingFields,isValidating:!pr(n.validatingFields)}))},y=(M,D=[],V,he,ce=!0,ae=!0)=>{if(he&&V){if(a.action=!0,ae&&Array.isArray(de(r,M))){const ke=V(de(r,M),he.argA,he.argB);ce&&xt(r,M,ke)}if(ae&&Array.isArray(de(n.errors,M))){const ke=V(de(n.errors,M),he.argA,he.argB);ce&&xt(n.errors,M,ke),o8(n.errors,M)}if(d.touchedFields&&ae&&Array.isArray(de(n.touchedFields,M))){const ke=V(de(n.touchedFields,M),he.argA,he.argB);ce&&xt(n.touchedFields,M,ke)}d.dirtyFields&&(n.dirtyFields=$f(s,o)),p.state.next({name:M,isDirty:I(M,D),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else xt(o,M,D)},w=(M,D)=>{xt(n.errors,M,D),p.state.next({errors:n.errors})},S=M=>{n.errors=M,p.state.next({errors:n.errors,isValid:!1})},E=(M,D,V,he)=>{const ce=de(r,M);if(ce){const ae=de(o,M,Yt(V)?de(s,M):V);Yt(ae)||he&&he.defaultChecked||D?xt(o,M,D?ae:nv(ce._f)):Z(M,ae),a.mount&&x()}},C=(M,D,V,he,ce)=>{let ae=!1,ke=!1;const rt={name:M},Pt=!!(de(r,M)&&de(r,M)._f&&de(r,M)._f.disabled);if(!V||he){d.isDirty&&(ke=n.isDirty,n.isDirty=rt.isDirty=I(),ae=ke!==rt.isDirty);const hn=Pt||li(de(s,M),D);ke=!!(!Pt&&de(n.dirtyFields,M)),hn||Pt?cn(n.dirtyFields,M):xt(n.dirtyFields,M,!0),rt.dirtyFields=n.dirtyFields,ae=ae||d.dirtyFields&&ke!==!hn}if(V){const hn=de(n.touchedFields,M);hn||(xt(n.touchedFields,M,V),rt.touchedFields=n.touchedFields,ae=ae||d.touchedFields&&hn!==V)}return ae&&ce&&p.state.next(rt),ae?rt:{}},T=(M,D,V,he)=>{const ce=de(n.errors,M),ae=d.isValid&&Rs(D)&&n.isValid!==D;if(e.delayError&&V?(u=m(()=>w(M,V)),u(e.delayError)):(clearTimeout(i),u=null,V?xt(n.errors,M,V):cn(n.errors,M)),(V?!li(ce,V):ce)||!pr(he)||ae){const ke={...he,...ae&&Rs(D)?{isValid:D}:{},errors:n.errors,name:M};n={...n,...ke},p.state.next(ke)}},j=async M=>{b(M,!0);const D=await t.resolver(o,t.context,n8(M||c.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return b(M),D},_=async M=>{const{errors:D}=await j(M);if(M)for(const V of M){const he=de(D,V);he?xt(n.errors,V,he):cn(n.errors,V)}else n.errors=D;return D},O=async(M,D,V={valid:!0})=>{for(const he in M){const ce=M[he];if(ce){const{_f:ae,...ke}=ce;if(ae){const rt=c.array.has(ae.name);b([he],!0);const Pt=await IC(ce,o,h,t.shouldUseNativeValidation&&!D,rt);if(b([he]),Pt[ae.name]&&(V.valid=!1,D))break;!D&&(de(Pt,ae.name)?rt?YV(n.errors,Pt,ae.name):xt(n.errors,ae.name,Pt[ae.name]):cn(n.errors,ae.name))}ke&&await O(ke,D,V)}}return V.valid},K=()=>{for(const M of c.unMount){const D=de(r,M);D&&(D._f.refs?D._f.refs.every(V=>!tv(V)):!tv(D._f.ref))&&oe(M)}c.unMount=new Set},I=(M,D)=>(M&&D&&xt(o,M,D),!li(fe(),s)),Y=(M,D,V)=>uP(M,c,{...a.mount?o:Yt(D)?s:As(M)?{[M]:D}:D},V,D),q=M=>_h(de(a.mount?o:s,M,e.shouldUnregister?de(s,M,[]):[])),Z=(M,D,V={})=>{const he=de(r,M);let ce=D;if(he){const ae=he._f;ae&&(!ae.disabled&&xt(o,M,vP(D,ae)),ce=gg(ae.ref)&&qn(D)?"":D,gP(ae.ref)?[...ae.ref.options].forEach(ke=>ke.selected=ce.includes(ke.value)):ae.refs?Xd(ae.ref)?ae.refs.length>1?ae.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(ce)?!!ce.find(rt=>rt===ke.value):ce===ke.value)):ae.refs[0]&&(ae.refs[0].checked=!!ce):ae.refs.forEach(ke=>ke.checked=ke.value===ce):kw(ae.ref)?ae.ref.value="":(ae.ref.value=ce,ae.ref.type||p.values.next({name:M,values:{...o}})))}(V.shouldDirty||V.shouldTouch)&&C(M,ce,V.shouldTouch,V.shouldDirty,!0),V.shouldValidate&&X(M)},ee=(M,D,V)=>{for(const he in D){const ce=D[he],ae=`${M}.${he}`,ke=de(r,ae);(c.array.has(M)||!mg(ce)||ke&&!ke._f)&&!Ml(ce)?ee(ae,ce,V):Z(ae,ce,V)}},J=(M,D,V={})=>{const he=de(r,M),ce=c.array.has(M),ae=Xn(D);xt(o,M,ae),ce?(p.array.next({name:M,values:{...o}}),(d.isDirty||d.dirtyFields)&&V.shouldDirty&&p.state.next({name:M,dirtyFields:$f(s,o),isDirty:I(M,ae)})):he&&!he._f&&!qn(ae)?ee(M,ae,V):Z(M,ae,V),NC(M,c)&&p.state.next({...n}),p.values.next({name:a.mount?M:void 0,values:{...o}})},L=async M=>{a.mount=!0;const D=M.target;let V=D.name,he=!0;const ce=de(r,V),ae=()=>D.type?nv(ce._f):rP(M),ke=rt=>{he=Number.isNaN(rt)||rt===de(o,V,rt)};if(ce){let rt,Pt;const hn=ae(),bn=M.type===pg.BLUR||M.type===pg.FOCUS_OUT,mn=!r8(ce._f)&&!t.resolver&&!de(n.errors,V)&&!ce._f.deps||s8(bn,de(n.touchedFields,V),n.isSubmitted,g,f),Oo=NC(V,c,bn);xt(o,V,hn),bn?(ce._f.onBlur&&ce._f.onBlur(M),u&&u(0)):ce._f.onChange&&ce._f.onChange(M);const bs=C(V,hn,bn,!1),qa=!pr(bs)||Oo;if(!bn&&p.values.next({name:V,type:M.type,values:{...o}}),mn)return d.isValid&&x(),qa&&p.state.next({name:V,...Oo?{}:bs});if(!bn&&Oo&&p.state.next({...n}),t.resolver){const{errors:zn}=await j([V]);if(ke(hn),he){const ue=DC(n.errors,r,V),He=DC(zn,r,ue.name||V);rt=He.error,V=He.name,Pt=pr(zn)}}else b([V],!0),rt=(await IC(ce,o,h,t.shouldUseNativeValidation))[V],b([V]),ke(hn),he&&(rt?Pt=!1:d.isValid&&(Pt=await O(r,!0)));he&&(ce._f.deps&&X(ce._f.deps),T(V,Pt,rt,bs))}},A=(M,D)=>{if(de(n.errors,D)&&M.focus)return M.focus(),1},X=async(M,D={})=>{let V,he;const ce=Du(M);if(t.resolver){const ae=await _(Yt(M)?M:ce);V=pr(ae),he=M?!ce.some(ke=>de(ae,ke)):V}else M?(he=(await Promise.all(ce.map(async ae=>{const ke=de(r,ae);return await O(ke&&ke._f?{[ae]:ke}:ke)}))).every(Boolean),!(!he&&!n.isValid)&&x()):he=V=await O(r);return p.state.next({...!As(M)||d.isValid&&V!==n.isValid?{}:{name:M},...t.resolver||!M?{isValid:V}:{},errors:n.errors}),D.shouldFocus&&!he&&Au(r,A,M?ce:c.mount),he},fe=M=>{const D={...a.mount?o:s};return Yt(M)?D:As(M)?de(D,M):M.map(V=>de(D,V))},H=(M,D)=>({invalid:!!de((D||n).errors,M),isDirty:!!de((D||n).dirtyFields,M),error:de((D||n).errors,M),isValidating:!!de(n.validatingFields,M),isTouched:!!de((D||n).touchedFields,M)}),se=M=>{M&&Du(M).forEach(D=>cn(n.errors,D)),p.state.next({errors:M?n.errors:{}})},ne=(M,D,V)=>{const he=(de(r,M,{_f:{}})._f||{}).ref,ce=de(n.errors,M)||{},{ref:ae,message:ke,type:rt,...Pt}=ce;xt(n.errors,M,{...Pt,...D,ref:he}),p.state.next({name:M,errors:n.errors,isValid:!1}),V&&V.shouldFocus&&he&&he.focus&&he.focus()},le=(M,D)=>aa(M)?p.values.subscribe({next:V=>M(Y(void 0,D),V)}):Y(M,D,!0),oe=(M,D={})=>{for(const V of M?Du(M):c.mount)c.mount.delete(V),c.array.delete(V),D.keepValue||(cn(r,V),cn(o,V)),!D.keepError&&cn(n.errors,V),!D.keepDirty&&cn(n.dirtyFields,V),!D.keepTouched&&cn(n.touchedFields,V),!D.keepIsValidating&&cn(n.validatingFields,V),!t.shouldUnregister&&!D.keepDefaultValue&&cn(s,V);p.values.next({values:{...o}}),p.state.next({...n,...D.keepDirty?{isDirty:I()}:{}}),!D.keepIsValid&&x()},Q=({disabled:M,name:D,field:V,fields:he,value:ce})=>{if(Rs(M)&&a.mount||M){const ae=M?void 0:Yt(ce)?nv(V?V._f:de(he,D)._f):ce;xt(o,D,ae),C(D,ae,!1,!1,!0)}},Ee=(M,D={})=>{let V=de(r,M);const he=Rs(D.disabled);return xt(r,M,{...V||{},_f:{...V&&V._f?V._f:{ref:{name:M}},name:M,mount:!0,...D}}),c.mount.add(M),V?Q({field:V,disabled:D.disabled,name:M,value:D.value}):E(M,!0,D.value),{...he?{disabled:D.disabled}:{},...t.progressive?{required:!!D.required,min:ru(D.min),max:ru(D.max),minLength:ru(D.minLength),maxLength:ru(D.maxLength),pattern:ru(D.pattern)}:{},name:M,onChange:L,onBlur:L,ref:ce=>{if(ce){Ee(M,D),V=de(r,M);const ae=Yt(ce.value)&&ce.querySelectorAll&&ce.querySelectorAll("input,select,textarea")[0]||ce,ke=t8(ae),rt=V._f.refs||[];if(ke?rt.find(Pt=>Pt===ae):ae===V._f.ref)return;xt(r,M,{_f:{...V._f,...ke?{refs:[...rt.filter(tv),ae,...Array.isArray(de(s,M))?[{}]:[]],ref:{type:ae.type,name:M}}:{ref:ae}}}),E(M,!1,void 0,ae)}else V=de(r,M,{}),V._f&&(V._f.mount=!1),(t.shouldUnregister||D.shouldUnregister)&&!(sP(c.array,M)&&a.action)&&c.unMount.add(M)}}},Pe=()=>t.shouldFocusError&&Au(r,A,c.mount),Be=M=>{Rs(M)&&(p.state.next({disabled:M}),Au(r,(D,V)=>{const he=de(r,V);he&&(D.disabled=he._f.disabled||M,Array.isArray(he._f.refs)&&he._f.refs.forEach(ce=>{ce.disabled=he._f.disabled||M}))},0,!1))},Re=(M,D)=>async V=>{let he;V&&(V.preventDefault&&V.preventDefault(),V.persist&&V.persist());let ce=Xn(o);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:ae,values:ke}=await j();n.errors=ae,ce=ke}else await O(r);if(cn(n.errors,"root"),pr(n.errors)){p.state.next({errors:{}});try{await M(ce,V)}catch(ae){he=ae}}else D&&await D({...n.errors},V),Pe(),setTimeout(Pe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:pr(n.errors)&&!he,submitCount:n.submitCount+1,errors:n.errors}),he)throw he},ve=(M,D={})=>{de(r,M)&&(Yt(D.defaultValue)?J(M,Xn(de(s,M))):(J(M,D.defaultValue),xt(s,M,Xn(D.defaultValue))),D.keepTouched||cn(n.touchedFields,M),D.keepDirty||(cn(n.dirtyFields,M),n.isDirty=D.defaultValue?I(M,Xn(de(s,M))):I()),D.keepError||(cn(n.errors,M),d.isValid&&x()),p.state.next({...n}))},ot=(M,D={})=>{const V=M?Xn(M):s,he=Xn(V),ce=pr(M),ae=ce?s:he;if(D.keepDefaultValues||(s=V),!D.keepValues){if(D.keepDirtyValues)for(const ke of c.mount)de(n.dirtyFields,ke)?xt(ae,ke,de(o,ke)):J(ke,de(ae,ke));else{if(Sw&&Yt(M))for(const ke of c.mount){const rt=de(r,ke);if(rt&&rt._f){const Pt=Array.isArray(rt._f.refs)?rt._f.refs[0]:rt._f.ref;if(gg(Pt)){const hn=Pt.closest("form");if(hn){hn.reset();break}}}}r={}}o=e.shouldUnregister?D.keepDefaultValues?Xn(s):{}:Xn(ae),p.array.next({values:{...ae}}),p.values.next({values:{...ae}})}c={mount:D.keepDirtyValues?c.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!d.isValid||!!D.keepIsValid||!!D.keepDirtyValues,a.watch=!!e.shouldUnregister,p.state.next({submitCount:D.keepSubmitCount?n.submitCount:0,isDirty:ce?!1:D.keepDirty?n.isDirty:!!(D.keepDefaultValues&&!li(M,s)),isSubmitted:D.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ce?{}:D.keepDirtyValues?D.keepDefaultValues&&o?$f(s,o):n.dirtyFields:D.keepDefaultValues&&M?$f(s,M):D.keepDirty?n.dirtyFields:{},touchedFields:D.keepTouched?n.touchedFields:{},errors:D.keepErrors?n.errors:{},isSubmitSuccessful:D.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Vt=(M,D)=>ot(aa(M)?M(o):M,D);return{control:{register:Ee,unregister:oe,getFieldState:H,handleSubmit:Re,setError:ne,_executeSchema:j,_getWatch:Y,_getDirty:I,_updateValid:x,_removeUnmounted:K,_updateFieldArray:y,_updateDisabledField:Q,_getFieldArray:q,_reset:ot,_resetDefaultValues:()=>aa(t.defaultValues)&&t.defaultValues().then(M=>{Vt(M,t.resetOptions),p.state.next({isLoading:!1})}),_updateFormState:M=>{n={...n,...M}},_disableForm:Be,_subjects:p,_proxyFormState:d,_setErrors:S,get _fields(){return r},get _formValues(){return o},get _state(){return a},set _state(M){a=M},get _defaultValues(){return s},get _names(){return c},set _names(M){c=M},get _formState(){return n},set _formState(M){n=M},get _options(){return t},set _options(M){t={...t,...M}}},trigger:X,register:Ee,handleSubmit:Re,watch:le,setValue:J,getValues:fe,reset:Vt,resetField:ve,clearErrors:se,unregister:oe,setError:ne,setFocus:(M,D={})=>{const V=de(r,M),he=V&&V._f;if(he){const ce=he.refs?he.refs[0]:he.ref;ce.focus&&(ce.focus(),D.shouldSelect&&ce.select())}},getFieldState:H}}function zt(e={}){const t=je.useRef(),n=je.useRef(),[r,s]=je.useState({isDirty:!1,isValidating:!1,isLoading:aa(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:aa(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...i8(e),formState:r});const o=t.current.control;return o._options=e,Ew({subject:o._subjects.state,next:a=>{lP(a,o._proxyFormState,o._updateFormState,!0)&&s({...o._formState})}}),je.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),je.useEffect(()=>{if(o._proxyFormState.isDirty){const a=o._getDirty();a!==r.isDirty&&o._subjects.state.next({isDirty:a})}},[o,r.isDirty]),je.useEffect(()=>{e.values&&!li(e.values,n.current)?(o._reset(e.values,o._options.resetOptions),n.current=e.values,s(a=>({...a}))):o._resetDefaultValues()},[e.values,o]),je.useEffect(()=>{e.errors&&o._setErrors(e.errors)},[e.errors,o]),je.useEffect(()=>{o._state.mount||(o._updateValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),je.useEffect(()=>{e.shouldUnregister&&o._subjects.values.next({values:o._getWatch()})},[e.shouldUnregister,o]),t.current.formState=iP(r,o),t.current}const AC=(e,t,n)=>{if(e&&"reportValidity"in e){const r=de(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},yP=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?AC(r.ref,n,e):r.refs&&r.refs.forEach(s=>AC(s,n,e))}},l8=(e,t)=>{t.shouldUseNativeValidation&&yP(e,t);const n={};for(const r in e){const s=de(t.fields,r),o=Object.assign(e[r]||{},{ref:s&&s.ref});if(c8(t.names||Object.keys(e),r)){const a=Object.assign({},de(n,r));xt(a,"root",o),xt(n,r,a)}else xt(n,r,o)}return n},c8=(e,t)=>e.some(n=>n.startsWith(t+"."));var u8=function(e,t){for(var n={};e.length;){var r=e[0],s=r.code,o=r.message,a=r.path.join(".");if(!n[a])if("unionErrors"in r){var c=r.unionErrors[0].errors[0];n[a]={message:c.message,type:c.code}}else n[a]={message:o,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(d){return d.errors.forEach(function(p){return e.push(p)})}),t){var u=n[a].types,i=u&&u[r.code];n[a]=dP(a,t,n,s,i?[].concat(i,r.message):r.message)}e.shift()}return n},Ut=function(e,t,n){return n===void 0&&(n={}),function(r,s,o){try{return Promise.resolve(function(a,c){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(i){return o.shouldUseNativeValidation&&yP({},o),{errors:{},values:n.raw?r:i}})}catch(i){return c(i)}return u&&u.then?u.then(void 0,c):u}(0,function(a){if(function(c){return Array.isArray(c==null?void 0:c.errors)}(a))return{values:{},errors:l8(u8(a.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw a}))}catch(a){return Promise.reject(a)}}},wn=[];for(var rv=0;rv<256;++rv)wn.push((rv+256).toString(16).slice(1));function d8(e,t=0){return(wn[e[t+0]]+wn[e[t+1]]+wn[e[t+2]]+wn[e[t+3]]+"-"+wn[e[t+4]]+wn[e[t+5]]+"-"+wn[e[t+6]]+wn[e[t+7]]+"-"+wn[e[t+8]]+wn[e[t+9]]+"-"+wn[e[t+10]]+wn[e[t+11]]+wn[e[t+12]]+wn[e[t+13]]+wn[e[t+14]]+wn[e[t+15]]).toLowerCase()}var Bf,f8=new Uint8Array(16);function p8(){if(!Bf&&(Bf=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Bf))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Bf(f8)}var g8=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const FC={randomUUID:g8};function LC(e,t,n){if(FC.randomUUID&&!t&&!e)return FC.randomUUID();e=e||{};var r=e.random||(e.rng||p8)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,d8(r)}var ft;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},e.find=(s,o)=>{for(const a of s)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ft||(ft={}));var rb;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(rb||(rb={}));const xe=ft.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Go=e=>{switch(typeof e){case"undefined":return xe.undefined;case"string":return xe.string;case"number":return isNaN(e)?xe.nan:xe.number;case"boolean":return xe.boolean;case"function":return xe.function;case"bigint":return xe.bigint;case"symbol":return xe.symbol;case"object":return Array.isArray(e)?xe.array:e===null?xe.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?xe.promise:typeof Map<"u"&&e instanceof Map?xe.map:typeof Set<"u"&&e instanceof Set?xe.set:typeof Date<"u"&&e instanceof Date?xe.date:xe.object;default:return xe.unknown}},re=ft.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),h8=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Sr extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,u=0;for(;un.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Sr.create=e=>new Sr(e);const gc=(e,t)=>{let n;switch(e.code){case re.invalid_type:e.received===xe.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case re.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ft.jsonStringifyReplacer)}`;break;case re.unrecognized_keys:n=`Unrecognized key(s) in object: ${ft.joinValues(e.keys,", ")}`;break;case re.invalid_union:n="Invalid input";break;case re.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ft.joinValues(e.options)}`;break;case re.invalid_enum_value:n=`Invalid enum value. Expected ${ft.joinValues(e.options)}, received '${e.received}'`;break;case re.invalid_arguments:n="Invalid function arguments";break;case re.invalid_return_type:n="Invalid function return type";break;case re.invalid_date:n="Invalid date";break;case re.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ft.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case re.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case re.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case re.custom:n="Invalid input";break;case re.invalid_intersection_types:n="Intersection results could not be merged";break;case re.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case re.not_finite:n="Number must be finite";break;default:n=t.defaultError,ft.assertNever(e)}return{message:n}};let bP=gc;function m8(e){bP=e}function yg(){return bP}const bg=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const u=r.filter(i=>!!i).slice().reverse();for(const i of u)c=i(a,{data:t,defaultError:c}).message;return{...s,path:o,message:c}},v8=[];function ye(e,t){const n=yg(),r=bg({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===gc?void 0:gc].filter(s=>!!s)});e.common.issues.push(r)}class $n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return Ue;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const o=await s.key,a=await s.value;r.push({key:o,value:a})}return $n.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return Ue;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}}const Ue=Object.freeze({status:"aborted"}),Nl=e=>({status:"dirty",value:e}),Jn=e=>({status:"valid",value:e}),sb=e=>e.status==="aborted",ob=e=>e.status==="dirty",md=e=>e.status==="valid",vd=e=>typeof Promise<"u"&&e instanceof Promise;function xg(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function xP(e,t,n,r,s){if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));var yu,bu;class Hs{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $C=(e,t)=>{if(md(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Sr(e.common.issues);return this._error=n,this._error}}};function Ge(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,c)=>{var u,i;const{message:d}=e;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??r)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(i=d??n)!==null&&i!==void 0?i:c.defaultError}},description:s}}class Xe{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return Go(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Go(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new $n,ctx:{common:t.parent.common,data:t.data,parsedType:Go(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(vd(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Go(t)},o=this._parseSync({data:t,path:s.path,parent:s});return $C(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Go(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(vd(s)?s:Promise.resolve(s));return $C(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const a=t(s),c=()=>o.addIssue({code:re.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ps({schema:this,typeName:$e.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return zs.create(this,this._def)}nullable(){return ka.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ls.create(this,this._def)}promise(){return mc.create(this,this._def)}or(t){return wd.create([this,t],this._def)}and(t){return Sd.create(this,t,this._def)}transform(t){return new ps({...Ge(this._def),schema:this,typeName:$e.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Td({...Ge(this._def),innerType:this,defaultValue:n,typeName:$e.ZodDefault})}brand(){return new Tw({typeName:$e.ZodBranded,type:this,...Ge(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Md({...Ge(this._def),innerType:this,catchValue:n,typeName:$e.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ef.create(this,t)}readonly(){return Nd.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const y8=/^c[^\s-]{8,}$/i,b8=/^[0-9a-z]+$/,x8=/^[0-9A-HJKMNP-TV-Z]{26}$/,w8=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,S8=/^[a-z0-9_-]{21}$/i,C8=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,E8=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,k8="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let sv;const j8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,T8=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,M8=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wP="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",N8=new RegExp(`^${wP}$`);function SP(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function _8(e){return new RegExp(`^${SP(e)}$`)}function CP(e){let t=`${wP}T${SP(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function P8(e,t){return!!((t==="v4"||!t)&&j8.test(e)||(t==="v6"||!t)&&T8.test(e))}class rs extends Xe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==xe.string){const o=this._getOrReturnCtx(t);return ye(o,{code:re.invalid_type,expected:xe.string,received:o.parsedType}),Ue}const r=new $n;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),ye(s,{code:re.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const a=t.data.length>o.value,c=t.data.lengtht.test(s),{validation:n,code:re.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new rs({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,local:(r=t==null?void 0:t.local)!==null&&r!==void 0?r:!1,...Ne.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...Ne.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...Ne.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new rs({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new rs({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new rs({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new rs({checks:[],typeName:$e.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ge(e)})};function R8(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class Sa extends Xe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==xe.number){const o=this._getOrReturnCtx(t);return ye(o,{code:re.invalid_type,expected:xe.number,received:o.parsedType}),Ue}let r;const s=new $n;for(const o of this._def.checks)o.kind==="int"?ft.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ye(r,{code:re.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ye(r,{code:re.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?R8(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),ye(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ye(r,{code:re.not_finite,message:o.message}),s.dirty()):ft.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,s){return new Sa({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(s)}]})}_addCheck(t){return new Sa({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&ft.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew Sa({checks:[],typeName:$e.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Ge(e)});class Ca extends Xe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==xe.bigint){const o=this._getOrReturnCtx(t);return ye(o,{code:re.invalid_type,expected:xe.bigint,received:o.parsedType}),Ue}let r;const s=new $n;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ye(r,{code:re.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ye(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ft.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,s){return new Ca({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(s)}]})}_addCheck(t){return new Ca({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Ca({checks:[],typeName:$e.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ge(e)})};class yd extends Xe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==xe.boolean){const r=this._getOrReturnCtx(t);return ye(r,{code:re.invalid_type,expected:xe.boolean,received:r.parsedType}),Ue}return Jn(t.data)}}yd.create=e=>new yd({typeName:$e.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Ge(e)});class Di extends Xe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==xe.date){const o=this._getOrReturnCtx(t);return ye(o,{code:re.invalid_type,expected:xe.date,received:o.parsedType}),Ue}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return ye(o,{code:re.invalid_date}),Ue}const r=new $n;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),ye(s,{code:re.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ft.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Di({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Di({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:$e.ZodDate,...Ge(e)});class wg extends Xe{_parse(t){if(this._getType(t)!==xe.symbol){const r=this._getOrReturnCtx(t);return ye(r,{code:re.invalid_type,expected:xe.symbol,received:r.parsedType}),Ue}return Jn(t.data)}}wg.create=e=>new wg({typeName:$e.ZodSymbol,...Ge(e)});class bd extends Xe{_parse(t){if(this._getType(t)!==xe.undefined){const r=this._getOrReturnCtx(t);return ye(r,{code:re.invalid_type,expected:xe.undefined,received:r.parsedType}),Ue}return Jn(t.data)}}bd.create=e=>new bd({typeName:$e.ZodUndefined,...Ge(e)});class xd extends Xe{_parse(t){if(this._getType(t)!==xe.null){const r=this._getOrReturnCtx(t);return ye(r,{code:re.invalid_type,expected:xe.null,received:r.parsedType}),Ue}return Jn(t.data)}}xd.create=e=>new xd({typeName:$e.ZodNull,...Ge(e)});class hc extends Xe{constructor(){super(...arguments),this._any=!0}_parse(t){return Jn(t.data)}}hc.create=e=>new hc({typeName:$e.ZodAny,...Ge(e)});class Si extends Xe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Jn(t.data)}}Si.create=e=>new Si({typeName:$e.ZodUnknown,...Ge(e)});class Eo extends Xe{_parse(t){const n=this._getOrReturnCtx(t);return ye(n,{code:re.invalid_type,expected:xe.never,received:n.parsedType}),Ue}}Eo.create=e=>new Eo({typeName:$e.ZodNever,...Ge(e)});class Sg extends Xe{_parse(t){if(this._getType(t)!==xe.undefined){const r=this._getOrReturnCtx(t);return ye(r,{code:re.invalid_type,expected:xe.void,received:r.parsedType}),Ue}return Jn(t.data)}}Sg.create=e=>new Sg({typeName:$e.ZodVoid,...Ge(e)});class ls extends Xe{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==xe.array)return ye(n,{code:re.invalid_type,expected:xe.array,received:n.parsedType}),Ue;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,c=n.data.lengths.maxLength.value&&(ye(n,{code:re.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new Hs(n,a,n.path,c)))).then(a=>$n.mergeArray(r,a));const o=[...n.data].map((a,c)=>s.type._parseSync(new Hs(n,a,n.path,c)));return $n.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new ls({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new ls({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new ls({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}ls.create=(e,t)=>new ls({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$e.ZodArray,...Ge(t)});function pl(e){if(e instanceof Ht){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=zs.create(pl(r))}return new Ht({...e._def,shape:()=>t})}else return e instanceof ls?new ls({...e._def,type:pl(e.element)}):e instanceof zs?zs.create(pl(e.unwrap())):e instanceof ka?ka.create(pl(e.unwrap())):e instanceof Ks?Ks.create(e.items.map(t=>pl(t))):e}class Ht extends Xe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ft.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==xe.object){const i=this._getOrReturnCtx(t);return ye(i,{code:re.invalid_type,expected:xe.object,received:i.parsedType}),Ue}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Eo&&this._def.unknownKeys==="strip"))for(const i in s.data)a.includes(i)||c.push(i);const u=[];for(const i of a){const d=o[i],p=s.data[i];u.push({key:{status:"valid",value:i},value:d._parse(new Hs(s,p,s.path,i)),alwaysSet:i in s.data})}if(this._def.catchall instanceof Eo){const i=this._def.unknownKeys;if(i==="passthrough")for(const d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(i==="strict")c.length>0&&(ye(s,{code:re.unrecognized_keys,keys:c}),r.dirty());else if(i!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const i=this._def.catchall;for(const d of c){const p=s.data[d];u.push({key:{status:"valid",value:d},value:i._parse(new Hs(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const i=[];for(const d of u){const p=await d.key,f=await d.value;i.push({key:p,value:f,alwaysSet:d.alwaysSet})}return i}).then(i=>$n.mergeObjectSync(r,i)):$n.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Ht({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,a,c;const u=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=Ne.errToObj(t).message)!==null&&c!==void 0?c:u}:{message:u}}}:{}})}strip(){return new Ht({...this._def,unknownKeys:"strip"})}passthrough(){return new Ht({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ht({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ht({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:$e.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ht({...this._def,catchall:t})}pick(t){const n={};return ft.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ht({...this._def,shape:()=>n})}omit(t){const n={};return ft.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ht({...this._def,shape:()=>n})}deepPartial(){return pl(this)}partial(t){const n={};return ft.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Ht({...this._def,shape:()=>n})}required(t){const n={};return ft.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof zs;)o=o._def.innerType;n[r]=o}}),new Ht({...this._def,shape:()=>n})}keyof(){return EP(ft.objectKeys(this.shape))}}Ht.create=(e,t)=>new Ht({shape:()=>e,unknownKeys:"strip",catchall:Eo.create(),typeName:$e.ZodObject,...Ge(t)});Ht.strictCreate=(e,t)=>new Ht({shape:()=>e,unknownKeys:"strict",catchall:Eo.create(),typeName:$e.ZodObject,...Ge(t)});Ht.lazycreate=(e,t)=>new Ht({shape:e,unknownKeys:"strip",catchall:Eo.create(),typeName:$e.ZodObject,...Ge(t)});class wd extends Xe{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new Sr(c.ctx.common.issues));return ye(n,{code:re.invalid_union,unionErrors:a}),Ue}if(n.common.async)return Promise.all(r.map(async o=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const u of r){const i={...n,common:{...n.common,issues:[]},parent:null},d=u._parseSync({data:n.data,path:n.path,parent:i});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:i}),i.common.issues.length&&a.push(i.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(u=>new Sr(u));return ye(n,{code:re.invalid_union,unionErrors:c}),Ue}}get options(){return this._def.options}}wd.create=(e,t)=>new wd({options:e,typeName:$e.ZodUnion,...Ge(t)});const to=e=>e instanceof Ed?to(e.schema):e instanceof ps?to(e.innerType()):e instanceof kd?[e.value]:e instanceof Ea?e.options:e instanceof jd?ft.objectValues(e.enum):e instanceof Td?to(e._def.innerType):e instanceof bd?[void 0]:e instanceof xd?[null]:e instanceof zs?[void 0,...to(e.unwrap())]:e instanceof ka?[null,...to(e.unwrap())]:e instanceof Tw||e instanceof Nd?to(e.unwrap()):e instanceof Md?to(e._def.innerType):[];class Rh extends Xe{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==xe.object)return ye(n,{code:re.invalid_type,expected:xe.object,received:n.parsedType}),Ue;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(ye(n,{code:re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ue)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const a=to(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,o)}}return new Rh({typeName:$e.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Ge(r)})}}function ab(e,t){const n=Go(e),r=Go(t);if(e===t)return{valid:!0,data:e};if(n===xe.object&&r===xe.object){const s=ft.objectKeys(t),o=ft.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(const c of o){const u=ab(e[c],t[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(n===xe.array&&r===xe.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(sb(o)||sb(a))return Ue;const c=ab(o.value,a.value);return c.valid?((ob(o)||ob(a))&&n.dirty(),{status:n.value,value:c.data}):(ye(r,{code:re.invalid_intersection_types}),Ue)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Sd.create=(e,t,n)=>new Sd({left:e,right:t,typeName:$e.ZodIntersection,...Ge(n)});class Ks extends Xe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==xe.array)return ye(r,{code:re.invalid_type,expected:xe.array,received:r.parsedType}),Ue;if(r.data.lengththis._def.items.length&&(ye(r,{code:re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((a,c)=>{const u=this._def.items[c]||this._def.rest;return u?u._parse(new Hs(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>$n.mergeArray(n,a)):$n.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Ks({...this._def,rest:t})}}Ks.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ks({items:e,typeName:$e.ZodTuple,rest:null,...Ge(t)})};class Cd extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==xe.object)return ye(r,{code:re.invalid_type,expected:xe.object,received:r.parsedType}),Ue;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new Hs(r,c,r.path,c)),value:a._parse(new Hs(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?$n.mergeObjectAsync(n,s):$n.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Xe?new Cd({keyType:t,valueType:n,typeName:$e.ZodRecord,...Ge(r)}):new Cd({keyType:rs.create(),valueType:t,typeName:$e.ZodRecord,...Ge(n)})}}class Cg extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==xe.map)return ye(r,{code:re.invalid_type,expected:xe.map,received:r.parsedType}),Ue;const s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,u],i)=>({key:s._parse(new Hs(r,c,r.path,[i,"key"])),value:o._parse(new Hs(r,u,r.path,[i,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const u of a){const i=await u.key,d=await u.value;if(i.status==="aborted"||d.status==="aborted")return Ue;(i.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(i.value,d.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const u of a){const i=u.key,d=u.value;if(i.status==="aborted"||d.status==="aborted")return Ue;(i.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(i.value,d.value)}return{status:n.value,value:c}}}}Cg.create=(e,t,n)=>new Cg({valueType:t,keyType:e,typeName:$e.ZodMap,...Ge(n)});class Ai extends Xe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==xe.set)return ye(r,{code:re.invalid_type,expected:xe.set,received:r.parsedType}),Ue;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(ye(r,{code:re.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function a(u){const i=new Set;for(const d of u){if(d.status==="aborted")return Ue;d.status==="dirty"&&n.dirty(),i.add(d.value)}return{status:n.value,value:i}}const c=[...r.data.values()].map((u,i)=>o._parse(new Hs(r,u,r.path,i)));return r.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(t,n){return new Ai({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new Ai({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Ai.create=(e,t)=>new Ai({valueType:e,minSize:null,maxSize:null,typeName:$e.ZodSet,...Ge(t)});class Bl extends Xe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==xe.function)return ye(n,{code:re.invalid_type,expected:xe.function,received:n.parsedType}),Ue;function r(c,u){return bg({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,yg(),gc].filter(i=>!!i),issueData:{code:re.invalid_arguments,argumentsError:u}})}function s(c,u){return bg({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,yg(),gc].filter(i=>!!i),issueData:{code:re.invalid_return_type,returnTypeError:u}})}const o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof mc){const c=this;return Jn(async function(...u){const i=new Sr([]),d=await c._def.args.parseAsync(u,o).catch(g=>{throw i.addIssue(r(u,g)),i}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,o).catch(g=>{throw i.addIssue(s(p,g)),i})})}else{const c=this;return Jn(function(...u){const i=c._def.args.safeParse(u,o);if(!i.success)throw new Sr([r(u,i.error)]);const d=Reflect.apply(a,this,i.data),p=c._def.returns.safeParse(d,o);if(!p.success)throw new Sr([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Bl({...this._def,args:Ks.create(t).rest(Si.create())})}returns(t){return new Bl({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Bl({args:t||Ks.create([]).rest(Si.create()),returns:n||Si.create(),typeName:$e.ZodFunction,...Ge(r)})}}class Ed extends Xe{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Ed.create=(e,t)=>new Ed({getter:e,typeName:$e.ZodLazy,...Ge(t)});class kd extends Xe{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return ye(n,{received:n.data,code:re.invalid_literal,expected:this._def.value}),Ue}return{status:"valid",value:t.data}}get value(){return this._def.value}}kd.create=(e,t)=>new kd({value:e,typeName:$e.ZodLiteral,...Ge(t)});function EP(e,t){return new Ea({values:e,typeName:$e.ZodEnum,...Ge(t)})}class Ea extends Xe{constructor(){super(...arguments),yu.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return ye(n,{expected:ft.joinValues(r),received:n.parsedType,code:re.invalid_type}),Ue}if(xg(this,yu)||xP(this,yu,new Set(this._def.values)),!xg(this,yu).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return ye(n,{received:n.data,code:re.invalid_enum_value,options:r}),Ue}return Jn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Ea.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ea.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}yu=new WeakMap;Ea.create=EP;class jd extends Xe{constructor(){super(...arguments),bu.set(this,void 0)}_parse(t){const n=ft.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==xe.string&&r.parsedType!==xe.number){const s=ft.objectValues(n);return ye(r,{expected:ft.joinValues(s),received:r.parsedType,code:re.invalid_type}),Ue}if(xg(this,bu)||xP(this,bu,new Set(ft.getValidEnumValues(this._def.values))),!xg(this,bu).has(t.data)){const s=ft.objectValues(n);return ye(r,{received:r.data,code:re.invalid_enum_value,options:s}),Ue}return Jn(t.data)}get enum(){return this._def.values}}bu=new WeakMap;jd.create=(e,t)=>new jd({values:e,typeName:$e.ZodNativeEnum,...Ge(t)});class mc extends Xe{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==xe.promise&&n.common.async===!1)return ye(n,{code:re.invalid_type,expected:xe.promise,received:n.parsedType}),Ue;const r=n.parsedType===xe.promise?n.data:Promise.resolve(n.data);return Jn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}mc.create=(e,t)=>new mc({type:e,typeName:$e.ZodPromise,...Ge(t)});class ps extends Xe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:a=>{ye(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return Ue;const u=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return u.status==="aborted"?Ue:u.status==="dirty"||n.value==="dirty"?Nl(u.value):u});{if(n.value==="aborted")return Ue;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?Ue:c.status==="dirty"||n.value==="dirty"?Nl(c.value):c}}if(s.type==="refinement"){const a=c=>{const u=s.refinement(c,o);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?Ue:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?Ue:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!md(a))return a;const c=s.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>md(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:n.value,value:c})):a);ft.assertNever(s)}}ps.create=(e,t,n)=>new ps({schema:e,typeName:$e.ZodEffects,effect:t,...Ge(n)});ps.createWithPreprocess=(e,t,n)=>new ps({schema:t,effect:{type:"preprocess",transform:e},typeName:$e.ZodEffects,...Ge(n)});class zs extends Xe{_parse(t){return this._getType(t)===xe.undefined?Jn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}zs.create=(e,t)=>new zs({innerType:e,typeName:$e.ZodOptional,...Ge(t)});class ka extends Xe{_parse(t){return this._getType(t)===xe.null?Jn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ka.create=(e,t)=>new ka({innerType:e,typeName:$e.ZodNullable,...Ge(t)});class Td extends Xe{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===xe.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Td.create=(e,t)=>new Td({innerType:e,typeName:$e.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ge(t)});class Md extends Xe{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return vd(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Sr(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Sr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Md.create=(e,t)=>new Md({innerType:e,typeName:$e.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ge(t)});class Eg extends Xe{_parse(t){if(this._getType(t)!==xe.nan){const r=this._getOrReturnCtx(t);return ye(r,{code:re.invalid_type,expected:xe.nan,received:r.parsedType}),Ue}return{status:"valid",value:t.data}}}Eg.create=e=>new Eg({typeName:$e.ZodNaN,...Ge(e)});const O8=Symbol("zod_brand");class Tw extends Xe{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ef extends Xe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ue:o.status==="dirty"?(n.dirty(),Nl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Ue:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new ef({in:t,out:n,typeName:$e.ZodPipeline})}}class Nd extends Xe{_parse(t){const n=this._def.innerType._parse(t),r=s=>(md(s)&&(s.value=Object.freeze(s.value)),s);return vd(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Nd.create=(e,t)=>new Nd({innerType:e,typeName:$e.ZodReadonly,...Ge(t)});function kP(e,t={},n){return e?hc.create().superRefine((r,s)=>{var o,a;if(!e(r)){const c=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,u=(a=(o=c.fatal)!==null&&o!==void 0?o:n)!==null&&a!==void 0?a:!0,i=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...i,fatal:u})}}):hc.create()}const I8={object:Ht.lazycreate};var $e;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})($e||($e={}));const D8=(e,t={message:`Input not instance of ${e.name}`})=>kP(n=>n instanceof e,t),jP=rs.create,TP=Sa.create,A8=Eg.create,F8=Ca.create,MP=yd.create,L8=Di.create,$8=wg.create,B8=bd.create,z8=xd.create,U8=hc.create,V8=Si.create,H8=Eo.create,K8=Sg.create,q8=ls.create,W8=Ht.create,G8=Ht.strictCreate,J8=wd.create,Q8=Rh.create,Z8=Sd.create,Y8=Ks.create,X8=Cd.create,e6=Cg.create,t6=Ai.create,n6=Bl.create,r6=Ed.create,s6=kd.create,o6=Ea.create,a6=jd.create,i6=mc.create,BC=ps.create,l6=zs.create,c6=ka.create,u6=ps.createWithPreprocess,d6=ef.create,f6=()=>jP().optional(),p6=()=>TP().optional(),g6=()=>MP().optional(),h6={string:e=>rs.create({...e,coerce:!0}),number:e=>Sa.create({...e,coerce:!0}),boolean:e=>yd.create({...e,coerce:!0}),bigint:e=>Ca.create({...e,coerce:!0}),date:e=>Di.create({...e,coerce:!0})},m6=Ue;var k=Object.freeze({__proto__:null,defaultErrorMap:gc,setErrorMap:m8,getErrorMap:yg,makeIssue:bg,EMPTY_PATH:v8,addIssueToContext:ye,ParseStatus:$n,INVALID:Ue,DIRTY:Nl,OK:Jn,isAborted:sb,isDirty:ob,isValid:md,isAsync:vd,get util(){return ft},get objectUtil(){return rb},ZodParsedType:xe,getParsedType:Go,ZodType:Xe,datetimeRegex:CP,ZodString:rs,ZodNumber:Sa,ZodBigInt:Ca,ZodBoolean:yd,ZodDate:Di,ZodSymbol:wg,ZodUndefined:bd,ZodNull:xd,ZodAny:hc,ZodUnknown:Si,ZodNever:Eo,ZodVoid:Sg,ZodArray:ls,ZodObject:Ht,ZodUnion:wd,ZodDiscriminatedUnion:Rh,ZodIntersection:Sd,ZodTuple:Ks,ZodRecord:Cd,ZodMap:Cg,ZodSet:Ai,ZodFunction:Bl,ZodLazy:Ed,ZodLiteral:kd,ZodEnum:Ea,ZodNativeEnum:jd,ZodPromise:mc,ZodEffects:ps,ZodTransformer:ps,ZodOptional:zs,ZodNullable:ka,ZodDefault:Td,ZodCatch:Md,ZodNaN:Eg,BRAND:O8,ZodBranded:Tw,ZodPipeline:ef,ZodReadonly:Nd,custom:kP,Schema:Xe,ZodSchema:Xe,late:I8,get ZodFirstPartyTypeKind(){return $e},coerce:h6,any:U8,array:q8,bigint:F8,boolean:MP,date:L8,discriminatedUnion:Q8,effect:BC,enum:o6,function:n6,instanceof:D8,intersection:Z8,lazy:r6,literal:s6,map:e6,nan:A8,nativeEnum:a6,never:H8,null:z8,nullable:c6,number:TP,object:W8,oboolean:g6,onumber:p6,optional:l6,ostring:f6,pipeline:d6,preprocess:u6,promise:i6,record:X8,set:t6,strictObject:G8,string:jP,symbol:$8,transformer:BC,tuple:Y8,undefined:B8,union:J8,unknown:V8,void:K8,NEVER:m6,ZodIssueCode:re,quotelessJson:h8,ZodError:Sr}),NP=v.createContext({dragDropManager:void 0}),Lr;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(Lr||(Lr={}));function Ke(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),s=2;s-1})}var w6={type:Mw,payload:{clientOffset:null,sourceClientOffset:null}};function S6(e){return function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},s=r.publishSource,o=s===void 0?!0:s,a=r.clientOffset,c=r.getSourceClientOffset,u=e.getMonitor(),i=e.getRegistry();e.dispatch(zC(a)),C6(n,u,i);var d=j6(n,u);if(d===null){e.dispatch(w6);return}var p=null;if(a){if(!c)throw new Error("getSourceClientOffset must be defined");E6(c),p=c(d)}e.dispatch(zC(a,p));var f=i.getSource(d),g=f.beginDrag(u,d);if(g!=null){k6(g),i.pinSource(d);var h=i.getSourceType(d);return{type:Oh,payload:{itemType:h,item:g,sourceId:d,clientOffset:a||null,sourceClientOffset:p||null,isSourcePublic:!!o}}}}}function C6(e,t,n){Ke(!t.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(r){Ke(n.getSource(r),"Expected sourceIds to be registered.")})}function E6(e){Ke(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function k6(e){Ke(_P(e),"Item must be an object.")}function j6(e,t){for(var n=null,r=e.length-1;r>=0;r--)if(t.canDragSource(e[r])){n=e[r];break}return n}function T6(e){return function(){var n=e.getMonitor();if(n.isDragging())return{type:Nw}}}function ib(e,t){return t===null?e===null:Array.isArray(e)?e.some(function(n){return n===t}):e===t}function M6(e){return function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=r.clientOffset;N6(n);var o=n.slice(0),a=e.getMonitor(),c=e.getRegistry();_6(o,a,c);var u=a.getItemType();return P6(o,c,u),R6(o,a,c),{type:Ih,payload:{targetIds:o,clientOffset:s||null}}}}function N6(e){Ke(Array.isArray(e),"Expected targetIds to be an array.")}function _6(e,t,n){Ke(t.isDragging(),"Cannot call hover while not dragging."),Ke(!t.didDrop(),"Cannot call hover after drop.");for(var r=0;r=0;r--){var s=e[r],o=t.getTargetType(s);ib(o,n)||e.splice(r,1)}}function R6(e,t,n){e.forEach(function(r){var s=n.getTarget(r);s.hover(t,r)})}function UC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function VC(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},r=e.getMonitor(),s=e.getRegistry();D6(r);var o=L6(r);o.forEach(function(a,c){var u=A6(a,c,s,r),i={type:Dh,payload:{dropResult:VC(VC({},n),u)}};e.dispatch(i)})}}function D6(e){Ke(e.isDragging(),"Cannot call drop while not dragging."),Ke(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function A6(e,t,n,r){var s=n.getTarget(e),o=s?s.drop(r,e):void 0;return F6(o),typeof o>"u"&&(o=t===0?{}:r.getDropResult()),o}function F6(e){Ke(typeof e>"u"||_P(e),"Drop result must either be an object or undefined.")}function L6(e){var t=e.getTargetIds().filter(e.canDropOnTarget,e);return t.reverse(),t}function $6(e){return function(){var n=e.getMonitor(),r=e.getRegistry();B6(n);var s=n.getSourceId();if(s!=null){var o=r.getSource(s,!0);o.endDrag(n,s),r.unpinSource()}return{type:Ah}}}function B6(e){Ke(e.isDragging(),"Cannot call endDrag while not dragging.")}function z6(e){return{beginDrag:S6(e),publishDragSource:T6(e),hover:M6(e),drop:I6(e),endDrag:$6(e)}}function U6(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function V6(e,t){for(var n=0;n0;r.backend&&(s&&!r.isSetUp?(r.backend.setup(),r.isSetUp=!0):!s&&r.isSetUp&&(r.backend.teardown(),r.isSetUp=!1))}),this.store=t,this.monitor=n,t.subscribe(this.handleRefCountChange)}return H6(e,[{key:"receiveBackend",value:function(n){this.backend=n}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var n=this,r=this.store.dispatch;function s(a){return function(){for(var c=arguments.length,u=new Array(c),i=0;i"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(_r(1));return n(PP)(e,t)}if(typeof e!="function")throw new Error(_r(2));var s=e,o=t,a=[],c=a,u=!1;function i(){c===a&&(c=a.slice())}function d(){if(u)throw new Error(_r(3));return o}function p(m){if(typeof m!="function")throw new Error(_r(4));if(u)throw new Error(_r(5));var x=!0;return i(),c.push(m),function(){if(x){if(u)throw new Error(_r(6));x=!1,i();var y=c.indexOf(m);c.splice(y,1),a=null}}}function f(m){if(!q6(m))throw new Error(_r(7));if(typeof m.type>"u")throw new Error(_r(8));if(u)throw new Error(_r(9));try{u=!0,o=s(o,m)}finally{u=!1}for(var x=a=c,b=0;b2&&arguments[2]!==void 0?arguments[2]:W6;if(e.length!==t.length)return!1;for(var r=0;r0&&arguments[0]!==void 0?arguments[0]:GC,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Mw:case Oh:return{initialSourceClientOffset:n.sourceClientOffset,initialClientOffset:n.clientOffset,clientOffset:n.clientOffset};case Ih:return G6(e.clientOffset,n.clientOffset)?e:WC(WC({},e),{},{clientOffset:n.clientOffset});case Ah:case Dh:return GC;default:return e}}var _w="dnd-core/ADD_SOURCE",Pw="dnd-core/ADD_TARGET",Rw="dnd-core/REMOVE_SOURCE",Fh="dnd-core/REMOVE_TARGET";function Y6(e){return{type:_w,payload:{sourceId:e}}}function X6(e){return{type:Pw,payload:{targetId:e}}}function eH(e){return{type:Rw,payload:{sourceId:e}}}function tH(e){return{type:Fh,payload:{targetId:e}}}function JC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function Pr(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:rH,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Oh:return Pr(Pr({},e),{},{itemType:n.itemType,item:n.item,sourceId:n.sourceId,isSourcePublic:n.isSourcePublic,dropResult:null,didDrop:!1});case Nw:return Pr(Pr({},e),{},{isSourcePublic:!0});case Ih:return Pr(Pr({},e),{},{targetIds:n.targetIds});case Fh:return e.targetIds.indexOf(n.targetId)===-1?e:Pr(Pr({},e),{},{targetIds:y6(e.targetIds,n.targetId)});case Dh:return Pr(Pr({},e),{},{dropResult:n.dropResult,didDrop:!0,targetIds:[]});case Ah:return Pr(Pr({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function oH(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case _w:case Pw:return e+1;case Rw:case Fh:return e-1;default:return e}}var kg=[],Ow=[];kg.__IS_NONE__=!0;Ow.__IS_ALL__=!0;function aH(e,t){if(e===kg)return!1;if(e===Ow||typeof t>"u")return!0;var n=x6(t,e);return n.length>0}function iH(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case Ih:break;case _w:case Pw:case Fh:case Rw:return kg;case Oh:case Nw:case Ah:case Dh:default:return Ow}var t=e.payload,n=t.targetIds,r=n===void 0?[]:n,s=t.prevTargetIds,o=s===void 0?[]:s,a=b6(r,o),c=a.length>0||!J6(r,o);if(!c)return kg;var u=o[o.length-1],i=r[r.length-1];return u!==i&&(u&&a.push(u),i&&a.push(i)),a}function lH(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function QC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function ZC(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:iH(e.dirtyHandlerIds,{type:t.type,payload:ZC(ZC({},t.payload),{},{prevTargetIds:v6(e,"dragOperation.targetIds",[])})}),dragOffset:Z6(e.dragOffset,t),refCount:oH(e.refCount,t),dragOperation:sH(e.dragOperation,t),stateId:lH(e.stateId)}}function dH(e,t){return{x:e.x+t.x,y:e.y+t.y}}function RP(e,t){return{x:e.x-t.x,y:e.y-t.y}}function fH(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return!t||!n||!r?null:RP(dH(t,r),n)}function pH(e){var t=e.clientOffset,n=e.initialClientOffset;return!t||!n?null:RP(t,n)}function gH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function hH(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},o=s.handlerIds;Ke(typeof n=="function","listener must be a function."),Ke(typeof o>"u"||Array.isArray(o),"handlerIds, when specified, must be an array of strings.");var a=this.store.getState().stateId,c=function(){var i=r.store.getState(),d=i.stateId;try{var p=d===a||d===a+1&&!aH(i.dirtyHandlerIds,o);p||n()}finally{a=d}};return this.store.subscribe(c)}},{key:"subscribeToOffsetChange",value:function(n){var r=this;Ke(typeof n=="function","listener must be a function.");var s=this.store.getState().dragOffset,o=function(){var c=r.store.getState().dragOffset;c!==s&&(s=c,n())};return this.store.subscribe(o)}},{key:"canDragSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n);return Ke(r,"Expected to find a valid source. sourceId=".concat(n)),this.isDragging()?!1:r.canDrag(this,n)}},{key:"canDropOnTarget",value:function(n){if(!n)return!1;var r=this.registry.getTarget(n);if(Ke(r,"Expected to find a valid target. targetId=".concat(n)),!this.isDragging()||this.didDrop())return!1;var s=this.registry.getTargetType(n),o=this.getItemType();return ib(s,o)&&r.canDrop(this,n)}},{key:"isDragging",value:function(){return!!this.getItemType()}},{key:"isDraggingSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n,!0);if(Ke(r,"Expected to find a valid source. sourceId=".concat(n)),!this.isDragging()||!this.isSourcePublic())return!1;var s=this.registry.getSourceType(n),o=this.getItemType();return s!==o?!1:r.isDragging(this,n)}},{key:"isOverTarget",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!n)return!1;var s=r.shallow;if(!this.isDragging())return!1;var o=this.registry.getTargetType(n),a=this.getItemType();if(a&&!ib(o,a))return!1;var c=this.getTargetIds();if(!c.length)return!1;var u=c.indexOf(n);return s?u===c.length-1:u>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return!!this.store.getState().dragOperation.isSourcePublic}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return fH(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return pH(this.store.getState().dragOffset)}}]),e}(),yH=0;function bH(){return yH++}function xp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?xp=function(n){return typeof n}:xp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},xp(e)}function xH(e){Ke(typeof e.canDrag=="function","Expected canDrag to be a function."),Ke(typeof e.beginDrag=="function","Expected beginDrag to be a function."),Ke(typeof e.endDrag=="function","Expected endDrag to be a function.")}function wH(e){Ke(typeof e.canDrop=="function","Expected canDrop to be a function."),Ke(typeof e.hover=="function","Expected hover to be a function."),Ke(typeof e.drop=="function","Expected beginDrag to be a function.")}function lb(e,t){if(t&&Array.isArray(e)){e.forEach(function(n){return lb(n,!1)});return}Ke(typeof e=="string"||xp(e)==="symbol",t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}const XC=typeof global<"u"?global:self,OP=XC.MutationObserver||XC.WebKitMutationObserver;function IP(e){return function(){const n=setTimeout(s,0),r=setInterval(s,50);function s(){clearTimeout(n),clearInterval(r),e()}}}function SH(e){let t=1;const n=new OP(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}const CH=typeof OP=="function"?SH:IP;class EH{enqueueTask(t){const{queue:n,requestFlush:r}=this;n.length||(r(),this.flushing=!0),n[n.length]=t}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:t}=this;for(;this.indexthis.capacity){for(let r=0,s=t.length-this.index;r{this.pendingErrors.push(t),this.requestErrorThrow()},this.requestFlush=CH(this.flush),this.requestErrorThrow=IP(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class kH{call(){try{this.task&&this.task()}catch(t){this.onError(t)}finally{this.task=null,this.release(this)}}constructor(t,n){this.onError=t,this.release=n,this.task=null}}class jH{create(t){const n=this.freeTasks,r=n.length?n.pop():new kH(this.onError,s=>n[n.length]=s);return r.task=t,r}constructor(t){this.onError=t,this.freeTasks=[]}}const DP=new EH,TH=new jH(DP.registerPendingError);function MH(e){DP.enqueueTask(TH.create(e))}function NH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _H(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:!1;Ke(this.isSourceId(n),"Expected a valid source ID.");var s=r&&n===this.pinnedSourceId,o=s?this.pinnedSource:this.dragSources.get(n);return o}},{key:"getTarget",value:function(n){return Ke(this.isTargetId(n),"Expected a valid target ID."),this.dropTargets.get(n)}},{key:"getSourceType",value:function(n){return Ke(this.isSourceId(n),"Expected a valid source ID."),this.types.get(n)}},{key:"getTargetType",value:function(n){return Ke(this.isTargetId(n),"Expected a valid target ID."),this.types.get(n)}},{key:"isSourceId",value:function(n){var r=t1(n);return r===Lr.SOURCE}},{key:"isTargetId",value:function(n){var r=t1(n);return r===Lr.TARGET}},{key:"removeSource",value:function(n){var r=this;Ke(this.getSource(n),"Expected an existing source."),this.store.dispatch(eH(n)),MH(function(){r.dragSources.delete(n),r.types.delete(n)})}},{key:"removeTarget",value:function(n){Ke(this.getTarget(n),"Expected an existing target."),this.store.dispatch(tH(n)),this.dropTargets.delete(n),this.types.delete(n)}},{key:"pinSource",value:function(n){var r=this.getSource(n);Ke(r,"Expected an existing source."),this.pinnedSourceId=n,this.pinnedSource=r}},{key:"unpinSource",value:function(){Ke(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(n,r,s){var o=FH(n);return this.types.set(o,r),n===Lr.SOURCE?this.dragSources.set(o,s):n===Lr.TARGET&&this.dropTargets.set(o,s),o}}]),e}();function $H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=BH(r),o=new vH(s,new LH(s)),a=new K6(s,o),c=e(a,t,n);return a.receiveBackend(c),a}function BH(e){var t=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__;return PP(uH,e&&t&&t({name:"dnd-core",instanceId:"dnd-core"}))}var zH=["children"];function UH(e,t){return qH(e)||KH(e,t)||HH(e,t)||VH()}function VH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HH(e,t){if(e){if(typeof e=="string")return r1(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r1(e,t)}}function r1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function GH(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o=0)&&(n[s]=e[s]);return n}var s1=0,wp=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),JH=v.memo(function(t){var n=t.children,r=WH(t,zH),s=QH(r),o=UH(s,2),a=o[0],c=o[1];return v.useEffect(function(){if(c){var u=AP();return++s1,function(){--s1===0&&(u[wp]=null)}}},[]),l.jsx(NP.Provider,Object.assign({value:a},{children:n}),void 0)});function QH(e){if("manager"in e){var t={dragDropManager:e.manager};return[t,!1]}var n=ZH(e.backend,e.context,e.options,e.debugMode),r=!e.context;return[n,r]}function ZH(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:AP(),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,s=t;return s[wp]||(s[wp]={dragDropManager:$H(e,t,n,r)}),s[wp]}function AP(){return typeof global<"u"?global:window}function YH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function XH(e,t){for(var n=0;n, or turn it into a ")+"drag source or a drop target itself.")}}function iK(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!v.isValidElement(t)){var r=t;return e(r,n),r}var s=t;aK(s);var o=n?function(a){return e(a,n)}:e;return lK(s,o)}}function FP(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n];if(n.endsWith("Ref"))t[n]=e[n];else{var s=iK(r);t[n]=function(){return s}}}),t}function i1(e,t){typeof e=="function"?e(t):e.current=t}function lK(e,t){var n=e.ref;return Ke(typeof n!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),n?v.cloneElement(e,{ref:function(s){i1(n,s),i1(t,s)}}):v.cloneElement(e,{ref:t})}function Sp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Sp=function(n){return typeof n}:Sp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Sp(e)}function cb(e){return e!==null&&Sp(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ub(e,t,n,r){var s=void 0;if(s!==void 0)return!!s;if(e===t)return!0;if(typeof e!="object"||!e||typeof t!="object"||!t)return!1;var o=Object.keys(e),a=Object.keys(t);if(o.length!==a.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(t),u=0;ue.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"leave",value:function(n){var r=this.entered.length;return this.entered=v7(this.entered.filter(this.isNodeInDocument),n),r>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),e}(),C7=BP(function(){return/firefox/i.test(navigator.userAgent)}),zP=BP(function(){return!!window.safari});function E7(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function k7(e,t){for(var n=0;nn)d=p-1;else return s[p]}u=Math.max(0,d);var g=n-r[u],h=g*g;return s[u]+o[u]*g+a[u]*h+c[u]*g*h}}]),e}(),T7=1;function UP(e){var t=e.nodeType===T7?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,s=n.left;return{x:s,y:r}}function zf(e){return{x:e.clientX,y:e.clientY}}function M7(e){var t;return e.nodeName==="IMG"&&(C7()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(e)))}function N7(e,t,n,r){var s=e?t.width:n,o=e?t.height:r;return zP()&&e&&(o/=window.devicePixelRatio,s/=window.devicePixelRatio),{dragPreviewWidth:s,dragPreviewHeight:o}}function _7(e,t,n,r,s){var o=M7(t),a=o?e:t,c=UP(a),u={x:n.x-c.x,y:n.y-c.y},i=e.offsetWidth,d=e.offsetHeight,p=r.anchorX,f=r.anchorY,g=N7(o,t,i,d),h=g.dragPreviewWidth,m=g.dragPreviewHeight,x=function(){var T=new g1([0,.5,1],[u.y,u.y/d*m,u.y+m-d]),j=T.interpolate(f);return zP()&&o&&(j+=(window.devicePixelRatio-1)*m),j},b=function(){var T=new g1([0,.5,1],[u.x,u.x/i*h,u.x+h-i]);return T.interpolate(p)},y=s.offsetX,w=s.offsetY,S=y===0||y,E=w===0||w;return{x:S?y:b(),y:E?w:x()}}var VP="__NATIVE_FILE__",HP="__NATIVE_URL__",KP="__NATIVE_TEXT__",qP="__NATIVE_HTML__";const h1=Object.freeze(Object.defineProperty({__proto__:null,FILE:VP,HTML:qP,TEXT:KP,URL:HP},Symbol.toStringTag,{value:"Module"}));function uv(e,t,n){var r=t.reduce(function(s,o){return s||e.getData(o)},"");return r??n}var ll;function Uf(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var fb=(ll={},Uf(ll,VP,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items},dataTransfer:function(t){return t}},matchesTypes:["Files"]}),Uf(ll,qP,{exposeProperties:{html:function(t,n){return uv(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Html","text/html"]}),Uf(ll,HP,{exposeProperties:{urls:function(t,n){return uv(t,n,"").split(` +`)},dataTransfer:function(t){return t}},matchesTypes:["Url","text/uri-list"]}),Uf(ll,KP,{exposeProperties:{text:function(t,n){return uv(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Text","text/plain"]}),ll);function P7(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function R7(e,t){for(var n=0;n-1})})[0]||null}function A7(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function F7(e,t){for(var n=0;n0&&s.actions.hover(a,{clientOffset:zf(o)});var c=a.some(function(u){return s.monitor.canDropOnTarget(u)});c&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect()))}}),at(this,"handleTopDragOverCapture",function(){s.dragOverTargetIds=[]}),at(this,"handleTopDragOver",function(o){var a=s.dragOverTargetIds;if(s.dragOverTargetIds=[],!s.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}s.altKeyPressed=o.altKey,s.lastClientOffset=zf(o),s.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(s.hoverRafId=requestAnimationFrame(function(){s.monitor.isDragging()&&s.actions.hover(a||[],{clientOffset:s.lastClientOffset}),s.hoverRafId=null}));var c=(a||[]).some(function(u){return s.monitor.canDropOnTarget(u)});c?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect())):s.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))}),at(this,"handleTopDragLeaveCapture",function(o){s.isDraggingNativeItem()&&o.preventDefault();var a=s.enterLeaveCounter.leave(o.target);a&&s.isDraggingNativeItem()&&setTimeout(function(){return s.endDragNativeItem()},0)}),at(this,"handleTopDropCapture",function(o){if(s.dropTargetIds=[],s.isDraggingNativeItem()){var a;o.preventDefault(),(a=s.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}else dv(o.dataTransfer)&&o.preventDefault();s.enterLeaveCounter.reset()}),at(this,"handleTopDrop",function(o){var a=s.dropTargetIds;s.dropTargetIds=[],s.actions.hover(a,{clientOffset:zf(o)}),s.actions.drop({dropEffect:s.getCurrentDropEffect()}),s.isDraggingNativeItem()?s.endDragNativeItem():s.monitor.isDragging()&&s.actions.endDrag()}),at(this,"handleSelectStart",function(o){var a=o.target;typeof a.dragDrop=="function"&&(a.tagName==="INPUT"||a.tagName==="SELECT"||a.tagName==="TEXTAREA"||a.isContentEditable||(o.preventDefault(),a.dragDrop()))}),this.options=new $7(n,r),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new S7(this.isNodeInDocument)}return U7(e,[{key:"profile",value:function(){var n,r;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((n=this.dragStartSourceIds)===null||n===void 0?void 0:n.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((r=this.dragOverTargetIds)===null||r===void 0?void 0:r.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var n=this.rootElement;if(n!==void 0){if(n.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");n.__isReactDndBackendSetUp=!0,this.addEventListeners(n)}}},{key:"teardown",value:function(){var n=this.rootElement;if(n!==void 0&&(n.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var r;(r=this.window)===null||r===void 0||r.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(n,r,s){var o=this;return this.sourcePreviewNodeOptions.set(n,s),this.sourcePreviewNodes.set(n,r),function(){o.sourcePreviewNodes.delete(n),o.sourcePreviewNodeOptions.delete(n)}}},{key:"connectDragSource",value:function(n,r,s){var o=this;this.sourceNodes.set(n,r),this.sourceNodeOptions.set(n,s);var a=function(i){return o.handleDragStart(i,n)},c=function(i){return o.handleSelectStart(i)};return r.setAttribute("draggable","true"),r.addEventListener("dragstart",a),r.addEventListener("selectstart",c),function(){o.sourceNodes.delete(n),o.sourceNodeOptions.delete(n),r.removeEventListener("dragstart",a),r.removeEventListener("selectstart",c),r.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(n,r){var s=this,o=function(i){return s.handleDragEnter(i,n)},a=function(i){return s.handleDragOver(i,n)},c=function(i){return s.handleDrop(i,n)};return r.addEventListener("dragenter",o),r.addEventListener("dragover",a),r.addEventListener("drop",c),function(){r.removeEventListener("dragenter",o),r.removeEventListener("dragover",a),r.removeEventListener("drop",c)}}},{key:"addEventListeners",value:function(n){n.addEventListener&&(n.addEventListener("dragstart",this.handleTopDragStart),n.addEventListener("dragstart",this.handleTopDragStartCapture,!0),n.addEventListener("dragend",this.handleTopDragEndCapture,!0),n.addEventListener("dragenter",this.handleTopDragEnter),n.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.addEventListener("dragover",this.handleTopDragOver),n.addEventListener("dragover",this.handleTopDragOverCapture,!0),n.addEventListener("drop",this.handleTopDrop),n.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(n){n.removeEventListener&&(n.removeEventListener("dragstart",this.handleTopDragStart),n.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),n.removeEventListener("dragend",this.handleTopDragEndCapture,!0),n.removeEventListener("dragenter",this.handleTopDragEnter),n.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.removeEventListener("dragover",this.handleTopDragOver),n.removeEventListener("dragover",this.handleTopDragOverCapture,!0),n.removeEventListener("drop",this.handleTopDrop),n.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(n);return y1({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(n);return y1({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}},{key:"isDraggingNativeItem",value:function(){var n=this.monitor.getItemType();return Object.keys(h1).some(function(r){return h1[r]===n})}},{key:"beginDragNativeItem",value:function(n,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=D7(n,r),this.currentNativeHandle=this.registry.addSource(n,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(n){var r=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=n;var s=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var o;return(o=r.rootElement)===null||o===void 0?void 0:o.addEventListener("mousemove",r.endDragIfSourceWasRemovedFromDOM,!0)},s)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var n;(n=this.window)===null||n===void 0||n.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(n,r){n.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}},{key:"handleDragEnter",value:function(n,r){this.dragEnterTargetIds.unshift(r)}},{key:"handleDragOver",value:function(n,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}},{key:"handleDrop",value:function(n,r){this.dropTargetIds.unshift(r)}}]),e}(),H7=function(t,n,r){return new V7(t,n,r)},K7=Object.create,WP=Object.defineProperty,q7=Object.getOwnPropertyDescriptor,GP=Object.getOwnPropertyNames,W7=Object.getPrototypeOf,G7=Object.prototype.hasOwnProperty,J7=(e,t)=>function(){return t||(0,e[GP(e)[0]])((t={exports:{}}).exports,t),t.exports},Q7=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of GP(t))!G7.call(e,s)&&s!==n&&WP(e,s,{get:()=>t[s],enumerable:!(r=q7(t,s))||r.enumerable});return e},JP=(e,t,n)=>(n=e!=null?K7(W7(e)):{},Q7(WP(n,"default",{value:e,enumerable:!0}),e)),QP=J7({"node_modules/classnames/index.js"(e,t){(function(){var n={}.hasOwnProperty;function r(){for(var s=[],o=0;o-1}var oW=sW,aW=9007199254740991,iW=/^(?:0|[1-9]\d*)$/;function lW(e,t){var n=typeof e;return t=t??aW,!!t&&(n=="number"||n!="symbol"&&iW.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=dW}var rR=fW;function pW(e){return e!=null&&rR(e.length)&&!tR(e)}var gW=pW,hW=Object.prototype;function mW(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||hW;return e===n}var vW=mW;function yW(e,t){for(var n=-1,r=Array(e);++n-1}var JG=GG;function QG(e,t){var n=this.__data__,r=Lh(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var ZG=QG;function Dc(e){var t=-1,n=e==null?0:e.length;for(this.clear();++tc))return!1;var i=o.get(e),d=o.get(t);if(i&&d)return i==t&&d==e;var p=-1,f=!0,g=n&sJ?new uR:void 0;for(o.set(e,t),o.set(t,e);++p":">",'"':""","'":"'"},FJ=m9(AJ),LJ=FJ,gR=/[&<>"']/g,$J=RegExp(gR.source);function BJ(e){return e=cR(e),e&&$J.test(e)?e.replace(gR,LJ):e}var zJ=BJ,hR=/[\\^$.*+?()[\]{}|]/g,UJ=RegExp(hR.source);function VJ(e){return e=cR(e),e&&UJ.test(e)?e.replace(hR,"\\$&"):e}var HJ=VJ;function KJ(e,t){return OJ(e,t)}var qJ=KJ,WJ=1/0,GJ=Ul&&1/Iw(new Ul([,-0]))[1]==WJ?function(e){return new Ul(e)}:Jq,JJ=GJ,QJ=200;function ZJ(e,t,n){var r=-1,s=oW,o=e.length,a=!0,c=[],u=c;if(n)a=!1,s=DJ;else if(o>=QJ){var i=t?null:JJ(e);if(i)return Iw(i);a=!1,s=dR,u=new uR}else u=t?[]:c;e:for(;++rl.jsx("button",{className:e.classNames.clearAll,onClick:e.onClick,children:"Clear all"}),nQ=tQ,rQ=(e,t)=>{const n=t.offsetHeight,r=e.offsetHeight,s=e.offsetTop-t.scrollTop;s+r>=n?t.scrollTop+=s-n+r:s<0&&(t.scrollTop+=s)},vb=(e,t,n,r)=>typeof r=="function"?r(e):e.length>=t&&n,sQ=e=>{const t=v.createRef(),{labelField:n,minQueryLength:r,isFocused:s,classNames:o,selectedIndex:a,query:c}=e;v.useEffect(()=>{if(!t.current)return;const p=t.current.querySelector(`.${o.activeSuggestion}`);p&&rQ(p,t.current)},[a]);const u=(p,f)=>{const g=f.trim().replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&"),{[n]:h}=p;return{__html:h.replace(RegExp(g,"gi"),m=>`${zJ(m)}`)}},i=(p,f)=>typeof e.renderSuggestion=="function"?e.renderSuggestion(p,f):l.jsx("span",{dangerouslySetInnerHTML:u(p,f)}),d=e.suggestions.map((p,f)=>l.jsx("li",{onMouseDown:e.handleClick.bind(null,f),onTouchStart:e.handleClick.bind(null,f),onMouseOver:e.handleHover.bind(null,f),className:f===e.selectedIndex?e.classNames.activeSuggestion:"",children:i(p,e.query)},f));return d.length===0||!vb(c,r||2,s,e.shouldRenderSuggestions)?null:l.jsx("div",{ref:t,className:o.suggestions,"data-testid":"suggestions",children:l.jsxs("ul",{children:[" ",d," "]})})},oQ=(e,t)=>{const{query:n,minQueryLength:r=2,isFocused:s,suggestions:o}=t;return!!(e.isFocused===s&&qJ(e.suggestions,o)&&vb(n,r,s,t.shouldRenderSuggestions)===vb(e.query,e.minQueryLength??2,e.isFocused,e.shouldRenderSuggestions)&&e.selectedIndex===t.selectedIndex)},aQ=v.memo(sQ,oQ),iQ=aQ,lQ=JP(QP()),cQ=JP(QP());function uQ(e){const t=e.map(r=>{const s=r-48*Math.floor(r/48);return String.fromCharCode(96<=r?s:r)}).join(""),n=HJ(t);return new RegExp(`[${n}]+`)}function dQ(e){switch(e){case Os.ENTER:return[10,13];case Os.TAB:return 9;case Os.COMMA:return 188;case Os.SPACE:return 32;case Os.SEMICOLON:return 186;default:return 0}}function H1(e){const{moveTag:t,readOnly:n,allowDragDrop:r}=e;return t!==void 0&&!n&&r}function fQ(e){const{readOnly:t,allowDragDrop:n}=e;return!t&&n}var pQ=e=>{const{readOnly:t,removeComponent:n,onRemove:r,className:s,tag:o,index:a}=e,c=i=>{if(zl.ENTER.includes(i.keyCode)||i.keyCode===zl.SPACE){i.preventDefault(),i.stopPropagation();return}i.keyCode===zl.BACKSPACE&&r(i)};if(t)return l.jsx("span",{});const u=`Tag at index ${a} with value ${o.id} focussed. Press backspace to remove`;if(n){const i=n;return l.jsx(i,{"data-testid":"remove",onRemove:r,onKeyDown:c,className:s,"aria-label":u,tag:o,index:a})}return l.jsx("button",{"data-testid":"remove",onClick:r,onKeyDown:c,className:s,type:"button","aria-label":u,children:l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"12",width:"12",fill:"#fff",children:l.jsx("path",{d:"M376.6 84.5c11.3-13.6 9.5-33.8-4.1-45.1s-33.8-9.5-45.1 4.1L192 206 56.6 43.5C45.3 29.9 25.1 28.1 11.5 39.4S-3.9 70.9 7.4 84.5L150.3 256 7.4 427.5c-11.3 13.6-9.5 33.8 4.1 45.1s33.8 9.5 45.1-4.1L192 306 327.4 468.5c11.3 13.6 31.5 15.4 45.1 4.1s15.4-31.5 4.1-45.1L233.7 256 376.6 84.5z"})})})},gQ=pQ,K1={TAG:"tag"},hQ=e=>{const t=v.useRef(null),{readOnly:n=!1,tag:r,classNames:s,index:o,moveTag:a,allowDragDrop:c=!0,labelField:u="text",tags:i}=e,[{isDragging:d},p]=e7(()=>({type:K1.TAG,collect:x=>({isDragging:!!x.isDragging()}),item:e,canDrag:()=>H1({moveTag:a,readOnly:n,allowDragDrop:c})}),[i]),[,f]=m7(()=>({accept:K1.TAG,drop:x=>{var w;const b=x.index,y=o;b!==y&&((w=e==null?void 0:e.moveTag)==null||w.call(e,b,y))},canDrop:x=>fQ(x)}),[i]);p(f(t));const g=e.tag[u],{className:h=""}=r,m=d?0:1;return l.jsxs("span",{ref:t,className:(0,cQ.default)("tag-wrapper",s.tag,h),style:{opacity:m,cursor:H1({moveTag:a,readOnly:n,allowDragDrop:c})?"move":"auto"},"data-testid":"tag",onClick:e.onTagClicked,onTouchStart:e.onTagClicked,children:[g,l.jsx(gQ,{tag:e.tag,className:s.remove,removeComponent:e.removeComponent,onRemove:e.onDelete,readOnly:n,index:o})]})},mQ=e=>{const{autofocus:t,autoFocus:n,readOnly:r,labelField:s,allowDeleteFromEmptyInput:o,allowAdditionFromPaste:a,allowDragDrop:c,minQueryLength:u,shouldRenderSuggestions:i,removeComponent:d,autocomplete:p,inline:f,maxTags:g,allowUnique:h,editable:m,placeholder:x,delimiters:b,separators:y,tags:w,inputFieldPosition:S,inputProps:E,classNames:C,maxLength:T,inputValue:j,clearAll:_}=e,[O,K]=v.useState(e.suggestions),[I,Y]=v.useState(""),[q,Z]=v.useState(!1),[ee,J]=v.useState(-1),[L,A]=v.useState(!1),[X,fe]=v.useState(""),[H,se]=v.useState(-1),[ne,le]=v.useState(""),oe=v.createRef(),Q=v.useRef(null),Ee=v.useRef(null);v.useEffect(()=>{b.length&&console.warn("[Deprecation] The delimiters prop is deprecated and will be removed in v7.x.x, please use separators instead. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/960")},[]),v.useEffect(()=>{typeof f<"u"&&console.warn("[Deprecation] The inline attribute is deprecated and will be removed in v7.x.x, please use inputFieldPosition instead.")},[f]),v.useEffect(()=>{typeof t<"u"&&console.warn("[Deprecated] autofocus prop will be removed in 7.x so please migrate to autoFocus prop."),(t||n&&t!==!1)&&!r&&Re()},[n,n,r]),v.useEffect(()=>{Xt()},[I,e.suggestions]);const Pe=ue=>{let He=e.suggestions.slice();if(h){const _n=w.map(xs=>xs.id.trim().toLowerCase());He=He.filter(xs=>!_n.includes(xs.id.toLowerCase()))}if(e.handleFilterSuggestions)return e.handleFilterSuggestions(ue,He);const Tt=He.filter(_n=>Be(ue,_n)===0),vt=He.filter(_n=>Be(ue,_n)>0);return Tt.concat(vt)},Be=(ue,He)=>He[s].toLowerCase().indexOf(ue.toLowerCase()),Re=()=>{Y(""),Q.current&&(Q.current.value="",Q.current.focus())},ve=(ue,He)=>{var vt;He.preventDefault(),He.stopPropagation();const Tt=w.slice();Tt.length!==0&&(le(""),(vt=e==null?void 0:e.handleDelete)==null||vt.call(e,ue,He),ot(ue,Tt))},ot=(ue,He)=>{var _n;if(!(oe!=null&&oe.current))return;const Tt=oe.current.querySelectorAll(".ReactTags__remove");let vt="";ue===0&&He.length>1?(vt=`Tag at index ${ue} with value ${He[ue].id} deleted. Tag at index 0 with value ${He[1].id} focussed. Press backspace to remove`,Tt[0].focus()):ue>0?(vt=`Tag at index ${ue} with value ${He[ue].id} deleted. Tag at index ${ue-1} with value ${He[ue-1].id} focussed. Press backspace to remove`,Tt[ue-1].focus()):(vt=`Tag at index ${ue} with value ${He[ue].id} deleted. Input focussed. Press enter to add a new tag`,(_n=Q.current)==null||_n.focus()),fe(vt)},Vt=(ue,He,Tt)=>{var vt,_n;r||(m&&(se(ue),Y(He[s]),(vt=Ee.current)==null||vt.focus()),(_n=e.handleTagClick)==null||_n.call(e,ue,Tt))},tn=ue=>{e.handleInputChange&&e.handleInputChange(ue.target.value,ue);const He=ue.target.value.trim();Y(He)},Xt=()=>{const ue=Pe(I);K(ue),J(ee>=ue.length?ue.length-1:ee)},ln=ue=>{const He=ue.target.value;e.handleInputFocus&&e.handleInputFocus(He,ue),Z(!0)},M=ue=>{const He=ue.target.value;e.handleInputBlur&&(e.handleInputBlur(He,ue),Q.current&&(Q.current.value="")),Z(!1),se(-1)},D=ue=>{if(ue.key==="Escape"&&(ue.preventDefault(),ue.stopPropagation(),J(-1),A(!1),K([]),se(-1)),(y.indexOf(ue.key)!==-1||b.indexOf(ue.keyCode)!==-1)&&!ue.shiftKey){(ue.keyCode!==zl.TAB||I!=="")&&ue.preventDefault();const He=L&&ee!==-1?O[ee]:{id:I.trim(),[s]:I.trim(),className:""};Object.keys(He)&&ce(He)}ue.key==="Backspace"&&I===""&&(o||S===au.INLINE)&&ve(w.length-1,ue),ue.keyCode===zl.UP_ARROW&&(ue.preventDefault(),J(ee<=0?O.length-1:ee-1),A(!0)),ue.keyCode===zl.DOWN_ARROW&&(ue.preventDefault(),A(!0),O.length===0?J(-1):J((ee+1)%O.length))},V=()=>g&&w.length>=g,he=ue=>{if(!a)return;if(V()){le(x1.TAG_LIMIT),Re();return}le(""),ue.preventDefault();const He=ue.clipboardData||window.clipboardData,Tt=He.getData("text"),{maxLength:vt=Tt.length}=e,_n=Math.min(vt,Tt.length),xs=He.getData("text").substr(0,_n);let Io=b;y.length&&(Io=[],y.forEach(ws=>{const zc=dQ(ws);Array.isArray(zc)?Io=[...Io,...zc]:Io.push(zc)}));const Bc=uQ(Io),Zi=xs.split(Bc).map(ws=>ws.trim());eQ(Zi).forEach(ws=>ce({id:ws.trim(),[s]:ws.trim(),className:""}))},ce=ue=>{var Tt;if(!ue.id||!ue[s])return;if(H===-1){if(V()){le(x1.TAG_LIMIT),Re();return}le("")}const He=w.map(vt=>vt.id.toLowerCase());if(!(h&&He.indexOf(ue.id.trim().toLowerCase())>=0)){if(p){const vt=Pe(ue[s]);console.warn("[Deprecation] The autocomplete prop will be removed in 7.x to simplify the integration and make it more intutive. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/949"),(p===1&&vt.length===1||p===!0&&vt.length)&&(ue=vt[0])}H!==-1&&e.onTagUpdate?e.onTagUpdate(H,ue):(Tt=e==null?void 0:e.handleAddition)==null||Tt.call(e,ue),Y(""),A(!1),J(-1),se(-1),Re()}},ae=ue=>{ce(O[ue])},ke=()=>{e.onClearAll&&e.onClearAll(),le(""),Re()},rt=ue=>{J(ue),A(!0)},Pt=(ue,He)=>{var vt;const Tt=w[ue];(vt=e==null?void 0:e.handleDrag)==null||vt.call(e,Tt,ue,He)},bn=(()=>{const ue={...b1,...e.classNames};return w.map((He,Tt)=>l.jsx(v.Fragment,{children:H===Tt?l.jsx("div",{className:ue.editTagInput,children:l.jsx("input",{ref:vt=>{Ee.current=vt},onFocus:ln,value:I,onChange:tn,onKeyDown:D,onBlur:M,className:ue.editTagInputField,onPaste:he,"data-testid":"tag-edit"})}):l.jsx(hQ,{index:Tt,tag:He,tags:w,labelField:s,onDelete:vt=>ve(Tt,vt),moveTag:c?Pt:void 0,removeComponent:d,onTagClicked:vt=>Vt(Tt,He,vt),readOnly:r,classNames:ue,allowDragDrop:c})},Tt))})(),mn={...b1,...C},{name:Oo,id:bs}=e,qa=f===!1?au.BOTTOM:S,zn=r?null:l.jsxs("div",{className:mn.tagInput,children:[l.jsx("input",{...E,ref:ue=>{Q.current=ue},className:mn.tagInputField,type:"text",placeholder:x,"aria-label":x,onFocus:ln,onBlur:M,onChange:tn,onKeyDown:D,onPaste:he,name:Oo,id:bs,maxLength:T,value:j,"data-automation":"input","data-testid":"input"}),l.jsx(iQ,{query:I.trim(),suggestions:O,labelField:s,selectedIndex:ee,handleClick:ae,handleHover:rt,minQueryLength:u,shouldRenderSuggestions:i,isFocused:q,classNames:mn,renderSuggestion:e.renderSuggestion}),_&&w.length>0&&l.jsx(nQ,{classNames:mn,onClick:ke}),ne&&l.jsxs("div",{"data-testid":"error",className:"ReactTags__error",children:[l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"24",width:"24",fill:"#e03131",children:l.jsx("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"})}),ne]})]});return l.jsxs("div",{className:(0,lQ.default)(mn.tags,"react-tags-wrapper"),ref:oe,children:[l.jsx("p",{role:"alert",className:"sr-only",style:{position:"absolute",overflow:"hidden",clip:"rect(0 0 0 0)",margin:"-1px",padding:0,width:"1px",height:"1px",border:0},children:X}),qa===au.TOP&&zn,l.jsxs("div",{className:mn.selected,children:[bn,qa===au.INLINE&&zn]}),qa===au.BOTTOM&&zn]})},vQ=mQ,yQ=e=>{var ne;const{placeholder:t=Z7,labelField:n=Y7,suggestions:r=[],delimiters:s=[],separators:o=(ne=e.delimiters)!=null&&ne.length?[]:[Os.ENTER,Os.TAB],autofocus:a,autoFocus:c=!0,inline:u,inputFieldPosition:i="inline",allowDeleteFromEmptyInput:d=!1,allowAdditionFromPaste:p=!0,autocomplete:f=!1,readOnly:g=!1,allowUnique:h=!0,allowDragDrop:m=!0,tags:x=[],inputProps:b={},editable:y=!1,clearAll:w=!1,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:T,handleFilterSuggestions:j,handleTagClick:_,handleInputChange:O,handleInputFocus:K,handleInputBlur:I,minQueryLength:Y,shouldRenderSuggestions:q,removeComponent:Z,onClearAll:ee,classNames:J,name:L,id:A,maxLength:X,inputValue:fe,maxTags:H,renderSuggestion:se}=e;return l.jsx(vQ,{placeholder:t,labelField:n,suggestions:r,delimiters:s,separators:o,autofocus:a,autoFocus:c,inline:u,inputFieldPosition:i,allowDeleteFromEmptyInput:d,allowAdditionFromPaste:p,autocomplete:f,readOnly:g,allowUnique:h,allowDragDrop:m,tags:x,inputProps:b,editable:y,clearAll:w,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:T,handleFilterSuggestions:j,handleTagClick:_,handleInputChange:O,handleInputFocus:K,handleInputBlur:I,minQueryLength:Y,shouldRenderSuggestions:q,removeComponent:Z,onClearAll:ee,classNames:J,name:L,id:A,maxLength:X,inputValue:fe,maxTags:H,renderSuggestion:se})},bQ=({...e})=>l.jsx(JH,{backend:H7,children:l.jsx(yQ,{...e})});/*! Bundled license information: + +classnames/index.js: + (*! + Copyright (c) 2018 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames + *) + +lodash-es/lodash.js: + (** + * @license + * Lodash (Custom Build) + * Build: `lodash modularize exports="es" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + *) +*/var xQ="Label",mR=v.forwardRef((e,t)=>l.jsx(Ie.label,{...e,ref:t,onMouseDown:n=>{var s;n.target.closest("button, input, select, textarea")||((s=e.onMouseDown)==null||s.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));mR.displayName=xQ;var vR=mR;const wQ=ch("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),yR=v.forwardRef(({className:e,...t},n)=>l.jsx(vR,{ref:n,className:me(wQ(),e),...t}));yR.displayName=vR.displayName;function bR(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var SQ="VisuallyHidden",xR=v.forwardRef((e,t)=>l.jsx(Ie.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));xR.displayName=SQ;var CQ=[" ","Enter","ArrowUp","ArrowDown"],EQ=[" ","Enter"],tf="Select",[zh,Uh,kQ]=Ux(tf),[Lc,aae]=qr(tf,[kQ,mh]),Vh=mh(),[jQ,Aa]=Lc(tf),[TQ,MQ]=Lc(tf),wR=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:a,defaultValue:c,onValueChange:u,dir:i,name:d,autoComplete:p,disabled:f,required:g}=e,h=Vh(t),[m,x]=v.useState(null),[b,y]=v.useState(null),[w,S]=v.useState(!1),E=Jd(i),[C=!1,T]=ya({prop:r,defaultProp:s,onChange:o}),[j,_]=ya({prop:a,defaultProp:c,onChange:u}),O=v.useRef(null),K=m?!!m.closest("form"):!0,[I,Y]=v.useState(new Set),q=Array.from(I).map(Z=>Z.props.value).join(";");return l.jsx(HM,{...h,children:l.jsxs(jQ,{required:g,scope:t,trigger:m,onTriggerChange:x,valueNode:b,onValueNodeChange:y,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:is(),value:j,onValueChange:_,open:C,onOpenChange:T,dir:E,triggerPointerDownPosRef:O,disabled:f,children:[l.jsx(zh.Provider,{scope:t,children:l.jsx(TQ,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(Z=>{Y(ee=>new Set(ee).add(Z))},[]),onNativeOptionRemove:v.useCallback(Z=>{Y(ee=>{const J=new Set(ee);return J.delete(Z),J})},[]),children:n})}),K?l.jsxs(qR,{"aria-hidden":!0,required:g,tabIndex:-1,name:d,autoComplete:p,value:j,onChange:Z=>_(Z.target.value),disabled:f,children:[j===void 0?l.jsx("option",{value:""}):null,Array.from(I)]},q):null]})})};wR.displayName=tf;var SR="SelectTrigger",CR=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=Vh(n),a=Aa(SR,n),c=a.disabled||r,u=ct(t,a.onTriggerChange),i=Uh(n),[d,p,f]=WR(h=>{const m=i().filter(y=>!y.disabled),x=m.find(y=>y.value===a.value),b=GR(m,h,x);b!==void 0&&a.onValueChange(b.value)}),g=()=>{c||(a.onOpenChange(!0),f())};return l.jsx(KM,{asChild:!0,...o,children:l.jsx(Ie.button,{type:"button",role:"combobox","aria-controls":a.contentId,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":KR(a.value)?"":void 0,...s,ref:u,onClick:Ce(s.onClick,h=>{h.currentTarget.focus()}),onPointerDown:Ce(s.onPointerDown,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&m.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&(g(),a.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)},h.preventDefault())}),onKeyDown:Ce(s.onKeyDown,h=>{const m=d.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&p(h.key),!(m&&h.key===" ")&&CQ.includes(h.key)&&(g(),h.preventDefault())})})})});CR.displayName=SR;var ER="SelectValue",kR=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:a="",...c}=e,u=Aa(ER,n),{onValueNodeHasChildrenChange:i}=u,d=o!==void 0,p=ct(t,u.onValueNodeChange);return pn(()=>{i(d)},[i,d]),l.jsx(Ie.span,{...c,ref:p,style:{pointerEvents:"none"},children:KR(u.value)?l.jsx(l.Fragment,{children:a}):o})});kR.displayName=ER;var NQ="SelectIcon",jR=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return l.jsx(Ie.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});jR.displayName=NQ;var _Q="SelectPortal",TR=e=>l.jsx(vh,{asChild:!0,...e});TR.displayName=_Q;var Li="SelectContent",MR=v.forwardRef((e,t)=>{const n=Aa(Li,e.__scopeSelect),[r,s]=v.useState();if(pn(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?Pa.createPortal(l.jsx(NR,{scope:e.__scopeSelect,children:l.jsx(zh.Slot,{scope:e.__scopeSelect,children:l.jsx("div",{children:e.children})})}),o):null}return l.jsx(_R,{...e,ref:t})});MR.displayName=Li;var ro=10,[NR,Fa]=Lc(Li),PQ="SelectContentImpl",_R=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:a,side:c,sideOffset:u,align:i,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:g,sticky:h,hideWhenDetached:m,avoidCollisions:x,...b}=e,y=Aa(Li,n),[w,S]=v.useState(null),[E,C]=v.useState(null),T=ct(t,Q=>S(Q)),[j,_]=v.useState(null),[O,K]=v.useState(null),I=Uh(n),[Y,q]=v.useState(!1),Z=v.useRef(!1);v.useEffect(()=>{if(w)return Yx(w)},[w]),Vx();const ee=v.useCallback(Q=>{const[Ee,...Pe]=I().map(ve=>ve.ref.current),[Be]=Pe.slice(-1),Re=document.activeElement;for(const ve of Q)if(ve===Re||(ve==null||ve.scrollIntoView({block:"nearest"}),ve===Ee&&E&&(E.scrollTop=0),ve===Be&&E&&(E.scrollTop=E.scrollHeight),ve==null||ve.focus(),document.activeElement!==Re))return},[I,E]),J=v.useCallback(()=>ee([j,w]),[ee,j,w]);v.useEffect(()=>{Y&&J()},[Y,J]);const{onOpenChange:L,triggerPointerDownPosRef:A}=y;v.useEffect(()=>{if(w){let Q={x:0,y:0};const Ee=Be=>{var Re,ve;Q={x:Math.abs(Math.round(Be.pageX)-(((Re=A.current)==null?void 0:Re.x)??0)),y:Math.abs(Math.round(Be.pageY)-(((ve=A.current)==null?void 0:ve.y)??0))}},Pe=Be=>{Q.x<=10&&Q.y<=10?Be.preventDefault():w.contains(Be.target)||L(!1),document.removeEventListener("pointermove",Ee),A.current=null};return A.current!==null&&(document.addEventListener("pointermove",Ee),document.addEventListener("pointerup",Pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ee),document.removeEventListener("pointerup",Pe,{capture:!0})}}},[w,L,A]),v.useEffect(()=>{const Q=()=>L(!1);return window.addEventListener("blur",Q),window.addEventListener("resize",Q),()=>{window.removeEventListener("blur",Q),window.removeEventListener("resize",Q)}},[L]);const[X,fe]=WR(Q=>{const Ee=I().filter(Re=>!Re.disabled),Pe=Ee.find(Re=>Re.ref.current===document.activeElement),Be=GR(Ee,Q,Pe);Be&&setTimeout(()=>Be.ref.current.focus())}),H=v.useCallback((Q,Ee,Pe)=>{const Be=!Z.current&&!Pe;(y.value!==void 0&&y.value===Ee||Be)&&(_(Q),Be&&(Z.current=!0))},[y.value]),se=v.useCallback(()=>w==null?void 0:w.focus(),[w]),ne=v.useCallback((Q,Ee,Pe)=>{const Be=!Z.current&&!Pe;(y.value!==void 0&&y.value===Ee||Be)&&K(Q)},[y.value]),le=r==="popper"?yb:PR,oe=le===yb?{side:c,sideOffset:u,align:i,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:g,sticky:h,hideWhenDetached:m,avoidCollisions:x}:{};return l.jsx(NR,{scope:n,content:w,viewport:E,onViewportChange:C,itemRefCallback:H,selectedItem:j,onItemLeave:se,itemTextRefCallback:ne,focusSelectedItem:J,selectedItemText:O,position:r,isPositioned:Y,searchRef:X,children:l.jsx(wh,{as:wo,allowPinchZoom:!0,children:l.jsx(ph,{asChild:!0,trapped:y.open,onMountAutoFocus:Q=>{Q.preventDefault()},onUnmountAutoFocus:Ce(s,Q=>{var Ee;(Ee=y.trigger)==null||Ee.focus({preventScroll:!0}),Q.preventDefault()}),children:l.jsx(fh,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:Q=>Q.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:l.jsx(le,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:Q=>Q.preventDefault(),...b,...oe,onPlaced:()=>q(!0),ref:T,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Ce(b.onKeyDown,Q=>{const Ee=Q.ctrlKey||Q.altKey||Q.metaKey;if(Q.key==="Tab"&&Q.preventDefault(),!Ee&&Q.key.length===1&&fe(Q.key),["ArrowUp","ArrowDown","Home","End"].includes(Q.key)){let Be=I().filter(Re=>!Re.disabled).map(Re=>Re.ref.current);if(["ArrowUp","End"].includes(Q.key)&&(Be=Be.slice().reverse()),["ArrowUp","ArrowDown"].includes(Q.key)){const Re=Q.target,ve=Be.indexOf(Re);Be=Be.slice(ve+1)}setTimeout(()=>ee(Be)),Q.preventDefault()}})})})})})})});_R.displayName=PQ;var RQ="SelectItemAlignedPosition",PR=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Aa(Li,n),a=Fa(Li,n),[c,u]=v.useState(null),[i,d]=v.useState(null),p=ct(t,T=>d(T)),f=Uh(n),g=v.useRef(!1),h=v.useRef(!0),{viewport:m,selectedItem:x,selectedItemText:b,focusSelectedItem:y}=a,w=v.useCallback(()=>{if(o.trigger&&o.valueNode&&c&&i&&m&&x&&b){const T=o.trigger.getBoundingClientRect(),j=i.getBoundingClientRect(),_=o.valueNode.getBoundingClientRect(),O=b.getBoundingClientRect();if(o.dir!=="rtl"){const Re=O.left-j.left,ve=_.left-Re,ot=T.left-ve,Vt=T.width+ot,tn=Math.max(Vt,j.width),Xt=window.innerWidth-ro,ln=tb(ve,[ro,Xt-tn]);c.style.minWidth=Vt+"px",c.style.left=ln+"px"}else{const Re=j.right-O.right,ve=window.innerWidth-_.right-Re,ot=window.innerWidth-T.right-ve,Vt=T.width+ot,tn=Math.max(Vt,j.width),Xt=window.innerWidth-ro,ln=tb(ve,[ro,Xt-tn]);c.style.minWidth=Vt+"px",c.style.right=ln+"px"}const K=f(),I=window.innerHeight-ro*2,Y=m.scrollHeight,q=window.getComputedStyle(i),Z=parseInt(q.borderTopWidth,10),ee=parseInt(q.paddingTop,10),J=parseInt(q.borderBottomWidth,10),L=parseInt(q.paddingBottom,10),A=Z+ee+Y+L+J,X=Math.min(x.offsetHeight*5,A),fe=window.getComputedStyle(m),H=parseInt(fe.paddingTop,10),se=parseInt(fe.paddingBottom,10),ne=T.top+T.height/2-ro,le=I-ne,oe=x.offsetHeight/2,Q=x.offsetTop+oe,Ee=Z+ee+Q,Pe=A-Ee;if(Ee<=ne){const Re=x===K[K.length-1].ref.current;c.style.bottom="0px";const ve=i.clientHeight-m.offsetTop-m.offsetHeight,ot=Math.max(le,oe+(Re?se:0)+ve+J),Vt=Ee+ot;c.style.height=Vt+"px"}else{const Re=x===K[0].ref.current;c.style.top="0px";const ot=Math.max(ne,Z+m.offsetTop+(Re?H:0)+oe)+Pe;c.style.height=ot+"px",m.scrollTop=Ee-ne+m.offsetTop}c.style.margin=`${ro}px 0`,c.style.minHeight=X+"px",c.style.maxHeight=I+"px",r==null||r(),requestAnimationFrame(()=>g.current=!0)}},[f,o.trigger,o.valueNode,c,i,m,x,b,o.dir,r]);pn(()=>w(),[w]);const[S,E]=v.useState();pn(()=>{i&&E(window.getComputedStyle(i).zIndex)},[i]);const C=v.useCallback(T=>{T&&h.current===!0&&(w(),y==null||y(),h.current=!1)},[w,y]);return l.jsx(IQ,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:g,onScrollButtonChange:C,children:l.jsx("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:l.jsx(Ie.div,{...s,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});PR.displayName=RQ;var OQ="SelectPopperPosition",yb=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=ro,...o}=e,a=Vh(n);return l.jsx(qM,{...a,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});yb.displayName=OQ;var[IQ,Dw]=Lc(Li,{}),bb="SelectViewport",RR=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Fa(bb,n),a=Dw(bb,n),c=ct(t,o.onViewportChange),u=v.useRef(0);return l.jsxs(l.Fragment,{children:[l.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),l.jsx(zh.Slot,{scope:n,children:l.jsx(Ie.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:c,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:Ce(s.onScroll,i=>{const d=i.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:f}=a;if(f!=null&&f.current&&p){const g=Math.abs(u.current-d.scrollTop);if(g>0){const h=window.innerHeight-ro*2,m=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),b=Math.max(m,x);if(b0?S:0,p.style.justifyContent="flex-end")}}}u.current=d.scrollTop})})})]})});RR.displayName=bb;var OR="SelectGroup",[DQ,AQ]=Lc(OR),FQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=is();return l.jsx(DQ,{scope:n,id:s,children:l.jsx(Ie.div,{role:"group","aria-labelledby":s,...r,ref:t})})});FQ.displayName=OR;var IR="SelectLabel",DR=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=AQ(IR,n);return l.jsx(Ie.div,{id:s.id,...r,ref:t})});DR.displayName=IR;var Tg="SelectItem",[LQ,AR]=Lc(Tg),FR=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...a}=e,c=Aa(Tg,n),u=Fa(Tg,n),i=c.value===r,[d,p]=v.useState(o??""),[f,g]=v.useState(!1),h=ct(t,b=>{var y;return(y=u.itemRefCallback)==null?void 0:y.call(u,b,r,s)}),m=is(),x=()=>{s||(c.onValueChange(r),c.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return l.jsx(LQ,{scope:n,value:r,disabled:s,textId:m,isSelected:i,onItemTextChange:v.useCallback(b=>{p(y=>y||((b==null?void 0:b.textContent)??"").trim())},[]),children:l.jsx(zh.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:l.jsx(Ie.div,{role:"option","aria-labelledby":m,"data-highlighted":f?"":void 0,"aria-selected":i&&f,"data-state":i?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:h,onFocus:Ce(a.onFocus,()=>g(!0)),onBlur:Ce(a.onBlur,()=>g(!1)),onPointerUp:Ce(a.onPointerUp,x),onPointerMove:Ce(a.onPointerMove,b=>{var y;s?(y=u.onItemLeave)==null||y.call(u):b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ce(a.onPointerLeave,b=>{var y;b.currentTarget===document.activeElement&&((y=u.onItemLeave)==null||y.call(u))}),onKeyDown:Ce(a.onKeyDown,b=>{var w;((w=u.searchRef)==null?void 0:w.current)!==""&&b.key===" "||(EQ.includes(b.key)&&x(),b.key===" "&&b.preventDefault())})})})})});FR.displayName=Tg;var xu="SelectItemText",LR=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,a=Aa(xu,n),c=Fa(xu,n),u=AR(xu,n),i=MQ(xu,n),[d,p]=v.useState(null),f=ct(t,b=>p(b),u.onItemTextChange,b=>{var y;return(y=c.itemTextRefCallback)==null?void 0:y.call(c,b,u.value,u.disabled)}),g=d==null?void 0:d.textContent,h=v.useMemo(()=>l.jsx("option",{value:u.value,disabled:u.disabled,children:g},u.value),[u.disabled,u.value,g]),{onNativeOptionAdd:m,onNativeOptionRemove:x}=i;return pn(()=>(m(h),()=>x(h)),[m,x,h]),l.jsxs(l.Fragment,{children:[l.jsx(Ie.span,{id:u.textId,...o,ref:f}),u.isSelected&&a.valueNode&&!a.valueNodeHasChildren?Pa.createPortal(o.children,a.valueNode):null]})});LR.displayName=xu;var $R="SelectItemIndicator",BR=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return AR($R,n).isSelected?l.jsx(Ie.span,{"aria-hidden":!0,...r,ref:t}):null});BR.displayName=$R;var xb="SelectScrollUpButton",zR=v.forwardRef((e,t)=>{const n=Fa(xb,e.__scopeSelect),r=Dw(xb,e.__scopeSelect),[s,o]=v.useState(!1),a=ct(t,r.onScrollButtonChange);return pn(()=>{if(n.viewport&&n.isPositioned){let c=function(){const i=u.scrollTop>0;o(i)};const u=n.viewport;return c(),u.addEventListener("scroll",c),()=>u.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),s?l.jsx(VR,{...e,ref:a,onAutoScroll:()=>{const{viewport:c,selectedItem:u}=n;c&&u&&(c.scrollTop=c.scrollTop-u.offsetHeight)}}):null});zR.displayName=xb;var wb="SelectScrollDownButton",UR=v.forwardRef((e,t)=>{const n=Fa(wb,e.__scopeSelect),r=Dw(wb,e.__scopeSelect),[s,o]=v.useState(!1),a=ct(t,r.onScrollButtonChange);return pn(()=>{if(n.viewport&&n.isPositioned){let c=function(){const i=u.scrollHeight-u.clientHeight,d=Math.ceil(u.scrollTop)u.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),s?l.jsx(VR,{...e,ref:a,onAutoScroll:()=>{const{viewport:c,selectedItem:u}=n;c&&u&&(c.scrollTop=c.scrollTop+u.offsetHeight)}}):null});UR.displayName=wb;var VR=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Fa("SelectScrollButton",n),a=v.useRef(null),c=Uh(n),u=v.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return v.useEffect(()=>()=>u(),[u]),pn(()=>{var d;const i=c().find(p=>p.ref.current===document.activeElement);(d=i==null?void 0:i.ref.current)==null||d.scrollIntoView({block:"nearest"})},[c]),l.jsx(Ie.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Ce(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(r,50))}),onPointerMove:Ce(s.onPointerMove,()=>{var i;(i=o.onItemLeave)==null||i.call(o),a.current===null&&(a.current=window.setInterval(r,50))}),onPointerLeave:Ce(s.onPointerLeave,()=>{u()})})}),$Q="SelectSeparator",HR=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return l.jsx(Ie.div,{"aria-hidden":!0,...r,ref:t})});HR.displayName=$Q;var Sb="SelectArrow",BQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Vh(n),o=Aa(Sb,n),a=Fa(Sb,n);return o.open&&a.position==="popper"?l.jsx(WM,{...s,...r,ref:t}):null});BQ.displayName=Sb;function KR(e){return e===""||e===void 0}var qR=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=v.useRef(null),o=ct(t,s),a=bR(n);return v.useEffect(()=>{const c=s.current,u=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(u,"value").set;if(a!==n&&d){const p=new Event("change",{bubbles:!0});d.call(c,n),c.dispatchEvent(p)}},[a,n]),l.jsx(xR,{asChild:!0,children:l.jsx("select",{...r,ref:o,defaultValue:n})})});qR.displayName="BubbleSelect";function WR(e){const t=on(e),n=v.useRef(""),r=v.useRef(0),s=v.useCallback(a=>{const c=n.current+a;t(c),function u(i){n.current=i,window.clearTimeout(r.current),i!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(c)},[t]),o=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function GR(e,t,n){const s=t.length>1&&Array.from(t).every(i=>i===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=zQ(e,Math.max(o,0));s.length===1&&(a=a.filter(i=>i!==n));const u=a.find(i=>i.textValue.toLowerCase().startsWith(s.toLowerCase()));return u!==n?u:void 0}function zQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var UQ=wR,JR=CR,VQ=kR,HQ=jR,KQ=TR,QR=MR,qQ=RR,ZR=DR,YR=FR,WQ=LR,GQ=BR,XR=zR,eO=UR,tO=HR;const JQ=UQ,QQ=VQ,nO=v.forwardRef(({className:e,children:t,...n},r)=>l.jsxs(JR,{ref:r,className:me("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-default disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,l.jsx(HQ,{asChild:!0,children:l.jsx(uh,{className:"h-4 w-4 opacity-50"})})]}));nO.displayName=JR.displayName;const rO=v.forwardRef(({className:e,...t},n)=>l.jsx(XR,{ref:n,className:me("flex cursor-default items-center justify-center py-1",e),...t,children:l.jsx(UB,{className:"h-4 w-4"})}));rO.displayName=XR.displayName;const sO=v.forwardRef(({className:e,...t},n)=>l.jsx(eO,{ref:n,className:me("flex cursor-default items-center justify-center py-1",e),...t,children:l.jsx(uh,{className:"h-4 w-4"})}));sO.displayName=eO.displayName;const oO=v.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>l.jsx(KQ,{children:l.jsxs(QR,{ref:s,className:me("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[l.jsx(rO,{}),l.jsx(qQ,{className:me("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),l.jsx(sO,{})]})}));oO.displayName=QR.displayName;const ZQ=v.forwardRef(({className:e,...t},n)=>l.jsx(ZR,{ref:n,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));ZQ.displayName=ZR.displayName;const aO=v.forwardRef(({className:e,children:t,...n},r)=>l.jsxs(YR,{ref:r,className:me("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[l.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:l.jsx(GQ,{children:l.jsx(mM,{className:"h-4 w-4"})})}),l.jsx(WQ,{children:t})]}));aO.displayName=YR.displayName;const YQ=v.forwardRef(({className:e,...t},n)=>l.jsx(tO,{ref:n,className:me("-mx-1 my-1 h-px bg-muted",e),...t}));YQ.displayName=tO.displayName;var Aw="Switch",[XQ,iae]=qr(Aw),[eZ,tZ]=XQ(Aw),iO=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:a,disabled:c,value:u="on",onCheckedChange:i,...d}=e,[p,f]=v.useState(null),g=ct(t,y=>f(y)),h=v.useRef(!1),m=p?!!p.closest("form"):!0,[x=!1,b]=ya({prop:s,defaultProp:o,onChange:i});return l.jsxs(eZ,{scope:n,checked:x,disabled:c,children:[l.jsx(Ie.button,{type:"button",role:"switch","aria-checked":x,"aria-required":a,"data-state":uO(x),"data-disabled":c?"":void 0,disabled:c,value:u,...d,ref:g,onClick:Ce(e.onClick,y=>{b(w=>!w),m&&(h.current=y.isPropagationStopped(),h.current||y.stopPropagation())})}),m&&l.jsx(nZ,{control:p,bubbles:!h.current,name:r,value:u,checked:x,required:a,disabled:c,style:{transform:"translateX(-100%)"}})]})});iO.displayName=Aw;var lO="SwitchThumb",cO=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=tZ(lO,n);return l.jsx(Ie.span,{"data-state":uO(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});cO.displayName=lO;var nZ=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=v.useRef(null),a=bR(n),c=IM(t);return v.useEffect(()=>{const u=o.current,i=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(i,"checked").set;if(a!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[a,n,r]),l.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function uO(e){return e?"checked":"unchecked"}var dO=iO,rZ=cO;const $c=v.forwardRef(({className:e,...t},n)=>l.jsx(dO,{className:me("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:l.jsx(rZ,{className:me("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));$c.displayName=dO.displayName;const La=Mn,fO=v.createContext({}),$a=({...e})=>l.jsx(fO.Provider,{value:{name:e.name},children:l.jsx(ZV,{...e})}),Hh=()=>{const e=v.useContext(fO),t=v.useContext(pO),{getFieldState:n,formState:r}=Ph(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},pO=v.createContext({}),Ro=v.forwardRef(({className:e,...t},n)=>{const r=v.useId();return l.jsx(pO.Provider,{value:{id:r},children:l.jsx("div",{ref:n,className:me("space-y-2",e),...t})})});Ro.displayName="FormItem";const Er=v.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=Hh();return l.jsx(yR,{ref:n,className:me(r&&"text-rose-600",e),htmlFor:s,...t})});Er.displayName="FormLabel";const qs=v.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=Hh();return l.jsx(wo,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});qs.displayName="FormControl";const Kh=v.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=Hh();return l.jsx("p",{ref:n,id:r,className:me("text-sm text-muted-foreground",e),...t})});Kh.displayName="FormDescription";const nf=v.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=Hh(),a=s?String(s==null?void 0:s.message):t;return a?l.jsx("p",{ref:r,id:o,className:me("text-sm font-medium text-rose-600",e),...n,children:a}):null});nf.displayName="FormMessage";const $=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...a})=>l.jsx($a,{...a,name:e,render:({field:c})=>l.jsxs(Ro,{className:o,children:[t&&l.jsxs(Er,{children:[t,r&&l.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),l.jsx(qs,{children:v.isValidElement(n)&&v.cloneElement(n,{...c,value:c.value??"",required:r,readOnly:s,checked:c.value,onCheckedChange:c.onChange})}),l.jsx(nf,{})]})}),ge=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...a})=>l.jsx($a,{...a,name:e,render:({field:c})=>l.jsxs(Ro,{className:me("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[l.jsx("div",{className:"flex flex-col gap-2",children:t&&l.jsxs(Er,{children:[l.jsxs("p",{className:"break-all",children:[t,n&&l.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&l.jsx(Kh,{className:"mt-2",children:s})]})}),l.jsx(qs,{children:l.jsx($c,{checked:c.value,onCheckedChange:c.onChange,required:n})}),l.jsx(nf,{})]})}),jt=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,disabled:a,...c})=>l.jsx($a,{...c,name:e,render:({field:u})=>l.jsxs(Ro,{children:[t&&l.jsxs(Er,{children:[t,r&&l.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),l.jsx(qs,{children:l.jsxs(JQ,{onValueChange:u.onChange,defaultValue:u.value,disabled:a,children:[l.jsx(qs,{children:l.jsx(nO,{children:l.jsx(QQ,{placeholder:o})})}),l.jsx(oO,{children:s.map(i=>l.jsx(aO,{value:i.value,children:i.label},i.value))})]})}),n&&l.jsx(Kh,{children:n}),l.jsx(nf,{})]})}),Ba=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>l.jsx($a,{...o,name:e,render:({field:a})=>{let c=[];return Array.isArray(a.value)&&(c=a.value),l.jsxs(Ro,{children:[t&&l.jsxs(Er,{children:[t,r&&l.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),l.jsx(qs,{children:l.jsx(bQ,{tags:c.map(u=>({id:u,text:u,className:""})),handleDelete:u=>a.onChange(c.filter((i,d)=>d!==u)),handleAddition:u=>a.onChange([...c,u.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[Os.ENTER,Os.TAB,Os.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:tP,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&l.jsx(Kh,{children:n}),l.jsx(nf,{})]})}}),vv=k.string().optional().transform(e=>e===""?void 0:e),sZ=k.object({name:k.string(),token:vv,number:vv,businessId:vv,integration:k.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","EVOLUTION"])});function oZ({resetTable:e}){const{t}=Te(),{createInstance:n}=Nh(),[r,s]=v.useState(!1),o=[{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")},{value:"EVOLUTION",label:t("instance.form.integration.evolution")}],a=zt({resolver:Ut(sZ),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:LC().replace("-","").toUpperCase(),number:"",businessId:""}}),c=a.watch("integration"),u=async d=>{var p,f,g;try{const h={instanceName:d.name,integration:d.integration,token:d.token===""?null:d.token,number:d.number===""?null:d.number,businessId:d.businessId===""?null:d.businessId};await n(h),G.success(t("toast.instance.created")),s(!1),i(),e()}catch(h){console.error("Error:",h),G.error(`Error : ${(g=(f=(p=h==null?void 0:h.response)==null?void 0:p.data)==null?void 0:f.response)==null?void 0:g.message}`)}},i=()=>{a.reset({name:"",integration:"WHATSAPP-BAILEYS",token:LC().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return l.jsxs(pt,{open:r,onOpenChange:s,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"default",size:"sm",children:[t("instance.button.create")," ",l.jsx(Ws,{size:"18"})]})}),l.jsxs(ut,{className:"sm:max-w-[650px]",onCloseAutoFocus:i,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("instance.modal.title")})}),l.jsx(Mn,{...a,children:l.jsxs("form",{onSubmit:a.handleSubmit(u),className:"grid gap-4 py-4",children:[l.jsx($,{required:!0,name:"name",label:t("instance.form.name"),children:l.jsx(F,{})}),l.jsx(jt,{name:"integration",label:t("instance.form.integration.label"),options:o}),l.jsx($,{required:!0,name:"token",label:t("instance.form.token"),children:l.jsx(F,{})}),l.jsx($,{name:"number",label:t("instance.form.number"),children:l.jsx(F,{type:"tel"})}),c==="WHATSAPP-BUSINESS"&&l.jsx($,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:l.jsx(F,{})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:t("instance.button.save")})})]})})]})]})}function aZ(){const{t:e}=Te(),[t,n]=v.useState(null),{deleteInstance:r,logout:s}=Nh(),{data:o,refetch:a}=$V(),[c,u]=v.useState([]),[i,d]=v.useState("all"),[p,f]=v.useState(""),g=async()=>{await a()},h=async b=>{var y,w,S;n(null),u([...c,b]);try{try{await s(b)}catch(E){console.error("Error logout:",E)}await r(b),await new Promise(E=>setTimeout(E,1e3)),g()}catch(E){console.error("Error instance delete:",E),G.error(`Error : ${(S=(w=(y=E==null?void 0:E.response)==null?void 0:y.data)==null?void 0:w.response)==null?void 0:S.message}`)}finally{u(c.filter(E=>E!==b))}},m=v.useMemo(()=>{let b=o?[...o]:[];return i!=="all"&&(b=b.filter(y=>y.connectionStatus===i)),p!==""&&(b=b.filter(y=>y.name.toLowerCase().includes(p.toLowerCase()))),b},[o,p,i]),x=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return l.jsxs("div",{className:"my-4 px-4",children:[l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(z,{variant:"outline",size:"icon",children:l.jsx(rg,{onClick:g,size:"20"})}),l.jsx(oZ,{resetTable:g})]})]}),l.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[l.jsx("div",{className:"flex-1",children:l.jsx(F,{placeholder:e("dashboard.search"),value:p,onChange:b=>f(b.target.value)})}),l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"secondary",children:[e("dashboard.status")," ",l.jsx(VB,{size:"15"})]})}),l.jsx(Mr,{children:x.map(b=>l.jsx(XN,{checked:i===b.value,onCheckedChange:y=>{y&&d(b.value)},children:b.label},b.value))})]})]}),l.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:m.length>0&&Array.isArray(o)&&o.map(b=>{var y,w;return l.jsxs(oi,{children:[l.jsx(ai,{children:l.jsxs(ld,{to:`/manager/instance/${b.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[l.jsx("h3",{className:"text-wrap font-semibold",children:b.name}),l.jsx(z,{variant:"ghost",size:"icon",children:l.jsx(To,{className:"card-icon",size:"20"})})]})}),l.jsxs(ii,{className:"flex-1 space-y-6",children:[l.jsx(X_,{token:b.token}),l.jsxs("div",{className:"flex w-full flex-wrap",children:[l.jsx("div",{className:"flex flex-1 gap-2",children:b.profileName&&l.jsxs(l.Fragment,{children:[l.jsx(Eh,{children:l.jsx(kh,{src:b.profilePicUrl,alt:""})}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("strong",{children:b.profileName}),l.jsx("p",{className:"text-sm text-muted-foreground",children:b.ownerJid&&b.ownerJid.split("@")[0]})]})]})}),l.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[l.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[l.jsx(vM,{className:"text-muted-foreground",size:"20"}),l.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((y=b==null?void 0:b._count)==null?void 0:y.Contact)||0)})]}),l.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[l.jsx(dh,{className:"text-muted-foreground",size:"20"}),l.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((w=b==null?void 0:b._count)==null?void 0:w.Message)||0)})]})]})]})]}),l.jsxs(Mh,{className:"justify-between",children:[l.jsx(Y_,{status:b.connectionStatus}),l.jsx(z,{variant:"destructive",size:"sm",onClick:()=>n(b.name),disabled:c.includes(b.name),children:c.includes(b.name)?l.jsx("span",{children:e("button.deleting")}):l.jsx("span",{children:e("button.delete")})})]})]},b.id)})}),!!t&&l.jsx(pt,{onOpenChange:()=>n(null),open:!0,children:l.jsxs(ut,{children:[l.jsx(__,{}),l.jsx(dt,{children:e("modal.delete.title")}),l.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),l.jsx(_t,{children:l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx(z,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),l.jsx(z,{onClick:()=>h(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:yc,createContext:iZ,createRef:lae,forwardRef:gO,useCallback:dr,useContext:hO,useEffect:Ci,useImperativeHandle:mO,useLayoutEffect:lZ,useMemo:cZ,useRef:nr,useState:Lu}=Dg,q1=Dg.useId,uZ=lZ,qh=iZ(null);qh.displayName="PanelGroupContext";const Ei=uZ,dZ=typeof q1=="function"?q1:()=>null;let fZ=0;function Fw(e=null){const t=dZ(),n=nr(e||t||null);return n.current===null&&(n.current=""+fZ++),e??n.current}function vO({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:a,maxSize:c,minSize:u,onCollapse:i,onExpand:d,onResize:p,order:f,style:g,tagName:h="div",...m}){const x=hO(qh);if(x===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:b,expandPanel:y,getPanelSize:w,getPanelStyle:S,groupId:E,isPanelCollapsed:C,reevaluatePanelConstraints:T,registerPanel:j,resizePanel:_,unregisterPanel:O}=x,K=Fw(a),I=nr({callbacks:{onCollapse:i,onExpand:d,onResize:p},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:c,minSize:u},id:K,idIsFromProps:a!==void 0,order:f});nr({didLogMissingDefaultSizeWarning:!1}),Ei(()=>{const{callbacks:q,constraints:Z}=I.current,ee={...Z};I.current.id=K,I.current.idIsFromProps=a!==void 0,I.current.order=f,q.onCollapse=i,q.onExpand=d,q.onResize=p,Z.collapsedSize=n,Z.collapsible=r,Z.defaultSize=s,Z.maxSize=c,Z.minSize=u,(ee.collapsedSize!==Z.collapsedSize||ee.collapsible!==Z.collapsible||ee.maxSize!==Z.maxSize||ee.minSize!==Z.minSize)&&T(I.current,ee)}),Ei(()=>{const q=I.current;return j(q),()=>{O(q)}},[f,K,j,O]),mO(o,()=>({collapse:()=>{b(I.current)},expand:q=>{y(I.current,q)},getId(){return K},getSize(){return w(I.current)},isCollapsed(){return C(I.current)},isExpanded(){return!C(I.current)},resize:q=>{_(I.current,q)}}),[b,y,w,C,K,_]);const Y=S(I.current,s);return yc(h,{...m,children:e,className:t,id:a,style:{...Y,...g},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":E,"data-panel-id":K,"data-panel-size":parseFloat(""+Y.flexGrow).toFixed(1)})}const yO=gO((e,t)=>yc(vO,{...e,forwardedRef:t}));vO.displayName="Panel";yO.displayName="forwardRef(Panel)";let Cb=null,ci=null;function pZ(e,t){if(t){const n=(t&CO)!==0,r=(t&EO)!==0,s=(t&kO)!==0,o=(t&jO)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function gZ(){ci!==null&&(document.head.removeChild(ci),Cb=null,ci=null)}function yv(e,t){const n=pZ(e,t);Cb!==n&&(Cb=n,ci===null&&(ci=document.createElement("style"),document.head.appendChild(ci)),ci.innerHTML=`*{cursor: ${n}!important;}`)}function bO(e){return e.type==="keydown"}function xO(e){return e.type.startsWith("pointer")}function wO(e){return e.type.startsWith("mouse")}function Wh(e){if(xO(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(wO(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function hZ(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function mZ(e,t,n){return e.xt.x&&e.yt.y}function vZ(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:J1(e),b:J1(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;st(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:G1(W1(n.a)),b:G1(W1(n.b))};if(s.a===s.b){const o=r.childNodes,a={a:n.a.at(-1),b:n.b.at(-1)};let c=o.length;for(;c--;){const u=o[c];if(u===a.a)return 1;if(u===a.b)return-1}}return Math.sign(s.a-s.b)}const yZ=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function bZ(e){var t;const n=getComputedStyle((t=SO(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function xZ(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||bZ(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||yZ.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function W1(e){let t=e.length;for(;t--;){const n=e[t];if(st(n,"Missing node"),xZ(n))return n}return null}function G1(e){return e&&Number(getComputedStyle(e).zIndex)||0}function J1(e){const t=[];for(;e;)t.push(e),e=SO(e);return t}function SO(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const CO=1,EO=2,kO=4,jO=8,wZ=hZ()==="coarse";let cs=[],Od=!1,Jo=new Map,Gh=new Map;const Id=new Set;function SZ(e,t,n,r,s){var o;const{ownerDocument:a}=t,c={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},u=(o=Jo.get(a))!==null&&o!==void 0?o:0;return Jo.set(a,u+1),Id.add(c),Mg(),function(){var d;Gh.delete(e),Id.delete(c);const p=(d=Jo.get(a))!==null&&d!==void 0?d:1;if(Jo.set(a,p-1),Mg(),p===1&&Jo.delete(a),cs.includes(c)){const f=cs.indexOf(c);f>=0&&cs.splice(f,1),$w()}}}function Q1(e){const{target:t}=e,{x:n,y:r}=Wh(e);Od=!0,Lw({target:t,x:n,y:r}),Mg(),cs.length>0&&(Ng("down",e),e.preventDefault(),e.stopPropagation())}function lu(e){const{x:t,y:n}=Wh(e);if(e.buttons===0&&(Od=!1,Ng("up",e)),!Od){const{target:r}=e;Lw({target:r,x:t,y:n})}Ng("move",e),$w(),cs.length>0&&e.preventDefault()}function cl(e){const{target:t}=e,{x:n,y:r}=Wh(e);Gh.clear(),Od=!1,cs.length>0&&e.preventDefault(),Ng("up",e),Lw({target:t,x:n,y:r}),$w(),Mg()}function Lw({target:e,x:t,y:n}){cs.splice(0);let r=null;e instanceof HTMLElement&&(r=e),Id.forEach(s=>{const{element:o,hitAreaMargins:a}=s,c=o.getBoundingClientRect(),{bottom:u,left:i,right:d,top:p}=c,f=wZ?a.coarse:a.fine;if(t>=i-f&&t<=d+f&&n>=p-f&&n<=u+f){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&vZ(r,o)>0){let h=r,m=!1;for(;h&&!h.contains(o);){if(mZ(h.getBoundingClientRect(),c)){m=!0;break}h=h.parentElement}if(m)return}cs.push(s)}})}function bv(e,t){Gh.set(e,t)}function $w(){let e=!1,t=!1;cs.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;Gh.forEach(r=>{n|=r}),e&&t?yv("intersection",n):e?yv("horizontal",n):t?yv("vertical",n):gZ()}function Mg(){Jo.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",cl),n.removeEventListener("pointerdown",Q1),n.removeEventListener("pointerleave",lu),n.removeEventListener("pointermove",lu)}),window.removeEventListener("pointerup",cl),window.removeEventListener("pointercancel",cl),Id.size>0&&(Od?(cs.length>0&&Jo.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",cl),n.addEventListener("pointerleave",lu),n.addEventListener("pointermove",lu))}),window.addEventListener("pointerup",cl),window.addEventListener("pointercancel",cl)):Jo.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",Q1,{capture:!0}),n.addEventListener("pointermove",lu))}))}function Ng(e,t){Id.forEach(n=>{const{setResizeHandlerState:r}=n,s=cs.includes(n);r(e,s,t)})}function st(e,t){if(!e)throw console.error(t),Error(t)}const Bw=10;function $i(e,t,n=Bw){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function io(e,t,n=Bw){return $i(e,t,n)===0}function hr(e,t,n){return $i(e,t,n)===0}function CZ(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-b:b)}}}{const p=e<0?c:u,f=n[p];st(f,`No panel constraints found for index ${p}`);const{collapsedSize:g=0,collapsible:h,minSize:m=0}=f;if(h){const x=t[p];if(st(x!=null,`Previous layout not found for panel index ${p}`),hr(x,m)){const b=x-g;$i(b,Math.abs(e))>0&&(e=e<0?0-b:b)}}}}{const p=e<0?1:-1;let f=e<0?u:c,g=0;for(;;){const m=t[f];st(m!=null,`Previous layout not found for panel index ${f}`);const b=_l({panelConstraints:n,panelIndex:f,size:100})-m;if(g+=b,f+=p,f<0||f>=n.length)break}const h=Math.min(Math.abs(e),Math.abs(g));e=e<0?0-h:h}{let f=e<0?c:u;for(;f>=0&&f=0))break;e<0?f--:f++}}if(CZ(s,a))return s;{const p=e<0?u:c,f=t[p];st(f!=null,`Previous layout not found for panel index ${p}`);const g=f+i,h=_l({panelConstraints:n,panelIndex:p,size:g});if(a[p]=h,!hr(h,g)){let m=g-h,b=e<0?u:c;for(;b>=0&&b0?b--:b++}}}const d=a.reduce((p,f)=>f+p,0);return hr(d,100)?a:s}function EZ({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,a=0;const c=n[0];st(c!=null,"No pivot index found"),t.forEach((p,f)=>{const{constraints:g}=p,{maxSize:h=100,minSize:m=0}=g;f===c?(r=m,s=h):(o+=m,a+=h)});const u=Math.min(s,100-o),i=Math.max(r,100-a),d=e[c];return{valueMax:u,valueMin:i,valueNow:d}}function Dd(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function TO(e,t,n=document){const s=Dd(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function MO(e,t,n){const r=TO(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function NO(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function Jh(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function kZ(e,t,n,r=document){var s,o,a,c;const u=Jh(t,r),i=Dd(e,r),d=u?i.indexOf(u):-1,p=(s=(o=n[d])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,f=(a=(c=n[d+1])===null||c===void 0?void 0:c.id)!==null&&a!==void 0?a:null;return[p,f]}function jZ({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:a}){nr({didWarnAboutMissingResizeHandle:!1}),Ei(()=>{if(!o)return;const c=Dd(n,o);for(let u=0;u{c.forEach((u,i)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,r,s,o]),Ci(()=>{if(!o)return;const c=t.current;st(c,"Eager values not found");const{panelDataArray:u}=c,i=NO(n,o);st(i!=null,`No group found for id "${n}"`);const d=Dd(n,o);st(d,`No resize handles found for group id "${n}"`);const p=d.map(f=>{const g=f.getAttribute("data-panel-resize-handle-id");st(g,"Resize handle element has no handle id attribute");const[h,m]=kZ(n,g,u,o);if(h==null||m==null)return()=>{};const x=b=>{if(!b.defaultPrevented)switch(b.key){case"Enter":{b.preventDefault();const y=u.findIndex(w=>w.id===h);if(y>=0){const w=u[y];st(w,`No panel data found for index ${y}`);const S=r[y],{collapsedSize:E=0,collapsible:C,minSize:T=0}=w.constraints;if(S!=null&&C){const j=wu({delta:hr(S,E)?T-E:E-S,initialLayout:r,panelConstraints:u.map(_=>_.constraints),pivotIndices:MO(n,g,o),prevLayout:r,trigger:"keyboard"});r!==j&&a(j)}}break}}};return f.addEventListener("keydown",x),()=>{f.removeEventListener("keydown",x)}});return()=>{p.forEach(f=>f())}},[o,e,t,n,r,s,a])}function Z1(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];st(o,`Panel data not found for index ${s}`);const{callbacks:a,constraints:c,id:u}=o,{collapsedSize:i=0,collapsible:d}=c,p=n[u];if(p==null||r!==p){n[u]=r;const{onCollapse:f,onExpand:g,onResize:h}=a;h&&h(r,p),d&&(f||g)&&(g&&(p==null||io(p,i))&&!io(r,i)&&g(),f&&(p==null||!io(p,i))&&io(r,i)&&f())}})}function Hf(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function Y1(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function PO(e){return`react-resizable-panels:${e}`}function RO(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function OO(e,t){try{const n=PO(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function RZ(e,t,n){var r,s;const o=(r=OO(e,n))!==null&&r!==void 0?r:{},a=RO(t);return(s=o[a])!==null&&s!==void 0?s:null}function OZ(e,t,n,r,s){var o;const a=PO(e),c=RO(t),u=(o=OO(e,s))!==null&&o!==void 0?o:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(a,JSON.stringify(u))}catch(i){console.error(i)}}function X1({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,a)=>o+a,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!hr(r,100))for(let o=0;o(Y1(Su),Su.getItem(e)),setItem:(e,t)=>{Y1(Su),Su.setItem(e,t)}},eE={};function IO({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:a=null,keyboardResizeBy:c=null,storage:u=Su,style:i,tagName:d="div",...p}){const f=Fw(o),g=nr(null),[h,m]=Lu(null),[x,b]=Lu([]),y=nr({}),w=nr(new Map),S=nr(0),E=nr({autoSaveId:e,direction:r,dragState:h,id:f,keyboardResizeBy:c,onLayout:a,storage:u}),C=nr({layout:x,panelDataArray:[],panelDataArrayChanged:!1});nr({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),mO(s,()=>({getId:()=>E.current.id,getLayout:()=>{const{layout:H}=C.current;return H},setLayout:H=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:le}=C.current,oe=X1({layout:H,panelConstraints:le.map(Q=>Q.constraints)});Z1(ne,oe)||(b(oe),C.current.layout=oe,se&&se(oe),ul(le,oe,y.current))}}),[]),Ei(()=>{E.current.autoSaveId=e,E.current.direction=r,E.current.dragState=h,E.current.id=f,E.current.onLayout=a,E.current.storage=u}),jZ({committedValuesRef:E,eagerValuesRef:C,groupId:f,layout:x,panelDataArray:C.current.panelDataArray,setLayout:b,panelGroupElement:g.current}),Ci(()=>{const{panelDataArray:H}=C.current;if(e){if(x.length===0||x.length!==H.length)return;let se=eE[e];se==null&&(se=PZ(OZ,IZ),eE[e]=se);const ne=[...H],le=new Map(w.current);se(e,ne,le,x,u)}},[e,x,u]),Ci(()=>{});const T=dr(H=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:le}=C.current;if(H.constraints.collapsible){const oe=le.map(Be=>Be.constraints),{collapsedSize:Q=0,panelSize:Ee,pivotIndices:Pe}=Wa(le,H,ne);if(st(Ee!=null,`Panel size not found for panel "${H.id}"`),!io(Ee,Q)){w.current.set(H.id,Ee);const Re=gl(le,H)===le.length-1?Ee-Q:Q-Ee,ve=wu({delta:Re,initialLayout:ne,panelConstraints:oe,pivotIndices:Pe,prevLayout:ne,trigger:"imperative-api"});Hf(ne,ve)||(b(ve),C.current.layout=ve,se&&se(ve),ul(le,ve,y.current))}}},[]),j=dr((H,se)=>{const{onLayout:ne}=E.current,{layout:le,panelDataArray:oe}=C.current;if(H.constraints.collapsible){const Q=oe.map(ot=>ot.constraints),{collapsedSize:Ee=0,panelSize:Pe=0,minSize:Be=0,pivotIndices:Re}=Wa(oe,H,le),ve=se??Be;if(io(Pe,Ee)){const ot=w.current.get(H.id),Vt=ot!=null&&ot>=ve?ot:ve,Xt=gl(oe,H)===oe.length-1?Pe-Vt:Vt-Pe,ln=wu({delta:Xt,initialLayout:le,panelConstraints:Q,pivotIndices:Re,prevLayout:le,trigger:"imperative-api"});Hf(le,ln)||(b(ln),C.current.layout=ln,ne&&ne(ln),ul(oe,ln,y.current))}}},[]),_=dr(H=>{const{layout:se,panelDataArray:ne}=C.current,{panelSize:le}=Wa(ne,H,se);return st(le!=null,`Panel size not found for panel "${H.id}"`),le},[]),O=dr((H,se)=>{const{panelDataArray:ne}=C.current,le=gl(ne,H);return _Z({defaultSize:se,dragState:h,layout:x,panelData:ne,panelIndex:le})},[h,x]),K=dr(H=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:le=0,collapsible:oe,panelSize:Q}=Wa(ne,H,se);return st(Q!=null,`Panel size not found for panel "${H.id}"`),oe===!0&&io(Q,le)},[]),I=dr(H=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:le=0,collapsible:oe,panelSize:Q}=Wa(ne,H,se);return st(Q!=null,`Panel size not found for panel "${H.id}"`),!oe||$i(Q,le)>0},[]),Y=dr(H=>{const{panelDataArray:se}=C.current;se.push(H),se.sort((ne,le)=>{const oe=ne.order,Q=le.order;return oe==null&&Q==null?0:oe==null?-1:Q==null?1:oe-Q}),C.current.panelDataArrayChanged=!0},[]);Ei(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:H,onLayout:se,storage:ne}=E.current,{layout:le,panelDataArray:oe}=C.current;let Q=null;if(H){const Pe=RZ(H,oe,ne);Pe&&(w.current=new Map(Object.entries(Pe.expandToSizes)),Q=Pe.layout)}Q==null&&(Q=NZ({panelDataArray:oe}));const Ee=X1({layout:Q,panelConstraints:oe.map(Pe=>Pe.constraints)});Z1(le,Ee)||(b(Ee),C.current.layout=Ee,se&&se(Ee),ul(oe,Ee,y.current))}}),Ei(()=>{const H=C.current;return()=>{H.layout=[]}},[]);const q=dr(H=>function(ne){ne.preventDefault();const le=g.current;if(!le)return()=>null;const{direction:oe,dragState:Q,id:Ee,keyboardResizeBy:Pe,onLayout:Be}=E.current,{layout:Re,panelDataArray:ve}=C.current,{initialLayout:ot}=Q??{},Vt=MO(Ee,H,le);let tn=MZ(ne,H,oe,Q,Pe,le);const Xt=oe==="horizontal";document.dir==="rtl"&&Xt&&(tn=-tn);const ln=ve.map(V=>V.constraints),M=wu({delta:tn,initialLayout:ot??Re,panelConstraints:ln,pivotIndices:Vt,prevLayout:Re,trigger:bO(ne)?"keyboard":"mouse-or-touch"}),D=!Hf(Re,M);(xO(ne)||wO(ne))&&S.current!=tn&&(S.current=tn,D?bv(H,0):Xt?bv(H,tn<0?CO:EO):bv(H,tn<0?kO:jO)),D&&(b(M),C.current.layout=M,Be&&Be(M),ul(ve,M,y.current))},[]),Z=dr((H,se)=>{const{onLayout:ne}=E.current,{layout:le,panelDataArray:oe}=C.current,Q=oe.map(ot=>ot.constraints),{panelSize:Ee,pivotIndices:Pe}=Wa(oe,H,le);st(Ee!=null,`Panel size not found for panel "${H.id}"`);const Re=gl(oe,H)===oe.length-1?Ee-se:se-Ee,ve=wu({delta:Re,initialLayout:le,panelConstraints:Q,pivotIndices:Pe,prevLayout:le,trigger:"imperative-api"});Hf(le,ve)||(b(ve),C.current.layout=ve,ne&&ne(ve),ul(oe,ve,y.current))},[]),ee=dr((H,se)=>{const{layout:ne,panelDataArray:le}=C.current,{collapsedSize:oe=0,collapsible:Q}=se,{collapsedSize:Ee=0,collapsible:Pe,maxSize:Be=100,minSize:Re=0}=H.constraints,{panelSize:ve}=Wa(le,H,ne);ve!=null&&(Q&&Pe&&io(ve,oe)?io(oe,Ee)||Z(H,Ee):veBe&&Z(H,Be))},[Z]),J=dr((H,se)=>{const{direction:ne}=E.current,{layout:le}=C.current;if(!g.current)return;const oe=Jh(H,g.current);st(oe,`Drag handle element not found for id "${H}"`);const Q=_O(ne,se);m({dragHandleId:H,dragHandleRect:oe.getBoundingClientRect(),initialCursorPosition:Q,initialLayout:le})},[]),L=dr(()=>{m(null)},[]),A=dr(H=>{const{panelDataArray:se}=C.current,ne=gl(se,H);ne>=0&&(se.splice(ne,1),delete y.current[H.id],C.current.panelDataArrayChanged=!0)},[]),X=cZ(()=>({collapsePanel:T,direction:r,dragState:h,expandPanel:j,getPanelSize:_,getPanelStyle:O,groupId:f,isPanelCollapsed:K,isPanelExpanded:I,reevaluatePanelConstraints:ee,registerPanel:Y,registerResizeHandle:q,resizePanel:Z,startDragging:J,stopDragging:L,unregisterPanel:A,panelGroupElement:g.current}),[T,h,r,j,_,O,f,K,I,ee,Y,q,Z,J,L,A]),fe={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return yc(qh.Provider,{value:X},yc(d,{...p,children:t,className:n,id:o,ref:g,style:{...fe,...i},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":f}))}const DO=gO((e,t)=>yc(IO,{...e,forwardedRef:t}));IO.displayName="PanelGroup";DO.displayName="forwardRef(PanelGroup)";function gl(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Wa(e,t,n){const r=gl(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:o}}function DZ({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){Ci(()=>{if(e||n==null||r==null)return;const s=Jh(t,r);if(s==null)return;const o=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),n(a);break}case"F6":{a.preventDefault();const c=s.getAttribute("data-panel-group-id");st(c,`No group element found for id "${c}"`);const u=Dd(c,r),i=TO(c,t,r);st(i!==null,`No resize element found for id "${t}"`);const d=a.shiftKey?i>0?i-1:u.length-1:i+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function AO({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:a,onFocus:c,style:u={},tabIndex:i=0,tagName:d="div",...p}){var f,g;const h=nr(null),m=nr({onDragging:a});Ci(()=>{m.current.onDragging=a});const x=hO(qh);if(x===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:b,groupId:y,registerResizeHandle:w,startDragging:S,stopDragging:E,panelGroupElement:C}=x,T=Fw(s),[j,_]=Lu("inactive"),[O,K]=Lu(!1),[I,Y]=Lu(null),q=nr({state:j});Ei(()=>{q.current.state=j}),Ci(()=>{if(n)Y(null);else{const L=w(T);Y(()=>L)}},[n,T,w]);const Z=(f=r==null?void 0:r.coarse)!==null&&f!==void 0?f:15,ee=(g=r==null?void 0:r.fine)!==null&&g!==void 0?g:5;return Ci(()=>{if(n||I==null)return;const L=h.current;return st(L,"Element ref not attached"),SZ(T,L,b,{coarse:Z,fine:ee},(X,fe,H)=>{if(fe)switch(X){case"down":{_("drag"),S(T,H);const{onDragging:se}=m.current;se&&se(!0);break}case"move":{const{state:se}=q.current;se!=="drag"&&_("hover"),I(H);break}case"up":{_("hover"),E();const{onDragging:se}=m.current;se&&se(!1);break}}else _("inactive")})},[Z,b,n,ee,w,T,I,S,E]),DZ({disabled:n,handleId:T,resizeHandler:I,panelGroupElement:C}),yc(d,{...p,children:e,className:t,id:s,onBlur:()=>{K(!1),o==null||o()},onFocus:()=>{K(!0),c==null||c()},ref:h,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...u},tabIndex:i,"data-panel-group-direction":b,"data-panel-group-id":y,"data-resize-handle":"","data-resize-handle-active":j==="drag"?"pointer":O?"keyboard":void 0,"data-resize-handle-state":j,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":T})}AO.displayName="PanelResizeHandle";const za=({className:e,...t})=>l.jsx(DO,{className:me("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),Bn=yO,Ua=({withHandle:e,className:t,...n})=>l.jsx(AO,{className:me("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&l.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:l.jsx(ZB,{className:"h-2.5 w-2.5"})})});var zw="Tabs",[AZ,cae]=qr(zw,[bh]),FO=bh(),[FZ,Uw]=AZ(zw),LO=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:a="horizontal",dir:c,activationMode:u="automatic",...i}=e,d=Jd(c),[p,f]=ya({prop:r,onChange:s,defaultProp:o});return l.jsx(FZ,{scope:n,baseId:is(),value:p,onValueChange:f,orientation:a,dir:d,activationMode:u,children:l.jsx(Ie.div,{dir:d,"data-orientation":a,...i,ref:t})})});LO.displayName=zw;var $O="TabsList",BO=v.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=Uw($O,n),a=FO(n);return l.jsx(XM,{asChild:!0,...a,orientation:o.orientation,dir:o.dir,loop:r,children:l.jsx(Ie.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});BO.displayName=$O;var zO="TabsTrigger",UO=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,a=Uw(zO,n),c=FO(n),u=KO(a.baseId,r),i=qO(a.baseId,r),d=r===a.value;return l.jsx(eN,{asChild:!0,...c,focusable:!s,active:d,children:l.jsx(Ie.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":i,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:u,...o,ref:t,onMouseDown:Ce(e.onMouseDown,p=>{!s&&p.button===0&&p.ctrlKey===!1?a.onValueChange(r):p.preventDefault()}),onKeyDown:Ce(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&a.onValueChange(r)}),onFocus:Ce(e.onFocus,()=>{const p=a.activationMode!=="manual";!d&&!s&&p&&a.onValueChange(r)})})})});UO.displayName=zO;var VO="TabsContent",HO=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...a}=e,c=Uw(VO,n),u=KO(c.baseId,r),i=qO(c.baseId,r),d=r===c.value,p=v.useRef(d);return v.useEffect(()=>{const f=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(f)},[]),l.jsx(cr,{present:s||d,children:({present:f})=>l.jsx(Ie.div,{"data-state":d?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":u,hidden:!f,id:i,tabIndex:0,...a,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:f&&o})})});HO.displayName=VO;function KO(e,t){return`${e}-trigger-${t}`}function qO(e,t){return`${e}-content-${t}`}var LZ=LO,WO=BO,GO=UO,JO=HO;const $Z=LZ,QO=v.forwardRef(({className:e,...t},n)=>l.jsx(WO,{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));QO.displayName=WO.displayName;const Eb=v.forwardRef(({className:e,...t},n)=>l.jsx(GO,{ref:n,className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));Eb.displayName=GO.displayName;const kb=v.forwardRef(({className:e,...t},n)=>l.jsx(JO,{ref:n,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));kb.displayName=JO.displayName;const BZ=e=>["chats","findChats",JSON.stringify(e)],zZ=async({instanceName:e})=>(await ie.post(`/chat/findChats/${e}`,{where:{}})).data,UZ=e=>{const{instanceName:t,...n}=e;return qe({...n,queryKey:BZ({instanceName:t}),queryFn:()=>zZ({instanceName:t}),enabled:!!t})};function Va(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=v.useState(t(e));function s(){r(t(e))}return v.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const Vl=v.forwardRef(({className:e,...t},n)=>l.jsx("textarea",{className:me("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Vl.displayName="Textarea";const VZ=e=>["chats","findChats",JSON.stringify(e)],HZ=async({instanceName:e,remoteJid:t})=>{const n=await ie.post(`/chat/findChats/${e}`,{where:{remoteJid:t}});return Array.isArray(n.data)?n.data[0]:n.data},KZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return qe({...r,queryKey:VZ({instanceName:t,remoteJid:n}),queryFn:()=>HZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})},qZ=e=>["chats","findMessages",JSON.stringify(e)],WZ=async({instanceName:e,remoteJid:t})=>{var r,s;const n=await ie.post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}});return(s=(r=n.data)==null?void 0:r.messages)!=null&&s.records?n.data.messages.records:n.data},GZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return qe({...r,queryKey:qZ({instanceName:t,remoteJid:n}),queryFn:()=>WZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})};function JZ({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=Ve(),{remoteJid:a}=gs(),{data:c}=KZ({remoteJid:a,instanceName:o==null?void 0:o.name}),{data:u,isSuccess:i}=GZ({remoteJid:a,instanceName:o==null?void 0:o.name});v.useEffect(()=>{i&&u&&s()},[i,u,s]);const d=f=>l.jsx("div",{className:"bubble-right",children:l.jsx("div",{className:"flex items-start gap-4 self-end",children:l.jsx("div",{className:"grid gap-1",children:l.jsx("div",{className:"prose text-muted-foreground",children:l.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})}),p=f=>l.jsx("div",{className:"bubble-left",children:l.jsx("div",{className:"flex items-start gap-4",children:l.jsx("div",{className:"grid gap-1",children:l.jsx("div",{className:"prose text-muted-foreground",children:l.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})});return l.jsxs("div",{className:"flex min-h-screen flex-col",children:[l.jsx("div",{className:"sticky top-0 p-2",children:l.jsxs(iw,{children:[l.jsx(lw,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-10 gap-1 rounded-xl px-3 text-lg data-[state=open]:bg-muted",children:[(c==null?void 0:c.pushName)||(c==null?void 0:c.remoteJid.split("@")[0]),l.jsx(uh,{className:"h-4 w-4 text-muted-foreground"})]})}),l.jsxs(Mr,{align:"start",className:"max-w-[300px]",children:[l.jsxs(tt,{className:"items-start gap-2",children:[l.jsx(o3,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),l.jsxs("div",{children:[l.jsx("div",{className:"font-medium",children:"GPT-4"}),l.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),l.jsx(Gs,{}),l.jsxs(tt,{className:"items-start gap-2",children:[l.jsx(yM,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),l.jsxs("div",{children:[l.jsx("div",{className:"font-medium",children:"GPT-3"}),l.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),l.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-8 overflow-y-auto px-4",children:[u==null?void 0:u.map(f=>f.key.fromMe?d(f):p(f)),l.jsx("div",{ref:r})]}),l.jsx("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-4 py-2",children:l.jsxs("div",{className:"input-message relative",children:[l.jsxs(z,{type:"button",size:"icon",className:"absolute bottom-3 left-3 h-8 w-8 rounded-full bg-transparent text-white hover:bg-transparent",children:[l.jsx(s3,{className:"h-4 w-4 text-white"}),l.jsx("span",{className:"sr-only",children:"Anexar"})]}),l.jsx(Vl,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"max-h-[240px] min-h-[48px] resize-none rounded-3xl border border-none p-4 pl-12 pr-16 shadow-sm"}),l.jsxs(z,{type:"submit",size:"icon",className:"absolute bottom-3 right-3 h-8 w-8 rounded-full",children:[l.jsx(BB,{className:"h-4 w-4"}),l.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}function tE(){const e=Va("(min-width: 768px)"),t=v.useRef(null),[n]=v.useState("auto"),r=v.useRef(null),{instance:s}=Ve(),{data:o,isSuccess:a}=UZ({instanceName:s==null?void 0:s.name}),{instanceId:c,remoteJid:u}=gs(),i=an(),d=v.useCallback(()=>{t.current&&t.current.scrollIntoView({})},[]),p=()=>{if(r.current){r.current.style.height="auto";const g=r.current.scrollHeight,m=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(g,m)}px`}};v.useEffect(()=>{a&&d()},[a,d]);const f=g=>{i(`/manager/instance/${c}/chat/${g}`)};return l.jsxs(za,{direction:e?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:20,children:l.jsxs("div",{className:"hidden flex-col gap-2 bg-background text-foreground md:flex",children:[l.jsx("div",{className:"sticky top-0 p-2",children:l.jsxs(z,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:l.jsx(dh,{className:"h-4 w-4"})}),l.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),l.jsx(Ws,{className:"h-4 w-4"})]})}),l.jsxs($Z,{defaultValue:"contacts",children:[l.jsxs(QO,{className:"tabs-chat",children:[l.jsx(Eb,{value:"contacts",children:"Contatos"}),l.jsx(Eb,{value:"groups",children:"Grupos"})]}),l.jsx(kb,{value:"contacts",children:l.jsx("div",{className:"flex-1 overflow-auto",children:l.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[l.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),o==null?void 0:o.map(g=>g.remoteJid.includes("@s.whatsapp.net")&&l.jsxs(ld,{to:"#",onClick:()=>f(g.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${u===g.remoteJid?"active":""}`,children:[l.jsx("span",{className:"chat-avatar mr-2",children:l.jsx("img",{src:g.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("span",{className:"chat-title block font-medium",children:g.pushName}),l.jsx("span",{className:"chat-description block text-xs text-gray-500",children:g.remoteJid.split("@")[0]})]})]},g.id))]})})}),l.jsx(kb,{value:"groups",children:l.jsx("div",{className:"flex-1 overflow-auto",children:l.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:o==null?void 0:o.map(g=>g.remoteJid.includes("@g.us")&&l.jsxs(ld,{to:"#",onClick:()=>f(g.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${u===g.remoteJid?"active":""}`,children:[l.jsx("span",{className:"chat-avatar mr-2",children:l.jsx("img",{src:g.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("span",{className:"chat-title block font-medium",children:g.pushName}),l.jsx("span",{className:"chat-description block text-xs text-gray-500",children:g.remoteJid})]})]},g.id))})})})]})]})}),l.jsx(Ua,{withHandle:!0,className:"border border-black"}),l.jsx(Bn,{children:u&&l.jsx(JZ,{textareaRef:r,handleTextareaChange:p,textareaHeight:n,lastMessageRef:t,scrollToBottom:d})})]})}const QZ=e=>["chatwoot","fetchChatwoot",JSON.stringify(e)],ZZ=async({instanceName:e,token:t})=>(await ie.get(`/chatwoot/find/${e}`,{headers:{apiKey:t}})).data,YZ=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:QZ({instanceName:t,token:n}),queryFn:()=>ZZ({instanceName:t,token:n}),enabled:!!t})},XZ=async({instanceName:e,token:t,data:n})=>(await ie.post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data;function eY(){return{createChatwoot:Le(XZ,{invalidateKeys:[["chatwoot","fetchChatwoot"]]})}}const Kf=k.string().optional().transform(e=>e===""?void 0:e),tY=k.object({enabled:k.boolean(),accountId:k.string(),token:k.string(),url:k.string(),signMsg:k.boolean().optional(),signDelimiter:Kf,nameInbox:Kf,organization:Kf,logo:Kf,reopenConversation:k.boolean().optional(),conversationPending:k.boolean().optional(),mergeBrazilContacts:k.boolean().optional(),importContacts:k.boolean().optional(),importMessages:k.boolean().optional(),daysLimitImportMessages:k.coerce.number().optional(),autoCreate:k.boolean(),ignoreJids:k.array(k.string()).default([])});function nY(){const{t:e}=Te(),{instance:t}=Ve(),[,n]=v.useState(!1),{createChatwoot:r}=eY(),{data:s}=YZ({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),o=zt({resolver:Ut(tY),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});v.useEffect(()=>{if(s){o.setValue("ignoreJids",s.ignoreJids||[]);const c={enabled:s.enabled,accountId:s.accountId,token:s.token,url:s.url,signMsg:s.signMsg||!1,signDelimiter:s.signDelimiter||"\\n",nameInbox:s.nameInbox||"",organization:s.organization||"",logo:s.logo||"",reopenConversation:s.reopenConversation||!1,conversationPending:s.conversationPending||!1,mergeBrazilContacts:s.mergeBrazilContacts||!1,importContacts:s.importContacts||!1,importMessages:s.importMessages||!1,daysLimitImportMessages:s.daysLimitImportMessages||7,autoCreate:s.autoCreate||!1,ignoreJids:s.ignoreJids};o.reset(c)}},[s,o]);const a=async c=>{if(!t)return;n(!0);const u={enabled:c.enabled,accountId:c.accountId,token:c.token,url:c.url,signMsg:c.signMsg||!1,signDelimiter:c.signDelimiter||"\\n",nameInbox:c.nameInbox||"",organization:c.organization||"",logo:c.logo||"",reopenConversation:c.reopenConversation||!1,conversationPending:c.conversationPending||!1,mergeBrazilContacts:c.mergeBrazilContacts||!1,importContacts:c.importContacts||!1,importMessages:c.importMessages||!1,daysLimitImportMessages:c.daysLimitImportMessages||7,autoCreate:c.autoCreate,ignoreJids:c.ignoreJids};await r({instanceName:t.name,token:t.token,data:u},{onSuccess:()=>{G.success(e("chatwoot.toast.success"))},onError:i=>{var d,p,f;console.error(e("chatwoot.toast.error"),i),G4(i)?G.error(`Error: ${(f=(p=(d=i==null?void 0:i.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`):G.error(e("chatwoot.toast.error"))},onSettled:()=>{n(!1)}})};return l.jsx(l.Fragment,{children:l.jsx(La,{...o,children:l.jsxs("form",{onSubmit:o.handleSubmit(a),className:"w-full space-y-6",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),l.jsx(Da,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[l.jsx(ge,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),l.jsx($,{name:"url",label:e("chatwoot.form.url.label"),children:l.jsx(F,{})}),l.jsx($,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:l.jsx(F,{})}),l.jsx($,{name:"token",label:e("chatwoot.form.token.label"),children:l.jsx(F,{type:"password"})}),l.jsx(ge,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),l.jsx($,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:l.jsx(F,{})}),l.jsx($,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:l.jsx(F,{})}),l.jsx($,{name:"organization",label:e("chatwoot.form.organization.label"),children:l.jsx(F,{})}),l.jsx($,{name:"logo",label:e("chatwoot.form.logo.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),l.jsx(ge,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),l.jsx(ge,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),l.jsx(ge,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),l.jsx($,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),l.jsx(ge,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),l.jsx("div",{className:"mx-4 flex justify-end",children:l.jsx(z,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var Qh={},ZO={exports:{}},rY="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",sY=rY,oY=sY;function YO(){}function XO(){}XO.resetWarningCache=YO;var aY=function(){function e(r,s,o,a,c,u){if(u!==oY){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:XO,resetWarningCache:YO};return n.PropTypes=n,n};ZO.exports=aY();var eI=ZO.exports,tI={L:1,M:0,Q:3,H:2},nI={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},iY=nI;function rI(e){this.mode=iY.MODE_8BIT_BYTE,this.data=e}rI.prototype={getLength:function(e){return this.data.length},write:function(e){for(var t=0;t>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var uY=sI,ns={glog:function(e){if(e<1)throw new Error("glog("+e+")");return ns.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return ns.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var En=0;En<8;En++)ns.EXP_TABLE[En]=1<=0;)t^=Sn.G15<=0;)t^=Sn.G18<>>=1;return t},getPatternPosition:function(e){return Sn.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case Bo.PATTERN000:return(t+n)%2==0;case Bo.PATTERN001:return t%2==0;case Bo.PATTERN010:return n%3==0;case Bo.PATTERN011:return(t+n)%3==0;case Bo.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case Bo.PATTERN101:return t*n%2+t*n%3==0;case Bo.PATTERN110:return(t*n%2+t*n%3)%2==0;case Bo.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new nE([1],0),n=0;n5&&(n+=3+o-5)}for(var r=0;r=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=Fs.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)};Nr.setupPositionProbePattern=function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r==0||r==6)||0<=r&&r<=6&&(n==0||n==6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)};Nr.getBestMaskPattern=function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=Ha.getLostPoint(this);(n==0||e>r)&&(e=r,t=n)}return t};Nr.createMovieClip=function(e,t,n){var r=e.createEmptyMovieClip(t,n),s=1;this.make();for(var o=0;o>n&1)==1;this.modules[Math.floor(n/3)][n%3+this.moduleCount-8-3]=r}for(var n=0;n<18;n++){var r=!e&&(t>>n&1)==1;this.modules[n%3+this.moduleCount-8-3][Math.floor(n/3)]=r}};Nr.setupTypeInfo=function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=Ha.getBCHTypeInfo(n),s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<6?this.modules[s][8]=o:s<8?this.modules[s+1][8]=o:this.modules[this.moduleCount-15+s][8]=o}for(var s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=o:s<9?this.modules[8][15-s-1+1]=o:this.modules[8][15-s-1]=o}this.modules[this.moduleCount-8][8]=!e};Nr.mapData=function(e,t){for(var n=-1,r=this.moduleCount-1,s=7,o=0,a=this.moduleCount-1;a>0;a-=2)for(a==6&&a--;;){for(var c=0;c<2;c++)if(this.modules[r][a-c]==null){var u=!1;o>>s&1)==1);var i=Ha.getMask(t,r,a-c);i&&(u=!u),this.modules[r][a-c]=u,s--,s==-1&&(o++,s=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}};Fs.PAD0=236;Fs.PAD1=17;Fs.createData=function(e,t,n){for(var r=iI.getRSBlocks(e,t),s=new lI,o=0;oc*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+c*8+")");for(s.getLengthInBits()+4<=c*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=c*8||(s.put(Fs.PAD0,8),s.getLengthInBits()>=c*8));)s.put(Fs.PAD1,8);return Fs.createBytes(s,r)};Fs.createBytes=function(e,t){for(var n=0,r=0,s=0,o=new Array(t.length),a=new Array(t.length),c=0;c=0?g.get(h):0}}for(var m=0,d=0;d=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var bY={bgColor:Or.default.oneOfType([Or.default.object,Or.default.string]).isRequired,bgD:Or.default.string.isRequired,fgColor:Or.default.oneOfType([Or.default.object,Or.default.string]).isRequired,fgD:Or.default.string.isRequired,size:Or.default.number.isRequired,title:Or.default.string,viewBoxSize:Or.default.number.isRequired,xmlns:Or.default.string},Hw=(0,cI.forwardRef)(function(e,t){var n=e.bgColor,r=e.bgD,s=e.fgD,o=e.fgColor,a=e.size,c=e.title,u=e.viewBoxSize,i=e.xmlns,d=i===void 0?"http://www.w3.org/2000/svg":i,p=yY(e,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return Wf.default.createElement("svg",mY({},p,{height:a,ref:t,viewBox:"0 0 "+u+" "+u,width:a,xmlns:d}),c?Wf.default.createElement("title",null,c):null,Wf.default.createElement("path",{d:r,fill:n}),Wf.default.createElement("path",{d:s,fill:o}))});Hw.displayName="QRCodeSvg";Hw.propTypes=bY;Vw.default=Hw;Object.defineProperty(Qh,"__esModule",{value:!0});Qh.QRCode=void 0;var xY=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var _Y={bgColor:Xs.default.oneOfType([Xs.default.object,Xs.default.string]),fgColor:Xs.default.oneOfType([Xs.default.object,Xs.default.string]),level:Xs.default.string,size:Xs.default.number,value:Xs.default.string.isRequired},Zh=(0,dI.forwardRef)(function(e,t){var n=e.bgColor,r=n===void 0?"#FFFFFF":n,s=e.fgColor,o=s===void 0?"#000000":s,a=e.level,c=a===void 0?"L":a,u=e.size,i=u===void 0?256:u,d=e.value,p=NY(e,["bgColor","fgColor","level","size","value"]),f=new kY.default(-1,CY.default[c]);f.addData(d),f.make();var g=f.modules;return jY.default.createElement(MY.default,xY({},p,{bgColor:r,bgD:g.map(function(h,m){return h.map(function(x,b){return x?"":"M "+b+" "+m+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:o,fgD:g.map(function(h,m){return h.map(function(x,b){return x?"M "+b+" "+m+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:t,size:i,viewBoxSize:g.length}))});Qh.QRCode=Zh;Zh.displayName="QRCode";Zh.propTypes=_Y;var PY=Qh.default=Zh;const RY=ch("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),fI=v.forwardRef(({className:e,variant:t,...n},r)=>l.jsx("div",{ref:r,role:"alert",className:me(RY({variant:t}),e),...n}));fI.displayName="Alert";const pI=v.forwardRef(({className:e,...t},n)=>l.jsx("h5",{ref:n,className:me("font-medium leading-none tracking-tight",e),...t}));pI.displayName="AlertTitle";const OY=v.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:me("text-sm [&_p]:leading-relaxed",e),...t}));OY.displayName="AlertDescription";const Tn=({size:e=45,className:t,...n})=>l.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:me("animate-spin",t),children:l.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})});function IY(){const{t:e,i18n:t}=Te(),n=new Intl.NumberFormat(t.language),[r,s]=v.useState(null),[o,a]=v.useState(""),c=zr(Fn.TOKEN),{theme:u}=Dx(),{connect:i,logout:d,restart:p}=Nh(),{instance:f,reloadInstance:g}=Ve();v.useEffect(()=>{f&&(localStorage.setItem(Fn.INSTANCE_ID,f.id),localStorage.setItem(Fn.INSTANCE_NAME,f.name),localStorage.setItem(Fn.INSTANCE_TOKEN,f.token))},[f]);const h=async()=>{await g()},m=async E=>{try{await p(E),await g()}catch(C){console.error("Error:",C)}},x=async E=>{try{await d(E),await g()}catch(C){console.error("Error:",C)}},b=async(E,C)=>{try{if(s(null),!c){console.error("Token not found.");return}if(C){const T=await i({instanceName:E,token:c,number:f==null?void 0:f.number});a(T.pairingCode)}else{const T=await i({instanceName:E,token:c});s(T.code)}}catch(T){console.error("Error:",T)}},y=async()=>{s(null),a(""),await g()},w=v.useMemo(()=>{var E,C,T;return f?{contacts:((E=f._count)==null?void 0:E.Contact)||0,chats:((C=f._count)==null?void 0:C.Chat)||0,messages:((T=f._count)==null?void 0:T.Message)||0}:{contacts:0,chats:0,messages:0}},[f]),S=v.useMemo(()=>u==="dark"?"#fff":u==="light"?"#000":"#189d68",[u]);return f?l.jsxs("main",{className:"flex flex-col gap-8",children:[l.jsx("section",{children:l.jsxs(oi,{children:[l.jsx(ai,{children:l.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[l.jsx("h2",{className:"break-all text-lg font-semibold",children:f.name}),l.jsx(Y_,{status:f.connectionStatus})]})}),l.jsxs(ii,{className:"flex flex-col items-start space-y-6",children:[l.jsx("div",{className:"flex w-full flex-1",children:l.jsx(X_,{token:f.token})}),f.profileName&&l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsx(Eh,{children:l.jsx(kh,{src:f.profilePicUrl,alt:""})}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("strong",{children:f.profileName}),l.jsx("p",{className:"break-all text-sm text-muted-foreground",children:f.ownerJid})]})]}),f.connectionStatus!=="open"&&l.jsxs(fI,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[l.jsx(pI,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),l.jsxs(pt,{children:[l.jsx(mt,{onClick:()=>b(f.name,!1),asChild:!0,children:l.jsx(z,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),l.jsxs(ut,{onCloseAutoFocus:y,children:[l.jsx(dt,{children:e("instance.dashboard.button.qrcode.title")}),l.jsx("div",{className:"flex items-center justify-center",children:r&&l.jsx(PY,{value:r,size:256,bgColor:"transparent",fgColor:S,className:"rounded-sm"})})]})]}),f.number&&l.jsxs(pt,{children:[l.jsx(mt,{className:"connect-code-button",onClick:()=>b(f.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),l.jsx(ut,{onCloseAutoFocus:y,children:l.jsx(dt,{children:l.jsx(_o,{children:o?l.jsxs("div",{className:"py-3",children:[l.jsx("p",{className:"text-center",children:l.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),l.jsxs("p",{className:"pairing-code text-center",children:[o.substring(0,4),"-",o.substring(4,8)]})]}):l.jsx(Tn,{})})})})]})]})]}),l.jsxs(Mh,{className:"flex flex-wrap items-center justify-end gap-3",children:[l.jsx(z,{variant:"outline",className:"refresh-button",size:"icon",onClick:h,children:l.jsx(rg,{size:"20"})}),l.jsx(z,{className:"action-button",variant:"secondary",onClick:()=>m(f.name),children:e("instance.dashboard.button.restart").toUpperCase()}),l.jsx(z,{variant:"destructive",onClick:()=>x(f.name),disabled:f.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),l.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[l.jsxs(oi,{className:"instance-card",children:[l.jsx(ai,{children:l.jsxs(Iu,{className:"flex items-center gap-2",children:[l.jsx(vM,{size:"20"}),e("instance.dashboard.contacts")]})}),l.jsx(ii,{children:n.format(w.contacts)})]}),l.jsxs(oi,{className:"instance-card",children:[l.jsx(ai,{children:l.jsxs(Iu,{className:"flex items-center gap-2",children:[l.jsx(i3,{size:"20"}),e("instance.dashboard.chats")]})}),l.jsx(ii,{children:n.format(w.chats)})]}),l.jsxs(oi,{className:"instance-card",children:[l.jsx(ai,{children:l.jsxs(Iu,{className:"flex items-center gap-2",children:[l.jsx(dh,{size:"20"}),e("instance.dashboard.messages")]})}),l.jsx(ii,{children:n.format(w.messages)})]})]})]}):l.jsx(Tn,{})}var DY="Separator",rE="horizontal",AY=["horizontal","vertical"],gI=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=rE,...s}=e,o=FY(r)?r:rE,c=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return l.jsx(Ie.div,{"data-orientation":o,...c,...s,ref:t})});gI.displayName=DY;function FY(e){return AY.includes(e)}var hI=gI;const ht=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>l.jsx(hI,{ref:s,decorative:n,orientation:t,className:me("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));ht.displayName=hI.displayName;const LY=e=>["dify","fetchDify",JSON.stringify(e)],$Y=async({instanceName:e,token:t})=>(await ie.get(`/dify/find/${e}`,{headers:{apikey:t}})).data,mI=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:LY({instanceName:t,token:n}),queryFn:()=>$Y({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},BY=async({instanceName:e,token:t,data:n})=>(await ie.post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,zY=async({instanceName:e,difyId:t,data:n})=>(await ie.put(`/dify/update/${t}/${e}`,n)).data,UY=async({instanceName:e,difyId:t})=>(await ie.delete(`/dify/delete/${t}/${e}`)).data,VY=async({instanceName:e,token:t,data:n})=>(await ie.post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,HY=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Yh(){const e=Le(VY,{invalidateKeys:[["dify","fetchDefaultSettings"]]}),t=Le(HY,{invalidateKeys:[["dify","getDify"],["dify","fetchSessions"]]}),n=Le(UY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),r=Le(zY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),s=Le(BY,{invalidateKeys:[["dify","fetchDify"]]});return{setDefaultSettingsDify:e,changeStatusDify:t,deleteDify:n,updateDify:r,createDify:s}}const KY=e=>["dify","fetchDefaultSettings",JSON.stringify(e)],qY=async({instanceName:e,token:t})=>(await ie.get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,WY=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:KY({instanceName:t,token:n}),queryFn:()=>qY({instanceName:t,token:n}),enabled:!!t})},GY=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),difyIdFallback:k.union([k.null(),k.string()]).optional(),splitMessages:k.boolean(),timePerChar:k.string()});function JY(){const{t:e}=Te(),{instance:t}=Ve(),{setDefaultSettingsDify:n}=Yh(),[r,s]=v.useState(!1),{data:o,refetch:a}=mI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:r}),{data:c,refetch:u}=WY({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),i=zt({resolver:Ut(GY),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{c&&i.reset({expire:c!=null&&c.expire?c.expire.toString():"0",keywordFinish:c.keywordFinish,delayMessage:c.delayMessage?c.delayMessage.toString():"0",unknownMessage:c.unknownMessage,listeningFromMe:c.listeningFromMe,stopBotFromMe:c.stopBotFromMe,keepOpen:c.keepOpen,debounceTime:c.debounceTime?c.debounceTime.toString():"0",ignoreJids:c.ignoreJids,difyIdFallback:c.difyIdFallback,splitMessages:c.splitMessages,timePerChar:c.timePerChar?c.timePerChar.toString():"0"})},[c]);const d=async f=>{var g,h,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),difyIdFallback:f.difyIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),G.success(e("dify.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),G.error(`Error: ${(m=(h=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){u(),a()}return l.jsxs(pt,{open:r,onOpenChange:s,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("dify.defaultSettings")})}),l.jsx(Mn,{...i,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:(o==null?void 0:o.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),l.jsx($,{name:"expire",label:e("dify.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:e("dify.form.splitMessages.label"),reverse:!0}),l.jsx($,{name:"timePerChar",label:e("dify.form.timePerChar.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("dify.button.save")})})]})})]})]})}/** + * table-core + * + * Copyright (c) TanStack + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function ia(e,t){return typeof e=="function"?e(t):e}function kr(e,t){return n=>{t.setState(r=>({...r,[e]:ia(n,r[e])}))}}function Xh(e){return e instanceof Function}function QY(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function vI(e,t){const n=[],r=s=>{s.forEach(o=>{n.push(o);const a=t(o);a!=null&&a.length&&r(a)})};return r(e),n}function Ae(e,t,n){let r=[],s;return o=>{let a;n.key&&n.debug&&(a=Date.now());const c=e(o);if(!(c.length!==r.length||c.some((d,p)=>r[p]!==d)))return s;r=c;let i;if(n.key&&n.debug&&(i=Date.now()),s=t(...c),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const d=Math.round((Date.now()-a)*100)/100,p=Math.round((Date.now()-i)*100)/100,f=p/16,g=(h,m)=>{for(h=String(h);h.length{var s;return(s=e==null?void 0:e.debugAll)!=null?s:e[t]},key:!1,onChange:r}}function ZY(e,t,n,r){const s=()=>{var a;return(a=o.getValue())!=null?a:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:s,getContext:Ae(()=>[e,n,t,o],(a,c,u,i)=>({table:a,column:c,row:u,cell:i,getValue:i.getValue,renderValue:i.renderValue}),Fe(e.options,"debugCells"))};return e._features.forEach(a=>{a.createCell==null||a.createCell(o,n,t,e)},{}),o}function YY(e,t,n,r){var s,o;const c={...e._getDefaultColumnDef(),...t},u=c.accessorKey;let i=(s=(o=c.id)!=null?o:u?typeof String.prototype.replaceAll=="function"?u.replaceAll(".","_"):u.replace(/\./g,"_"):void 0)!=null?s:typeof c.header=="string"?c.header:void 0,d;if(c.accessorFn?d=c.accessorFn:u&&(u.includes(".")?d=f=>{let g=f;for(const m of u.split(".")){var h;g=(h=g)==null?void 0:h[m]}return g}:d=f=>f[c.accessorKey]),!i)throw new Error;let p={id:`${String(i)}`,accessorFn:d,parent:r,depth:n,columnDef:c,columns:[],getFlatColumns:Ae(()=>[!0],()=>{var f;return[p,...(f=p.columns)==null?void 0:f.flatMap(g=>g.getFlatColumns())]},Fe(e.options,"debugColumns")),getLeafColumns:Ae(()=>[e._getOrderColumnsFn()],f=>{var g;if((g=p.columns)!=null&&g.length){let h=p.columns.flatMap(m=>m.getLeafColumns());return f(h)}return[p]},Fe(e.options,"debugColumns"))};for(const f of e._features)f.createColumn==null||f.createColumn(p,e);return p}const In="debugHeaders";function sE(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const a=[],c=u=>{u.subHeaders&&u.subHeaders.length&&u.subHeaders.map(c),a.push(u)};return c(o),a},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(a=>{a.createHeader==null||a.createHeader(o,e)}),o}const XY={createTable:e=>{e.getHeaderGroups=Ae(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>{var o,a;const c=(o=r==null?void 0:r.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?o:[],u=(a=s==null?void 0:s.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?a:[],i=n.filter(p=>!(r!=null&&r.includes(p.id))&&!(s!=null&&s.includes(p.id)));return Gf(t,[...c,...i,...u],e)},Fe(e.options,In)),e.getCenterHeaderGroups=Ae(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),Gf(t,n,e,"center")),Fe(e.options,In)),e.getLeftHeaderGroups=Ae(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(c=>c.id===a)).filter(Boolean))!=null?s:[];return Gf(t,o,e,"left")},Fe(e.options,In)),e.getRightHeaderGroups=Ae(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(c=>c.id===a)).filter(Boolean))!=null?s:[];return Gf(t,o,e,"right")},Fe(e.options,In)),e.getFooterGroups=Ae(()=>[e.getHeaderGroups()],t=>[...t].reverse(),Fe(e.options,In)),e.getLeftFooterGroups=Ae(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),Fe(e.options,In)),e.getCenterFooterGroups=Ae(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),Fe(e.options,In)),e.getRightFooterGroups=Ae(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),Fe(e.options,In)),e.getFlatHeaders=Ae(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),Fe(e.options,In)),e.getLeftFlatHeaders=Ae(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),Fe(e.options,In)),e.getCenterFlatHeaders=Ae(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),Fe(e.options,In)),e.getRightFlatHeaders=Ae(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),Fe(e.options,In)),e.getCenterLeafHeaders=Ae(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Fe(e.options,In)),e.getLeftLeafHeaders=Ae(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Fe(e.options,In)),e.getRightLeafHeaders=Ae(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Fe(e.options,In)),e.getLeafHeaders=Ae(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var s,o,a,c,u,i;return[...(s=(o=t[0])==null?void 0:o.headers)!=null?s:[],...(a=(c=n[0])==null?void 0:c.headers)!=null?a:[],...(u=(i=r[0])==null?void 0:i.headers)!=null?u:[]].map(d=>d.getLeafHeaders()).flat()},Fe(e.options,In))}};function Gf(e,t,n,r){var s,o;let a=0;const c=function(f,g){g===void 0&&(g=1),a=Math.max(a,g),f.filter(h=>h.getIsVisible()).forEach(h=>{var m;(m=h.columns)!=null&&m.length&&c(h.columns,g+1)},0)};c(e);let u=[];const i=(f,g)=>{const h={depth:g,id:[r,`${g}`].filter(Boolean).join("_"),headers:[]},m=[];f.forEach(x=>{const b=[...m].reverse()[0],y=x.column.depth===h.depth;let w,S=!1;if(y&&x.column.parent?w=x.column.parent:(w=x.column,S=!0),b&&(b==null?void 0:b.column)===w)b.subHeaders.push(x);else{const E=sE(n,w,{id:[r,g,w.id,x==null?void 0:x.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${m.filter(C=>C.column===w).length}`:void 0,depth:g,index:m.length});E.subHeaders.push(x),m.push(E)}h.headers.push(x),x.headerGroup=h}),u.push(h),g>0&&i(m,g-1)},d=t.map((f,g)=>sE(n,f,{depth:a,index:g}));i(d,a-1),u.reverse();const p=f=>f.filter(h=>h.column.getIsVisible()).map(h=>{let m=0,x=0,b=[0];h.subHeaders&&h.subHeaders.length?(b=[],p(h.subHeaders).forEach(w=>{let{colSpan:S,rowSpan:E}=w;m+=S,b.push(E)})):m=1;const y=Math.min(...b);return x=x+y,h.colSpan=m,h.rowSpan=x,{colSpan:m,rowSpan:x}});return p((s=(o=u[0])==null?void 0:o.headers)!=null?s:[]),u}const em=(e,t,n,r,s,o,a)=>{let c={id:t,index:r,original:n,depth:s,parentId:a,_valuesCache:{},_uniqueValuesCache:{},getValue:u=>{if(c._valuesCache.hasOwnProperty(u))return c._valuesCache[u];const i=e.getColumn(u);if(i!=null&&i.accessorFn)return c._valuesCache[u]=i.accessorFn(c.original,r),c._valuesCache[u]},getUniqueValues:u=>{if(c._uniqueValuesCache.hasOwnProperty(u))return c._uniqueValuesCache[u];const i=e.getColumn(u);if(i!=null&&i.accessorFn)return i.columnDef.getUniqueValues?(c._uniqueValuesCache[u]=i.columnDef.getUniqueValues(c.original,r),c._uniqueValuesCache[u]):(c._uniqueValuesCache[u]=[c.getValue(u)],c._uniqueValuesCache[u])},renderValue:u=>{var i;return(i=c.getValue(u))!=null?i:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>vI(c.subRows,u=>u.subRows),getParentRow:()=>c.parentId?e.getRow(c.parentId,!0):void 0,getParentRows:()=>{let u=[],i=c;for(;;){const d=i.getParentRow();if(!d)break;u.push(d),i=d}return u.reverse()},getAllCells:Ae(()=>[e.getAllLeafColumns()],u=>u.map(i=>ZY(e,c,i,i.id)),Fe(e.options,"debugRows")),_getAllCellsByColumnId:Ae(()=>[c.getAllCells()],u=>u.reduce((i,d)=>(i[d.column.id]=d,i),{}),Fe(e.options,"debugRows"))};for(let u=0;u{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},yI=(e,t,n)=>{var r;const s=n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(s))};yI.autoRemove=e=>us(e);const bI=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};bI.autoRemove=e=>us(e);const xI=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===(n==null?void 0:n.toLowerCase())};xI.autoRemove=e=>us(e);const wI=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};wI.autoRemove=e=>us(e)||!(e!=null&&e.length);const SI=(e,t,n)=>!n.some(r=>{var s;return!((s=e.getValue(t))!=null&&s.includes(r))});SI.autoRemove=e=>us(e)||!(e!=null&&e.length);const CI=(e,t,n)=>n.some(r=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(r)});CI.autoRemove=e=>us(e)||!(e!=null&&e.length);const EI=(e,t,n)=>e.getValue(t)===n;EI.autoRemove=e=>us(e);const kI=(e,t,n)=>e.getValue(t)==n;kI.autoRemove=e=>us(e);const Kw=(e,t,n)=>{let[r,s]=n;const o=e.getValue(t);return o>=r&&o<=s};Kw.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,s=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,a=n===null||Number.isNaN(s)?1/0:s;if(o>a){const c=o;o=a,a=c}return[o,a]};Kw.autoRemove=e=>us(e)||us(e[0])&&us(e[1]);const so={includesString:yI,includesStringSensitive:bI,equalsString:xI,arrIncludes:wI,arrIncludesAll:SI,arrIncludesSome:CI,equals:EI,weakEquals:kI,inNumberRange:Kw};function us(e){return e==null||e===""}const tX={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:kr("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);return typeof r=="string"?so.includesString:typeof r=="number"?so.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?so.equals:Array.isArray(r)?so.arrIncludes:so.weakEquals},e.getFilterFn=()=>{var n,r;return Xh(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:so[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,s;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const s=e.getFilterFn(),o=r==null?void 0:r.find(d=>d.id===e.id),a=ia(n,o?o.value:void 0);if(oE(s,a,e)){var c;return(c=r==null?void 0:r.filter(d=>d.id!==e.id))!=null?c:[]}const u={id:e.id,value:a};if(o){var i;return(i=r==null?void 0:r.map(d=>d.id===e.id?u:d))!=null?i:[]}return r!=null&&r.length?[...r,u]:[u]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=s=>{var o;return(o=ia(t,s))==null?void 0:o.filter(a=>{const c=n.find(u=>u.id===a.id);if(c){const u=c.getFilterFn();if(oE(u,a.value,c))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function oE(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const nX=(e,t,n)=>n.reduce((r,s)=>{const o=s.getValue(e);return r+(typeof o=="number"?o:0)},0),rX=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},sX=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r=o)&&(r=o)}),r},oX=(e,t,n)=>{let r,s;return n.forEach(o=>{const a=o.getValue(e);a!=null&&(r===void 0?a>=a&&(r=s=a):(r>a&&(r=a),s{let n=0,r=0;if(t.forEach(s=>{let o=s.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},iX=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!QY(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,a)=>o-a);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},lX=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),cX=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,uX=(e,t)=>t.length,xv={sum:nX,min:rX,max:sX,extent:oX,mean:aX,median:iX,unique:lX,uniqueCount:cX,count:uX},dX={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:kr("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);if(typeof r=="number")return xv.sum;if(Object.prototype.toString.call(r)==="[object Date]")return xv.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return Xh(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:xv[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var s;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function fX(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(a=>a.id===o)).filter(Boolean),...r]}const pX={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:kr("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ae(n=>[$u(t,n)],n=>n.findIndex(r=>r.id===e.id),Fe(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=$u(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const s=$u(t,n);return((r=s[s.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ae(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>s=>{let o=[];if(!(t!=null&&t.length))o=s;else{const a=[...t],c=[...s];for(;c.length&&a.length;){const u=a.shift(),i=c.findIndex(d=>d.id===u);i>-1&&o.push(c.splice(i,1)[0])}o=[...o,...c]}return fX(o,n,r)},Fe(e.options,"debugTable"))}},wv=()=>({left:[],right:[]}),gX={getInitialState:e=>({columnPinning:wv(),...e}),getDefaultOptions:e=>({onColumnPinningChange:kr("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(s=>s.id).filter(Boolean);t.setColumnPinning(s=>{var o,a;if(n==="right"){var c,u;return{left:((c=s==null?void 0:s.left)!=null?c:[]).filter(p=>!(r!=null&&r.includes(p))),right:[...((u=s==null?void 0:s.right)!=null?u:[]).filter(p=>!(r!=null&&r.includes(p))),...r]}}if(n==="left"){var i,d;return{left:[...((i=s==null?void 0:s.left)!=null?i:[]).filter(p=>!(r!=null&&r.includes(p))),...r],right:((d=s==null?void 0:s.right)!=null?d:[]).filter(p=>!(r!=null&&r.includes(p)))}}return{left:((o=s==null?void 0:s.left)!=null?o:[]).filter(p=>!(r!=null&&r.includes(p))),right:((a=s==null?void 0:s.right)!=null?a:[]).filter(p=>!(r!=null&&r.includes(p)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var s,o,a;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(a=t.options.enableColumnPinning)!=null?a:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(c=>c.id),{left:r,right:s}=t.getState().columnPinning,o=n.some(c=>r==null?void 0:r.includes(c)),a=n.some(c=>s==null?void 0:s.includes(c));return o?"left":a?"right":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();return s?(n=(r=t.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ae(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(a=>!o.includes(a.column.id))},Fe(t.options,"debugRows")),e.getLeftVisibleCells=Ae(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),Fe(t.options,"debugRows")),e.getRightVisibleCells=Ae(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),Fe(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?wv():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:wv())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ae(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Fe(e.options,"debugColumns")),e.getRightLeafColumns=Ae(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Fe(e.options,"debugColumns")),e.getCenterLeafColumns=Ae(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const s=[...n??[],...r??[]];return t.filter(o=>!s.includes(o.id))},Fe(e.options,"debugColumns"))}},Jf={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},Sv=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),hX={getDefaultColumnDef:()=>Jf,getInitialState:e=>({columnSizing:{},columnSizingInfo:Sv(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:kr("columnSizing",e),onColumnSizingInfoChange:kr("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,s;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Jf.minSize,(r=o??e.columnDef.size)!=null?r:Jf.size),(s=e.columnDef.maxSize)!=null?s:Jf.maxSize)},e.getStart=Ae(n=>[n,$u(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),Fe(t.options,"debugColumns")),e.getAfter=Ae(n=>[n,$u(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),Fe(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...s}=n;return s})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),s=r==null?void 0:r.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),Cv(o)&&o.touches&&o.touches.length>1))return;const a=e.getSize(),c=e?e.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[r.id,r.getSize()]],u=Cv(o)?Math.round(o.touches[0].clientX):o.clientX,i={},d=(b,y)=>{typeof y=="number"&&(t.setColumnSizingInfo(w=>{var S,E;const C=t.options.columnResizeDirection==="rtl"?-1:1,T=(y-((S=w==null?void 0:w.startOffset)!=null?S:0))*C,j=Math.max(T/((E=w==null?void 0:w.startSize)!=null?E:0),-.999999);return w.columnSizingStart.forEach(_=>{let[O,K]=_;i[O]=Math.round(Math.max(K+K*j,0)*100)/100}),{...w,deltaOffset:T,deltaPercentage:j}}),(t.options.columnResizeMode==="onChange"||b==="end")&&t.setColumnSizing(w=>({...w,...i})))},p=b=>d("move",b),f=b=>{d("end",b),t.setColumnSizingInfo(y=>({...y,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},g=n||typeof document<"u"?document:null,h={moveHandler:b=>p(b.clientX),upHandler:b=>{g==null||g.removeEventListener("mousemove",h.moveHandler),g==null||g.removeEventListener("mouseup",h.upHandler),f(b.clientX)}},m={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),p(b.touches[0].clientX),!1),upHandler:b=>{var y;g==null||g.removeEventListener("touchmove",m.moveHandler),g==null||g.removeEventListener("touchend",m.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),f((y=b.touches[0])==null?void 0:y.clientX)}},x=mX()?{passive:!1}:!1;Cv(o)?(g==null||g.addEventListener("touchmove",m.moveHandler,x),g==null||g.addEventListener("touchend",m.upHandler,x)):(g==null||g.addEventListener("mousemove",h.moveHandler,x),g==null||g.addEventListener("mouseup",h.upHandler,x)),t.setColumnSizingInfo(b=>({...b,startOffset:u,startSize:a,deltaOffset:0,deltaPercentage:0,columnSizingStart:c,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?Sv():(n=e.initialState.columnSizingInfo)!=null?n:Sv())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0}}};let Qf=null;function mX(){if(typeof Qf=="boolean")return Qf;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Qf=e,Qf}function Cv(e){return e.type==="touchstart"}const vX={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:kr("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const s=e.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ae(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Fe(t.options,"debugRows")),e.getVisibleCells=Ae(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],Fe(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ae(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),Fe(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function $u(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const yX={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},bX={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:kr("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,s,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>so.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return Xh(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:so[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},xX={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:kr("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var s,o;e.setExpanded(r?{}:(s=(o=e.initialState)==null?void 0:o.expanded)!=null?s:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const a=o.split(".");r=Math.max(r,a.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[e.id]);let a={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(c=>{a[c]=!0}):a=r,n=(s=n)!=null?s:!o,!o&&n)return{...a,[e.id]:!0};if(o&&!n){const{[e.id]:c,...u}=a;return u}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r!=null&&r[e.id])},e.getCanExpand=()=>{var n,r,s;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((s=e.subRows)!=null&&s.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},jb=0,Tb=10,Ev=()=>({pageIndex:jb,pageSize:Tb}),wX={getInitialState:e=>({...e,pagination:{...Ev(),...e==null?void 0:e.pagination}}),getDefaultOptions:e=>({onPaginationChange:kr("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const s=o=>ia(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(s)},e.resetPagination=r=>{var s;e.setPagination(r?Ev():(s=e.initialState.pagination)!=null?s:Ev())},e.setPageIndex=r=>{e.setPagination(s=>{let o=ia(r,s.pageIndex);const a=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,a)),{...s,pageIndex:o}})},e.resetPageIndex=r=>{var s,o;e.setPageIndex(r?jb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:jb)},e.resetPageSize=r=>{var s,o;e.setPageSize(r?Tb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:Tb)},e.setPageSize=r=>{e.setPagination(s=>{const o=Math.max(1,ia(r,s.pageSize)),a=s.pageSize*s.pageIndex,c=Math.floor(a/o);return{...s,pageIndex:c,pageSize:o}})},e.setPageCount=r=>e.setPagination(s=>{var o;let a=ia(r,(o=e.options.pageCount)!=null?o:-1);return typeof a=="number"&&(a=Math.max(-1,a)),{...s,pageCount:a}}),e.getPageOptions=Ae(()=>[e.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,a)=>a)),s},Fe(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,s=e.getPageCount();return s===-1?!0:s===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},kv=()=>({top:[],bottom:[]}),SX={getInitialState:e=>({rowPinning:kv(),...e}),getDefaultOptions:e=>({onRowPinningChange:kr("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,s)=>{const o=r?e.getLeafRows().map(u=>{let{id:i}=u;return i}):[],a=s?e.getParentRows().map(u=>{let{id:i}=u;return i}):[],c=new Set([...a,e.id,...o]);t.setRowPinning(u=>{var i,d;if(n==="bottom"){var p,f;return{top:((p=u==null?void 0:u.top)!=null?p:[]).filter(m=>!(c!=null&&c.has(m))),bottom:[...((f=u==null?void 0:u.bottom)!=null?f:[]).filter(m=>!(c!=null&&c.has(m))),...Array.from(c)]}}if(n==="top"){var g,h;return{top:[...((g=u==null?void 0:u.top)!=null?g:[]).filter(m=>!(c!=null&&c.has(m))),...Array.from(c)],bottom:((h=u==null?void 0:u.bottom)!=null?h:[]).filter(m=>!(c!=null&&c.has(m)))}}return{top:((i=u==null?void 0:u.top)!=null?i:[]).filter(m=>!(c!=null&&c.has(m))),bottom:((d=u==null?void 0:u.bottom)!=null?d:[]).filter(m=>!(c!=null&&c.has(m)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=t.options;return typeof r=="function"?r(e):(n=r??s)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:s}=t.getState().rowPinning,o=n.some(c=>r==null?void 0:r.includes(c)),a=n.some(c=>s==null?void 0:s.includes(c));return o?"top":a?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();if(!s)return-1;const o=(n=s==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(a=>{let{id:c}=a;return c});return(r=o==null?void 0:o.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?kv():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:kv())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var s;return((s=e.options.keepPinnedRows)==null||s?(n??[]).map(a=>{const c=e.getRow(a,!0);return c.getIsAllParentsExpanded()?c:null}):(n??[]).map(a=>t.find(c=>c.id===a))).filter(Boolean).map(a=>({...a,position:r}))},e.getTopRows=Ae(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),Fe(e.options,"debugRows")),e.getBottomRows=Ae(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),Fe(e.options,"debugRows")),e.getCenterRows=Ae(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const s=new Set([...n??[],...r??[]]);return t.filter(o=>!s.has(o.id))},Fe(e.options,"debugRows"))}},CX={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:kr("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},s=e.getPreGroupedRowModel().flatRows;return t?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),s={...n};return e.getRowModel().rows.forEach(o=>{Mb(s,o.id,r,!0,e)}),s}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ae(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?jv(e,n):{rows:[],flatRows:[],rowsById:{}},Fe(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ae(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?jv(e,n):{rows:[],flatRows:[],rowsById:{}},Fe(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ae(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?jv(e,n):{rows:[],flatRows:[],rowsById:{}},Fe(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(s=>!n[s.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const s=e.getIsSelected();t.setRowSelection(o=>{var a;if(n=typeof n<"u"?n:!s,e.getCanSelect()&&s===n)return o;const c={...o};return Mb(c,e.id,n,(a=r==null?void 0:r.selectChildren)!=null?a:!0,t),c})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return qw(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Nb(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Nb(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var s;n&&e.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},Mb=(e,t,n,r,s)=>{var o;const a=s.getRow(t,!0);n?(a.getCanMultiSelect()||Object.keys(e).forEach(c=>delete e[c]),a.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=a.subRows)!=null&&o.length&&a.getCanSelectSubRows()&&a.subRows.forEach(c=>Mb(e,c.id,n,r,s))};function jv(e,t){const n=e.getState().rowSelection,r=[],s={},o=function(a,c){return a.map(u=>{var i;const d=qw(u,n);if(d&&(r.push(u),s[u.id]=u),(i=u.subRows)!=null&&i.length&&(u={...u,subRows:o(u.subRows)}),d)return u}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:s}}function qw(e,t){var n;return(n=t[e.id])!=null?n:!1}function Nb(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return e.subRows.forEach(a=>{if(!(o&&!s)&&(a.getCanSelect()&&(qw(a,t)?o=!0:s=!1),a.subRows&&a.subRows.length)){const c=Nb(a,t);c==="all"?o=!0:(c==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const _b=/([0-9]+)/gm,EX=(e,t,n)=>jI(Ta(e.getValue(n)).toLowerCase(),Ta(t.getValue(n)).toLowerCase()),kX=(e,t,n)=>jI(Ta(e.getValue(n)),Ta(t.getValue(n))),jX=(e,t,n)=>Ww(Ta(e.getValue(n)).toLowerCase(),Ta(t.getValue(n)).toLowerCase()),TX=(e,t,n)=>Ww(Ta(e.getValue(n)),Ta(t.getValue(n))),MX=(e,t,n)=>{const r=e.getValue(n),s=t.getValue(n);return r>s?1:rWw(e.getValue(n),t.getValue(n));function Ww(e,t){return e===t?0:e>t?1:-1}function Ta(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function jI(e,t){const n=e.split(_b).filter(Boolean),r=t.split(_b).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),a=parseInt(s,10),c=parseInt(o,10),u=[a,c].sort();if(isNaN(u[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(u[1]))return isNaN(a)?-1:1;if(a>c)return 1;if(c>a)return-1}return n.length-r.length}const cu={alphanumeric:EX,alphanumericCaseSensitive:kX,text:jX,textCaseSensitive:TX,datetime:MX,basic:NX},_X={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:kr("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s==null?void 0:s.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return cu.datetime;if(typeof o=="string"&&(r=!0,o.split(_b).length>1))return cu.alphanumeric}return r?cu.text:cu.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof(n==null?void 0:n.getValue(e.id))=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return Xh(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:cu[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const s=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(a=>{const c=a==null?void 0:a.find(g=>g.id===e.id),u=a==null?void 0:a.findIndex(g=>g.id===e.id);let i=[],d,p=o?n:s==="desc";if(a!=null&&a.length&&e.getCanMultiSort()&&r?c?d="toggle":d="add":a!=null&&a.length&&u!==a.length-1?d="replace":c?d="toggle":d="replace",d==="toggle"&&(o||s||(d="remove")),d==="add"){var f;i=[...a,{id:e.id,desc:p}],i.splice(0,i.length-((f=t.options.maxMultiSortColCount)!=null?f:Number.MAX_SAFE_INTEGER))}else d==="toggle"?i=a.map(g=>g.id===e.id?{...g,desc:p}:g):d==="remove"?i=a.filter(g=>g.id!==e.id):i=[{id:e.id,desc:p}];return i})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,s;const o=e.getFirstSortDir(),a=e.getIsSorted();return a?a!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(s=t.options.enableMultiRemove)!=null)||s)?!1:a==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(s=>s.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},PX=[XY,vX,pX,gX,eX,tX,yX,bX,_X,dX,xX,wX,SX,CX,hX];function RX(e){var t,n;const r=[...PX,...(t=e._features)!=null?t:[]];let s={_features:r};const o=s._features.reduce((f,g)=>Object.assign(f,g.getDefaultOptions==null?void 0:g.getDefaultOptions(s)),{}),a=f=>s.options.mergeOptions?s.options.mergeOptions(o,f):{...o,...f};let u={...{},...(n=e.initialState)!=null?n:{}};s._features.forEach(f=>{var g;u=(g=f.getInitialState==null?void 0:f.getInitialState(u))!=null?g:u});const i=[];let d=!1;const p={_features:r,options:{...o,...e},initialState:u,_queue:f=>{i.push(f),d||(d=!0,Promise.resolve().then(()=>{for(;i.length;)i.shift()();d=!1}).catch(g=>setTimeout(()=>{throw g})))},reset:()=>{s.setState(s.initialState)},setOptions:f=>{const g=ia(f,s.options);s.options=a(g)},getState:()=>s.options.state,setState:f=>{s.options.onStateChange==null||s.options.onStateChange(f)},_getRowId:(f,g,h)=>{var m;return(m=s.options.getRowId==null?void 0:s.options.getRowId(f,g,h))!=null?m:`${h?[h.id,g].join("."):g}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(f,g)=>{let h=(g?s.getPrePaginationRowModel():s.getRowModel()).rowsById[f];if(!h&&(h=s.getCoreRowModel().rowsById[f],!h))throw new Error;return h},_getDefaultColumnDef:Ae(()=>[s.options.defaultColumn],f=>{var g;return f=(g=f)!=null?g:{},{header:h=>{const m=h.header.column.columnDef;return m.accessorKey?m.accessorKey:m.accessorFn?m.id:null},cell:h=>{var m,x;return(m=(x=h.renderValue())==null||x.toString==null?void 0:x.toString())!=null?m:null},...s._features.reduce((h,m)=>Object.assign(h,m.getDefaultColumnDef==null?void 0:m.getDefaultColumnDef()),{}),...f}},Fe(e,"debugColumns")),_getColumnDefs:()=>s.options.columns,getAllColumns:Ae(()=>[s._getColumnDefs()],f=>{const g=function(h,m,x){return x===void 0&&(x=0),h.map(b=>{const y=YY(s,b,x,m),w=b;return y.columns=w.columns?g(w.columns,y,x+1):[],y})};return g(f)},Fe(e,"debugColumns")),getAllFlatColumns:Ae(()=>[s.getAllColumns()],f=>f.flatMap(g=>g.getFlatColumns()),Fe(e,"debugColumns")),_getAllFlatColumnsById:Ae(()=>[s.getAllFlatColumns()],f=>f.reduce((g,h)=>(g[h.id]=h,g),{}),Fe(e,"debugColumns")),getAllLeafColumns:Ae(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(f,g)=>{let h=f.flatMap(m=>m.getLeafColumns());return g(h)},Fe(e,"debugColumns")),getColumn:f=>s._getAllFlatColumnsById()[f]};Object.assign(s,p);for(let f=0;fAe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,a){o===void 0&&(o=0);const c=[];for(let i=0;ie._autoResetPageIndex()))}function IX(e,t,n){return n.options.filterFromLeafRows?DX(e,t,n):AX(e,t,n)}function DX(e,t,n){var r;const s=[],o={},a=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,c=function(u,i){i===void 0&&(i=0);const d=[];for(let f=0;fAe(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,n,r)=>{if(!t.rows.length||!(n!=null&&n.length)&&!r){for(let f=0;f{var g;const h=e.getColumn(f.id);if(!h)return;const m=h.getFilterFn();m&&s.push({id:f.id,filterFn:m,resolvedValue:(g=m.resolveFilterValue==null?void 0:m.resolveFilterValue(f.value))!=null?g:f.value})});const a=(n??[]).map(f=>f.id),c=e.getGlobalFilterFn(),u=e.getAllLeafColumns().filter(f=>f.getCanGlobalFilter());r&&c&&u.length&&(a.push("__global__"),u.forEach(f=>{var g;o.push({id:f.id,filterFn:c,resolvedValue:(g=c.resolveFilterValue==null?void 0:c.resolveFilterValue(r))!=null?g:r})}));let i,d;for(let f=0;f{g.columnFiltersMeta[m]=x})}if(o.length){for(let h=0;h{g.columnFiltersMeta[m]=x})){g.columnFilters.__global__=!0;break}}g.columnFilters.__global__!==!0&&(g.columnFilters.__global__=!1)}}const p=f=>{for(let g=0;ge._autoResetPageIndex()))}function LX(){return e=>Ae(()=>[e.getState().grouping,e.getPreGroupedRowModel()],(t,n)=>{if(!n.rows.length||!t.length)return n.rows.forEach(u=>{u.depth=0,u.parentId=void 0}),n;const r=t.filter(u=>e.getColumn(u)),s=[],o={},a=function(u,i,d){if(i===void 0&&(i=0),i>=r.length)return u.map(h=>(h.depth=i,s.push(h),o[h.id]=h,h.subRows&&(h.subRows=a(h.subRows,i+1,h.id)),h));const p=r[i],f=$X(u,p);return Array.from(f.entries()).map((h,m)=>{let[x,b]=h,y=`${p}:${x}`;y=d?`${d}>${y}`:y;const w=a(b,i+1,y);w.forEach(C=>{C.parentId=y});const S=i?vI(b,C=>C.subRows):b,E=em(e,y,S[0].original,m,i,void 0,d);return Object.assign(E,{groupingColumnId:p,groupingValue:x,subRows:w,leafRows:S,getValue:C=>{if(r.includes(C)){if(E._valuesCache.hasOwnProperty(C))return E._valuesCache[C];if(b[0]){var T;E._valuesCache[C]=(T=b[0].getValue(C))!=null?T:void 0}return E._valuesCache[C]}if(E._groupingValuesCache.hasOwnProperty(C))return E._groupingValuesCache[C];const j=e.getColumn(C),_=j==null?void 0:j.getAggregationFn();if(_)return E._groupingValuesCache[C]=_(C,S,b),E._groupingValuesCache[C]}}),w.forEach(C=>{s.push(C),o[C.id]=C}),E})},c=a(n.rows,0);return c.forEach(u=>{s.push(u),o[u.id]=u}),{rows:c,flatRows:s,rowsById:o}},Fe(e.options,"debugTable","getGroupedRowModel",()=>{e._queue(()=>{e._autoResetExpanded(),e._autoResetPageIndex()})}))}function $X(e,t){const n=new Map;return e.reduce((r,s)=>{const o=`${s.getGroupingValue(t)}`,a=r.get(o);return a?a.push(s):r.set(o,[s]),r},n)}function BX(){return e=>Ae(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,s=[],o=r.filter(u=>{var i;return(i=e.getColumn(u.id))==null?void 0:i.getCanSort()}),a={};o.forEach(u=>{const i=e.getColumn(u.id);i&&(a[u.id]={sortUndefined:i.columnDef.sortUndefined,invertSorting:i.columnDef.invertSorting,sortingFn:i.getSortingFn()})});const c=u=>{const i=u.map(d=>({...d}));return i.sort((d,p)=>{for(let g=0;g{var p;s.push(d),(p=d.subRows)!=null&&p.length&&(d.subRows=c(d.subRows))}),i};return{rows:c(n.rows),flatRows:s,rowsById:n.rowsById}},Fe(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/** + * react-table + * + * Copyright (c) TanStack + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function aE(e,t){return e?zX(e)?v.createElement(e,t):e:null}function zX(e){return UX(e)||typeof e=="function"||VX(e)}function UX(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function VX(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function HX(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=v.useState(()=>({current:RX(t)})),[r,s]=v.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:a=>{s(a),e.onStateChange==null||e.onStateChange(a)}})),n.current}const TI=v.forwardRef(({className:e,...t},n)=>l.jsx("div",{className:"relative w-full overflow-auto",children:l.jsx("table",{ref:n,className:me("w-full caption-bottom text-sm",e),...t})}));TI.displayName="Table";const MI=v.forwardRef(({className:e,...t},n)=>l.jsx("thead",{ref:n,className:me("[&_tr]:border-b",e),...t}));MI.displayName="TableHeader";const NI=v.forwardRef(({className:e,...t},n)=>l.jsx("tbody",{ref:n,className:me("[&_tr:last-child]:border-0",e),...t}));NI.displayName="TableBody";const KX=v.forwardRef(({className:e,...t},n)=>l.jsx("tfoot",{ref:n,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));KX.displayName="TableFooter";const Cu=v.forwardRef(({className:e,...t},n)=>l.jsx("tr",{ref:n,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));Cu.displayName="TableRow";const _I=v.forwardRef(({className:e,...t},n)=>l.jsx("th",{ref:n,className:me("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));_I.displayName="TableHead";const kp=v.forwardRef(({className:e,...t},n)=>l.jsx("td",{ref:n,className:me("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));kp.displayName="TableCell";const qX=v.forwardRef(({className:e,...t},n)=>l.jsx("caption",{ref:n,className:me("mt-4 text-sm text-muted-foreground",e),...t}));qX.displayName="TableCaption";function Ka({columns:e,data:t,isLoading:n,loadingMessage:r,noResultsMessage:s,enableHeaders:o=!0,className:a,highlightedRows:c,...u}){var d;const i=HX({...u,data:t,columns:e,getCoreRowModel:OX(),getFilteredRowModel:FX(),getGroupedRowModel:LX(),getSortedRowModel:BX()});return l.jsx("div",{className:me("rounded-md border",a),children:l.jsxs(TI,{children:[o&&l.jsx(MI,{children:i.getHeaderGroups().map(p=>l.jsx(Cu,{children:p.headers.map(f=>l.jsx(_I,{children:f.isPlaceholder?null:aE(f.column.columnDef.header,f.getContext())},f.id))},p.id))}),l.jsx(NI,{children:n?l.jsx(Cu,{children:l.jsx(kp,{colSpan:e.length,className:"h-24 text-center text-muted-foreground",children:r??"Carregando..."})}):l.jsx(l.Fragment,{children:(d=i.getRowModel().rows)!=null&&d.length?i.getRowModel().rows.map(p=>l.jsx(Cu,{"data-state":p.getIsSelected()?"selected":c!=null&&c.includes(p.id)?"highlighted":"",children:p.getVisibleCells().map(f=>l.jsx(kp,{children:aE(f.column.columnDef.cell,f.getContext())},f.id))},p.id)):l.jsx(Cu,{children:l.jsx(kp,{colSpan:e.length,className:"h-24 text-center",children:s??"Nenhum resultado encontrado!"})})})})]})})}const WX=e=>["dify","fetchSessions",JSON.stringify(e)],GX=async({difyId:e,instanceName:t})=>(await ie.get(`/dify/fetchSessions/${e}/${t}`)).data,JX=e=>{const{difyId:t,instanceName:n,...r}=e;return qe({...r,queryKey:WX({difyId:t,instanceName:n}),queryFn:()=>GX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function PI({difyId:e}){const{t}=Te(),{instance:n}=Ve(),{changeStatusDify:r}=Yh(),[s,o]=v.useState([]),{data:a,refetch:c}=JX({difyId:e,instanceName:n==null?void 0:n.name}),[u,i]=v.useState(!1),[d,p]=v.useState("");function f(){c()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("dify.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:t("dify.sessions.table.actions.title")}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:u,onOpenChange:i,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("dify.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("dify.sessions.search"),value:d,onChange:m=>p(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{})})]}),l.jsx(Ka,{columns:h,data:a??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("dify.sessions.table.none")})]})]})]})}const QX=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function RI({initialData:e,onSubmit:t,handleDelete:n,difyId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{}}){const{t:u}=Te(),i=zt({resolver:Ut(QX),defaultValues:e||{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return l.jsx(Mn,{...i,children:l.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:u("dify.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:u("dify.form.description.label"),required:!0,children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("dify.form.difySettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"botType",label:u("dify.form.botType.label"),options:[{label:u("dify.form.botType.chatBot"),value:"chatBot"},{label:u("dify.form.botType.textGenerator"),value:"textGenerator"},{label:u("dify.form.botType.agent"),value:"agent"},{label:u("dify.form.botType.workflow"),value:"workflow"}]}),l.jsx($,{name:"apiUrl",label:u("dify.form.apiUrl.label"),required:!0,children:l.jsx(F,{})}),l.jsx($,{name:"apiKey",label:u("dify.form.apiKey.label"),required:!0,children:l.jsx(F,{type:"password"})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("dify.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:u("dify.form.triggerType.label"),options:[{label:u("dify.form.triggerType.keyword"),value:"keyword"},{label:u("dify.form.triggerType.all"),value:"all"},{label:u("dify.form.triggerType.advanced"),value:"advanced"},{label:u("dify.form.triggerType.none"),value:"none"}]}),d==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:u("dify.form.triggerOperator.label"),options:[{label:u("dify.form.triggerOperator.contains"),value:"contains"},{label:u("dify.form.triggerOperator.equals"),value:"equals"},{label:u("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:u("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:u("dify.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:u("dify.form.triggerValue.label"),children:l.jsx(F,{})})]}),d==="advanced"&&l.jsx($,{name:"triggerValue",label:u("dify.form.triggerConditions.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("dify.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:u("dify.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:u("dify.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:u("dify.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:u("dify.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:u("dify.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:u("dify.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:u("dify.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:u("dify.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:u("dify.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:u("dify.form.timePerChar.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:u(o?"dify.button.saving":"dify.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(PI,{difyId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:u("dify.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:u("modal.delete.title")}),l.jsx(_o,{children:u("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:u("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:u("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:u(o?"dify.button.saving":"dify.button.update")})]})]})]})})}function ZX({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createDify:c}=Yh(),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:i.enabled,description:i.description,botType:i.botType,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await c({instanceName:n.name,token:n.token,data:g}),G.success(t("dify.toast.success.create")),a(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return l.jsxs(pt,{open:o,onOpenChange:a,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("dify.form.title")})}),l.jsx(RI,{onSubmit:u,isModal:!0,isLoading:r})]})]})}const YX=e=>["dify","getDify",JSON.stringify(e)],XX=async({difyId:e,instanceName:t})=>(await ie.get(`/dify/fetch/${e}/${t}`)).data,eee=e=>{const{difyId:t,instanceName:n,...r}=e;return qe({...r,queryKey:YX({difyId:t,instanceName:n}),queryFn:()=>XX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function tee({difyId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteDify:c,updateDify:u}=Yh(),{data:i,isLoading:d}=eee({difyId:e,instanceName:r==null?void 0:r.name}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",botType:(i==null?void 0:i.botType)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:(i==null?void 0:i.triggerValue)??"",expire:(i==null?void 0:i.expire)??0,keywordFinish:(i==null?void 0:i.keywordFinish)??"",delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:(i==null?void 0:i.unknownMessage)??"",listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.botType,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,botType:h.botType,apiUrl:h.apiUrl,apiKey:h.apiKey,triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0,splitMessages:h.splitMessages||!1,timePerChar:h.timePerChar||0};await u({instanceName:r.name,difyId:e,data:y}),G.success(n("dify.toast.success.update")),t(),s(`/manager/instance/${r.id}/dify/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,difyId:e}),G.success(n("dify.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/dify`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir dify:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(RI,{initialData:p,onSubmit:f,difyId:e,handleDelete:g,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function iE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{difyId:r}=gs(),{data:s,refetch:o,isLoading:a}=mI({instanceName:n==null?void 0:n.name}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/dify/${d}`)},i=()=>{o()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(PI,{}),l.jsx(JY,{}),l.jsx(ZX,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:a?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsxs(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[l.jsx("h4",{className:"text-base",children:d.description||d.id}),l.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):l.jsx(z,{variant:"link",children:e("dify.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-border"}),l.jsx(Bn,{children:l.jsx(tee,{difyId:r,resetTable:i})})]})]})]})}const nee=e=>["evoai","fetchEvoai",JSON.stringify(e)],ree=async({instanceName:e,token:t})=>(await ie.get(`/evoai/find/${e}`,{headers:{apikey:t}})).data,OI=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:nee({instanceName:t,token:n}),queryFn:()=>ree({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},see=async({instanceName:e,token:t,data:n})=>(await ie.post(`/evoai/create/${e}`,n,{headers:{apikey:t}})).data,oee=async({instanceName:e,evoaiId:t,data:n})=>(await ie.put(`/evoai/update/${t}/${e}`,n)).data,aee=async({instanceName:e,evoaiId:t})=>(await ie.delete(`/evoai/delete/${t}/${e}`)).data,iee=async({instanceName:e,token:t,data:n})=>(await ie.post(`/evoai/settings/${e}`,n,{headers:{apikey:t}})).data,lee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/evoai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function tm(){const e=Le(iee,{invalidateKeys:[["evoai","fetchDefaultSettings"]]}),t=Le(lee,{invalidateKeys:[["evoai","getEvoai"],["evoai","fetchSessions"]]}),n=Le(aee,{invalidateKeys:[["evoai","getEvoai"],["evoai","fetchEvoai"],["evoai","fetchSessions"]]}),r=Le(oee,{invalidateKeys:[["evoai","getEvoai"],["evoai","fetchEvoai"],["evoai","fetchSessions"]]}),s=Le(see,{invalidateKeys:[["evoai","fetchEvoai"]]});return{setDefaultSettingsEvoai:e,changeStatusEvoai:t,deleteEvoai:n,updateEvoai:r,createEvoai:s}}const cee=e=>["evoai","fetchDefaultSettings",JSON.stringify(e)],uee=async({instanceName:e,token:t})=>(await ie.get(`/evoai/fetchSettings/${e}`,{headers:{apikey:t}})).data,dee=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:cee({instanceName:t,token:n}),queryFn:()=>uee({instanceName:t,token:n}),enabled:!!t})},fee=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),evoaiIdFallback:k.union([k.null(),k.string()]).optional(),splitMessages:k.boolean(),timePerChar:k.string()});function pee(){const{t:e}=Te(),{instance:t}=Ve(),{setDefaultSettingsEvoai:n}=tm(),[r,s]=v.useState(!1),{data:o,refetch:a}=OI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:r}),{data:c,refetch:u}=dee({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),i=zt({resolver:Ut(fee),defaultValues:{expire:"0",keywordFinish:e("evoai.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evoai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],evoaiIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{c&&i.reset({expire:c!=null&&c.expire?c.expire.toString():"0",keywordFinish:c.keywordFinish,delayMessage:c.delayMessage?c.delayMessage.toString():"0",unknownMessage:c.unknownMessage,listeningFromMe:c.listeningFromMe,stopBotFromMe:c.stopBotFromMe,keepOpen:c.keepOpen,debounceTime:c.debounceTime?c.debounceTime.toString():"0",ignoreJids:c.ignoreJids,evoaiIdFallback:c.evoaiIdFallback,splitMessages:c.splitMessages,timePerChar:c.timePerChar?c.timePerChar.toString():"0"})},[c]);const d=async f=>{var g,h,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),evoaiIdFallback:f.evoaiIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),G.success(e("evoai.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),G.error(`Error: ${(m=(h=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){u(),a()}return l.jsxs(pt,{open:r,onOpenChange:s,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:e("evoai.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("evoai.defaultSettings")})}),l.jsx(Mn,{...i,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"evoaiIdFallback",label:e("evoai.form.evoaiIdFallback.label"),options:(o==null?void 0:o.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),l.jsx($,{name:"expire",label:e("evoai.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("evoai.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("evoai.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("evoai.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("evoai.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("evoai.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("evoai.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("evoai.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:e("evoai.form.splitMessages.label"),reverse:!0}),l.jsx($,{name:"timePerChar",label:e("evoai.form.timePerChar.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("evoai.form.ignoreJids.label"),placeholder:e("evoai.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("evoai.button.save")})})]})})]})]})}const gee=e=>["evoai","fetchSessions",JSON.stringify(e)],hee=async({evoaiId:e,instanceName:t})=>(await ie.get(`/evoai/fetchSessions/${e}/${t}`)).data,mee=e=>{const{evoaiId:t,instanceName:n,...r}=e;return qe({...r,queryKey:gee({evoaiId:t,instanceName:n}),queryFn:()=>hee({evoaiId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function II({evoaiId:e}){const{t}=Te(),{instance:n}=Ve(),{changeStatusEvoai:r}=tm(),[s,o]=v.useState([]),{data:a,refetch:c}=mee({evoaiId:e,instanceName:n==null?void 0:n.name}),[u,i]=v.useState(!1),[d,p]=v.useState("");function f(){c()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("evoai.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("evoai.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("evoai.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("evoai.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("evoai.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:t("evoai.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:t("evoai.sessions.table.actions.title")}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:u,onOpenChange:i,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("evoai.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("evoai.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("evoai.sessions.search"),value:d,onChange:m=>p(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{})})]}),l.jsx(Ka,{columns:h,data:a??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("evoai.sessions.table.none")})]})]})]})}const vee=k.object({enabled:k.boolean(),description:k.string(),agentUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function DI({initialData:e,onSubmit:t,handleDelete:n,evoaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{}}){const{t:u}=Te(),i=zt({resolver:Ut(vee),defaultValues:e||{enabled:!0,description:"",agentUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return l.jsx(Mn,{...i,children:l.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:u("evoai.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:u("evoai.form.description.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("evoai.form.evoaiSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"agentUrl",label:u("evoai.form.agentUrl.label"),required:!0,children:l.jsx(F,{})}),l.jsx($,{name:"apiKey",label:u("evoai.form.apiKey.label"),className:"flex-1",children:l.jsx(F,{type:"password"})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("evoai.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:u("evoai.form.triggerType.label"),options:[{label:u("evoai.form.triggerType.keyword"),value:"keyword"},{label:u("evoai.form.triggerType.all"),value:"all"},{label:u("evoai.form.triggerType.advanced"),value:"advanced"},{label:u("evoai.form.triggerType.none"),value:"none"}]}),d==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:u("evoai.form.triggerOperator.label"),options:[{label:u("evoai.form.triggerOperator.contains"),value:"contains"},{label:u("evoai.form.triggerOperator.equals"),value:"equals"},{label:u("evoai.form.triggerOperator.startsWith"),value:"startsWith"},{label:u("evoai.form.triggerOperator.endsWith"),value:"endsWith"},{label:u("evoai.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:u("evoai.form.triggerValue.label"),children:l.jsx(F,{})})]}),d==="advanced"&&l.jsx($,{name:"triggerValue",label:u("evoai.form.triggerConditions.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("evoai.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:u("evoai.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:u("evoai.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:u("evoai.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:u("evoai.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:u("evoai.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:u("evoai.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:u("evoai.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:u("evoai.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:u("evoai.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:u("evoai.form.timePerChar.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:u(o?"evoai.button.saving":"evoai.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(II,{evoaiId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:u("evoai.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:u("modal.delete.title")}),l.jsx(_o,{children:u("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:u("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:u("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:u(o?"evoai.button.saving":"evoai.button.update")})]})]})]})})}function yee({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createEvoai:c}=tm(),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:i.enabled,description:i.description,agentUrl:i.agentUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await c({instanceName:n.name,token:n.token,data:g}),G.success(t("evoai.toast.success.create")),a(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return l.jsxs(pt,{open:o,onOpenChange:a,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("evoai.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("evoai.form.title")})}),l.jsx(DI,{onSubmit:u,isModal:!0,isLoading:r})]})]})}const bee=e=>["evoai","getEvoai",JSON.stringify(e)],xee=async({evoaiId:e,instanceName:t})=>(await ie.get(`/evoai/fetch/${e}/${t}`)).data,wee=e=>{const{evoaiId:t,instanceName:n,...r}=e;return qe({...r,queryKey:bee({evoaiId:t,instanceName:n}),queryFn:()=>xee({evoaiId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function See({evoaiId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteEvoai:c,updateEvoai:u}=tm(),{data:i,isLoading:d}=wee({evoaiId:e,instanceName:r==null?void 0:r.name}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",agentUrl:(i==null?void 0:i.agentUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:(i==null?void 0:i.triggerValue)??"",expire:(i==null?void 0:i.expire)??0,keywordFinish:(i==null?void 0:i.keywordFinish)??"",delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:(i==null?void 0:i.unknownMessage)??"",listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.agentUrl,i==null?void 0:i.apiKey,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,agentUrl:h.agentUrl,apiKey:h.apiKey,triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0,splitMessages:h.splitMessages||!1,timePerChar:h.timePerChar||0};await u({instanceName:r.name,evoaiId:e,data:y}),G.success(n("evoai.toast.success.update")),t(),s(`/manager/instance/${r.id}/evoai/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,evoaiId:e}),G.success(n("evoai.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/evoai`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir evoai:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(DI,{initialData:p,onSubmit:f,evoaiId:e,handleDelete:g,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function lE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{evoaiId:r}=gs(),{data:s,refetch:o,isLoading:a}=OI({instanceName:n==null?void 0:n.name}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/evoai/${d}`)},i=()=>{o()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("evoai.title")}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(II,{}),l.jsx(pee,{}),l.jsx(yee,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:a?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsx(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:l.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):l.jsx(z,{variant:"link",children:e("evoai.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-border"}),l.jsx(Bn,{children:l.jsx(See,{evoaiId:r,resetTable:i})})]})]})]})}const Cee=e=>["evolutionBot","findEvolutionBot",JSON.stringify(e)],Eee=async({instanceName:e,token:t})=>(await ie.get(`/evolutionBot/find/${e}`,{headers:{apiKey:t}})).data,AI=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:Cee({instanceName:t}),queryFn:()=>Eee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},kee=e=>["evolutionBot","fetchDefaultSettings",JSON.stringify(e)],jee=async({instanceName:e,token:t})=>{const n=await ie.get(`/evolutionBot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Tee=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:kee({instanceName:t}),queryFn:()=>jee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Mee=async({instanceName:e,token:t,data:n})=>(await ie.post(`/evolutionBot/create/${e}`,n,{headers:{apikey:t}})).data,Nee=async({instanceName:e,token:t,evolutionBotId:n,data:r})=>(await ie.put(`/evolutionBot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,_ee=async({instanceName:e,evolutionBotId:t})=>(await ie.delete(`/evolutionBot/delete/${t}/${e}`)).data,Pee=async({instanceName:e,token:t,data:n})=>(await ie.post(`/evolutionBot/settings/${e}`,n,{headers:{apikey:t}})).data,Ree=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/evolutionBot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function nm(){const e=Le(Pee,{invalidateKeys:[["evolutionBot","fetchDefaultSettings"]]}),t=Le(Ree,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","fetchSessions"]]}),n=Le(_ee,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),r=Le(Nee,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),s=Le(Mee,{invalidateKeys:[["evolutionBot","findEvolutionBot"]]});return{setDefaultSettingsEvolutionBot:e,changeStatusEvolutionBot:t,deleteEvolutionBot:n,updateEvolutionBot:r,createEvolutionBot:s}}const Oee=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),botIdFallback:k.union([k.null(),k.string()]).optional(),splitMessages:k.boolean(),timePerChar:k.string()});function Iee(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{data:s,refetch:o}=Tee({instanceName:t==null?void 0:t.name,enabled:n}),{data:a,refetch:c}=AI({instanceName:t==null?void 0:t.name,enabled:n}),{setDefaultSettingsEvolutionBot:u}=nm(),i=zt({resolver:Ut(Oee),defaultValues:{expire:"0",keywordFinish:e("evolutionBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evolutionBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{s&&i.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback,splitMessages:s.splitMessages,timePerChar:s.timePerChar?s.timePerChar.toString():"0"})},[s]);const d=async f=>{var g,h,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),botIdFallback:f.botIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await u({instanceName:t.name,token:t.token,data:x}),G.success(e("evolutionBot.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),G.error(`Error: ${(m=(h=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){o(),c()}return l.jsxs(pt,{open:n,onOpenChange:r,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:e("evolutionBot.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("evolutionBot.defaultSettings")})}),l.jsx(Mn,{...i,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"botIdFallback",label:e("evolutionBot.form.botIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),l.jsx($,{name:"expire",label:e("evolutionBot.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("evolutionBot.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("evolutionBot.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("evolutionBot.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("evolutionBot.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("evolutionBot.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("evolutionBot.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:e("evolutionBot.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:e("evolutionBot.form.timePerChar.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("evolutionBot.form.ignoreJids.label"),placeholder:e("evolutionBot.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("evolutionBot.button.save")})})]})})]})]})}const Dee=e=>["evolutionBot","fetchSessions",JSON.stringify(e)],Aee=async({instanceName:e,evolutionBotId:t,token:n})=>(await ie.get(`/evolutionBot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Fee=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return qe({...s,queryKey:Dee({instanceName:t}),queryFn:()=>Aee({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function FI({evolutionBotId:e}){const{t}=Te(),{instance:n}=Ve(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[c,u]=v.useState(""),{data:i,refetch:d}=Fee({instanceName:n==null?void 0:n.name,evolutionBotId:e,enabled:o}),{changeStatusEvolutionBot:p}=nm();function f(){d()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await p({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("evolutionBot.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:t("evolutionBot.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:t("evolutionBot.sessions.table.actions.title")}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:o,onOpenChange:a,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("evolutionBot.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("evolutionBot.sessions.search"),value:c,onChange:m=>u(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{})})]}),l.jsx(Ka,{columns:h,data:i??[],onSortingChange:s,state:{sorting:r,globalFilter:c},onGlobalFilterChange:u,enableGlobalFilter:!0,noResultsMessage:t("evolutionBot.sessions.table.none")})]})]})]})}const Lee=k.object({enabled:k.boolean(),description:k.string(),apiUrl:k.string(),apiKey:k.string().optional(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function LI({initialData:e,onSubmit:t,handleDelete:n,evolutionBotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{}}){const{t:u}=Te(),i=zt({resolver:Ut(Lee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return l.jsx(Mn,{...i,children:l.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:u("evolutionBot.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:u("evolutionBot.form.description.label"),required:!0,children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("evolutionBot.form.evolutionBotSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"apiUrl",label:u("evolutionBot.form.apiUrl.label"),required:!0,children:l.jsx(F,{})}),l.jsx($,{name:"apiKey",label:u("evolutionBot.form.apiKey.label"),children:l.jsx(F,{type:"password"})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("evolutionBot.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:u("evolutionBot.form.triggerType.label"),options:[{label:u("evolutionBot.form.triggerType.keyword"),value:"keyword"},{label:u("evolutionBot.form.triggerType.all"),value:"all"},{label:u("evolutionBot.form.triggerType.advanced"),value:"advanced"},{label:u("evolutionBot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:u("evolutionBot.form.triggerOperator.label"),options:[{label:u("evolutionBot.form.triggerOperator.contains"),value:"contains"},{label:u("evolutionBot.form.triggerOperator.equals"),value:"equals"},{label:u("evolutionBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:u("evolutionBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:u("evolutionBot.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:u("evolutionBot.form.triggerValue.label"),children:l.jsx(F,{})})]}),d==="advanced"&&l.jsx($,{name:"triggerValue",label:u("evolutionBot.form.triggerConditions.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("evolutionBot.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:u("evolutionBot.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:u("evolutionBot.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:u("evolutionBot.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:u("evolutionBot.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:u("evolutionBot.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:u("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:u("evolutionBot.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:u("evolutionBot.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:u("evolutionBot.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:u("evolutionBot.form.timePerChar.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:u(o?"evolutionBot.button.saving":"evolutionBot.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(FI,{evolutionBotId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:u("dify.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:u("modal.delete.title")}),l.jsx(_o,{children:u("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:u("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:u("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:u(o?"evolutionBot.button.saving":"evolutionBot.button.update")})]})]})]})})}function $ee({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createEvolutionBot:c}=nm(),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:i.enabled,description:i.description,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar?i.timePerChar:0};await c({instanceName:n.name,token:n.token,data:g}),G.success(t("evolutionBot.toast.success.create")),a(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return l.jsxs(pt,{open:o,onOpenChange:a,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("evolutionBot.form.title")})}),l.jsx(LI,{onSubmit:u,isModal:!0,isLoading:r})]})]})}const Bee=e=>["evolutionBot","getEvolutionBot",JSON.stringify(e)],zee=async({instanceName:e,token:t,evolutionBotId:n})=>{const r=await ie.get(`/evolutionBot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Uee=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return qe({...s,queryKey:Bee({instanceName:t}),queryFn:()=>zee({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function Vee({evolutionBotId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteEvolutionBot:c,updateEvolutionBot:u}=nm(),{data:i,isLoading:d}=Uee({instanceName:r==null?void 0:r.name,evolutionBotId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:i!=null&&i.timePerChar?i==null?void 0:i.timePerChar:0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,apiUrl:h.apiUrl,apiKey:h.apiKey,triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0,splitMessages:h.splitMessages||!1,timePerChar:h.timePerChar?h.timePerChar:0};await u({instanceName:r.name,evolutionBotId:e,data:y}),G.success(n("evolutionBot.toast.success.update")),t(),s(`/manager/instance/${r.id}/evolutionBot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,evolutionBotId:e}),G.success(n("evolutionBot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/evolutionBot`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir evolutionBot:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(LI,{initialData:p,onSubmit:f,evolutionBotId:e,handleDelete:g,isModal:!1,openDeletionDialog:o,setOpenDeletionDialog:a})})}function cE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{evolutionBotId:r}=gs(),{data:s,isLoading:o,refetch:a}=AI({instanceName:n==null?void 0:n.name}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/evolutionBot/${d}`)},i=()=>{a()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("evolutionBot.title")}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(FI,{}),l.jsx(Iee,{}),l.jsx($ee,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:o?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsx(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:l.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):l.jsx(z,{variant:"link",children:e("evolutionBot.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-border"}),l.jsx(Bn,{children:l.jsx(Vee,{evolutionBotId:r,resetTable:i})})]})]})]})}const Hee=e=>["flowise","findFlowise",JSON.stringify(e)],Kee=async({instanceName:e,token:t})=>(await ie.get(`/flowise/find/${e}`,{headers:{apiKey:t}})).data,$I=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:Hee({instanceName:t}),queryFn:()=>Kee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},qee=e=>["flowise","fetchDefaultSettings",JSON.stringify(e)],Wee=async({instanceName:e,token:t})=>{const n=await ie.get(`/flowise/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Gee=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:qee({instanceName:t}),queryFn:()=>Wee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Jee=async({instanceName:e,token:t,data:n})=>(await ie.post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,Qee=async({instanceName:e,flowiseId:t,data:n})=>(await ie.put(`/flowise/update/${t}/${e}`,n)).data,Zee=async({instanceName:e,flowiseId:t})=>(await ie.delete(`/flowise/delete/${t}/${e}`)).data,Yee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,Xee=async({instanceName:e,token:t,data:n})=>(await ie.post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data;function rm(){const e=Le(Xee,{invalidateKeys:[["flowise","fetchDefaultSettings"]]}),t=Le(Yee,{invalidateKeys:[["flowise","getFlowise"],["flowise","fetchSessions"]]}),n=Le(Zee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),r=Le(Qee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),s=Le(Jee,{invalidateKeys:[["flowise","findFlowise"]]});return{setDefaultSettingsFlowise:e,changeStatusFlowise:t,deleteFlowise:n,updateFlowise:r,createFlowise:s}}const ete=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),flowiseIdFallback:k.union([k.null(),k.string()]).optional(),splitMessages:k.boolean(),timePerChar:k.string()});function tte(){const{t:e}=Te(),{instance:t}=Ve(),{setDefaultSettingsFlowise:n}=rm(),[r,s]=v.useState(!1),{data:o,refetch:a}=Gee({instanceName:t==null?void 0:t.name,enabled:r}),{data:c,refetch:u}=$I({instanceName:t==null?void 0:t.name,enabled:r}),i=zt({resolver:Ut(ete),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{o&&i.reset({expire:o!=null&&o.expire?o.expire.toString():"0",keywordFinish:o.keywordFinish,delayMessage:o.delayMessage?o.delayMessage.toString():"0",unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime?o.debounceTime.toString():"0",ignoreJids:o.ignoreJids,flowiseIdFallback:o.flowiseIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar?o.timePerChar.toString():"0"})},[o]);const d=async f=>{var g,h,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),flowiseIdFallback:f.flowiseIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),G.success(e("flowise.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),G.error(`Error: ${(m=(h=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){a(),u()}return l.jsxs(pt,{open:r,onOpenChange:s,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("flowise.defaultSettings")})}),l.jsx(Mn,{...i,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:(c==null?void 0:c.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),l.jsx($,{name:"expire",label:e("flowise.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:e("flowise.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:e("flowise.form.timePerChar.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const nte=e=>["flowise","fetchSessions",JSON.stringify(e)],rte=async({instanceName:e,flowiseId:t,token:n})=>(await ie.get(`/flowise/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,ste=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return qe({...s,queryKey:nte({instanceName:t}),queryFn:()=>rte({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function BI({flowiseId:e}){const{t}=Te(),{instance:n}=Ve(),{changeStatusFlowise:r}=rm(),[s,o]=v.useState([]),[a,c]=v.useState(!1),[u,i]=v.useState(""),{data:d,refetch:p}=ste({instanceName:n==null?void 0:n.name,flowiseId:e,enabled:a});function f(){p()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("flowise.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:t("flowise.sessions.table.actions.title")}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("flowise.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("flowise.sessions.search"),value:u,onChange:m=>i(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{})})]}),l.jsx(Ka,{columns:h,data:d??[],onSortingChange:o,state:{sorting:s,globalFilter:u},onGlobalFilterChange:i,enableGlobalFilter:!0,noResultsMessage:t("flowise.sessions.table.none")})]})]})]})}const ote=k.object({enabled:k.boolean(),description:k.string(),apiUrl:k.string(),apiKey:k.string().optional(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function zI({initialData:e,onSubmit:t,handleDelete:n,flowiseId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{}}){const{t:u}=Te(),i=zt({resolver:Ut(ote),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return l.jsx(Mn,{...i,children:l.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:u("flowise.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:u("flowise.form.description.label"),required:!0,children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("flowise.form.flowiseSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"apiUrl",label:u("flowise.form.apiUrl.label"),required:!0,children:l.jsx(F,{})}),l.jsx($,{name:"apiKey",label:u("flowise.form.apiKey.label"),children:l.jsx(F,{type:"password"})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("flowise.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:u("flowise.form.triggerType.label"),options:[{label:u("flowise.form.triggerType.keyword"),value:"keyword"},{label:u("flowise.form.triggerType.all"),value:"all"},{label:u("flowise.form.triggerType.advanced"),value:"advanced"},{label:u("flowise.form.triggerType.none"),value:"none"}]}),d==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:u("flowise.form.triggerOperator.label"),options:[{label:u("flowise.form.triggerOperator.contains"),value:"contains"},{label:u("flowise.form.triggerOperator.equals"),value:"equals"},{label:u("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:u("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:u("flowise.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:u("flowise.form.triggerValue.label"),children:l.jsx(F,{})})]}),d==="advanced"&&l.jsx($,{name:"triggerValue",label:u("flowise.form.triggerConditions.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("flowise.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:u("flowise.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:u("flowise.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:u("flowise.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:u("flowise.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:u("flowise.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:u("flowise.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:u("flowise.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:u("flowise.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:u("flowise.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:u("flowise.form.timePerChar.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:u(o?"flowise.button.saving":"flowise.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(BI,{flowiseId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:u("dify.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:u("modal.delete.title")}),l.jsx(_o,{children:u("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:u("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:u("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:u(o?"flowise.button.saving":"flowise.button.update")})]})]})]})})}function ate({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),{createFlowise:r}=rm(),[s,o]=v.useState(!1),[a,c]=v.useState(!1),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const g={enabled:i.enabled,description:i.description,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await r({instanceName:n.name,token:n.token,data:g}),G.success(t("flowise.toast.success.create")),c(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("flowise.form.title")})}),l.jsx(zI,{onSubmit:u,isModal:!0,isLoading:s})]})]})}const ite=e=>["flowise","getFlowise",JSON.stringify(e)],lte=async({instanceName:e,token:t,flowiseId:n})=>{const r=await ie.get(`/flowise/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},cte=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return qe({...s,queryKey:ite({instanceName:t}),queryFn:()=>lte({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ute({flowiseId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteFlowise:c,updateFlowise:u}=rm(),{data:i,isLoading:d}=cte({instanceName:r==null?void 0:r.name,flowiseId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:i==null?void 0:i.stopBotFromMe,keepOpen:i==null?void 0:i.keepOpen,debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,apiUrl:h.apiUrl,apiKey:h.apiKey,triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0,splitMessages:h.splitMessages||!1,timePerChar:h.timePerChar||0};await u({instanceName:r.name,flowiseId:e,data:y}),G.success(n("flowise.toast.success.update")),t(),s(`/manager/instance/${r.id}/flowise/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,flowiseId:e}),G.success(n("flowise.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/flowise`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir dify:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(zI,{initialData:p,onSubmit:f,flowiseId:e,handleDelete:g,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function uE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{flowiseId:r}=gs(),{data:s,isLoading:o,refetch:a}=$I({instanceName:n==null?void 0:n.name}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/flowise/${d}`)},i=()=>{a()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(BI,{}),l.jsx(tte,{}),l.jsx(ate,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:o?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsx(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:l.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):l.jsx(z,{variant:"link",children:e("flowise.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-border"}),l.jsx(Bn,{children:l.jsx(ute,{flowiseId:r,resetTable:i})})]})]})]})}const dte=e=>["n8n","fetchN8n",JSON.stringify(e)],fte=async({instanceName:e,token:t})=>(await ie.get(`/n8n/find/${e}`,{headers:{apikey:t}})).data,UI=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:dte({instanceName:t,token:n}),queryFn:()=>fte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},pte=async({instanceName:e,token:t,data:n})=>(await ie.post(`/n8n/create/${e}`,n,{headers:{apikey:t}})).data,gte=async({instanceName:e,n8nId:t,data:n})=>(await ie.put(`/n8n/update/${t}/${e}`,n)).data,hte=async({instanceName:e,n8nId:t})=>(await ie.delete(`/n8n/delete/${t}/${e}`)).data,mte=async({instanceName:e,token:t,data:n})=>(await ie.post(`/n8n/settings/${e}`,n,{headers:{apikey:t}})).data,vte=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/n8n/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function sm(){const e=Le(mte,{invalidateKeys:[["n8n","fetchDefaultSettings"]]}),t=Le(vte,{invalidateKeys:[["n8n","getN8n"],["n8n","fetchSessions"]]}),n=Le(hte,{invalidateKeys:[["n8n","getN8n"],["n8n","fetchN8n"],["n8n","fetchSessions"]]}),r=Le(gte,{invalidateKeys:[["n8n","getN8n"],["n8n","fetchN8n"],["n8n","fetchSessions"]]}),s=Le(pte,{invalidateKeys:[["n8n","fetchN8n"]]});return{setDefaultSettingsN8n:e,changeStatusN8n:t,deleteN8n:n,updateN8n:r,createN8n:s}}const yte=e=>["n8n","fetchDefaultSettings",JSON.stringify(e)],bte=async({instanceName:e,token:t})=>(await ie.get(`/n8n/fetchSettings/${e}`,{headers:{apikey:t}})).data,xte=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:yte({instanceName:t,token:n}),queryFn:()=>bte({instanceName:t,token:n}),enabled:!!t})},wte=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),n8nIdFallback:k.union([k.null(),k.string()]).optional(),splitMessages:k.boolean(),timePerChar:k.string()});function Ste(){const{t:e}=Te(),{instance:t}=Ve(),{setDefaultSettingsN8n:n}=sm(),[r,s]=v.useState(!1),{data:o,refetch:a}=UI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:r}),{data:c,refetch:u}=xte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),i=zt({resolver:Ut(wte),defaultValues:{expire:"0",keywordFinish:e("n8n.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("n8n.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],n8nIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{c&&i.reset({expire:c!=null&&c.expire?c.expire.toString():"0",keywordFinish:c.keywordFinish,delayMessage:c.delayMessage?c.delayMessage.toString():"0",unknownMessage:c.unknownMessage,listeningFromMe:c.listeningFromMe,stopBotFromMe:c.stopBotFromMe,keepOpen:c.keepOpen,debounceTime:c.debounceTime?c.debounceTime.toString():"0",ignoreJids:c.ignoreJids,n8nIdFallback:c.n8nIdFallback,splitMessages:c.splitMessages,timePerChar:c.timePerChar?c.timePerChar.toString():"0"})},[c]);const d=async f=>{var g,h,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),n8nIdFallback:f.n8nIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),G.success(e("n8n.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),G.error(`Error: ${(m=(h=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){u(),a()}return l.jsxs(pt,{open:r,onOpenChange:s,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:e("n8n.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("n8n.defaultSettings")})}),l.jsx(Mn,{...i,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"n8nIdFallback",label:e("n8n.form.n8nIdFallback.label"),options:(o==null?void 0:o.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),l.jsx($,{name:"expire",label:e("n8n.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("n8n.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("n8n.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("n8n.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("n8n.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("n8n.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("n8n.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("n8n.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:e("n8n.form.splitMessages.label"),reverse:!0}),l.jsx($,{name:"timePerChar",label:e("n8n.form.timePerChar.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("n8n.form.ignoreJids.label"),placeholder:e("n8n.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("n8n.button.save")})})]})})]})]})}const Cte=e=>["n8n","fetchSessions",JSON.stringify(e)],Ete=async({n8nId:e,instanceName:t})=>(await ie.get(`/n8n/fetchSessions/${e}/${t}`)).data,kte=e=>{const{n8nId:t,instanceName:n,...r}=e;return qe({...r,queryKey:Cte({n8nId:t,instanceName:n}),queryFn:()=>Ete({n8nId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function VI({n8nId:e}){const{t}=Te(),{instance:n}=Ve(),{changeStatusN8n:r}=sm(),[s,o]=v.useState([]),{data:a,refetch:c}=kte({n8nId:e,instanceName:n==null?void 0:n.name}),[u,i]=v.useState(!1),[d,p]=v.useState("");function f(){c()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("n8n.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("n8n.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("n8n.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("n8n.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("n8n.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:t("n8n.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:t("n8n.sessions.table.actions.title")}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:u,onOpenChange:i,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("n8n.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("n8n.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("n8n.sessions.search"),value:d,onChange:m=>p(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{})})]}),l.jsx(Ka,{columns:h,data:a??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("n8n.sessions.table.none")})]})]})]})}const jte=k.object({enabled:k.boolean(),description:k.string(),webhookUrl:k.string(),basicAuthUser:k.string(),basicAuthPass:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function HI({initialData:e,onSubmit:t,handleDelete:n,n8nId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{}}){const{t:u}=Te(),i=zt({resolver:Ut(jte),defaultValues:e||{enabled:!0,description:"",webhookUrl:"",basicAuthUser:"",basicAuthPass:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return l.jsx(Mn,{...i,children:l.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:u("n8n.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:u("n8n.form.description.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("n8n.form.n8nSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"webhookUrl",label:u("n8n.form.webhookUrl.label"),required:!0,children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("n8n.form.basicAuth.label")}),l.jsx(ht,{})]}),l.jsxs("div",{className:"flex w-full flex-row gap-4",children:[l.jsx($,{name:"basicAuthUser",label:u("n8n.form.basicAuthUser.label"),className:"flex-1",children:l.jsx(F,{})}),l.jsx($,{name:"basicAuthPass",label:u("n8n.form.basicAuthPass.label"),className:"flex-1",children:l.jsx(F,{type:"password"})})]}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("n8n.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:u("n8n.form.triggerType.label"),options:[{label:u("n8n.form.triggerType.keyword"),value:"keyword"},{label:u("n8n.form.triggerType.all"),value:"all"},{label:u("n8n.form.triggerType.advanced"),value:"advanced"},{label:u("n8n.form.triggerType.none"),value:"none"}]}),d==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:u("n8n.form.triggerOperator.label"),options:[{label:u("n8n.form.triggerOperator.contains"),value:"contains"},{label:u("n8n.form.triggerOperator.equals"),value:"equals"},{label:u("n8n.form.triggerOperator.startsWith"),value:"startsWith"},{label:u("n8n.form.triggerOperator.endsWith"),value:"endsWith"},{label:u("n8n.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:u("n8n.form.triggerValue.label"),children:l.jsx(F,{})})]}),d==="advanced"&&l.jsx($,{name:"triggerValue",label:u("n8n.form.triggerConditions.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("n8n.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:u("n8n.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:u("n8n.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:u("n8n.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:u("n8n.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:u("n8n.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:u("n8n.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:u("n8n.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:u("n8n.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:u("n8n.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:u("n8n.form.timePerChar.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:u(o?"n8n.button.saving":"n8n.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(VI,{n8nId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:u("n8n.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:u("modal.delete.title")}),l.jsx(_o,{children:u("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:u("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:u("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:u(o?"n8n.button.saving":"n8n.button.update")})]})]})]})})}function Tte({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createN8n:c}=sm(),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:i.enabled,description:i.description,webhookUrl:i.webhookUrl,basicAuthUser:i.basicAuthUser,basicAuthPass:i.basicAuthPass,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await c({instanceName:n.name,token:n.token,data:g}),G.success(t("n8n.toast.success.create")),a(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return l.jsxs(pt,{open:o,onOpenChange:a,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("n8n.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("n8n.form.title")})}),l.jsx(HI,{onSubmit:u,isModal:!0,isLoading:r})]})]})}const Mte=e=>["n8n","getN8n",JSON.stringify(e)],Nte=async({n8nId:e,instanceName:t})=>(await ie.get(`/n8n/fetch/${e}/${t}`)).data,_te=e=>{const{n8nId:t,instanceName:n,...r}=e;return qe({...r,queryKey:Mte({n8nId:t,instanceName:n}),queryFn:()=>Nte({n8nId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function Pte({n8nId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteN8n:c,updateN8n:u}=sm(),{data:i,isLoading:d}=_te({n8nId:e,instanceName:r==null?void 0:r.name}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",webhookUrl:(i==null?void 0:i.webhookUrl)??"",basicAuthUser:(i==null?void 0:i.basicAuthUser)??"",basicAuthPass:(i==null?void 0:i.basicAuthPass)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:(i==null?void 0:i.triggerValue)??"",expire:(i==null?void 0:i.expire)??0,keywordFinish:(i==null?void 0:i.keywordFinish)??"",delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:(i==null?void 0:i.unknownMessage)??"",listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.webhookUrl,i==null?void 0:i.basicAuthUser,i==null?void 0:i.basicAuthPass,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,webhookUrl:h.webhookUrl,basicAuthUser:h.basicAuthUser,basicAuthPass:h.basicAuthPass,triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0,splitMessages:h.splitMessages||!1,timePerChar:h.timePerChar||0};await u({instanceName:r.name,n8nId:e,data:y}),G.success(n("n8n.toast.success.update")),t(),s(`/manager/instance/${r.id}/n8n/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,n8nId:e}),G.success(n("n8n.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/n8n`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir n8n:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(HI,{initialData:p,onSubmit:f,n8nId:e,handleDelete:g,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function dE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{n8nId:r}=gs(),{data:s,refetch:o,isLoading:a}=UI({instanceName:n==null?void 0:n.name}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/n8n/${d}`)},i=()=>{o()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("n8n.title")}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(VI,{}),l.jsx(Ste,{}),l.jsx(Tte,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:a?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsx(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:l.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):l.jsx(z,{variant:"link",children:e("n8n.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-border"}),l.jsx(Bn,{children:l.jsx(Pte,{n8nId:r,resetTable:i})})]})]})]})}const Rte=e=>["openai","findOpenai",JSON.stringify(e)],Ote=async({instanceName:e,token:t})=>(await ie.get(`/openai/find/${e}`,{headers:{apiKey:t}})).data,KI=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:Rte({instanceName:t}),queryFn:()=>Ote({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Ite=e=>["openai","findOpenaiCreds",JSON.stringify(e)],Dte=async({instanceName:e,token:t})=>(await ie.get(`/openai/creds/${e}`,{headers:{apiKey:t}})).data,Gw=e=>{const{instanceName:t,token:n,...r}=e;return qe({staleTime:1e3*60*60*6,...r,queryKey:Ite({instanceName:t}),queryFn:()=>Dte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Ate=async({instanceName:e,token:t,data:n})=>(await ie.post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,Fte=async({openaiCredsId:e,instanceName:t})=>(await ie.delete(`/openai/creds/${e}/${t}`)).data,Lte=async({instanceName:e,token:t,data:n})=>(await ie.post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,$te=async({instanceName:e,token:t,openaiId:n,data:r})=>(await ie.put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,Bte=async({instanceName:e,token:t,openaiId:n})=>(await ie.delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,zte=async({instanceName:e,token:t,data:n})=>(await ie.post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,Ute=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function sf(){const e=Le(zte,{invalidateKeys:[["openai","fetchDefaultSettings"]]}),t=Le(Ute,{invalidateKeys:[["openai","getOpenai"],["openai","fetchSessions"]]}),n=Le(Bte,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),r=Le($te,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),s=Le(Lte,{invalidateKeys:[["openai","findOpenai"]]}),o=Le(Ate,{invalidateKeys:[["openai","findOpenaiCreds"]]}),a=Le(Fte,{invalidateKeys:[["openai","findOpenaiCreds"]]});return{setDefaultSettingsOpenai:e,changeStatusOpenai:t,deleteOpenai:n,updateOpenai:r,createOpenai:s,createOpenaiCreds:o,deleteOpenaiCreds:a}}const Vte=k.object({name:k.string(),apiKey:k.string()});function qI({onCredentialsUpdate:e,showText:t=!0}){const{t:n}=Te(),{instance:r}=Ve(),{createOpenaiCreds:s,deleteOpenaiCreds:o}=sf(),[a,c]=v.useState(!1),[u,i]=v.useState([]),{data:d}=Gw({instanceName:r==null?void 0:r.name,enabled:a}),p=zt({resolver:Ut(Vte),defaultValues:{name:"",apiKey:""}}),f=async m=>{var x,b,y;try{if(!r||!r.name)throw new Error("instance not found.");const w={name:m.name,apiKey:m.apiKey};await s({instanceName:r.name,token:r.token,data:w}),G.success(n("openai.toast.success.credentialsCreate")),p.reset(),e&&e()}catch(w){console.error("Error:",w),G.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}},g=async m=>{var x,b,y;if(!(r!=null&&r.name)){G.error("Instance not found.");return}try{await o({openaiCredsId:m,instanceName:r==null?void 0:r.name}),G.success(n("openai.toast.success.credentialsDelete")),e&&e()}catch(w){console.error("Error:",w),G.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}},h=[{accessorKey:"name",header:({column:m})=>l.jsxs(z,{variant:"ghost",onClick:()=>m.toggleSorting(m.getIsSorted()==="asc"),children:[n("openai.credentials.table.name"),l.jsx($B,{className:"ml-2 h-4 w-4"})]}),cell:({row:m})=>l.jsx("div",{children:m.getValue("name")})},{accessorKey:"apiKey",header:()=>l.jsx("div",{className:"text-right",children:n("openai.credentials.table.apiKey")}),cell:({row:m})=>l.jsxs("div",{children:[`${m.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:n("openai.credentials.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:n("openai.credentials.table.actions.title")}),l.jsx(Gs,{}),l.jsx(tt,{onClick:()=>g(x.id),children:n("openai.credentials.table.actions.delete")})]})]})}}];return l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"secondary",size:"sm",type:"button",children:t?l.jsxs(l.Fragment,{children:[l.jsx(n3,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden md:inline",children:n("openai.credentials.title")})]}):l.jsx(Ws,{size:16})})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:n("openai.credentials.title")})}),l.jsx(Mn,{...p,children:l.jsx("div",{onClick:m=>m.stopPropagation(),onSubmit:m=>m.stopPropagation(),onKeyDown:m=>m.stopPropagation(),children:l.jsxs("form",{onSubmit:m=>{m.preventDefault(),m.stopPropagation(),p.handleSubmit(f)(m)},className:"w-full space-y-6",children:[l.jsx("div",{children:l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsx($,{name:"name",label:n("openai.credentials.table.name"),children:l.jsx(F,{})}),l.jsx($,{name:"apiKey",label:n("openai.credentials.table.apiKey"),children:l.jsx(F,{type:"password"})})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:n("openai.button.save")})})]})})}),l.jsx(ht,{}),l.jsx("div",{children:l.jsx(Ka,{columns:h,data:d??[],onSortingChange:i,state:{sorting:u},noResultsMessage:n("openai.credentials.table.none")})})]})]})}const Hte=e=>["openai","fetchDefaultSettings",JSON.stringify(e)],Kte=async({instanceName:e,token:t})=>{const n=await ie.get(`/openai/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},qte=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:Hte({instanceName:t}),queryFn:()=>Kte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Wte=k.object({openaiCredsId:k.string(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number().default(0),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),speechToText:k.boolean(),ignoreJids:k.array(k.string()).default([]),openaiIdFallback:k.union([k.null(),k.string()]).optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function Gte(){const{t:e}=Te(),{instance:t}=Ve(),{setDefaultSettingsOpenai:n}=sf(),[r,s]=v.useState(!1),{data:o,refetch:a}=qte({instanceName:t==null?void 0:t.name,enabled:r}),{data:c,refetch:u}=KI({instanceName:t==null?void 0:t.name,enabled:r}),{data:i}=Gw({instanceName:t==null?void 0:t.name,enabled:r}),d=zt({resolver:Ut(Wte),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0,splitMessages:!1,timePerChar:0}});v.useEffect(()=>{o&&d.reset({openaiCredsId:o.openaiCredsId,expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0,speechToText:o.speechToText,ignoreJids:o.ignoreJids,openaiIdFallback:o.openaiIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar??0})},[o]);const p=async g=>{var h,m,x;try{if(!t||!t.name)throw new Error("instance not found.");const b={openaiCredsId:g.openaiCredsId,expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime,speechToText:g.speechToText,openaiIdFallback:g.openaiIdFallback||void 0,ignoreJids:g.ignoreJids,splitMessages:g.splitMessages,timePerChar:g.timePerChar};await n({instanceName:t.name,token:t.token,data:b}),G.success(e("openai.toast.defaultSettings.success"))}catch(b){console.error("Error:",b),G.error(`Error: ${(x=(m=(h=b==null?void 0:b.response)==null?void 0:h.data)==null?void 0:m.response)==null?void 0:x.message}`)}};function f(){a(),u()}return l.jsxs(pt,{open:r,onOpenChange:s,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("openai.defaultSettings")})}),l.jsx(Mn,{...d,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:d.handleSubmit(p),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:(i==null?void 0:i.filter(g=>!!g.id).map(g=>({label:g.name?g.name:g.apiKey.substring(0,15)+"...",value:g.id})))||[]}),l.jsx(jt,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:(c==null?void 0:c.filter(g=>!!g.id).map(g=>({label:g.description,value:g.id})))??[]}),l.jsx($,{name:"expire",label:e("openai.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),l.jsx(ge,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:e("openai.form.splitMessages.label"),reverse:!0}),d.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:e("openai.form.timePerChar.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const Jte=e=>["openai","getModels",JSON.stringify(e)],Qte=async({instanceName:e,openaiCredsId:t,token:n})=>{const r=t?{openaiCredsId:t}:{};return(await ie.get(`/openai/getModels/${e}`,{headers:{apiKey:n},params:r})).data},Zte=e=>{const{instanceName:t,openaiCredsId:n,token:r,...s}=e;return qe({staleTime:1e3*60*60*6,...s,queryKey:Jte({instanceName:t,openaiCredsId:n}),queryFn:()=>Qte({instanceName:t,openaiCredsId:n,token:r}),enabled:!!t&&!!n&&(e.enabled??!0)})},Yte=e=>["openai","fetchSessions",JSON.stringify(e)],Xte=async({instanceName:e,openaiId:t,token:n})=>(await ie.get(`/openai/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,ene=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return qe({...s,queryKey:Yte({instanceName:t}),queryFn:()=>Xte({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function WI({openaiId:e}){const{t}=Te(),{instance:n}=Ve(),{changeStatusOpenai:r}=sf(),[s,o]=v.useState([]),[a,c]=v.useState(!1),{data:u,refetch:i}=ene({instanceName:n==null?void 0:n.name,openaiId:e,enabled:a}),[d,p]=v.useState("");function f(){i()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("openai.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",size:"icon",children:[l.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:t("openai.sessions.table.actions.title")}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("openai.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("openai.sessions.search"),value:d,onChange:m=>p(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{size:16})})]}),l.jsx(Ka,{columns:h,data:u??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("openai.sessions.table.none")})]})]})]})}const tne=k.object({enabled:k.boolean(),description:k.string(),openaiCredsId:k.string(),botType:k.string(),assistantId:k.string().optional(),functionUrl:k.string().optional(),model:k.string().optional(),systemMessages:k.string().optional(),assistantMessages:k.string().optional(),userMessages:k.string().optional(),maxTokens:k.coerce.number().optional(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional(),splitMessages:k.boolean().optional(),timePerChar:k.coerce.number().optional()});function GI({initialData:e,onSubmit:t,handleDelete:n,openaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{},open:u}){const{t:i}=Te(),{instance:d}=Ve(),[p,f]=v.useState(!1),{data:g,refetch:h}=Gw({instanceName:d==null?void 0:d.name,enabled:u}),m=zt({resolver:Ut(tne),defaultValues:e||{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:0,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),x=m.watch("botType"),b=m.watch("triggerType"),y=m.watch("openaiCredsId"),{data:w,isLoading:S,refetch:E}=Zte({instanceName:d==null?void 0:d.name,openaiCredsId:y,token:d==null?void 0:d.token,enabled:p&&!!y}),C=()=>{y&&(f(!0),E())},T=()=>{h()};return l.jsx(Mn,{...m,children:l.jsxs("form",{onSubmit:m.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:i("openai.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:i("openai.form.description.label"),required:!0,children:l.jsx(F,{})}),l.jsx("div",{className:"space-y-2",children:l.jsxs("div",{className:"flex items-end gap-2",children:[l.jsx("div",{className:"flex-1",children:l.jsx(jt,{name:"openaiCredsId",label:i("openai.form.openaiCredsId.label"),required:!0,options:(g==null?void 0:g.filter(j=>!!j.id).map(j=>({label:j.name?j.name:j.apiKey.substring(0,15)+"...",value:j.id})))??[]})}),l.jsx(qI,{onCredentialsUpdate:T,showText:!1})]})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.openaiSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"botType",label:i("openai.form.botType.label"),required:!0,options:[{label:i("openai.form.botType.assistant"),value:"assistant"},{label:i("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),x==="assistant"&&l.jsxs(l.Fragment,{children:[l.jsx($,{name:"assistantId",label:i("openai.form.assistantId.label"),required:!0,children:l.jsx(F,{})}),l.jsx($,{name:"functionUrl",label:i("openai.form.functionUrl.label"),required:!0,children:l.jsx(F,{})})]}),x==="chatCompletion"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"space-y-2",children:l.jsxs("div",{className:"flex items-end gap-2",children:[l.jsx("div",{className:"flex-1",children:l.jsx(jt,{name:"model",label:i("openai.form.model.label"),required:!0,disabled:!w||w.length===0,options:(w==null?void 0:w.map(j=>({label:j.id,value:j.id})))??[]})}),l.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:!y||S,onClick:C,className:"mb-2",children:S?l.jsxs(l.Fragment,{children:[l.jsx(rg,{className:"mr-2 h-4 w-4 animate-spin"}),i("openai.button.loading")]}):l.jsxs(l.Fragment,{children:[l.jsx(rg,{className:"mr-2 h-4 w-4"}),i("openai.button.loadModels")]})})]})}),l.jsx($,{name:"systemMessages",label:i("openai.form.systemMessages.label"),children:l.jsx(Vl,{})}),l.jsx($,{name:"assistantMessages",label:i("openai.form.assistantMessages.label"),children:l.jsx(Vl,{})}),l.jsx($,{name:"userMessages",label:i("openai.form.userMessages.label"),children:l.jsx(Vl,{})}),l.jsx($,{name:"maxTokens",label:i("openai.form.maxTokens.label"),children:l.jsx(F,{type:"number"})})]}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:i("openai.form.triggerType.label"),required:!0,options:[{label:i("openai.form.triggerType.keyword"),value:"keyword"},{label:i("openai.form.triggerType.all"),value:"all"},{label:i("openai.form.triggerType.advanced"),value:"advanced"},{label:i("openai.form.triggerType.none"),value:"none"}]}),b==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:i("openai.form.triggerOperator.label"),required:!0,options:[{label:i("openai.form.triggerOperator.contains"),value:"contains"},{label:i("openai.form.triggerOperator.equals"),value:"equals"},{label:i("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:i("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:i("openai.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:i("openai.form.triggerValue.label"),required:!0,children:l.jsx(F,{})})]}),b==="advanced"&&l.jsx($,{name:"triggerValue",label:i("openai.form.triggerConditions.label"),required:!0,children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:i("openai.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:i("openai.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:i("openai.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:i("openai.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:i("openai.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:i("openai.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:i("openai.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:i("openai.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(ge,{name:"splitMessages",label:i("openai.form.splitMessages.label"),reverse:!0}),m.watch("splitMessages")&&l.jsx($,{name:"timePerChar",label:i("openai.form.timePerChar.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:i(o?"openai.button.saving":"openai.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(WI,{openaiId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:i("dify.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:i("modal.delete.title")}),l.jsx(_o,{children:i("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:i("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:i("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:i(o?"openai.button.saving":"openai.button.update")})]})]})]})})}function nne({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),{createOpenai:r}=sf(),[s,o]=v.useState(!1),[a,c]=v.useState(!1),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const g={enabled:i.enabled,description:i.description,openaiCredsId:i.openaiCredsId,botType:i.botType,assistantId:i.assistantId||"",functionUrl:i.functionUrl||"",model:i.model||"",systemMessages:[i.systemMessages||""],assistantMessages:[i.assistantMessages||""],userMessages:[i.userMessages||""],maxTokens:i.maxTokens||0,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await r({instanceName:n.name,token:n.token,data:g}),G.success(t("openai.toast.success.create")),c(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("openai.form.title")})}),l.jsx(GI,{onSubmit:u,isModal:!0,isLoading:s,open:a})]})]})}const rne=e=>["openai","getOpenai",JSON.stringify(e)],sne=async({instanceName:e,token:t,openaiId:n})=>{const r=await ie.get(`/openai/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},one=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return qe({...s,queryKey:rne({instanceName:t}),queryFn:()=>sne({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ane({openaiId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteOpenai:c,updateOpenai:u}=sf(),{data:i,isLoading:d}=one({instanceName:r==null?void 0:r.name,openaiId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",openaiCredsId:(i==null?void 0:i.openaiCredsId)??"",botType:(i==null?void 0:i.botType)??"",assistantId:(i==null?void 0:i.assistantId)||"",functionUrl:(i==null?void 0:i.functionUrl)||"",model:(i==null?void 0:i.model)||"",systemMessages:Array.isArray(i==null?void 0:i.systemMessages)?i==null?void 0:i.systemMessages.join(", "):(i==null?void 0:i.systemMessages)||"",assistantMessages:Array.isArray(i==null?void 0:i.assistantMessages)?i==null?void 0:i.assistantMessages.join(", "):(i==null?void 0:i.assistantMessages)||"",userMessages:Array.isArray(i==null?void 0:i.userMessages)?i==null?void 0:i.userMessages.join(", "):(i==null?void 0:i.userMessages)||"",maxTokens:(i==null?void 0:i.maxTokens)||0,triggerType:(i==null?void 0:i.triggerType)||"",triggerOperator:(i==null?void 0:i.triggerOperator)||"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)||0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)||0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:i==null?void 0:i.stopBotFromMe,keepOpen:i==null?void 0:i.keepOpen,debounceTime:(i==null?void 0:i.debounceTime)||0,splitMessages:(i==null?void 0:i.splitMessages)||!1,timePerChar:(i==null?void 0:i.timePerChar)||0}),[i==null?void 0:i.assistantId,i==null?void 0:i.assistantMessages,i==null?void 0:i.botType,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.functionUrl,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.maxTokens,i==null?void 0:i.model,i==null?void 0:i.openaiCredsId,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.systemMessages,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.userMessages,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,openaiCredsId:h.openaiCredsId,botType:h.botType,assistantId:h.assistantId||"",functionUrl:h.functionUrl||"",model:h.model||"",systemMessages:[h.systemMessages||""],assistantMessages:[h.assistantMessages||""],userMessages:[h.userMessages||""],maxTokens:h.maxTokens||0,triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0,splitMessages:h.splitMessages||!1,timePerChar:h.timePerChar||0};await u({instanceName:r.name,openaiId:e,data:y}),G.success(n("openai.toast.success.update")),t(),s(`/manager/instance/${r.id}/openai/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,openaiId:e}),G.success(n("openai.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/openai`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir dify:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(GI,{initialData:p,onSubmit:f,openaiId:e,handleDelete:g,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function fE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{botId:r}=gs(),{data:s,isLoading:o,refetch:a}=KI({instanceName:n==null?void 0:n.name}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/openai/${d}`)},i=()=>{a()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(WI,{}),l.jsx(Gte,{}),l.jsx(qI,{}),l.jsx(nne,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:o?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsxs(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[l.jsx("h4",{className:"text-base",children:d.description||d.id}),l.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):l.jsx(z,{variant:"link",children:e("openai.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-border"}),l.jsx(Bn,{children:l.jsx(ane,{openaiId:r,resetTable:i})})]})]})]})}const ine=e=>["proxy","fetchProxy",JSON.stringify(e)],lne=async({instanceName:e,token:t})=>(await ie.get(`/proxy/find/${e}`,{headers:{apiKey:t}})).data,cne=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:ine({instanceName:t,token:n}),queryFn:()=>lne({instanceName:t,token:n}),enabled:!!t})},une=async({instanceName:e,token:t,data:n})=>(await ie.post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data;function dne(){return{createProxy:Le(une,{invalidateKeys:[["proxy","fetchProxy"]]})}}const fne=k.object({enabled:k.boolean(),host:k.string(),port:k.string(),protocol:k.string(),username:k.string(),password:k.string()});function pne(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{createProxy:s}=dne(),{data:o}=cne({instanceName:t==null?void 0:t.name}),a=zt({resolver:Ut(fne),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,host:o.host,port:o.port,protocol:o.protocol,username:o.username,password:o.password})},[o]);const c=async u=>{var i,d,p;if(t){r(!0);try{const f={enabled:u.enabled,host:u.host,port:u.port,protocol:u.protocol,username:u.username,password:u.password};await s({instanceName:t.name,token:t.token,data:f}),G.success(e("proxy.toast.success"))}catch(f){console.error(e("proxy.toast.error"),f),G.error(`Error : ${(p=(d=(i=f==null?void 0:f.response)==null?void 0:i.data)==null?void 0:d.response)==null?void 0:p.message}`)}finally{r(!1)}}};return l.jsx(l.Fragment,{children:l.jsx(La,{...a,children:l.jsx("form",{onSubmit:a.handleSubmit(c),className:"w-full space-y-6",children:l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),l.jsx(Da,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[l.jsx(ge,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),l.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[l.jsx($,{name:"protocol",label:e("proxy.form.protocol.label"),children:l.jsx(F,{})}),l.jsx($,{name:"host",label:e("proxy.form.host.label"),children:l.jsx(F,{})}),l.jsx($,{name:"port",label:e("proxy.form.port.label"),children:l.jsx(F,{type:"number"})})]}),l.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[l.jsx($,{name:"username",label:e("proxy.form.username.label"),children:l.jsx(F,{})}),l.jsx($,{name:"password",label:e("proxy.form.password.label"),children:l.jsx(F,{type:"password"})})]}),l.jsx("div",{className:"flex justify-end px-4 pt-6",children:l.jsx(z,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const gne=e=>["rabbitmq","fetchRabbitmq",JSON.stringify(e)],hne=async({instanceName:e,token:t})=>(await ie.get(`/rabbitmq/find/${e}`,{headers:{apiKey:t}})).data,mne=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:gne({instanceName:t,token:n}),queryFn:()=>hne({instanceName:t,token:n}),enabled:!!t})},vne=async({instanceName:e,token:t,data:n})=>(await ie.post(`/rabbitmq/set/${e}`,{rabbitmq:n},{headers:{apikey:t}})).data;function yne(){return{createRabbitmq:Le(vne,{invalidateKeys:[["rabbitmq","fetchRabbitmq"]]})}}const bne=k.object({enabled:k.boolean(),events:k.array(k.string())});function xne(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{createRabbitmq:s}=yne(),{data:o}=mne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=zt({resolver:Ut(bne),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const c=async p=>{var f,g,h;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),G.success(e("rabbitmq.toast.success"))}catch(m){console.error(e("rabbitmq.toast.error"),m),G.error(`Error: ${(h=(g=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:g.response)==null?void 0:h.message}`)}finally{r(!1)}}},u=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",u)},d=()=>{a.setValue("events",[])};return l.jsx(l.Fragment,{children:l.jsx(La,{...a,children:l.jsx("form",{onSubmit:a.handleSubmit(c),className:"w-full space-y-6",children:l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),l.jsx(Da,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[l.jsx(ge,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),l.jsxs("div",{className:"mb-4 flex justify-between",children:[l.jsx(z,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),l.jsx(z,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),l.jsx($a,{control:a.control,name:"events",render:({field:p})=>l.jsxs(Ro,{className:"flex flex-col",children:[l.jsx(Er,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),l.jsx(qs,{children:l.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:u.sort((f,g)=>f.localeCompare(g)).map(f=>l.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[l.jsx(Er,{className:me("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),l.jsx($c,{checked:p.value.includes(f),onCheckedChange:g=>{g?p.onChange([...p.value,f]):p.onChange(p.value.filter(h=>h!==f))}})]},f))})})]})})]}),l.jsx("div",{className:"mx-4 flex justify-end pt-6",children:l.jsx(z,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const wne=e=>["instance","fetchSettings",JSON.stringify(e)],Sne=async({instanceName:e,token:t})=>(await ie.get(`/settings/find/${e}`,{headers:{apikey:t}})).data,Cne=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:wne({instanceName:t,token:n}),queryFn:()=>Sne({instanceName:t,token:n}),enabled:!!t})},Ene=k.object({rejectCall:k.boolean(),msgCall:k.string().optional(),groupsIgnore:k.boolean(),alwaysOnline:k.boolean(),readMessages:k.boolean(),syncFullHistory:k.boolean(),readStatus:k.boolean()});function kne(){const{t:e}=Te(),[t,n]=v.useState(!1),{instance:r}=Ve(),{updateSettings:s}=Nh(),{data:o,isLoading:a}=Cne({instanceName:r==null?void 0:r.name,token:r==null?void 0:r.token}),c=zt({resolver:Ut(Ene),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});v.useEffect(()=>{o&&c.reset({rejectCall:o.rejectCall,msgCall:o.msgCall||"",groupsIgnore:o.groupsIgnore,alwaysOnline:o.alwaysOnline,readMessages:o.readMessages,syncFullHistory:o.syncFullHistory,readStatus:o.readStatus})},[c,o]);const u=async p=>{try{if(!r||!r.name)throw new Error("instance not found");n(!0);const f={rejectCall:p.rejectCall,msgCall:p.msgCall,groupsIgnore:p.groupsIgnore,alwaysOnline:p.alwaysOnline,readMessages:p.readMessages,syncFullHistory:p.syncFullHistory,readStatus:p.readStatus};await s({instanceName:r.name,token:r.token,data:f}),G.success(e("settings.toast.success"))}catch(f){console.error(e("settings.toast.success"),f),G.error(e("settings.toast.error"))}finally{n(!1)}},i=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],d=c.watch("rejectCall");return a?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:l.jsx(La,{...c,children:l.jsx("form",{onSubmit:c.handleSubmit(u),className:"w-full space-y-6",children:l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),l.jsx(ht,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[l.jsxs("div",{className:"flex flex-col p-4",children:[l.jsx(ge,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),d&&l.jsx("div",{className:"mr-16 mt-2",children:l.jsx($,{name:"msgCall",children:l.jsx(Vl,{placeholder:e("settings.form.msgCall.description")})})})]}),i.map(p=>l.jsx("div",{className:"flex p-4",children:l.jsx(ge,{name:p.name,label:p.label,className:"w-full justify-between",helper:p.description})},p.name)),l.jsx("div",{className:"flex justify-end pt-6",children:l.jsx(z,{type:"submit",disabled:t,children:e(t?"settings.button.saving":"settings.button.save")})})]})]})})})})}const jne=e=>["sqs","fetchSqs",JSON.stringify(e)],Tne=async({instanceName:e,token:t})=>(await ie.get(`/sqs/find/${e}`,{headers:{apiKey:t}})).data,Mne=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:jne({instanceName:t,token:n}),queryFn:()=>Tne({instanceName:t,token:n}),enabled:!!t})},Nne=async({instanceName:e,token:t,data:n})=>(await ie.post(`/sqs/set/${e}`,{sqs:n},{headers:{apikey:t}})).data;function _ne(){return{createSqs:Le(Nne,{invalidateKeys:[["sqs","fetchSqs"]]})}}const Pne=k.object({enabled:k.boolean(),events:k.array(k.string())});function Rne(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{createSqs:s}=_ne(),{data:o}=Mne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=zt({resolver:Ut(Pne),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const c=async p=>{var f,g,h;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),G.success(e("sqs.toast.success"))}catch(m){console.error(e("sqs.toast.error"),m),G.error(`Error: ${(h=(g=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:g.response)==null?void 0:h.message}`)}finally{r(!1)}}},u=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",u)},d=()=>{a.setValue("events",[])};return l.jsx(l.Fragment,{children:l.jsx(La,{...a,children:l.jsx("form",{onSubmit:a.handleSubmit(c),className:"w-full space-y-6",children:l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),l.jsx(Da,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[l.jsx(ge,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),l.jsxs("div",{className:"mb-4 flex justify-between",children:[l.jsx(z,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),l.jsx(z,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),l.jsx($a,{control:a.control,name:"events",render:({field:p})=>l.jsxs(Ro,{className:"flex flex-col",children:[l.jsx(Er,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),l.jsx(qs,{children:l.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:u.sort((f,g)=>f.localeCompare(g)).map(f=>l.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[l.jsx(Er,{className:me("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),l.jsx($c,{checked:p.value.includes(f),onCheckedChange:g=>{g?p.onChange([...p.value,f]):p.onChange(p.value.filter(h=>h!==f))}})]},f))})})]})})]}),l.jsx("div",{className:"mx-4 flex justify-end pt-6",children:l.jsx(z,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const One=e=>["typebot","findTypebot",JSON.stringify(e)],Ine=async({instanceName:e,token:t})=>(await ie.get(`/typebot/find/${e}`,{headers:{apiKey:t}})).data,JI=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:One({instanceName:t}),queryFn:()=>Ine({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Dne=e=>["typebot","fetchDefaultSettings",JSON.stringify(e)],Ane=async({instanceName:e,token:t})=>{const n=await ie.get(`/typebot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Fne=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:Dne({instanceName:t}),queryFn:()=>Ane({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Lne=async({instanceName:e,token:t,data:n})=>(await ie.post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,$ne=async({instanceName:e,token:t,typebotId:n,data:r})=>(await ie.put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,Bne=async({instanceName:e,typebotId:t})=>(await ie.delete(`/typebot/delete/${t}/${e}`)).data,zne=async({instanceName:e,token:t,data:n})=>(await ie.post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,Une=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await ie.post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function om(){const e=Le(zne,{invalidateKeys:[["typebot","fetchDefaultSettings"]]}),t=Le(Une,{invalidateKeys:[["typebot","getTypebot"],["typebot","fetchSessions"]]}),n=Le(Bne,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),r=Le($ne,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),s=Le(Lne,{invalidateKeys:[["typebot","findTypebot"]]});return{setDefaultSettingsTypebot:e,changeStatusTypebot:t,deleteTypebot:n,updateTypebot:r,createTypebot:s}}const Vne=k.object({expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function Hne(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{setDefaultSettingsTypebot:s}=om(),{data:o,refetch:a}=Fne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),{data:c,refetch:u}=JI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),i=zt({resolver:Ut(Vne),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});v.useEffect(()=>{o&&i.reset({expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0})},[o]);const d=async f=>{var g,h,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:f.expire,keywordFinish:f.keywordFinish,delayMessage:f.delayMessage,unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:f.debounceTime};await s({instanceName:t.name,token:t.token,data:x}),G.success(e("typebot.toast.defaultSettings.success"))}catch(x){console.error(e("typebot.toast.defaultSettings.error"),x),G.error(`Error: ${(m=(h=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){a(),u()}return l.jsxs(pt,{open:n,onOpenChange:r,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(To,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[l.jsx(dt,{children:l.jsx(yt,{children:e("typebot.modal.defaultSettings.title")})}),l.jsx(Mn,{...i,children:l.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[l.jsx("div",{children:l.jsxs("div",{className:"space-y-4",children:[l.jsx(jt,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:(c==null?void 0:c.filter(f=>!!f.id).map(f=>({label:f.typebot,value:f.description})))??[]}),l.jsx($,{name:"expire",label:e("typebot.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:l.jsx(F,{type:"number"})}),l.jsx(Ba,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),l.jsx(_t,{children:l.jsx(z,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const Kne=e=>["typebot","fetchSessions",JSON.stringify(e)],qne=async({instanceName:e,typebotId:t,token:n})=>(await ie.get(`/typebot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Wne=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return qe({...s,queryKey:Kne({instanceName:t}),queryFn:()=>qne({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function QI({typebotId:e}){const{t}=Te(),{instance:n}=Ve(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[c,u]=v.useState(""),{changeStatusTypebot:i}=om(),{data:d,refetch:p}=Wne({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token,typebotId:e});function f(){p()}const g=async(m,x)=>{var b,y,w;try{if(!n)return;await i({instanceName:n.name,token:n.token,remoteJid:m,status:x}),G.success(t("typebot.toast.success.status")),f()}catch(S){console.error("Error:",S),G.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},h=[{accessorKey:"remoteJid",header:()=>l.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>l.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>l.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>l.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:m})=>l.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return l.jsxs(ms,{children:[l.jsx(vs,{asChild:!0,children:l.jsxs(z,{variant:"ghost",className:"h-8 w-8 p-0",children:[l.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),l.jsx(Ia,{className:"h-4 w-4"})]})}),l.jsxs(Mr,{align:"end",children:[l.jsx(No,{children:"Actions"}),l.jsx(Gs,{}),x.status!=="opened"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"opened"),children:[l.jsx(qi,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"paused"),children:[l.jsx(Ki,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),x.status!=="closed"&&l.jsxs(tt,{onClick:()=>g(x.remoteJid,"closed"),children:[l.jsx(Ui,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),l.jsxs(tt,{onClick:()=>g(x.remoteJid,"delete"),children:[l.jsx(Vi,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}];return l.jsxs(pt,{open:o,onOpenChange:a,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{variant:"secondary",size:"sm",children:[l.jsx(Hi,{size:16,className:"mr-1"})," ",l.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[l.jsx(dt,{children:l.jsx(yt,{children:t("typebot.sessions.label")})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[l.jsx(F,{placeholder:t("typebot.sessions.search"),value:c,onChange:m=>u(m.target.value)}),l.jsx(z,{variant:"outline",onClick:f,size:"icon",children:l.jsx(Wi,{size:16})})]}),l.jsx(Ka,{columns:h,data:d??[],onSortingChange:s,state:{sorting:r,globalFilter:c},onGlobalFilterChange:u,enableGlobalFilter:!0,noResultsMessage:t("typebot.sessions.table.none")})]})]})]})}const Gne=k.object({enabled:k.boolean(),description:k.string(),url:k.string(),typebot:k.string().optional(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number().optional(),keywordFinish:k.string().optional(),delayMessage:k.coerce.number().optional(),unknownMessage:k.string().optional(),listeningFromMe:k.boolean().optional(),stopBotFromMe:k.boolean().optional(),keepOpen:k.boolean().optional(),debounceTime:k.coerce.number().optional()});function ZI({initialData:e,onSubmit:t,handleDelete:n,typebotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:c=()=>{}}){const{t:u}=Te(),i=zt({resolver:Ut(Gne),defaultValues:e||{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=i.watch("triggerType");return l.jsx(Mn,{...i,children:l.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx(ge,{name:"enabled",label:u("typebot.form.enabled.label"),reverse:!0}),l.jsx($,{name:"description",label:u("typebot.form.description.label"),required:!0,children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("typebot.form.typebotSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"url",label:u("typebot.form.url.label"),required:!0,children:l.jsx(F,{})}),l.jsx($,{name:"typebot",label:u("typebot.form.typebot.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("typebot.form.triggerSettings.label")}),l.jsx(ht,{})]}),l.jsx(jt,{name:"triggerType",label:u("typebot.form.triggerType.label"),options:[{label:u("typebot.form.triggerType.keyword"),value:"keyword"},{label:u("typebot.form.triggerType.all"),value:"all"},{label:u("typebot.form.triggerType.advanced"),value:"advanced"},{label:u("typebot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&l.jsxs(l.Fragment,{children:[l.jsx(jt,{name:"triggerOperator",label:u("typebot.form.triggerOperator.label"),options:[{label:u("typebot.form.triggerOperator.contains"),value:"contains"},{label:u("typebot.form.triggerOperator.equals"),value:"equals"},{label:u("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:u("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:u("typebot.form.triggerOperator.regex"),value:"regex"}]}),l.jsx($,{name:"triggerValue",label:u("typebot.form.triggerValue.label"),children:l.jsx(F,{})})]}),d==="advanced"&&l.jsx($,{name:"triggerValue",label:u("typebot.form.triggerConditions.label"),children:l.jsx(F,{})}),l.jsxs("div",{className:"flex flex-col",children:[l.jsx("h3",{className:"my-4 text-lg font-medium",children:u("typebot.form.generalSettings.label")}),l.jsx(ht,{})]}),l.jsx($,{name:"expire",label:u("typebot.form.expire.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"keywordFinish",label:u("typebot.form.keywordFinish.label"),children:l.jsx(F,{})}),l.jsx($,{name:"delayMessage",label:u("typebot.form.delayMessage.label"),children:l.jsx(F,{type:"number"})}),l.jsx($,{name:"unknownMessage",label:u("typebot.form.unknownMessage.label"),children:l.jsx(F,{})}),l.jsx(ge,{name:"listeningFromMe",label:u("typebot.form.listeningFromMe.label"),reverse:!0}),l.jsx(ge,{name:"stopBotFromMe",label:u("typebot.form.stopBotFromMe.label"),reverse:!0}),l.jsx(ge,{name:"keepOpen",label:u("typebot.form.keepOpen.label"),reverse:!0}),l.jsx($,{name:"debounceTime",label:u("typebot.form.debounceTime.label"),children:l.jsx(F,{type:"number"})})]}),s&&l.jsx(_t,{children:l.jsx(z,{disabled:o,type:"submit",children:u(o?"typebot.button.saving":"typebot.button.save")})}),!s&&l.jsxs("div",{children:[l.jsx(QI,{typebotId:r}),l.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsx(z,{variant:"destructive",size:"sm",children:u("dify.button.delete")})}),l.jsx(ut,{children:l.jsxs(dt,{children:[l.jsx(yt,{children:u("modal.delete.title")}),l.jsx(_o,{children:u("modal.delete.messageSingle")}),l.jsxs(_t,{children:[l.jsx(z,{size:"sm",variant:"outline",onClick:()=>c(!1),children:u("button.cancel")}),l.jsx(z,{variant:"destructive",onClick:n,children:u("button.delete")})]})]})})]}),l.jsx(z,{disabled:o,type:"submit",children:u(o?"typebot.button.saving":"typebot.button.update")})]})]})]})})}function Jne({resetTable:e}){const{t}=Te(),{instance:n}=Ve(),{createTypebot:r}=om(),[s,o]=v.useState(!1),[a,c]=v.useState(!1),u=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const g={enabled:i.enabled,description:i.description,url:i.url,typebot:i.typebot||"",triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0};await r({instanceName:n.name,token:n.token,data:g}),G.success(t("typebot.toast.success.create")),c(!1),e()}catch(g){console.error("Error:",g),G.error(`Error: ${(f=(p=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return l.jsxs(pt,{open:a,onOpenChange:c,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(z,{size:"sm",children:[l.jsx(Ws,{size:16,className:"mr-1"}),l.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),l.jsxs(ut,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[l.jsx(dt,{children:l.jsx(yt,{children:t("typebot.form.title")})}),l.jsx(ZI,{onSubmit:u,isModal:!0,isLoading:s})]})]})}const Qne=e=>["typebot","getTypebot",JSON.stringify(e)],Zne=async({instanceName:e,token:t,typebotId:n})=>{const r=await ie.get(`/typebot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Yne=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return qe({...s,queryKey:Qne({instanceName:t}),queryFn:()=>Zne({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function Xne({typebotId:e,resetTable:t}){const{t:n}=Te(),{instance:r}=Ve(),s=an(),[o,a]=v.useState(!1),{deleteTypebot:c,updateTypebot:u}=om(),{data:i,isLoading:d}=Yne({instanceName:r==null?void 0:r.name,typebotId:e}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",url:(i==null?void 0:i.url)??"",typebot:(i==null?void 0:i.typebot)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0}),[i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.typebot,i==null?void 0:i.unknownMessage,i==null?void 0:i.url]),f=async h=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:h.enabled,description:h.description,url:h.url,typebot:h.typebot||"",triggerType:h.triggerType,triggerOperator:h.triggerOperator||"",triggerValue:h.triggerValue||"",expire:h.expire||0,keywordFinish:h.keywordFinish||"",delayMessage:h.delayMessage||1e3,unknownMessage:h.unknownMessage||"",listeningFromMe:h.listeningFromMe||!1,stopBotFromMe:h.stopBotFromMe||!1,keepOpen:h.keepOpen||!1,debounceTime:h.debounceTime||0};await u({instanceName:r.name,typebotId:e,data:y}),G.success(n("typebot.toast.success.update")),t(),s(`/manager/instance/${r.id}/typebot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),G.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},g=async()=>{try{r&&r.name&&e?(await c({instanceName:r.name,typebotId:e}),G.success(n("typebot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/typebot`)):console.error("instance not found")}catch(h){console.error("Erro ao excluir dify:",h)}};return d?l.jsx(Tn,{}):l.jsx("div",{className:"m-4",children:l.jsx(ZI,{initialData:p,onSubmit:f,typebotId:e,handleDelete:g,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function pE(){const{t:e}=Te(),t=Va("(min-width: 768px)"),{instance:n}=Ve(),{typebotId:r}=gs(),{data:s,isLoading:o,refetch:a}=JI({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token}),c=an(),u=d=>{n&&c(`/manager/instance/${n.id}/typebot/${d}`)},i=()=>{a()};return l.jsxs("main",{className:"pt-5",children:[l.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[l.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),l.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[l.jsx(QI,{}),l.jsx(Hne,{}),l.jsx(Jne,{resetTable:i})]})]}),l.jsx(ht,{className:"my-4"}),l.jsxs(za,{direction:t?"horizontal":"vertical",children:[l.jsx(Bn,{defaultSize:35,className:"pr-4",children:l.jsx("div",{className:"flex flex-col gap-3",children:o?l.jsx(Tn,{}):l.jsx(l.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>l.jsx(z,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${d.id}`),variant:r===d.id?"secondary":"outline",children:d.description?l.jsxs(l.Fragment,{children:[l.jsx("h4",{className:"text-base",children:d.description}),l.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[d.url," - ",d.typebot]})]}):l.jsxs(l.Fragment,{children:[l.jsx("h4",{className:"text-base",children:d.url}),l.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:d.typebot})]})},d.id)):l.jsx(z,{variant:"link",children:e("typebot.table.none")})})})}),r&&l.jsxs(l.Fragment,{children:[l.jsx(Ua,{withHandle:!0,className:"border border-black"}),l.jsx(Bn,{children:l.jsx(Xne,{typebotId:r,resetTable:i})})]})]})]})}const ere=e=>["webhook","fetchWebhook",JSON.stringify(e)],tre=async({instanceName:e,token:t})=>(await ie.get(`/webhook/find/${e}`,{headers:{apiKey:t}})).data,nre=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:ere({instanceName:t,token:n}),queryFn:()=>tre({instanceName:t,token:n}),enabled:!!t})},rre=async({instanceName:e,token:t,data:n})=>(await ie.post(`/webhook/set/${e}`,{webhook:n},{headers:{apikey:t}})).data;function sre(){return{createWebhook:Le(rre,{invalidateKeys:[["webhook","fetchWebhook"]]})}}const ore=k.object({enabled:k.boolean(),url:k.string().url("Invalid URL format"),events:k.array(k.string()),base64:k.boolean(),byEvents:k.boolean()});function are(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{createWebhook:s}=sre(),{data:o}=nre({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=zt({resolver:Ut(ore),defaultValues:{enabled:!1,url:"",events:[],base64:!1,byEvents:!1}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,url:o.url,events:o.events,base64:o.webhookBase64,byEvents:o.webhookByEvents})},[o]);const c=async p=>{var f,g,h;if(t){r(!0);try{const m={enabled:p.enabled,url:p.url,events:p.events,base64:p.base64,byEvents:p.byEvents};await s({instanceName:t.name,token:t.token,data:m}),G.success(e("webhook.toast.success"))}catch(m){console.error(e("webhook.toast.error"),m),G.error(`Error: ${(h=(g=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:g.response)==null?void 0:h.message}`)}finally{r(!1)}}},u=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",u)},d=()=>{a.setValue("events",[])};return l.jsx(l.Fragment,{children:l.jsx(La,{...a,children:l.jsx("form",{onSubmit:a.handleSubmit(c),className:"w-full space-y-6",children:l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),l.jsx(Da,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[l.jsx(ge,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),l.jsx($,{name:"url",label:"URL",children:l.jsx(F,{})}),l.jsx(ge,{name:"byEvents",label:e("webhook.form.byEvents.label"),className:"w-full justify-between",helper:e("webhook.form.byEvents.description")}),l.jsx(ge,{name:"base64",label:e("webhook.form.base64.label"),className:"w-full justify-between",helper:e("webhook.form.base64.description")}),l.jsxs("div",{className:"mb-4 flex justify-between",children:[l.jsx(z,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),l.jsx(z,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),l.jsx($a,{control:a.control,name:"events",render:({field:p})=>l.jsxs(Ro,{className:"flex flex-col",children:[l.jsx(Er,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),l.jsx(qs,{children:l.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:u.sort((f,g)=>f.localeCompare(g)).map(f=>l.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[l.jsx(Er,{className:me("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),l.jsx($c,{checked:p.value.includes(f),onCheckedChange:g=>{g?p.onChange([...p.value,f]):p.onChange(p.value.filter(h=>h!==f))}})]},f))})})]})})]}),l.jsx("div",{className:"mx-4 flex justify-end pt-6",children:l.jsx(z,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const ire=e=>["websocket","fetchWebsocket",JSON.stringify(e)],lre=async({instanceName:e,token:t})=>(await ie.get(`/websocket/find/${e}`,{headers:{apiKey:t}})).data,cre=e=>{const{instanceName:t,token:n,...r}=e;return qe({...r,queryKey:ire({instanceName:t,token:n}),queryFn:()=>lre({instanceName:t,token:n}),enabled:!!t})},ure=async({instanceName:e,token:t,data:n})=>(await ie.post(`/websocket/set/${e}`,{websocket:n},{headers:{apikey:t}})).data;function dre(){return{createWebsocket:Le(ure,{invalidateKeys:[["websocket","fetchWebsocket"]]})}}const fre=k.object({enabled:k.boolean(),events:k.array(k.string())});function pre(){const{t:e}=Te(),{instance:t}=Ve(),[n,r]=v.useState(!1),{createWebsocket:s}=dre(),{data:o}=cre({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=zt({resolver:Ut(fre),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const c=async p=>{var f,g,h;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),G.success(e("websocket.toast.success"))}catch(m){console.error(e("websocket.toast.error"),m),G.error(`Error: ${(h=(g=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:g.response)==null?void 0:h.message}`)}finally{r(!1)}}},u=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",u)},d=()=>{a.setValue("events",[])};return l.jsx(l.Fragment,{children:l.jsx(La,{...a,children:l.jsx("form",{onSubmit:a.handleSubmit(c),className:"w-full space-y-6",children:l.jsxs("div",{children:[l.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),l.jsx(Da,{className:"my-4"}),l.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[l.jsx(ge,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),l.jsxs("div",{className:"mb-4 flex justify-between",children:[l.jsx(z,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),l.jsx(z,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),l.jsx($a,{control:a.control,name:"events",render:({field:p})=>l.jsxs(Ro,{className:"flex flex-col",children:[l.jsx(Er,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),l.jsx(qs,{children:l.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:u.sort((f,g)=>f.localeCompare(g)).map(f=>l.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[l.jsx(Er,{className:me("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),l.jsx($c,{checked:p.value.includes(f),onCheckedChange:g=>{g?p.onChange([...p.value,f]):p.onChange(p.value.filter(h=>h!==f))}})]},f))})})]})})]}),l.jsx("div",{className:"mx-4 flex justify-end pt-6",children:l.jsx(z,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const gre=async({url:e,token:t})=>{try{const{data:n}=await Bt.post(`${e}/verify-creds`,{},{headers:{apikey:t}});return AT({facebookAppId:n.facebookAppId,facebookConfigId:n.facebookConfigId,facebookUserToken:n.facebookUserToken}),n}catch{return null}},hre=k.object({serverUrl:k.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:k.string({required_error:"ApiKey is required"})});function mre(){const{t:e}=Te(),t=an(),n=zt({resolver:Ut(hre),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),r=async s=>{const o=await lM({url:s.serverUrl});if(!o||!o.version){FT(),n.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await gre({token:s.apiKey,url:s.serverUrl})){n.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}AT({version:o.version,clientName:o.clientName,url:s.serverUrl,token:s.apiKey}),t("/manager/")};return l.jsxs("div",{className:"flex min-h-screen flex-col",children:[l.jsx("div",{className:"flex items-center justify-center pt-2",children:l.jsx("img",{className:"h-10",src:"/assets/images/evolution-logo.png",alt:"logo"})}),l.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:l.jsxs(oi,{className:"b-none w-[350px] shadow-none",children:[l.jsxs(ai,{children:[l.jsx(Iu,{className:"text-center",children:e("login.title")}),l.jsx(eP,{className:"text-center",children:e("login.description")})]}),l.jsx(La,{...n,children:l.jsxs("form",{onSubmit:n.handleSubmit(r),children:[l.jsx(ii,{children:l.jsxs("div",{className:"grid w-full items-center gap-4",children:[l.jsx($,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:l.jsx(F,{})}),l.jsx($,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:l.jsx(F,{type:"password"})})]})}),l.jsx(Mh,{className:"flex justify-center",children:l.jsx(z,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),l.jsx(zx,{})]})}const vre=HL([{path:"/manager/login",element:l.jsx(x$,{children:l.jsx(mre,{})})},{path:"/manager/",element:l.jsx(Rt,{children:l.jsx(IV,{children:l.jsx(aZ,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(IY,{})})})},{path:"/manager/instance/:instanceId/chat",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(tE,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(tE,{})})})},{path:"/manager/instance/:instanceId/settings",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(kne,{})})})},{path:"/manager/instance/:instanceId/openai",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(fE,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(fE,{})})})},{path:"/manager/instance/:instanceId/webhook",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(are,{})})})},{path:"/manager/instance/:instanceId/websocket",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(pre,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(xne,{})})})},{path:"/manager/instance/:instanceId/sqs",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(Rne,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(nY,{})})})},{path:"/manager/instance/:instanceId/typebot",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(pE,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(pE,{})})})},{path:"/manager/instance/:instanceId/dify",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(iE,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(iE,{})})})},{path:"/manager/instance/:instanceId/n8n",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(dE,{})})})},{path:"/manager/instance/:instanceId/n8n/:n8nId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(dE,{})})})},{path:"/manager/instance/:instanceId/evoai",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(lE,{})})})},{path:"/manager/instance/:instanceId/evoai/:evoaiId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(lE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(cE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot/:evolutionBotId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(cE,{})})})},{path:"/manager/instance/:instanceId/flowise",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(uE,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(uE,{})})})},{path:"/manager/instance/:instanceId/proxy",element:l.jsx(Rt,{children:l.jsx(Lt,{children:l.jsx(pne,{})})})}]),yre={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class _g{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||yre,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[c,u]=a;for(let i=0;i{let[c,u]=a;for(let i=0;i{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},gE=e=>e==null?"":""+e,bre=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},xre=/###/g,hE=e=>e&&e.indexOf("###")>-1?e.replace(xre,"."):e,mE=e=>!e||typeof e=="string",Bu=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=Bu(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],a=t.slice(0,t.length-1),c=Bu(e,a,Object);for(;c.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),c=Bu(e,a,Object),c&&c.obj&&typeof c.obj[`${c.k}.${o}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${o}`]=n},wre=(e,t,n,r)=>{const{obj:s,k:o}=Bu(e,t,Object);s[o]=s[o]||[],s[o].push(n)},Pg=(e,t)=>{const{obj:n,k:r}=Bu(e,t);if(n)return n[r]},Sre=(e,t,n)=>{const r=Pg(e,n);return r!==void 0?r:Pg(t,n)},YI=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):YI(e[r],t[r],n):e[r]=t[r]);return e},dl=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Cre={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Ere=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>Cre[t]):e;class kre{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const jre=[" ",",","?","!",";"],Tre=new kre(20),Mre=(e,t,n)=>{t=t||"",n=n||"";const r=jre.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const s=Tre.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!s.test(e);if(!o){const a=e.indexOf(n);a>0&&!s.test(e.substring(0,a))&&(o=!0)}return o},Pb=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&ue&&e.indexOf("_")>0?e.replace("_","-"):e;class yE extends am{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;t.indexOf(".")>-1?c=t.split("."):(c=[t,n],r&&(Array.isArray(r)?c.push(...r):typeof r=="string"&&o?c.push(...r.split(o)):c.push(r)));const u=Pg(this.data,c);return!u&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),u||!a||typeof r!="string"?u:Pb(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let c=[t,n];r&&(c=c.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(c=t.split("."),s=n,n=c[1]),this.addNamespaces(n),vE(this.data,c,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},c=[t,n];t.indexOf(".")>-1&&(c=t.split("."),s=r,r=n,n=c[1]),this.addNamespaces(n);let u=Pg(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?YI(u,r,o):u={...u,...r},vE(this.data,c,u),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var XI={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const bE={};class Og extends am{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),bre(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Ls.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Mre(t,r,s);if(a&&!c){const u=t.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:t,namespaces:o};const i=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(i[0])>-1)&&(o=i.shift()),t=i.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(t[t.length-1],n),u=c[c.length-1],i=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(i&&i.toLowerCase()==="cimode"){if(d){const S=n.nsSeparator||this.options.nsSeparator;return s?{res:`${u}${S}${a}`,usedKey:a,exactUsedKey:a,usedLng:i,usedNS:u,usedParams:this.getUsedParamsDetails(n)}:`${u}${S}${a}`}return s?{res:a,usedKey:a,exactUsedKey:a,usedLng:i,usedNS:u,usedParams:this.getUsedParamsDetails(n)}:a}const p=this.resolve(t,n);let f=p&&p.res;const g=p&&p.usedKey||a,h=p&&p.exactUsedKey||a,m=Object.prototype.toString.apply(f),x=["[object Number]","[object Function]","[object RegExp]"],b=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject;if(y&&f&&(typeof f!="string"&&typeof f!="boolean"&&typeof f!="number")&&x.indexOf(m)<0&&!(typeof b=="string"&&Array.isArray(f))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,f,{...n,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(p.res=S,p.usedParams=this.getUsedParamsDetails(n),p):S}if(o){const S=Array.isArray(f),E=S?[]:{},C=S?h:g;for(const T in f)if(Object.prototype.hasOwnProperty.call(f,T)){const j=`${C}${o}${T}`;E[T]=this.translate(j,{...n,joinArrays:!1,ns:c}),E[T]===j&&(E[T]=f[T])}f=E}}else if(y&&typeof b=="string"&&Array.isArray(f))f=f.join(b),f&&(f=this.extendTranslation(f,t,n,r));else{let S=!1,E=!1;const C=n.count!==void 0&&typeof n.count!="string",T=Og.hasDefaultValue(n),j=C?this.pluralResolver.getSuffix(i,n.count,n):"",_=n.ordinal&&C?this.pluralResolver.getSuffix(i,n.count,{ordinal:!1}):"",O=C&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),K=O&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${j}`]||n[`defaultValue${_}`]||n.defaultValue;!this.isValidLookup(f)&&T&&(S=!0,f=K),this.isValidLookup(f)||(E=!0,f=a);const Y=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:f,q=T&&K!==f&&this.options.updateMissing;if(E||S||q){if(this.logger.log(q?"updateKey":"missingKey",i,u,a,q?K:f),o){const L=this.resolve(a,{...n,keySeparator:!1});L&&L.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Z=[];const ee=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ee&&ee[0])for(let L=0;L{const fe=T&&X!==f?X:Y;this.options.missingKeyHandler?this.options.missingKeyHandler(L,u,A,fe,q,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(L,u,A,fe,q,n),this.emit("missingKey",L,u,A,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?Z.forEach(L=>{const A=this.pluralResolver.getSuffixes(L,n);O&&n[`defaultValue${this.options.pluralSeparator}zero`]&&A.indexOf(`${this.options.pluralSeparator}zero`)<0&&A.push(`${this.options.pluralSeparator}zero`),A.forEach(X=>{J([L],a+X,n[`defaultValue${X}`]||K)})}):J(Z,a,K))}f=this.extendTranslation(f,t,n,p,r),E&&f===a&&this.options.appendNamespaceToMissingKey&&(f=`${u}:${a}`),(E||S)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}:${a}`:a,S?f:void 0):f=this.options.parseMissingKeyHandler(f))}return s?(p.res=f,p.usedParams=this.getUsedParamsDetails(n),p):f}extendTranslation(t,n,r,s,o){var a=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const i=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(i){const f=t.match(this.interpolator.nestingRegexp);d=f&&f.length}let p=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),t=this.interpolator.interpolate(t,p,r.lng||this.language||s.usedLng,r),i){const f=t.match(this.interpolator.nestingRegexp),g=f&&f.length;d1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,a,c;return typeof t=="string"&&(t=[t]),t.forEach(u=>{if(this.isValidLookup(r))return;const i=this.extractFromKey(u,n),d=i.key;s=d;let p=i.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const f=n.count!==void 0&&typeof n.count!="string",g=f&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),h=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);p.forEach(x=>{this.isValidLookup(r)||(c=x,!bE[`${m[0]}-${x}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(c)&&(bE[`${m[0]}-${x}`]=!0,this.logger.warn(`key "${s}" for languages "${m.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(b=>{if(this.isValidLookup(r))return;a=b;const y=[d];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(y,d,b,x,n);else{let S;f&&(S=this.pluralResolver.getSuffix(b,n.count,n));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(y.push(d+S),n.ordinal&&S.indexOf(C)===0&&y.push(d+S.replace(C,this.options.pluralSeparator)),g&&y.push(d+E)),h){const T=`${d}${this.options.contextSeparator}${n.context}`;y.push(T),f&&(y.push(T+S),n.ordinal&&S.indexOf(C)===0&&y.push(T+S.replace(C,this.options.pluralSeparator)),g&&y.push(T+E))}}let w;for(;w=y.pop();)this.isValidLookup(r)||(o=w,r=this.getResource(b,x,w,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:a,usedNS:c}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const Tv=e=>e.charAt(0).toUpperCase()+e.slice(1);class xE{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ls.create("languageUtils")}getScriptPartFromCode(t){if(t=Rg(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Rg(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Tv(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Tv(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=Tv(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(a=>{s.indexOf(a)<0&&o(this.formatLanguageCode(a))}),s}}let Nre=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],_re={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const Pre=["v1","v2","v3"],Rre=["v4"],wE={zero:0,one:1,two:2,few:3,many:4,other:5},Ore=()=>{const e={};return Nre.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:_re[t.fc]}})}),e};class Ire{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=Ls.create("pluralResolver"),(!this.options.compatibilityJSON||Rre.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=Ore(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=Rg(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const a=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=a,a}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>wE[s]-wE[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!Pre.includes(this.options.compatibilityJSON)}}const SE=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=Sre(e,t,n);return!o&&s&&typeof n=="string"&&(o=Pb(e,n,r),o===void 0&&(o=Pb(t,n,r))),o},Mv=e=>e.replace(/\$/g,"$$$$");class Dre{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Ls.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:a,suffix:c,suffixEscaped:u,formatSeparator:i,unescapeSuffix:d,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:g,nestingSuffix:h,nestingSuffixEscaped:m,nestingOptionsSeparator:x,maxReplaces:b,alwaysFormat:y}=t.interpolation;this.escape=n!==void 0?n:Ere,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?dl(o):a||"{{",this.suffix=c?dl(c):u||"}}",this.formatSeparator=i||",",this.unescapePrefix=d?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?dl(f):g||dl("$t("),this.nestingSuffix=h?dl(h):m||dl(")"),this.nestingOptionsSeparator=x||",",this.maxReplaces=b||1e3,this.alwaysFormat=y!==void 0?y:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,a,c;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},i=g=>{if(g.indexOf(this.formatSeparator)<0){const b=SE(n,u,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(b,void 0,r,{...s,...n,interpolationkey:g}):b}const h=g.split(this.formatSeparator),m=h.shift().trim(),x=h.join(this.formatSeparator).trim();return this.format(SE(n,u,m,this.options.keySeparator,this.options.ignoreJSONStructure),x,r,{...s,...n,interpolationkey:m})};this.resetRegExp();const d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,p=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>Mv(g)},{regex:this.regexp,safeValue:g=>this.escapeValue?Mv(this.escape(g)):Mv(g)}].forEach(g=>{for(c=0;o=g.regex.exec(t);){const h=o[1].trim();if(a=i(h),a===void 0)if(typeof d=="function"){const x=d(t,o,s);a=typeof x=="string"?x:""}else if(s&&Object.prototype.hasOwnProperty.call(s,h))a="";else if(p){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${h} for interpolating ${t}`),a="";else typeof a!="string"&&!this.useRawValueToEscape&&(a=gE(a));const m=g.safeValue(a);if(t=t.replace(o[0],m),p?(g.regex.lastIndex+=a.length,g.regex.lastIndex-=o[0].length):g.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,a;const c=(u,i)=>{const d=this.nestingOptionsSeparator;if(u.indexOf(d)<0)return u;const p=u.split(new RegExp(`${d}[ ]*{`));let f=`{${p[1]}`;u=p[0],f=this.interpolate(f,a);const g=f.match(/'/g),h=f.match(/"/g);(g&&g.length%2===0&&!h||h.length%2!==0)&&(f=f.replace(/'/g,'"'));try{a=JSON.parse(f),i&&(a={...i,...a})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,m),`${u}${d}${f}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,u};for(;s=this.nestingRegexp.exec(t);){let u=[];a={...r},a=a.replace&&typeof a.replace!="string"?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let i=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const d=s[1].split(this.formatSeparator).map(p=>p.trim());s[1]=d.shift(),u=d,i=!0}if(o=n(c.call(this,s[1].trim(),a),a),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=gE(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),i&&(o=u.reduce((d,p)=>this.format(d,p,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const Are=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(a=>{if(a){const[c,...u]=a.split(":"),i=u.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=i),i==="false"&&(n[d]=!1),i==="true"&&(n[d]=!0),isNaN(i)||(n[d]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},fl=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const a=r+JSON.stringify(o);let c=t[a];return c||(c=e(Rg(r),s),t[a]=c),c(n)}};class Fre{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Ls.create("formatter"),this.options=t,this.formats={number:fl((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:fl((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:fl((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:fl((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:fl((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=fl(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(c=>c.indexOf(")")>-1)){const c=o.findIndex(u=>u.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,c)].join(this.formatSeparator)}return o.reduce((c,u)=>{const{formatName:i,formatOptions:d}=Are(u);if(this.formats[i]){let p=c;try{const f=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},g=f.locale||f.lng||s.locale||s.lng||r;p=this.formats[i](c,g,{...d,...s,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${i}`);return c},t)}}const Lre=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class $re extends am{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=Ls.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},a={},c={},u={};return t.forEach(i=>{let d=!0;n.forEach(p=>{const f=`${i}|${p}`;!r.reload&&this.store.hasResourceBundle(i,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?a[f]===void 0&&(a[f]=!0):(this.state[f]=1,d=!1,a[f]===void 0&&(a[f]=!0),o[f]===void 0&&(o[f]=!0),u[p]===void 0&&(u[p]=!0)))}),d||(c[i]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(u)}}loaded(t,n,r){const s=t.split("|"),o=s[0],a=s[1];n&&this.emit("failedLoading",o,a,n),!n&&r&&this.store.addResourceBundle(o,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const c={};this.queue.forEach(u=>{wre(u.loaded,[o],a),Lre(u,t),n&&u.errors.push(n),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(i=>{c[i]||(c[i]={});const d=u.loaded[i];d.length&&d.forEach(p=>{c[i][p]===void 0&&(c[i][p]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(u=>!u.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:a});return}this.readingCalls++;const c=(i,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(i&&d&&s{this.read.call(this,t,n,r,s+1,o*2,a)},o);return}a(i,d)},u=this.backend[r].bind(this.backend);if(u.length===2){try{const i=u(t,n);i&&typeof i.then=="function"?i.then(d=>c(null,d)).catch(c):c(null,i)}catch(i){c(i)}return}return u(t,n,c)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,c),this.loaded(t,a,c)})}saveMissing(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const u={...a,isUpdate:o},i=this.backend.create.bind(this.backend);if(i.length<6)try{let d;i.length===5?d=i(t,n,r,s,u):d=i(t,n,r,s),d&&typeof d.then=="function"?d.then(p=>c(null,p)).catch(c):c(null,d)}catch(d){c(d)}else i(t,n,r,s,c,u)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const CE=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),EE=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),Zf=()=>{},Bre=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Ad extends am{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=EE(t),this.services={},this.logger=Ls,this.modules={external:[]},Bre(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=CE();this.options={...s,...this.options,...EE(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Ls.init(o(this.modules.logger),this.options):Ls.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:typeof Intl<"u"&&(d=Fre);const p=new xE(this.options);this.store=new yE(this.options.resources,this.options);const f=this.services;f.logger=Ls,f.resourceStore=this.store,f.languageUtils=p,f.pluralResolver=new Ire(p,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(f.formatter=o(d),f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new Dre(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new $re(o(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",function(g){for(var h=arguments.length,m=new Array(h>1?h-1:0),x=1;x1?h-1:0),x=1;x{g.init&&g.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Zf),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=function(){return t.store[d](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=function(){return t.store[d](...arguments),t}});const u=uu(),i=()=>{const d=(p,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),u.resolve(f),r(p,f)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initImmediate?i():setTimeout(i,0),u}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Zf;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(i=>{i!=="cimode"&&o.indexOf(i)<0&&o.push(i)})};s?a(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>a(u)),this.options.preload&&this.options.preload.forEach(c=>a(c)),this.services.backendConnector.load(o,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(c)})}else r(null)}reloadResources(t,n,r){const s=uu();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=Zf),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&XI.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=uu();this.emit("languageChanging",t);const o=u=>{this.language=u,this.languages=this.services.languageUtils.toResolveHierarchy(u),this.resolvedLanguage=void 0,this.setResolvedLanguage(u)},a=(u,i)=>{i?(o(i),this.translator.changeLanguage(i),this.isLanguageChangingTo=void 0,this.emit("languageChanged",i),this.logger.log("languageChanged",i)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(u,function(){return r.t(...arguments)})},c=u=>{!t&&!u&&this.services.languageDetector&&(u=[]);const i=typeof u=="string"?u:this.services.languageUtils.getBestMatchFromCodes(u);i&&(this.language||o(i),this.translator.language||this.translator.changeLanguage(i),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(i)),this.loadResources(i,d=>{a(d,i)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?c(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(c):this.services.languageDetector.detect(c):c(t),s}getFixedT(t,n,r){var s=this;const o=function(a,c){let u;if(typeof c!="object"){for(var i=arguments.length,d=new Array(i>2?i-2:0),p=2;p`${u.keyPrefix}${f}${h}`):g=u.keyPrefix?`${u.keyPrefix}${f}${a}`:a,s.t(g,u)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(c,u)=>{const i=this.services.backendConnector.state[`${c}|${u}`];return i===-1||i===0||i===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!s||a(o,t)))}loadNamespaces(t,n){const r=uu();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=uu();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(a=>s.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=s.concat(o),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new xE(CE());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Ad(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Zf;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new Ad(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(c=>{o[c]=this[c]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new yE(this.store.data,s),o.services.resourceStore=o.store),o.translator=new Og(o.services,s),o.translator.on("*",function(c){for(var u=arguments.length,i=new Array(u>1?u-1:0),d=1;d:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.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-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * 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-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))}.divide-x>:not([hidden])~:not([hidden]){--tw-divide-x-reverse: 0;border-right-width:calc(1px * var(--tw-divide-x-reverse));border-left-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.self-end{align-self:flex-end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.text-wrap{text-wrap:wrap}.break-all{word-break:break-all}.rounded-3xl{border-radius:1.5rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[--color-border\]{border-color:var(--color-border)}.border-amber-500\/20{border-color:#f59e0b33}.border-black{--tw-border-opacity: 1;border-color:rgb(0 0 0 / var(--tw-border-opacity))}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-emerald-500\/20{border-color:#10b98133}.border-gray-600\/50{border-color:#4b556380}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-red-500\/20{border-color:#ef444433}.border-sky-500\/20{border-color:#0ea5e933}.border-transparent{border-color:transparent}.border-zinc-500\/20{border-color:#71717a33}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-amber-50\/50{background-color:#fffbeb80}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity))}.bg-background{background-color:hsl(var(--background))}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-50\/50{background-color:#ecfdf580}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-primary\/30{background-color:hsl(var(--primary) / .3)}.bg-red-50\/50{background-color:#fef2f280}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sky-50\/50{background-color:#f0f9ff80}.bg-transparent{background-color:transparent}.bg-zinc-50\/50{background-color:#fafafa80}.fill-current{fill:currentColor}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pl-12{padding-left:3rem}.pl-2{padding-left:.5rem}.pl-3{padding-left:.75rem}.pl-8{padding-left:2rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-base{font-size:1rem;line-height:1.5rem}.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-normal{font-weight:400}.font-semibold{font-weight:600}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity))}.text-foreground{color:hsl(var(--foreground))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/80{color:hsl(var(--muted-foreground) / .8)}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity))}.text-rose-600{--tw-text-opacity: 1;color:rgb(225 29 72 / var(--tw-text-opacity))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.text-zinc-900{--tw-text-opacity: 1;color:rgb(24 24 27 / var(--tw-text-opacity))}.underline-offset-4{text-underline-offset:4px}.caret-transparent{caret-color:transparent}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.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)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 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-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--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(0px + 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-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-muted-foreground{--tw-ring-color: hsl(var(--muted-foreground))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.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}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;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))}.after\:bg-border:after{content:var(--tw-content);background-color:hsl(var(--border))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-amber-600\/80:hover{background-color:#d97706cc}.hover\:bg-amber-600\/90:hover{background-color:#d97706e6}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-transparent:hover{background-color:transparent}.hover\:stroke-destructive:hover{stroke:hsl(var(--destructive))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.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-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--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(1px + 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-visible\:ring-2:focus-visible{--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-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;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))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;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))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;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))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;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))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;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))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;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))}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-muted[data-state=open],.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-slate-400[data-state=unchecked]{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 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)}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;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))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;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))}.dark\:-rotate-90:is(.dark *){--tw-rotate: -90deg;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))}.dark\:rotate-0:is(.dark *){--tw-rotate: 0deg;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))}.dark\:scale-0:is(.dark *){--tw-scale-x: 0;--tw-scale-y: 0;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))}.dark\:scale-100:is(.dark *){--tw-scale-x: 1;--tw-scale-y: 1;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))}.dark\:border-amber-500\/30:is(.dark *){border-color:#f59e0b4d}.dark\:border-emerald-500\/30:is(.dark *){border-color:#10b9814d}.dark\:border-red-500\/30:is(.dark *){border-color:#ef44444d}.dark\:border-sky-500\/30:is(.dark *){border-color:#0ea5e94d}.dark\:border-zinc-500\/30:is(.dark *){border-color:#71717a4d}.dark\:bg-amber-500\/10:is(.dark *){background-color:#f59e0b1a}.dark\:bg-emerald-500\/10:is(.dark *){background-color:#10b9811a}.dark\:bg-red-500\/10:is(.dark *){background-color:#ef44441a}.dark\:bg-sky-500\/10:is(.dark *){background-color:#0ea5e91a}.dark\:bg-zinc-500\/10:is(.dark *){background-color:#71717a1a}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity))}.dark\:text-emerald-200:is(.dark *){--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}.dark\:text-sky-200:is(.dark *){--tw-text-opacity: 1;color:rgb(186 230 253 / var(--tw-text-opacity))}.dark\:text-zinc-300:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:m-4{margin:1rem}.sm\:inline{display:inline}.sm\:max-h-\[600px\]{max-height:600px}.sm\:max-w-\[650px\]{max-width:650px}.sm\:max-w-\[740px\]{max-width:740px}.sm\:max-w-\[950px\]{max-width:950px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[10rem_1fr_10rem\]{grid-template-columns:10rem 1fr 10rem}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:w-64{width:16rem}.md\:w-full{width:100%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:gap-8{gap:2rem}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>\*\]\:p-4>*{padding:1rem}.\[\&\>\*\]\:px-4>*{padding-left:1rem;padding-right:1rem}.\[\&\>\*\]\:py-2>*{padding-top:.5rem;padding-bottom:.5rem}.\[\&\>div\[style\]\]\:\!block>div[style]{display:block!important}.\[\&\>div\[style\]\]\:h-full>div[style]{height:100%}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;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))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:fill-rose-600>svg{fill:#e11d48}.\[\&\>svg\]\:text-amber-500>svg{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-emerald-600>svg{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-red-600>svg{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-sky-500>svg{--tw-text-opacity: 1;color:rgb(14 165 233 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-zinc-400>svg{--tw-text-opacity: 1;color:rgb(161 161 170 / var(--tw-text-opacity))}.hover\:\[\&\>svg\]\:fill-rose-700>svg:hover{fill:#be123c}.dark\:\[\&\>svg\]\:text-emerald-400\/80>svg:is(.dark *){color:#34d399cc}.dark\:\[\&\>svg\]\:text-red-400\/80>svg:is(.dark *){color:#f87171cc}.dark\:\[\&\>svg\]\:text-zinc-300>svg:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;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))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_strong\]\:text-foreground strong{color:hsl(var(--foreground))}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: #e74c3c;--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient( to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55 );--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width : 480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}}.Toastify__toast{--y: 0;position:relative;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px #0000001a;display:flex;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;flex:1 1 auto;padding:6px;display:flex;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;flex:1}.Toastify__toast-icon{margin-inline-end:10px;width:20px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width : 480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.tabs-chat{background-color:transparent;width:100%;border-radius:0}.chat-item{display:flex;padding:10px;cursor:pointer;background-color:hsl(var(--background))}.chat-item:hover,.chat-item.active{background-color:#2f2f2f}.bubble{border-radius:16px;padding:12px;word-wrap:break-word}.bubble-right .bubble{background-color:#0a0a0a;text-align:right;max-width:100%}.bubble-left .bubble{background-color:#1b1b1b;max-width:100%}.bubble-right{align-self:flex-end;display:flex;justify-content:flex-end;width:80%}.bubble-left{align-self:flex-start;display:flex;justify-content:flex-start;width:80%}.input-message textarea{background-color:#2f2f2f;padding-left:48px}.input-message textarea:focus{outline:none;border:none;box-shadow:none}.message-container{flex:1;overflow-y:auto;max-height:calc(100vh - 110px);padding-top:50px} diff --git a/manager/dist/index.html b/manager/dist/index.html index 0a85ca22..286c2893 100644 --- a/manager/dist/index.html +++ b/manager/dist/index.html @@ -2,11 +2,11 @@ - + Evolution Manager - - + +
diff --git a/package-lock.json b/package-lock.json index 83bd4d16..dc13f455 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "evolution-api", - "version": "2.2.3", + "version": "2.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "evolution-api", - "version": "2.2.3", + "version": "2.3.0", "license": "Apache-2.0", "dependencies": { "@adiwajshing/keyed-db": "^0.2.4", @@ -35,6 +35,7 @@ "jimp": "^0.16.13", "json-schema": "^0.4.0", "jsonschema": "^1.4.1", + "jsonwebtoken": "^9.0.2", "link-preview-js": "^3.0.13", "long": "^5.2.3", "mediainfo.js": "^0.3.4", @@ -42,6 +43,7 @@ "mime-types": "^2.1.35", "minio": "^8.0.3", "multer": "^1.4.5-lts.1", + "nats": "^2.29.1", "node-cache": "^5.1.2", "node-cron": "^3.0.3", "openai": "^4.77.3", @@ -82,19 +84,6 @@ "typescript": "^5.7.2" } }, - "node_modules/@acuminous/bitsyntax": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@acuminous/bitsyntax/-/bitsyntax-0.1.2.tgz", - "integrity": "sha512-29lUK80d1muEQqiUsSo+3A0yP6CdspgC95EnKBMi22Xlwt79i/En4Vr67+cXhU+cZjbti3TgGGC5wy1stIywVQ==", - "dependencies": { - "buffer-more-ints": "~1.0.0", - "debug": "^4.3.4", - "safe-buffer": "~5.1.2" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/@adiwajshing/keyed-db": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/@adiwajshing/keyed-db/-/keyed-db-0.2.4.tgz", @@ -216,49 +205,49 @@ } }, "node_modules/@aws-sdk/client-sqs": { - "version": "3.738.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sqs/-/client-sqs-3.738.0.tgz", - "integrity": "sha512-wGxZNV0m0NM+IXub61vkwoq3KD88joG45aYpS4+2ADnZLxnUe/Md1AH+ZMznIv5ZAppCXso7S0Tis3LLK85IGw==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sqs/-/client-sqs-3.810.0.tgz", + "integrity": "sha512-Ip/QCzuieozPFGkqeJmCrOkz9k+UXcJAVc5rkomgCjxNQoQ7T7grxKCUd9Q87eg4u0sCtuYSvwGa+15YwoARQA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.734.0", - "@aws-sdk/credential-provider-node": "3.738.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-sdk-sqs": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.734.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.734.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.734.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/md5-js": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.2", - "@smithy/middleware-retry": "^4.0.3", - "@smithy/middleware-serde": "^4.0.1", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.2", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.2", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/credential-provider-node": "3.810.0", + "@aws-sdk/middleware-host-header": "3.804.0", + "@aws-sdk/middleware-logger": "3.804.0", + "@aws-sdk/middleware-recursion-detection": "3.804.0", + "@aws-sdk/middleware-sdk-sqs": "3.810.0", + "@aws-sdk/middleware-user-agent": "3.810.0", + "@aws-sdk/region-config-resolver": "3.808.0", + "@aws-sdk/types": "3.804.0", + "@aws-sdk/util-endpoints": "3.808.0", + "@aws-sdk/util-user-agent-browser": "3.804.0", + "@aws-sdk/util-user-agent-node": "3.810.0", + "@smithy/config-resolver": "^4.1.2", + "@smithy/core": "^3.3.3", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/md5-js": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.6", + "@smithy/middleware-retry": "^4.1.7", + "@smithy/middleware-serde": "^4.0.5", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.3", - "@smithy/util-defaults-mode-node": "^4.0.3", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.14", + "@smithy/util-defaults-mode-node": "^4.0.14", + "@smithy/util-endpoints": "^3.0.4", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.3", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -267,46 +256,46 @@ } }, "node_modules/@aws-sdk/client-sso": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.734.0.tgz", - "integrity": "sha512-oerepp0mut9VlgTwnG5Ds/lb0C0b2/rQ+hL/rF6q+HGKPfGsCuPvFx1GtwGKCXd49ase88/jVgrhcA9OQbz3kg==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.810.0.tgz", + "integrity": "sha512-Txp/3jHqkfA4BTklQEOGiZ1yTUxg+hITislfaWEzJ904vlDt4DvAljTlhfaz7pceCLA2+LhRlYZYSv7t5b0Ltw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.734.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.734.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.734.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.734.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.2", - "@smithy/middleware-retry": "^4.0.3", - "@smithy/middleware-serde": "^4.0.1", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.2", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.2", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/middleware-host-header": "3.804.0", + "@aws-sdk/middleware-logger": "3.804.0", + "@aws-sdk/middleware-recursion-detection": "3.804.0", + "@aws-sdk/middleware-user-agent": "3.810.0", + "@aws-sdk/region-config-resolver": "3.808.0", + "@aws-sdk/types": "3.804.0", + "@aws-sdk/util-endpoints": "3.808.0", + "@aws-sdk/util-user-agent-browser": "3.804.0", + "@aws-sdk/util-user-agent-node": "3.810.0", + "@smithy/config-resolver": "^4.1.2", + "@smithy/core": "^3.3.3", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.6", + "@smithy/middleware-retry": "^4.1.7", + "@smithy/middleware-serde": "^4.0.5", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.3", - "@smithy/util-defaults-mode-node": "^4.0.3", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.14", + "@smithy/util-defaults-mode-node": "^4.0.14", + "@smithy/util-endpoints": "^3.0.4", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.3", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -315,19 +304,19 @@ } }, "node_modules/@aws-sdk/core": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.734.0.tgz", - "integrity": "sha512-SxnDqf3vobdm50OLyAKfqZetv6zzwnSqwIwd3jrbopxxHKqNIM/I0xcYjD6Tn+mPig+u7iRKb9q3QnEooFTlmg==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.810.0.tgz", + "integrity": "sha512-s2IJk+qa/15YZcv3pbdQNATDR+YdYnHf94MrAeVAWubtRLnzD8JciC+gh4LSPp7JzrWSvVOg2Ut1S+0y89xqCg==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/core": "^3.1.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/signature-v4": "^5.0.1", - "@smithy/smithy-client": "^4.1.2", - "@smithy/types": "^4.1.0", - "@smithy/util-middleware": "^4.0.1", + "@aws-sdk/types": "3.804.0", + "@smithy/core": "^3.3.3", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/property-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/signature-v4": "^5.1.0", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", + "@smithy/util-middleware": "^4.0.2", "fast-xml-parser": "4.4.1", "tslib": "^2.6.2" }, @@ -336,14 +325,14 @@ } }, "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.734.0.tgz", - "integrity": "sha512-gtRkzYTGafnm1FPpiNO8VBmJrYMoxhDlGPYDVcijzx3DlF8dhWnowuSBCxLSi+MJMx5hvwrX2A+e/q0QAeHqmw==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.810.0.tgz", + "integrity": "sha512-iwHqF+KryKONfbdFk3iKhhPk4fHxh5QP5fXXR//jhYwmszaLOwc7CLCE9AxhgiMzAs+kV8nBFQZvdjFpPzVGOA==", "dependencies": { - "@aws-sdk/core": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -351,19 +340,19 @@ } }, "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.734.0.tgz", - "integrity": "sha512-JFSL6xhONsq+hKM8xroIPhM5/FOhiQ1cov0lZxhzZWj6Ai3UAjucy3zyIFDr9MgP1KfCYNdvyaUq9/o+HWvEDg==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.810.0.tgz", + "integrity": "sha512-SKzjLd+8ugif7yy9sOAAdnPE1vCBHQe6jKgs2AadMpCmWm34DiHz/KuulHdvURUGMIi7CvmaC8aH77twDPYbtg==", "dependencies": { - "@aws-sdk/core": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/node-http-handler": "^4.0.2", - "@smithy/property-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.2", - "@smithy/types": "^4.1.0", - "@smithy/util-stream": "^4.0.2", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/property-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", + "@smithy/util-stream": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -371,22 +360,22 @@ } }, "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.734.0.tgz", - "integrity": "sha512-HEyaM/hWI7dNmb4NhdlcDLcgJvrilk8G4DQX6qz0i4pBZGC2l4iffuqP8K6ZQjUfz5/6894PzeFuhTORAMd+cg==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.810.0.tgz", + "integrity": "sha512-H2QCSnxWJ/mj8HTcyHmCmyQ5bO/+imRi4mlBIpUyKjiYKro52WD3gXlGgPIDo2q3UFIHq37kmYvS00i+qIY9tw==", "dependencies": { - "@aws-sdk/core": "3.734.0", - "@aws-sdk/credential-provider-env": "3.734.0", - "@aws-sdk/credential-provider-http": "3.734.0", - "@aws-sdk/credential-provider-process": "3.734.0", - "@aws-sdk/credential-provider-sso": "3.734.0", - "@aws-sdk/credential-provider-web-identity": "3.734.0", - "@aws-sdk/nested-clients": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/credential-provider-env": "3.810.0", + "@aws-sdk/credential-provider-http": "3.810.0", + "@aws-sdk/credential-provider-process": "3.810.0", + "@aws-sdk/credential-provider-sso": "3.810.0", + "@aws-sdk/credential-provider-web-identity": "3.810.0", + "@aws-sdk/nested-clients": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/credential-provider-imds": "^4.0.4", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -394,21 +383,21 @@ } }, "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.738.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.738.0.tgz", - "integrity": "sha512-3MuREsazwBxghKb2sQQHvie+uuK4dX4/ckFYiSoffzJQd0YHxaGxf8cr4NOSCQCUesWu8D3Y0SzlnHGboVSkpA==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.810.0.tgz", + "integrity": "sha512-9E3Chv3x+RBM3N1bwLCyvXxoiPAckCI74wG7ePN4F3b/7ieIkbEl/3Hd67j1fnt62Xa1cjUHRu2tz5pdEv5G1Q==", "dependencies": { - "@aws-sdk/credential-provider-env": "3.734.0", - "@aws-sdk/credential-provider-http": "3.734.0", - "@aws-sdk/credential-provider-ini": "3.734.0", - "@aws-sdk/credential-provider-process": "3.734.0", - "@aws-sdk/credential-provider-sso": "3.734.0", - "@aws-sdk/credential-provider-web-identity": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/credential-provider-env": "3.810.0", + "@aws-sdk/credential-provider-http": "3.810.0", + "@aws-sdk/credential-provider-ini": "3.810.0", + "@aws-sdk/credential-provider-process": "3.810.0", + "@aws-sdk/credential-provider-sso": "3.810.0", + "@aws-sdk/credential-provider-web-identity": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/credential-provider-imds": "^4.0.4", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -416,15 +405,15 @@ } }, "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.734.0.tgz", - "integrity": "sha512-zvjsUo+bkYn2vjT+EtLWu3eD6me+uun+Hws1IyWej/fKFAqiBPwyeyCgU7qjkiPQSXqk1U9+/HG9IQ6Iiz+eBw==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.810.0.tgz", + "integrity": "sha512-42kE6MLdsmMGp1id3Gisal4MbMiF7PIc0tAznTeIuE8r7cIF8yeQWw/PBOIvjyI57DxbyKzLUAMEJuigUpApCw==", "dependencies": { - "@aws-sdk/core": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -432,17 +421,17 @@ } }, "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.734.0.tgz", - "integrity": "sha512-cCwwcgUBJOsV/ddyh1OGb4gKYWEaTeTsqaAK19hiNINfYV/DO9r4RMlnWAo84sSBfJuj9shUNsxzyoe6K7R92Q==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.810.0.tgz", + "integrity": "sha512-8WjX6tz+FCvM93Y33gsr13p/HiiTJmVn5AK1O8PTkvHBclQDzmtAW5FdPqTpAJGswLW2FB0xRqdsSMN2dQEjNw==", "dependencies": { - "@aws-sdk/client-sso": "3.734.0", - "@aws-sdk/core": "3.734.0", - "@aws-sdk/token-providers": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-sso": "3.810.0", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/token-providers": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -450,15 +439,15 @@ } }, "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.734.0.tgz", - "integrity": "sha512-t4OSOerc+ppK541/Iyn1AS40+2vT/qE+MFMotFkhCgCJbApeRF2ozEdnDN6tGmnl4ybcUuxnp9JWLjwDVlR/4g==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.810.0.tgz", + "integrity": "sha512-uKQJY0AcPyrvMmfGLo36semgjqJ4vmLTqOSW9u40qQDspRnG73/P09lAO2ntqKlhwvMBt3XfcNnOpyyhKRcOfA==", "dependencies": { - "@aws-sdk/core": "3.734.0", - "@aws-sdk/nested-clients": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/nested-clients": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -466,13 +455,13 @@ } }, "node_modules/@aws-sdk/middleware-host-header": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.734.0.tgz", - "integrity": "sha512-LW7RRgSOHHBzWZnigNsDIzu3AiwtjeI2X66v+Wn1P1u+eXssy1+up4ZY/h+t2sU4LU36UvEf+jrZti9c6vRnFw==", + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.804.0.tgz", + "integrity": "sha512-bum1hLVBrn2lJCi423Z2fMUYtsbkGI2s4N+2RI2WSjvbaVyMSv/WcejIrjkqiiMR+2Y7m5exgoKeg4/TODLDPQ==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.804.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -480,12 +469,12 @@ } }, "node_modules/@aws-sdk/middleware-logger": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.734.0.tgz", - "integrity": "sha512-mUMFITpJUW3LcKvFok176eI5zXAUomVtahb9IQBwLzkqFYOrMJvWAvoV4yuxrJ8TlQBG8gyEnkb9SnhZvjg67w==", + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.804.0.tgz", + "integrity": "sha512-w/qLwL3iq0KOPQNat0Kb7sKndl9BtceigINwBU7SpkYWX9L/Lem6f8NPEKrC9Tl4wDBht3Yztub4oRTy/horJA==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.804.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -493,13 +482,13 @@ } }, "node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.734.0.tgz", - "integrity": "sha512-CUat2d9ITsFc2XsmeiRQO96iWpxSKYFjxvj27Hc7vo87YUHRnfMfnc8jw1EpxEwMcvBD7LsRa6vDNky6AjcrFA==", + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.804.0.tgz", + "integrity": "sha512-zqHOrvLRdsUdN/ehYfZ9Tf8svhbiLLz5VaWUz22YndFv6m9qaAcijkpAOlKexsv3nLBMJdSdJ6GUTAeIy3BZzw==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.804.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -507,13 +496,13 @@ } }, "node_modules/@aws-sdk/middleware-sdk-sqs": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-sqs/-/middleware-sdk-sqs-3.734.0.tgz", - "integrity": "sha512-WetobEBbOFt4WutMYNnhkqNG8FDU9ZTLQ7gY0tGdhUKzHo0h/k9TPRZc8WUeKqacZ7gMWMNOjY251izockqWsQ==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-sqs/-/middleware-sdk-sqs-3.810.0.tgz", + "integrity": "sha512-MKNX7TYtB3dn1UO+5ewTLJUtDNXLAIKbXokCEfzHuvqPJpsFPbBp7ERY2jn2KjCBMSaP3w1ZCCpFKcfVICsrXQ==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/smithy-client": "^4.1.2", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.804.0", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", "@smithy/util-hex-encoding": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -523,16 +512,16 @@ } }, "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.734.0.tgz", - "integrity": "sha512-MFVzLWRkfFz02GqGPjqSOteLe5kPfElUrXZft1eElnqulqs6RJfVSpOV7mO90gu293tNAeggMWAVSGRPKIYVMg==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.810.0.tgz", + "integrity": "sha512-gLMJcqgIq7k9skX8u0Yyi+jil4elbsmLf3TuDuqNdlqiZ44/AKdDFfU3mU5tRUtMfP42a3gvb2U3elP0BIeybQ==", "dependencies": { - "@aws-sdk/core": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.734.0", - "@smithy/core": "^3.1.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@aws-sdk/util-endpoints": "3.808.0", + "@smithy/core": "^3.3.3", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -540,46 +529,46 @@ } }, "node_modules/@aws-sdk/nested-clients": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.734.0.tgz", - "integrity": "sha512-iph2XUy8UzIfdJFWo1r0Zng9uWj3253yvW9gljhtu+y/LNmNvSnJxQk1f3D2BC5WmcoPZqTS3UsycT3mLPSzWA==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.810.0.tgz", + "integrity": "sha512-w+tGXFSQjzvJ3j2sQ4GJRdD+YXLTgwLd9eG/A+7pjrv2yLLV70M4HqRrFqH06JBjqT5rsOxonc/QSjROyxk+IA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.734.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.734.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.734.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.734.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.2", - "@smithy/middleware-retry": "^4.0.3", - "@smithy/middleware-serde": "^4.0.1", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.2", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.2", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.810.0", + "@aws-sdk/middleware-host-header": "3.804.0", + "@aws-sdk/middleware-logger": "3.804.0", + "@aws-sdk/middleware-recursion-detection": "3.804.0", + "@aws-sdk/middleware-user-agent": "3.810.0", + "@aws-sdk/region-config-resolver": "3.808.0", + "@aws-sdk/types": "3.804.0", + "@aws-sdk/util-endpoints": "3.808.0", + "@aws-sdk/util-user-agent-browser": "3.804.0", + "@aws-sdk/util-user-agent-node": "3.810.0", + "@smithy/config-resolver": "^4.1.2", + "@smithy/core": "^3.3.3", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.6", + "@smithy/middleware-retry": "^4.1.7", + "@smithy/middleware-serde": "^4.0.5", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.3", - "@smithy/util-defaults-mode-node": "^4.0.3", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.14", + "@smithy/util-defaults-mode-node": "^4.0.14", + "@smithy/util-endpoints": "^3.0.4", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.3", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -588,15 +577,15 @@ } }, "node_modules/@aws-sdk/region-config-resolver": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.734.0.tgz", - "integrity": "sha512-Lvj1kPRC5IuJBr9DyJ9T9/plkh+EfKLy+12s/mykOy1JaKHDpvj+XGy2YO6YgYVOb8JFtaqloid+5COtje4JTQ==", + "version": "3.808.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.808.0.tgz", + "integrity": "sha512-9x2QWfphkARZY5OGkl9dJxZlSlYM2l5inFeo2bKntGuwg4A4YUe5h7d5yJ6sZbam9h43eBrkOdumx03DAkQF9A==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.804.0", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/types": "^4.2.0", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -604,15 +593,15 @@ } }, "node_modules/@aws-sdk/token-providers": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.734.0.tgz", - "integrity": "sha512-2U6yWKrjWjZO8Y5SHQxkFvMVWHQWbS0ufqfAIBROqmIZNubOL7jXCiVdEFekz6MZ9LF2tvYGnOW4jX8OKDGfIw==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.810.0.tgz", + "integrity": "sha512-fdgHRCDpnzsD+0km7zuRbHRysJECfS8o9T9/pZ6XAr1z2FNV/UveHtnUYq0j6XpDMrIm0/suvXbshIjQU+a+sw==", "dependencies": { - "@aws-sdk/nested-clients": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/nested-clients": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -620,11 +609,11 @@ } }, "node_modules/@aws-sdk/types": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.734.0.tgz", - "integrity": "sha512-o11tSPTT70nAkGV1fN9wm/hAIiLPyWX6SuGf+9JyTp7S/rC2cFWhR26MvA69nplcjNaXVzB0f+QFrLXXjOqCrg==", + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.804.0.tgz", + "integrity": "sha512-A9qnsy9zQ8G89vrPPlNG9d1d8QcKRGqJKqwyGgS0dclJpwy6d1EWgQLIolKPl6vcFpLoe6avLOLxr+h8ur5wpg==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -632,13 +621,13 @@ } }, "node_modules/@aws-sdk/util-endpoints": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.734.0.tgz", - "integrity": "sha512-w2+/E88NUbqql6uCVAsmMxDQKu7vsKV0KqhlQb0lL+RCq4zy07yXYptVNs13qrnuTfyX7uPXkXrlugvK9R1Ucg==", + "version": "3.808.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.808.0.tgz", + "integrity": "sha512-N6Lic98uc4ADB7fLWlzx+1uVnq04VgVjngZvwHoujcRg9YDhIg9dUDiTzD5VZv13g1BrPYmvYP1HhsildpGV6w==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", - "@smithy/util-endpoints": "^3.0.1", + "@aws-sdk/types": "3.804.0", + "@smithy/types": "^4.2.0", + "@smithy/util-endpoints": "^3.0.4", "tslib": "^2.6.2" }, "engines": { @@ -646,9 +635,9 @@ } }, "node_modules/@aws-sdk/util-locate-window": { - "version": "3.723.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.723.0.tgz", - "integrity": "sha512-Yf2CS10BqK688DRsrKI/EO6B8ff5J86NXe4C+VCysK7UOgN0l1zOTeTukZ3H8Q9tYYX3oaF1961o8vRkFm7Nmw==", + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.804.0.tgz", + "integrity": "sha512-zVoRfpmBVPodYlnMjgVjfGoEZagyRF5IPn3Uo6ZvOZp24chnW/FRstH7ESDHDDRga4z3V+ElUQHKpFDXWyBW5A==", "dependencies": { "tslib": "^2.6.2" }, @@ -657,25 +646,25 @@ } }, "node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.734.0.tgz", - "integrity": "sha512-xQTCus6Q9LwUuALW+S76OL0jcWtMOVu14q+GoLnWPUM7QeUw963oQcLhF7oq0CtaLLKyl4GOUfcwc773Zmwwng==", + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.804.0.tgz", + "integrity": "sha512-KfW6T6nQHHM/vZBBdGn6fMyG/MgX5lq82TDdX4HRQRRuHKLgBWGpKXqqvBwqIaCdXwWHgDrg2VQups6GqOWW2A==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.804.0", + "@smithy/types": "^4.2.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.734.0.tgz", - "integrity": "sha512-c6Iinh+RVQKs6jYUFQ64htOU2HUXFQ3TVx+8Tu3EDF19+9vzWi9UukhIMH9rqyyEXIAkk9XL7avt8y2Uyw2dGA==", + "version": "3.810.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.810.0.tgz", + "integrity": "sha512-T56/ANEGNuvhqVoWZdr+0ZY2hjV93cH2OfGHIlVTVSAMACWG54XehDPESEso1CJNhJGYZPsE+FE42HGCk/XDMg==", "dependencies": { - "@aws-sdk/middleware-user-agent": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/middleware-user-agent": "3.810.0", + "@aws-sdk/types": "3.804.0", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -691,16 +680,23 @@ } }, "node_modules/@babel/runtime": { - "version": "7.26.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.7.tgz", - "integrity": "sha512-AOPI3D+a8dXnja+iwsUqGRjr1BbZIe771sXdapOtYI531gSqpi92vXivKcq2asu/DFpdl1ceFAKZyRzK2PCVcQ==", - "dependencies": { - "regenerator-runtime": "^0.14.0" - }, + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz", + "integrity": "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==", "engines": { "node": ">=6.9.0" } }, + "node_modules/@cacheable/node-cache": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@cacheable/node-cache/-/node-cache-1.5.5.tgz", + "integrity": "sha512-pCvDtZbYIwWi2Rs3fgakM/EkzfLwNsdDMjvlb1cpPxUx0q5wiULsxTYHHhoXamFHAwVwgOM5gLaQzSAhYkDVoA==", + "dependencies": { + "cacheable": "^1.9.0", + "hookified": "^1.8.2", + "keyv": "^5.3.3" + } + }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", @@ -714,9 +710,9 @@ } }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz", - "integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.4.tgz", + "integrity": "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q==", "cpu": [ "ppc64" ], @@ -729,9 +725,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz", - "integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.4.tgz", + "integrity": "sha512-QNdQEps7DfFwE3hXiU4BZeOV68HHzYwGd0Nthhd3uCkkEKK7/R6MTgM0P7H7FAs5pU/DIWsviMmEGxEoxIZ+ZQ==", "cpu": [ "arm" ], @@ -744,9 +740,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz", - "integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.4.tgz", + "integrity": "sha512-bBy69pgfhMGtCnwpC/x5QhfxAz/cBgQ9enbtwjf6V9lnPI/hMyT9iWpR1arm0l3kttTr4L0KSLpKmLp/ilKS9A==", "cpu": [ "arm64" ], @@ -759,9 +755,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz", - "integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.4.tgz", + "integrity": "sha512-TVhdVtQIFuVpIIR282btcGC2oGQoSfZfmBdTip2anCaVYcqWlZXGcdcKIUklfX2wj0JklNYgz39OBqh2cqXvcQ==", "cpu": [ "x64" ], @@ -774,9 +770,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz", - "integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.4.tgz", + "integrity": "sha512-Y1giCfM4nlHDWEfSckMzeWNdQS31BQGs9/rouw6Ub91tkK79aIMTH3q9xHvzH8d0wDru5Ci0kWB8b3up/nl16g==", "cpu": [ "arm64" ], @@ -789,9 +785,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz", - "integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.4.tgz", + "integrity": "sha512-CJsry8ZGM5VFVeyUYB3cdKpd/H69PYez4eJh1W/t38vzutdjEjtP7hB6eLKBoOdxcAlCtEYHzQ/PJ/oU9I4u0A==", "cpu": [ "x64" ], @@ -804,9 +800,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz", - "integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.4.tgz", + "integrity": "sha512-yYq+39NlTRzU2XmoPW4l5Ifpl9fqSk0nAJYM/V/WUGPEFfek1epLHJIkTQM6bBs1swApjO5nWgvr843g6TjxuQ==", "cpu": [ "arm64" ], @@ -819,9 +815,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz", - "integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.4.tgz", + "integrity": "sha512-0FgvOJ6UUMflsHSPLzdfDnnBBVoCDtBTVyn/MrWloUNvq/5SFmh13l3dvgRPkDihRxb77Y17MbqbCAa2strMQQ==", "cpu": [ "x64" ], @@ -834,9 +830,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz", - "integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.4.tgz", + "integrity": "sha512-kro4c0P85GMfFYqW4TWOpvmF8rFShbWGnrLqlzp4X1TNWjRY3JMYUfDCtOxPKOIY8B0WC8HN51hGP4I4hz4AaQ==", "cpu": [ "arm" ], @@ -849,9 +845,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz", - "integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.4.tgz", + "integrity": "sha512-+89UsQTfXdmjIvZS6nUnOOLoXnkUTB9hR5QAeLrQdzOSWZvNSAXAtcRDHWtqAUtAmv7ZM1WPOOeSxDzzzMogiQ==", "cpu": [ "arm64" ], @@ -864,9 +860,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz", - "integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.4.tgz", + "integrity": "sha512-yTEjoapy8UP3rv8dB0ip3AfMpRbyhSN3+hY8mo/i4QXFeDxmiYbEKp3ZRjBKcOP862Ua4b1PDfwlvbuwY7hIGQ==", "cpu": [ "ia32" ], @@ -879,9 +875,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz", - "integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.4.tgz", + "integrity": "sha512-NeqqYkrcGzFwi6CGRGNMOjWGGSYOpqwCjS9fvaUlX5s3zwOtn1qwg1s2iE2svBe4Q/YOG1q6875lcAoQK/F4VA==", "cpu": [ "loong64" ], @@ -894,9 +890,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz", - "integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.4.tgz", + "integrity": "sha512-IcvTlF9dtLrfL/M8WgNI/qJYBENP3ekgsHbYUIzEzq5XJzzVEV/fXY9WFPfEEXmu3ck2qJP8LG/p3Q8f7Zc2Xg==", "cpu": [ "mips64el" ], @@ -909,9 +905,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz", - "integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.4.tgz", + "integrity": "sha512-HOy0aLTJTVtoTeGZh4HSXaO6M95qu4k5lJcH4gxv56iaycfz1S8GO/5Jh6X4Y1YiI0h7cRyLi+HixMR+88swag==", "cpu": [ "ppc64" ], @@ -924,9 +920,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz", - "integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.4.tgz", + "integrity": "sha512-i8JUDAufpz9jOzo4yIShCTcXzS07vEgWzyX3NH2G7LEFVgrLEhjwL3ajFE4fZI3I4ZgiM7JH3GQ7ReObROvSUA==", "cpu": [ "riscv64" ], @@ -939,9 +935,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz", - "integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.4.tgz", + "integrity": "sha512-jFnu+6UbLlzIjPQpWCNh5QtrcNfMLjgIavnwPQAfoGx4q17ocOU9MsQ2QVvFxwQoWpZT8DvTLooTvmOQXkO51g==", "cpu": [ "s390x" ], @@ -954,9 +950,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz", - "integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.4.tgz", + "integrity": "sha512-6e0cvXwzOnVWJHq+mskP8DNSrKBr1bULBvnFLpc1KY+d+irZSgZ02TGse5FsafKS5jg2e4pbvK6TPXaF/A6+CA==", "cpu": [ "x64" ], @@ -969,9 +965,9 @@ } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz", - "integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.4.tgz", + "integrity": "sha512-vUnkBYxZW4hL/ie91hSqaSNjulOnYXE1VSLusnvHg2u3jewJBz3YzB9+oCw8DABeVqZGg94t9tyZFoHma8gWZQ==", "cpu": [ "arm64" ], @@ -984,9 +980,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz", - "integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.4.tgz", + "integrity": "sha512-XAg8pIQn5CzhOB8odIcAm42QsOfa98SBeKUdo4xa8OvX8LbMZqEtgeWE9P/Wxt7MlG2QqvjGths+nq48TrUiKw==", "cpu": [ "x64" ], @@ -999,9 +995,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz", - "integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.4.tgz", + "integrity": "sha512-Ct2WcFEANlFDtp1nVAXSNBPDxyU+j7+tId//iHXU2f/lN5AmO4zLyhDcpR5Cz1r08mVxzt3Jpyt4PmXQ1O6+7A==", "cpu": [ "arm64" ], @@ -1014,9 +1010,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz", - "integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.4.tgz", + "integrity": "sha512-xAGGhyOQ9Otm1Xu8NT1ifGLnA6M3sJxZ6ixylb+vIUVzvvd6GOALpwQrYrtlPouMqd/vSbgehz6HaVk4+7Afhw==", "cpu": [ "x64" ], @@ -1029,9 +1025,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz", - "integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.4.tgz", + "integrity": "sha512-Mw+tzy4pp6wZEK0+Lwr76pWLjrtjmJyUB23tHKqEDP74R3q95luY/bXqXZeYl4NYlvwOqoRKlInQialgCKy67Q==", "cpu": [ "x64" ], @@ -1044,9 +1040,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz", - "integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.4.tgz", + "integrity": "sha512-AVUP428VQTSddguz9dO9ngb+E5aScyg7nOeJDrF1HPYu555gmza3bDGMPhmVXL8svDSoqPCsCPjb265yG/kLKQ==", "cpu": [ "arm64" ], @@ -1059,9 +1055,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz", - "integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.4.tgz", + "integrity": "sha512-i1sW+1i+oWvQzSgfRcxxG2k4I9n3O9NRqy8U+uugaT2Dy7kLO9Y7wI72haOahxceMX8hZAzgGou1FhndRldxRg==", "cpu": [ "ia32" ], @@ -1074,9 +1070,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz", - "integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.4.tgz", + "integrity": "sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ==", "cpu": [ "x64" ], @@ -1088,15 +1084,10 @@ "node": ">=18" } }, - "node_modules/@eshaz/web-worker": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@eshaz/web-worker/-/web-worker-1.2.2.tgz", - "integrity": "sha512-WxXiHFmD9u/owrzempiDlBB1ZYqiLnm9s6aPc8AlFQalq2tKmqdmMr9GXOupDgzXtqnBipj8Un0gkIm7Sjf8mw==" - }, "node_modules/@eslint-community/eslint-utils": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", - "integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", + "integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==", "dependencies": { "eslint-visitor-keys": "^3.4.3" }, @@ -1286,9 +1277,9 @@ ] }, "node_modules/@figuro/chatwoot-sdk": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@figuro/chatwoot-sdk/-/chatwoot-sdk-1.1.16.tgz", - "integrity": "sha512-u3wGCAt0Y2KXuEi+tIssaP/x0mFFwD99d2cXsysmBsFA0Bus0LGjEVjD/pJ2RGLvG+M/kxzqDGsLkSgzLjcP0w==", + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@figuro/chatwoot-sdk/-/chatwoot-sdk-1.1.17.tgz", + "integrity": "sha512-KfrBoMLMAan3379evYqmC2gUKYWGRJb0g+1EQZ44vUcDxOGlH5riddK1OB998Knvm0TYNZBqKhhwJHqDYBUpSw==", "dependencies": { "axios": "^0.27.2" } @@ -1877,11 +1868,6 @@ "regenerator-runtime": "^0.13.3" } }, - "node_modules/@jimp/utils/node_modules/regenerator-runtime": { - "version": "0.13.11", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", - "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" - }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.8", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.8.tgz", @@ -1935,10 +1921,41 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@keyv/serialize": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.0.3.tgz", + "integrity": "sha512-qnEovoOp5Np2JDGonIDL6Ayihw0RhnRh6vxPuHo4RDn1UOzwEo4AeIfpL6UGIrsceWrCMiVPgwRjbHu4vYFc3g==", + "dependencies": { + "buffer": "^6.0.3" + } + }, + "node_modules/@keyv/serialize/node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, "node_modules/@noble/hashes": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.1.tgz", - "integrity": "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", "engines": { "node": "^14.21.3 || >=16" }, @@ -1987,9 +2004,9 @@ } }, "node_modules/@opentelemetry/api-logs": { - "version": "0.56.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.56.0.tgz", - "integrity": "sha512-Wr39+94UNNG3Ei9nv3pHd4AJ63gq5nSemMRpCd8fPwDL9rN3vK26lzxfH27mw16XzOSO+TpyQwBAMaLxaPWG0g==", + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.57.2.tgz", + "integrity": "sha512-uIX52NnTM0iBh84MShlpouI7UKqkZ7MrUszTmaypHBu4r7NofznSnQRfJ+uUeDtQDj6w8eFGg5KBLDAwAPz1+A==", "dependencies": { "@opentelemetry/api": "^1.3.0" }, @@ -2022,12 +2039,20 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, + "node_modules/@opentelemetry/core/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "engines": { + "node": ">=14" + } + }, "node_modules/@opentelemetry/instrumentation": { - "version": "0.56.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.56.0.tgz", - "integrity": "sha512-2KkGBKE+FPXU1F0zKww+stnlUxUTlBvLCiWdP63Z9sqXYeNI/ziNzsxAp4LAdUcTQmXjw1IWgvm5CAb/BHy99w==", + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.57.2.tgz", + "integrity": "sha512-BdBGhQBh8IjZ2oIIX6F2/Q3LKm/FDDKi6ccYKcBTeilh6SNdNKveDOLk73BkSJjQLJk6qe4Yh+hHw1UPhCDdrg==", "dependencies": { - "@opentelemetry/api-logs": "0.56.0", + "@opentelemetry/api-logs": "0.57.2", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", @@ -2042,12 +2067,12 @@ } }, "node_modules/@opentelemetry/instrumentation-amqplib": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-amqplib/-/instrumentation-amqplib-0.45.0.tgz", - "integrity": "sha512-SlKLsOS65NGMIBG1Lh/hLrMDU9WzTUF25apnV6ZmWZB1bBmUwan7qrwwrTu1cL5LzJWCXOdZPuTaxP7pC9qxnQ==", + "version": "0.46.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-amqplib/-/instrumentation-amqplib-0.46.1.tgz", + "integrity": "sha512-AyXVnlCf/xV3K/rNumzKxZqsULyITJH6OVLiW6730JPRqWA7Zc9bvYoVNpN6iOpTU8CasH34SU/ksVJmObFibQ==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.1", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2058,12 +2083,12 @@ } }, "node_modules/@opentelemetry/instrumentation-connect": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.42.0.tgz", - "integrity": "sha512-bOoYHBmbnq/jFaLHmXJ55VQ6jrH5fHDMAPjFM0d3JvR0dvIqW7anEoNC33QqYGFYUfVJ50S0d/eoyF61ALqQuA==", + "version": "0.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.43.0.tgz", + "integrity": "sha512-Q57JGpH6T4dkYHo9tKXONgLtxzsh1ZEW5M9A/OwKrZFyEpLqWgjhcZ3hIuVvDlhb426iDF1f9FPToV/mi5rpeA==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/connect": "3.4.36" }, @@ -2075,11 +2100,11 @@ } }, "node_modules/@opentelemetry/instrumentation-dataloader": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dataloader/-/instrumentation-dataloader-0.15.0.tgz", - "integrity": "sha512-5fP35A2jUPk4SerVcduEkpbRAIoqa2PaP5rWumn01T1uSbavXNccAr3Xvx1N6xFtZxXpLJq4FYqGFnMgDWgVng==", + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dataloader/-/instrumentation-dataloader-0.16.0.tgz", + "integrity": "sha512-88+qCHZC02up8PwKHk0UQKLLqGGURzS3hFQBZC7PnGwReuoKjHXS1o29H58S+QkXJpkTr2GACbx8j6mUoGjNPA==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0" + "@opentelemetry/instrumentation": "^0.57.0" }, "engines": { "node": ">=14" @@ -2089,12 +2114,12 @@ } }, "node_modules/@opentelemetry/instrumentation-express": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-express/-/instrumentation-express-0.46.0.tgz", - "integrity": "sha512-BCEClDj/HPq/1xYRAlOr6z+OUnbp2eFp18DSrgyQz4IT9pkdYk8eWHnMi9oZSqlC6J5mQzkFmaW5RrKb1GLQhg==", + "version": "0.47.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-express/-/instrumentation-express-0.47.0.tgz", + "integrity": "sha512-XFWVx6k0XlU8lu6cBlCa29ONtVt6ADEjmxtyAyeF2+rifk8uBJbk1La0yIVfI0DoKURGbaEDTNelaXG9l/lNNQ==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2105,12 +2130,12 @@ } }, "node_modules/@opentelemetry/instrumentation-fastify": { - "version": "0.43.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fastify/-/instrumentation-fastify-0.43.0.tgz", - "integrity": "sha512-Lmdsg7tYiV+K3/NKVAQfnnLNGmakUOFdB0PhoTh2aXuSyCmyNnnDvhn2MsArAPTZ68wnD5Llh5HtmiuTkf+DyQ==", + "version": "0.44.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fastify/-/instrumentation-fastify-0.44.1.tgz", + "integrity": "sha512-RoVeMGKcNttNfXMSl6W4fsYoCAYP1vi6ZAWIGhBY+o7R9Y0afA7f9JJL0j8LHbyb0P0QhSYk+6O56OwI2k4iRQ==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2121,12 +2146,12 @@ } }, "node_modules/@opentelemetry/instrumentation-fs": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.18.0.tgz", - "integrity": "sha512-kC40y6CEMONm8/MWwoF5GHWIC7gOdF+g3sgsjfwJaUkgD6bdWV+FgG0XApqSbTQndICKzw3RonVk8i7s6mHqhA==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.19.0.tgz", + "integrity": "sha512-JGwmHhBkRT2G/BYNV1aGI+bBjJu4fJUD/5/Jat0EWZa2ftrLV3YE8z84Fiij/wK32oMZ88eS8DI4ecLGZhpqsQ==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0" + "@opentelemetry/instrumentation": "^0.57.0" }, "engines": { "node": ">=14" @@ -2136,11 +2161,11 @@ } }, "node_modules/@opentelemetry/instrumentation-generic-pool": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-generic-pool/-/instrumentation-generic-pool-0.42.0.tgz", - "integrity": "sha512-J4QxqiQ1imtB9ogzsOnHra0g3dmmLAx4JCeoK3o0rFes1OirljNHnO8Hsj4s1jAir8WmWvnEEQO1y8yk6j2tog==", + "version": "0.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-generic-pool/-/instrumentation-generic-pool-0.43.0.tgz", + "integrity": "sha512-at8GceTtNxD1NfFKGAuwtqM41ot/TpcLh+YsGe4dhf7gvv1HW/ZWdq6nfRtS6UjIvZJOokViqLPJ3GVtZItAnQ==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0" + "@opentelemetry/instrumentation": "^0.57.0" }, "engines": { "node": ">=14" @@ -2150,11 +2175,11 @@ } }, "node_modules/@opentelemetry/instrumentation-graphql": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-graphql/-/instrumentation-graphql-0.46.0.tgz", - "integrity": "sha512-tplk0YWINSECcK89PGM7IVtOYenXyoOuhOQlN0X0YrcDUfMS4tZMKkVc0vyhNWYYrexnUHwNry2YNBNugSpjlQ==", + "version": "0.47.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-graphql/-/instrumentation-graphql-0.47.0.tgz", + "integrity": "sha512-Cc8SMf+nLqp0fi8oAnooNEfwZWFnzMiBHCGmDFYqmgjPylyLmi83b+NiTns/rKGwlErpW0AGPt0sMpkbNlzn8w==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0" + "@opentelemetry/instrumentation": "^0.57.0" }, "engines": { "node": ">=14" @@ -2164,12 +2189,12 @@ } }, "node_modules/@opentelemetry/instrumentation-hapi": { - "version": "0.44.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-hapi/-/instrumentation-hapi-0.44.0.tgz", - "integrity": "sha512-4HdNIMNXWK1O6nsaQOrACo83QWEVoyNODTdVDbUqtqXiv2peDfD0RAPhSQlSGWLPw3S4d9UoOmrV7s2HYj6T2A==", + "version": "0.45.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-hapi/-/instrumentation-hapi-0.45.1.tgz", + "integrity": "sha512-VH6mU3YqAKTePPfUPwfq4/xr049774qWtfTuJqVHoVspCLiT3bW+fCQ1toZxt6cxRPYASoYaBsMA3CWo8B8rcw==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2180,12 +2205,12 @@ } }, "node_modules/@opentelemetry/instrumentation-http": { - "version": "0.56.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.56.0.tgz", - "integrity": "sha512-/bWHBUAq8VoATnH9iLk5w8CE9+gj+RgYSUphe7hry472n6fYl7+4PvuScoQMdmSUTprKq/gyr2kOWL6zrC7FkQ==", + "version": "0.57.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.57.1.tgz", + "integrity": "sha512-ThLmzAQDs7b/tdKI3BV2+yawuF09jF111OFsovqT1Qj3D8vjwKBwhi/rDE5xethwn4tSXtZcJ9hBsVAlWFQZ7g==", "dependencies": { - "@opentelemetry/core": "1.29.0", - "@opentelemetry/instrumentation": "0.56.0", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/instrumentation": "0.57.1", "@opentelemetry/semantic-conventions": "1.28.0", "forwarded-parse": "2.1.2", "semver": "^7.5.2" @@ -2197,26 +2222,50 @@ "@opentelemetry/api": "^1.3.0" } }, - "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/core": { - "version": "1.29.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.29.0.tgz", - "integrity": "sha512-gmT7vAreXl0DTHD2rVZcw3+l2g84+5XiHIqdBUxXbExymPCvSsGOpiwMmn8nkiJur28STV31wnhIDrzWDPzjfA==", + "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/api-logs": { + "version": "0.57.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.57.1.tgz", + "integrity": "sha512-I4PHczeujhQAQv6ZBzqHYEUiggZL4IdSMixtVD3EYqbdrjujE7kRfI5QohjlPoJm8BvenoW5YaTMWRrbpot6tg==", "dependencies": { - "@opentelemetry/semantic-conventions": "1.28.0" + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/instrumentation": { + "version": "0.57.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.57.1.tgz", + "integrity": "sha512-SgHEKXoVxOjc20ZYusPG3Fh+RLIZTSa4x8QtD3NfgAUDyqdFFS9W1F2ZVbZkqDCdyMcQG02Ok4duUGLHJXHgbA==", + "dependencies": { + "@opentelemetry/api-logs": "0.57.1", + "@types/shimmer": "^1.2.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1", + "semver": "^7.5.2", + "shimmer": "^1.2.1" }, "engines": { "node": ">=14" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "engines": { + "node": ">=14" } }, "node_modules/@opentelemetry/instrumentation-ioredis": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.46.0.tgz", - "integrity": "sha512-sOdsq8oGi29V58p1AkefHvuB3l2ymP1IbxRIX3y4lZesQWKL8fLhBmy8xYjINSQ5gHzWul2yoz7pe7boxhZcqQ==", + "version": "0.47.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.47.0.tgz", + "integrity": "sha512-4HqP9IBC8e7pW9p90P3q4ox0XlbLGme65YTrA3UTLvqvo4Z6b0puqZQP203YFu8m9rE/luLfaG7/xrwwqMUpJw==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/redis-common": "^0.36.2", "@opentelemetry/semantic-conventions": "^1.27.0" }, @@ -2228,11 +2277,11 @@ } }, "node_modules/@opentelemetry/instrumentation-kafkajs": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-kafkajs/-/instrumentation-kafkajs-0.6.0.tgz", - "integrity": "sha512-MGQrzqEUAl0tacKJUFpuNHJesyTi51oUzSVizn7FdvJplkRIdS11FukyZBZJEscofSEdk7Ycmg+kNMLi5QHUFg==", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-kafkajs/-/instrumentation-kafkajs-0.7.0.tgz", + "integrity": "sha512-LB+3xiNzc034zHfCtgs4ITWhq6Xvdo8bsq7amR058jZlf2aXXDrN9SV4si4z2ya9QX4tz6r4eZJwDkXOp14/AQ==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2243,11 +2292,11 @@ } }, "node_modules/@opentelemetry/instrumentation-knex": { - "version": "0.43.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-knex/-/instrumentation-knex-0.43.0.tgz", - "integrity": "sha512-mOp0TRQNFFSBj5am0WF67fRO7UZMUmsF3/7HSDja9g3H4pnj+4YNvWWyZn4+q0rGrPtywminAXe0rxtgaGYIqg==", + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-knex/-/instrumentation-knex-0.44.0.tgz", + "integrity": "sha512-SlT0+bLA0Lg3VthGje+bSZatlGHw/vwgQywx0R/5u9QC59FddTQSPJeWNw29M6f8ScORMeUOOTwihlQAn4GkJQ==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2258,12 +2307,12 @@ } }, "node_modules/@opentelemetry/instrumentation-koa": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-koa/-/instrumentation-koa-0.46.0.tgz", - "integrity": "sha512-RcWXMQdJQANnPUaXbHY5G0Fg6gmleZ/ZtZeSsekWPaZmQq12FGk0L1UwodIgs31OlYfviAZ4yTeytoSUkgo5vQ==", + "version": "0.47.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-koa/-/instrumentation-koa-0.47.0.tgz", + "integrity": "sha512-HFdvqf2+w8sWOuwtEXayGzdZ2vWpCKEQv5F7+2DSA74Te/Cv4rvb2E5So5/lh+ok4/RAIPuvCbCb/SHQFzMmbw==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2274,11 +2323,11 @@ } }, "node_modules/@opentelemetry/instrumentation-lru-memoizer": { - "version": "0.43.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-lru-memoizer/-/instrumentation-lru-memoizer-0.43.0.tgz", - "integrity": "sha512-fZc+1eJUV+tFxaB3zkbupiA8SL3vhDUq89HbDNg1asweYrEb9OlHIB+Ot14ZiHUc1qCmmWmZHbPTwa56mVVwzg==", + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-lru-memoizer/-/instrumentation-lru-memoizer-0.44.0.tgz", + "integrity": "sha512-Tn7emHAlvYDFik3vGU0mdwvWJDwtITtkJ+5eT2cUquct6nIs+H8M47sqMJkCpyPe5QIBJoTOHxmc6mj9lz6zDw==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0" + "@opentelemetry/instrumentation": "^0.57.0" }, "engines": { "node": ">=14" @@ -2288,11 +2337,11 @@ } }, "node_modules/@opentelemetry/instrumentation-mongodb": { - "version": "0.50.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongodb/-/instrumentation-mongodb-0.50.0.tgz", - "integrity": "sha512-DtwJMjYFXFT5auAvv8aGrBj1h3ciA/dXQom11rxL7B1+Oy3FopSpanvwYxJ+z0qmBrQ1/iMuWELitYqU4LnlkQ==", + "version": "0.51.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongodb/-/instrumentation-mongodb-0.51.0.tgz", + "integrity": "sha512-cMKASxCX4aFxesoj3WK8uoQ0YUrRvnfxaO72QWI2xLu5ZtgX/QvdGBlU3Ehdond5eb74c2s1cqRQUIptBnKz1g==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2303,12 +2352,12 @@ } }, "node_modules/@opentelemetry/instrumentation-mongoose": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongoose/-/instrumentation-mongoose-0.45.0.tgz", - "integrity": "sha512-zHgNh+A01C5baI2mb5dAGyMC7DWmUpOfwpV8axtC0Hd5Uzqv+oqKgKbVDIVhOaDkPxjgVJwYF9YQZl2pw2qxIA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongoose/-/instrumentation-mongoose-0.46.0.tgz", + "integrity": "sha512-mtVv6UeaaSaWTeZtLo4cx4P5/ING2obSqfWGItIFSunQBrYROfhuVe7wdIrFUs2RH1tn2YYpAJyMaRe/bnTTIQ==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2319,11 +2368,11 @@ } }, "node_modules/@opentelemetry/instrumentation-mysql": { - "version": "0.44.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql/-/instrumentation-mysql-0.44.0.tgz", - "integrity": "sha512-al7jbXvT/uT1KV8gdNDzaWd5/WXf+mrjrsF0/NtbnqLa0UUFGgQnoK3cyborgny7I+KxWhL8h7YPTf6Zq4nKsg==", + "version": "0.45.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql/-/instrumentation-mysql-0.45.0.tgz", + "integrity": "sha512-tWWyymgwYcTwZ4t8/rLDfPYbOTF3oYB8SxnYMtIQ1zEf5uDm90Ku3i6U/vhaMyfHNlIHvDhvJh+qx5Nc4Z3Acg==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/mysql": "2.15.26" }, @@ -2335,11 +2384,11 @@ } }, "node_modules/@opentelemetry/instrumentation-mysql2": { - "version": "0.44.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql2/-/instrumentation-mysql2-0.44.0.tgz", - "integrity": "sha512-e9QY4AGsjGFwmfHd6kBa4yPaQZjAq2FuxMb0BbKlXCAjG+jwqw+sr9xWdJGR60jMsTq52hx3mAlE3dUJ9BipxQ==", + "version": "0.45.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql2/-/instrumentation-mysql2-0.45.0.tgz", + "integrity": "sha512-qLslv/EPuLj0IXFvcE3b0EqhWI8LKmrgRPIa4gUd8DllbBpqJAvLNJSv3cC6vWwovpbSI3bagNO/3Q2SuXv2xA==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.40.1" }, @@ -2351,11 +2400,11 @@ } }, "node_modules/@opentelemetry/instrumentation-nestjs-core": { - "version": "0.43.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-nestjs-core/-/instrumentation-nestjs-core-0.43.0.tgz", - "integrity": "sha512-NEo4RU7HTjiaXk3curqXUvCb9alRiFWxQY//+hvDXwWLlADX2vB6QEmVCeEZrKO+6I/tBrI4vNdAnbCY9ldZVg==", + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-nestjs-core/-/instrumentation-nestjs-core-0.44.0.tgz", + "integrity": "sha512-t16pQ7A4WYu1yyQJZhRKIfUNvl5PAaF2pEteLvgJb/BWdd1oNuU1rOYt4S825kMy+0q4ngiX281Ss9qiwHfxFQ==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { @@ -2366,12 +2415,12 @@ } }, "node_modules/@opentelemetry/instrumentation-pg": { - "version": "0.49.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pg/-/instrumentation-pg-0.49.0.tgz", - "integrity": "sha512-3alvNNjPXVdAPdY1G7nGRVINbDxRK02+KAugDiEpzw0jFQfU8IzFkSWA4jyU4/GbMxKvHD+XIOEfSjpieSodKw==", + "version": "0.50.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pg/-/instrumentation-pg-0.50.0.tgz", + "integrity": "sha512-TtLxDdYZmBhFswm8UIsrDjh/HFBeDXd4BLmE8h2MxirNHewLJ0VS9UUddKKEverb5Sm2qFVjqRjcU+8Iw4FJ3w==", "dependencies": { "@opentelemetry/core": "^1.26.0", - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "1.27.0", "@opentelemetry/sql-common": "^0.40.1", "@types/pg": "8.6.1", @@ -2393,11 +2442,11 @@ } }, "node_modules/@opentelemetry/instrumentation-redis-4": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-redis-4/-/instrumentation-redis-4-0.45.0.tgz", - "integrity": "sha512-Sjgym1xn3mdxPRH5CNZtoz+bFd3E3NlGIu7FoYr4YrQouCc9PbnmoBcmSkEdDy5LYgzNildPgsjx9l0EKNjKTQ==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-redis-4/-/instrumentation-redis-4-0.46.0.tgz", + "integrity": "sha512-aTUWbzbFMFeRODn3720TZO0tsh/49T8H3h8vVnVKJ+yE36AeW38Uj/8zykQ/9nO8Vrtjr5yKuX3uMiG/W8FKNw==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/redis-common": "^0.36.2", "@opentelemetry/semantic-conventions": "^1.27.0" }, @@ -2409,11 +2458,11 @@ } }, "node_modules/@opentelemetry/instrumentation-tedious": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-tedious/-/instrumentation-tedious-0.17.0.tgz", - "integrity": "sha512-yRBz2409an03uVd1Q2jWMt3SqwZqRFyKoWYYX3hBAtPDazJ4w5L+1VOij71TKwgZxZZNdDBXImTQjii+VeuzLg==", + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-tedious/-/instrumentation-tedious-0.18.0.tgz", + "integrity": "sha512-9zhjDpUDOtD+coeADnYEJQ0IeLVCj7w/hqzIutdp5NqS1VqTAanaEfsEcSypyvYv5DX3YOsTUoF+nr2wDXPETA==", "dependencies": { - "@opentelemetry/instrumentation": "^0.56.0", + "@opentelemetry/instrumentation": "^0.57.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/tedious": "^4.0.14" }, @@ -2425,12 +2474,12 @@ } }, "node_modules/@opentelemetry/instrumentation-undici": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.9.0.tgz", - "integrity": "sha512-lxc3cpUZ28CqbrWcUHxGW/ObDpMOYbuxF/ZOzeFZq54P9uJ2Cpa8gcrC9F716mtuiMaekwk8D6n34vg/JtkkxQ==", + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.10.0.tgz", + "integrity": "sha512-vm+V255NGw9gaSsPD6CP0oGo8L55BffBc8KnxqsMuc6XiAD1L8SFNzsW0RHhxJFqy9CJaJh+YiJ5EHXuZ5rZBw==", "dependencies": { "@opentelemetry/core": "^1.8.0", - "@opentelemetry/instrumentation": "^0.56.0" + "@opentelemetry/instrumentation": "^0.57.0" }, "engines": { "node": ">=14" @@ -2462,6 +2511,14 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, + "node_modules/@opentelemetry/resources/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "engines": { + "node": ">=14" + } + }, "node_modules/@opentelemetry/sdk-trace-base": { "version": "1.30.1", "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.30.1.tgz", @@ -2478,7 +2535,7 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, - "node_modules/@opentelemetry/semantic-conventions": { + "node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/semantic-conventions": { "version": "1.28.0", "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", @@ -2486,6 +2543,14 @@ "node": ">=14" } }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.33.0.tgz", + "integrity": "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w==", + "engines": { + "node": ">=14" + } + }, "node_modules/@opentelemetry/sql-common": { "version": "0.40.1", "resolved": "https://registry.npmjs.org/@opentelemetry/sql-common/-/sql-common-0.40.1.tgz", @@ -2518,21 +2583,21 @@ } }, "node_modules/@pkgr/core": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.1.tgz", - "integrity": "sha512-cq8o4cWH0ibXh9VGi5P20Tu9XF/0fFXl9EUinr9QfTM7a7p0oTA4iJRCQWppXR1Pg8dSM0UCItCkPwsk9qWWYA==", + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.4.tgz", + "integrity": "sha512-ROFF39F6ZrnzSUEmQQZUar0Jt4xVoP9WnDRdWwF4NNcXs3xBTLgBUDoOwW141y1jP+S8nahIbdxbFC7IShw9Iw==", "dev": true, "engines": { "node": "^12.20.0 || ^14.18.0 || >=16.0.0" }, "funding": { - "url": "https://opencollective.com/unts" + "url": "https://opencollective.com/pkgr" } }, "node_modules/@prisma/client": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.3.0.tgz", - "integrity": "sha512-BY3Fi28PUSk447Bpv22LhZp4HgNPo7NsEN+EteM1CLDnLjig5863jpW+3c3HHLFmml+nB/eJv1CjSriFZ8z7Cg==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.8.1.tgz", + "integrity": "sha512-OxkcBe9i/iQp4vNlXB2nRaTAIu3xtdshqKAUYenGve7MnT1YFsE2FOr92MMF2/5TuNTAJ1jGyls3t16YSfoOYA==", "hasInstallScript": true, "engines": { "node": ">=18.18" @@ -2550,44 +2615,52 @@ } } }, + "node_modules/@prisma/config": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.8.1.tgz", + "integrity": "sha512-8F8fPo32+L9pZ6iESJnFS/Q6R7jvKb5Bn8hsMcOYpkIRV4OQcdvCBQpLS60qol16F0TUAu2NXiE97a/hghex4Q==", + "dependencies": { + "jiti": "2.4.2" + } + }, "node_modules/@prisma/debug": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.3.0.tgz", - "integrity": "sha512-m1lQv//0Rc5RG8TBpNUuLCxC35Ghi5XfpPmL83Gh04/GICHD2J5H2ndMlaljrUNaQDF9dOxIuFAYP1rE9wkXkg==" + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.8.1.tgz", + "integrity": "sha512-3HrYLFje+ngEUBKH9x6LWBiqpX8pQEB791RWFS+anWoklM9b6MFdWGzK0bika3rGIs0KOb0ZTKVXo6OmWvjryg==" }, "node_modules/@prisma/engines": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.3.0.tgz", - "integrity": "sha512-RXqYhlZb9sx/xkUfYIZuEPn7sT0WgTxNOuEYQ7AGw3IMpP9QGVEDVsluc/GcNkM8NTJszeqk8AplJzI9lm7Jxw==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.8.1.tgz", + "integrity": "sha512-QPU2uNA33MDn1V7Kp2jMm4Ik9f1A5MOPsHDfWDVsS4cYDRO51Kli7/4mjOilmbmaVbHsTjtcTPcZ7K08v46Siw==", "hasInstallScript": true, "dependencies": { - "@prisma/debug": "6.3.0", - "@prisma/engines-version": "6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0", - "@prisma/fetch-engine": "6.3.0", - "@prisma/get-platform": "6.3.0" + "@prisma/debug": "6.8.1", + "@prisma/engines-version": "6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e", + "@prisma/fetch-engine": "6.8.1", + "@prisma/get-platform": "6.8.1" } }, "node_modules/@prisma/engines-version": { - "version": "6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0", - "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0.tgz", - "integrity": "sha512-R/ZcMuaWZT2UBmgX3Ko6PAV3f8//ZzsjRIG1eKqp3f2rqEqVtCv+mtzuH2rBPUC9ujJ5kCb9wwpxeyCkLcHVyA==" + "version": "6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e.tgz", + "integrity": "sha512-Rkik9lMyHpFNGaLpPF3H5q5TQTkm/aE7DsGM5m92FZTvWQsvmi6Va8On3pWvqLHOt5aPUvFb/FeZTmphI4CPiQ==" }, "node_modules/@prisma/fetch-engine": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.3.0.tgz", - "integrity": "sha512-GBy0iT4f1mH31ePzfcpVSUa7JLRTeq4914FG2vR3LqDwRweSm4ja1o5flGDz+eVIa/BNYfkBvRRxv4D6ve6Eew==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.8.1.tgz", + "integrity": "sha512-BaTTSTW0dKNQ4NYsm4qDYuP6wbqaqi1/wSjub4/PF9JBQ0sWspKknrpY7qKLrA/vNQjSfw6Hfd10HWtmT9Hq7g==", "dependencies": { - "@prisma/debug": "6.3.0", - "@prisma/engines-version": "6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0", - "@prisma/get-platform": "6.3.0" + "@prisma/debug": "6.8.1", + "@prisma/engines-version": "6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e", + "@prisma/get-platform": "6.8.1" } }, "node_modules/@prisma/get-platform": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.3.0.tgz", - "integrity": "sha512-V8zZ1d0xfyi6FjpNP4AcYuwSpGcdmu35OXWnTPm8IW594PYALzKXHwIa9+o0f+Lo9AecFWrwrwaoYe56UNfTtQ==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.8.1.tgz", + "integrity": "sha512-wOBUB/wiY1m4MDq9VtIy1nVF5bRhd+e0LShR4bxb9oPdfotFubxB3ZkLTRbcSppDkFU2mVSPMPu6YLHXYl5wFg==", "dependencies": { - "@prisma/debug": "6.3.0" + "@prisma/debug": "6.8.1" } }, "node_modules/@prisma/instrumentation": { @@ -2693,9 +2766,9 @@ } }, "node_modules/@redis/client": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.6.0.tgz", - "integrity": "sha512-aR0uffYI700OEEH4gYnitAnv3vzVGXCFvYfdpu/CJKvk4pHfLPEy/JSZyrpQ+15WhXe1yJRXLtfQ84s4mEXnPg==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.6.1.tgz", + "integrity": "sha512-/KCsg3xSlR+nCK8/8ZYSknYxvXHwubJrU82F3Lm1Fp6789VQ0/3RJKfsmRXjqfaTA++23CvC3hqmqe/2GEt6Kw==", "dependencies": { "cluster-key-slot": "1.1.2", "generic-pool": "3.9.0", @@ -2738,9 +2811,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.32.1.tgz", - "integrity": "sha512-/pqA4DmqyCm8u5YIDzIdlLcEmuvxb0v8fZdFhVMszSpDTgbQKdw3/mB3eMUHIbubtJ6F9j+LtmyCnHTEqIHyzA==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.40.2.tgz", + "integrity": "sha512-JkdNEq+DFxZfUwxvB58tHMHBHVgX23ew41g1OQinthJ+ryhdRk67O31S7sYw8u2lTjHUPFxwar07BBt1KHp/hg==", "cpu": [ "arm" ], @@ -2750,9 +2823,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.32.1.tgz", - "integrity": "sha512-If3PDskT77q7zgqVqYuj7WG3WC08G1kwXGVFi9Jr8nY6eHucREHkfpX79c0ACAjLj3QIWKPJR7w4i+f5EdLH5Q==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.40.2.tgz", + "integrity": "sha512-13unNoZ8NzUmnndhPTkWPWbX3vtHodYmy+I9kuLxN+F+l+x3LdVF7UCu8TWVMt1POHLh6oDHhnOA04n8oJZhBw==", "cpu": [ "arm64" ], @@ -2762,9 +2835,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.32.1.tgz", - "integrity": "sha512-zCpKHioQ9KgZToFp5Wvz6zaWbMzYQ2LJHQ+QixDKq52KKrF65ueu6Af4hLlLWHjX1Wf/0G5kSJM9PySW9IrvHA==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.40.2.tgz", + "integrity": "sha512-Gzf1Hn2Aoe8VZzevHostPX23U7N5+4D36WJNHK88NZHCJr7aVMG4fadqkIf72eqVPGjGc0HJHNuUaUcxiR+N/w==", "cpu": [ "arm64" ], @@ -2774,9 +2847,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.32.1.tgz", - "integrity": "sha512-sFvF+t2+TyUo/ZQqUcifrJIgznx58oFZbdHS9TvHq3xhPVL9nOp+yZ6LKrO9GWTP+6DbFtoyLDbjTpR62Mbr3Q==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.40.2.tgz", + "integrity": "sha512-47N4hxa01a4x6XnJoskMKTS8XZ0CZMd8YTbINbi+w03A2w4j1RTlnGHOz/P0+Bg1LaVL6ufZyNprSg+fW5nYQQ==", "cpu": [ "x64" ], @@ -2786,9 +2859,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.32.1.tgz", - "integrity": "sha512-NbOa+7InvMWRcY9RG+B6kKIMD/FsnQPH0MWUvDlQB1iXnF/UcKSudCXZtv4lW+C276g3w5AxPbfry5rSYvyeYA==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.40.2.tgz", + "integrity": "sha512-8t6aL4MD+rXSHHZUR1z19+9OFJ2rl1wGKvckN47XFRVO+QL/dUSpKA2SLRo4vMg7ELA8pzGpC+W9OEd1Z/ZqoQ==", "cpu": [ "arm64" ], @@ -2798,9 +2871,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.32.1.tgz", - "integrity": "sha512-JRBRmwvHPXR881j2xjry8HZ86wIPK2CcDw0EXchE1UgU0ubWp9nvlT7cZYKc6bkypBt745b4bglf3+xJ7hXWWw==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.40.2.tgz", + "integrity": "sha512-C+AyHBzfpsOEYRFjztcYUFsH4S7UsE9cDtHCtma5BK8+ydOZYgMmWg1d/4KBytQspJCld8ZIujFMAdKG1xyr4Q==", "cpu": [ "x64" ], @@ -2810,9 +2883,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.32.1.tgz", - "integrity": "sha512-PKvszb+9o/vVdUzCCjL0sKHukEQV39tD3fepXxYrHE3sTKrRdCydI7uldRLbjLmDA3TFDmh418XH19NOsDRH8g==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.40.2.tgz", + "integrity": "sha512-de6TFZYIvJwRNjmW3+gaXiZ2DaWL5D5yGmSYzkdzjBDS3W+B9JQ48oZEsmMvemqjtAFzE16DIBLqd6IQQRuG9Q==", "cpu": [ "arm" ], @@ -2822,9 +2895,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.32.1.tgz", - "integrity": "sha512-9WHEMV6Y89eL606ReYowXuGF1Yb2vwfKWKdD1A5h+OYnPZSJvxbEjxTRKPgi7tkP2DSnW0YLab1ooy+i/FQp/Q==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.40.2.tgz", + "integrity": "sha512-urjaEZubdIkacKc930hUDOfQPysezKla/O9qV+O89enqsqUmQm8Xj8O/vh0gHg4LYfv7Y7UsE3QjzLQzDYN1qg==", "cpu": [ "arm" ], @@ -2834,9 +2907,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.32.1.tgz", - "integrity": "sha512-tZWc9iEt5fGJ1CL2LRPw8OttkCBDs+D8D3oEM8mH8S1ICZCtFJhD7DZ3XMGM8kpqHvhGUTvNUYVDnmkj4BDXnw==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.40.2.tgz", + "integrity": "sha512-KlE8IC0HFOC33taNt1zR8qNlBYHj31qGT1UqWqtvR/+NuCVhfufAq9fxO8BMFC22Wu0rxOwGVWxtCMvZVLmhQg==", "cpu": [ "arm64" ], @@ -2846,9 +2919,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.32.1.tgz", - "integrity": "sha512-FTYc2YoTWUsBz5GTTgGkRYYJ5NGJIi/rCY4oK/I8aKowx1ToXeoVVbIE4LGAjsauvlhjfl0MYacxClLld1VrOw==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.40.2.tgz", + "integrity": "sha512-j8CgxvfM0kbnhu4XgjnCWJQyyBOeBI1Zq91Z850aUddUmPeQvuAy6OiMdPS46gNFgy8gN1xkYyLgwLYZG3rBOg==", "cpu": [ "arm64" ], @@ -2858,9 +2931,9 @@ ] }, "node_modules/@rollup/rollup-linux-loongarch64-gnu": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.32.1.tgz", - "integrity": "sha512-F51qLdOtpS6P1zJVRzYM0v6MrBNypyPEN1GfMiz0gPu9jN8ScGaEFIZQwteSsGKg799oR5EaP7+B2jHgL+d+Kw==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.40.2.tgz", + "integrity": "sha512-Ybc/1qUampKuRF4tQXc7G7QY9YRyeVSykfK36Y5Qc5dmrIxwFhrOzqaVTNoZygqZ1ZieSWTibfFhQ5qK8jpWxw==", "cpu": [ "loong64" ], @@ -2870,9 +2943,9 @@ ] }, "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.32.1.tgz", - "integrity": "sha512-wO0WkfSppfX4YFm5KhdCCpnpGbtgQNj/tgvYzrVYFKDpven8w2N6Gg5nB6w+wAMO3AIfSTWeTjfVe+uZ23zAlg==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.40.2.tgz", + "integrity": "sha512-3FCIrnrt03CCsZqSYAOW/k9n625pjpuMzVfeI+ZBUSDT3MVIFDSPfSUgIl9FqUftxcUXInvFah79hE1c9abD+Q==", "cpu": [ "ppc64" ], @@ -2882,9 +2955,21 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.32.1.tgz", - "integrity": "sha512-iWswS9cIXfJO1MFYtI/4jjlrGb/V58oMu4dYJIKnR5UIwbkzR0PJ09O0PDZT0oJ3LYWXBSWahNf/Mjo6i1E5/g==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.40.2.tgz", + "integrity": "sha512-QNU7BFHEvHMp2ESSY3SozIkBPaPBDTsfVNGx3Xhv+TdvWXFGOSH2NJvhD1zKAT6AyuuErJgbdvaJhYVhVqrWTg==", + "cpu": [ + "riscv64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.40.2.tgz", + "integrity": "sha512-5W6vNYkhgfh7URiXTO1E9a0cy4fSgfE4+Hl5agb/U1sa0kjOLMLC1wObxwKxecE17j0URxuTrYZZME4/VH57Hg==", "cpu": [ "riscv64" ], @@ -2894,9 +2979,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.32.1.tgz", - "integrity": "sha512-RKt8NI9tebzmEthMnfVgG3i/XeECkMPS+ibVZjZ6mNekpbbUmkNWuIN2yHsb/mBPyZke4nlI4YqIdFPgKuoyQQ==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.40.2.tgz", + "integrity": "sha512-B7LKIz+0+p348JoAL4X/YxGx9zOx3sR+o6Hj15Y3aaApNfAshK8+mWZEf759DXfRLeL2vg5LYJBB7DdcleYCoQ==", "cpu": [ "s390x" ], @@ -2906,9 +2991,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.32.1.tgz", - "integrity": "sha512-WQFLZ9c42ECqEjwg/GHHsouij3pzLXkFdz0UxHa/0OM12LzvX7DzedlY0SIEly2v18YZLRhCRoHZDxbBSWoGYg==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.40.2.tgz", + "integrity": "sha512-lG7Xa+BmBNwpjmVUbmyKxdQJ3Q6whHjMjzQplOs5Z+Gj7mxPtWakGHqzMqNER68G67kmCX9qX57aRsW5V0VOng==", "cpu": [ "x64" ], @@ -2918,9 +3003,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.32.1.tgz", - "integrity": "sha512-BLoiyHDOWoS3uccNSADMza6V6vCNiphi94tQlVIL5de+r6r/CCQuNnerf+1g2mnk2b6edp5dk0nhdZ7aEjOBsA==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.40.2.tgz", + "integrity": "sha512-tD46wKHd+KJvsmije4bUskNuvWKFcTOIM9tZ/RrmIvcXnbi0YK/cKS9FzFtAm7Oxi2EhV5N2OpfFB348vSQRXA==", "cpu": [ "x64" ], @@ -2930,9 +3015,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.32.1.tgz", - "integrity": "sha512-w2l3UnlgYTNNU+Z6wOR8YdaioqfEnwPjIsJ66KxKAf0p+AuL2FHeTX6qvM+p/Ue3XPBVNyVSfCrfZiQh7vZHLQ==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.40.2.tgz", + "integrity": "sha512-Bjv/HG8RRWLNkXwQQemdsWw4Mg+IJ29LK+bJPW2SCzPKOUaMmPEppQlu/Fqk1d7+DX3V7JbFdbkh/NMmurT6Pg==", "cpu": [ "arm64" ], @@ -2942,9 +3027,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.32.1.tgz", - "integrity": "sha512-Am9H+TGLomPGkBnaPWie4F3x+yQ2rr4Bk2jpwy+iV+Gel9jLAu/KqT8k3X4jxFPW6Zf8OMnehyutsd+eHoq1WQ==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.40.2.tgz", + "integrity": "sha512-dt1llVSGEsGKvzeIO76HToiYPNPYPkmjhMHhP00T9S4rDern8P2ZWvWAQUEJ+R1UdMWJ/42i/QqJ2WV765GZcA==", "cpu": [ "ia32" ], @@ -2954,9 +3039,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.32.1.tgz", - "integrity": "sha512-ar80GhdZb4DgmW3myIS9nRFYcpJRSME8iqWgzH2i44u+IdrzmiXVxeFnExQ5v4JYUSpg94bWjevMG8JHf1Da5Q==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.40.2.tgz", + "integrity": "sha512-bwspbWB04XJpeElvsp+DCylKfF4trJDa2Y9Go8O6A7YLX2LIKGcNK/CYImJN6ZP4DcuOHB4Utl3iCbnR62DudA==", "cpu": [ "x64" ], @@ -2972,52 +3057,52 @@ "dev": true }, "node_modules/@sentry/core": { - "version": "8.52.1", - "resolved": "https://registry.npmjs.org/@sentry/core/-/core-8.52.1.tgz", - "integrity": "sha512-FG0P9I03xk4jBI4O7NBkw8uqLGH9/RWOSFoRH3eYvUTyBLhkk9IaCFbAAGBNZhojky8T7gqYwnuRbFNlrAiuSA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@sentry/core/-/core-8.55.0.tgz", + "integrity": "sha512-6g7jpbefjHYs821Z+EBJ8r4Z7LT5h80YSWRJaylGS4nW5W5Z2KXzpdnyFarv37O7QjauzVC2E+PABmpkw5/JGA==", "engines": { "node": ">=14.18" } }, "node_modules/@sentry/node": { - "version": "8.52.1", - "resolved": "https://registry.npmjs.org/@sentry/node/-/node-8.52.1.tgz", - "integrity": "sha512-we9fIfn5Q0c6U4VPrXhNtJ7uz5HkTlnOQV7hP/GG09tmKa6hrL20tkhCosObl3XZ/qlIbD/GQMv4WmhOgNzgkQ==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@sentry/node/-/node-8.55.0.tgz", + "integrity": "sha512-h10LJLDTRAzYgay60Oy7moMookqqSZSviCWkkmHZyaDn+4WURnPp5SKhhfrzPRQcXKrweiOwDSHBgn1tweDssg==", "dependencies": { "@opentelemetry/api": "^1.9.0", - "@opentelemetry/context-async-hooks": "^1.29.0", - "@opentelemetry/core": "^1.29.0", - "@opentelemetry/instrumentation": "^0.56.0", - "@opentelemetry/instrumentation-amqplib": "^0.45.0", - "@opentelemetry/instrumentation-connect": "0.42.0", - "@opentelemetry/instrumentation-dataloader": "0.15.0", - "@opentelemetry/instrumentation-express": "0.46.0", - "@opentelemetry/instrumentation-fastify": "0.43.0", - "@opentelemetry/instrumentation-fs": "0.18.0", - "@opentelemetry/instrumentation-generic-pool": "0.42.0", - "@opentelemetry/instrumentation-graphql": "0.46.0", - "@opentelemetry/instrumentation-hapi": "0.44.0", - "@opentelemetry/instrumentation-http": "0.56.0", - "@opentelemetry/instrumentation-ioredis": "0.46.0", - "@opentelemetry/instrumentation-kafkajs": "0.6.0", - "@opentelemetry/instrumentation-knex": "0.43.0", - "@opentelemetry/instrumentation-koa": "0.46.0", - "@opentelemetry/instrumentation-lru-memoizer": "0.43.0", - "@opentelemetry/instrumentation-mongodb": "0.50.0", - "@opentelemetry/instrumentation-mongoose": "0.45.0", - "@opentelemetry/instrumentation-mysql": "0.44.0", - "@opentelemetry/instrumentation-mysql2": "0.44.0", - "@opentelemetry/instrumentation-nestjs-core": "0.43.0", - "@opentelemetry/instrumentation-pg": "0.49.0", - "@opentelemetry/instrumentation-redis-4": "0.45.0", - "@opentelemetry/instrumentation-tedious": "0.17.0", - "@opentelemetry/instrumentation-undici": "0.9.0", - "@opentelemetry/resources": "^1.29.0", - "@opentelemetry/sdk-trace-base": "^1.29.0", + "@opentelemetry/context-async-hooks": "^1.30.1", + "@opentelemetry/core": "^1.30.1", + "@opentelemetry/instrumentation": "^0.57.1", + "@opentelemetry/instrumentation-amqplib": "^0.46.0", + "@opentelemetry/instrumentation-connect": "0.43.0", + "@opentelemetry/instrumentation-dataloader": "0.16.0", + "@opentelemetry/instrumentation-express": "0.47.0", + "@opentelemetry/instrumentation-fastify": "0.44.1", + "@opentelemetry/instrumentation-fs": "0.19.0", + "@opentelemetry/instrumentation-generic-pool": "0.43.0", + "@opentelemetry/instrumentation-graphql": "0.47.0", + "@opentelemetry/instrumentation-hapi": "0.45.1", + "@opentelemetry/instrumentation-http": "0.57.1", + "@opentelemetry/instrumentation-ioredis": "0.47.0", + "@opentelemetry/instrumentation-kafkajs": "0.7.0", + "@opentelemetry/instrumentation-knex": "0.44.0", + "@opentelemetry/instrumentation-koa": "0.47.0", + "@opentelemetry/instrumentation-lru-memoizer": "0.44.0", + "@opentelemetry/instrumentation-mongodb": "0.51.0", + "@opentelemetry/instrumentation-mongoose": "0.46.0", + "@opentelemetry/instrumentation-mysql": "0.45.0", + "@opentelemetry/instrumentation-mysql2": "0.45.0", + "@opentelemetry/instrumentation-nestjs-core": "0.44.0", + "@opentelemetry/instrumentation-pg": "0.50.0", + "@opentelemetry/instrumentation-redis-4": "0.46.0", + "@opentelemetry/instrumentation-tedious": "0.18.0", + "@opentelemetry/instrumentation-undici": "0.10.0", + "@opentelemetry/resources": "^1.30.1", + "@opentelemetry/sdk-trace-base": "^1.30.1", "@opentelemetry/semantic-conventions": "^1.28.0", "@prisma/instrumentation": "5.22.0", - "@sentry/core": "8.52.1", - "@sentry/opentelemetry": "8.52.1", + "@sentry/core": "8.55.0", + "@sentry/opentelemetry": "8.55.0", "import-in-the-middle": "^1.11.2" }, "engines": { @@ -3025,29 +3110,30 @@ } }, "node_modules/@sentry/opentelemetry": { - "version": "8.52.1", - "resolved": "https://registry.npmjs.org/@sentry/opentelemetry/-/opentelemetry-8.52.1.tgz", - "integrity": "sha512-xaGm/KlfFi3yxK6PP+IRLnvfnd8Hp3yvJIdp3Mvc2aHW1Dh7zz+VTNNmWFZQmAbWrNqIoqZG2s1tZOeJwMHPpg==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@sentry/opentelemetry/-/opentelemetry-8.55.0.tgz", + "integrity": "sha512-UvatdmSr3Xf+4PLBzJNLZ2JjG1yAPWGe/VrJlJAqyTJ2gKeTzgXJJw8rp4pbvNZO8NaTGEYhhO+scLUj0UtLAQ==", "dependencies": { - "@sentry/core": "8.52.1" + "@sentry/core": "8.55.0" }, "engines": { "node": ">=14.18" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0", - "@opentelemetry/core": "^1.29.0", - "@opentelemetry/instrumentation": "^0.56.0", - "@opentelemetry/sdk-trace-base": "^1.29.0", + "@opentelemetry/context-async-hooks": "^1.30.1", + "@opentelemetry/core": "^1.30.1", + "@opentelemetry/instrumentation": "^0.57.1", + "@opentelemetry/sdk-trace-base": "^1.30.1", "@opentelemetry/semantic-conventions": "^1.28.0" } }, "node_modules/@smithy/abort-controller": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.1.tgz", - "integrity": "sha512-fiUIYgIgRjMWznk6iLJz35K2YxSLHzLBA/RC6lBrKfQ8fHbPfvk7Pk9UvpKoHgJjI18MnbPuEju53zcVy6KF1g==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.2.tgz", + "integrity": "sha512-Sl/78VDtgqKxN2+1qduaVE140XF+Xg+TafkncspwM4jFP/LHr76ZHmIY/y3V1M0mMLNk+Je6IGbzxy23RSToMw==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3055,14 +3141,14 @@ } }, "node_modules/@smithy/config-resolver": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.0.1.tgz", - "integrity": "sha512-Igfg8lKu3dRVkTSEm98QpZUvKEOa71jDX4vKRcvJVyRc3UgN3j7vFMf0s7xLQhYmKa8kyJGQgUJDOV5V3neVlQ==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.1.2.tgz", + "integrity": "sha512-7r6mZGwb5LmLJ+zPtkLoznf2EtwEuSWdtid10pjGl/7HefCE4mueOkrfki8JCUm99W6UfP47/r3tbxx9CfBN5A==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/types": "^4.2.0", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -3070,16 +3156,16 @@ } }, "node_modules/@smithy/core": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.1.2.tgz", - "integrity": "sha512-htwQXkbdF13uwwDevz9BEzL5ABK+1sJpVQXywwGSH973AVOvisHNfpcB8A8761G6XgHoS2kHPqc9DqHJ2gp+/Q==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.3.3.tgz", + "integrity": "sha512-CiJNc0b/WdnttAfQ6uMkxPQ3Z8hG/ba8wF89x9KtBBLDdZk6CX52K4F8hbe94uNbc8LDUuZFtbqfdhM3T21naw==", "dependencies": { - "@smithy/middleware-serde": "^4.0.2", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/middleware-serde": "^4.0.5", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-stream": "^4.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -3088,14 +3174,14 @@ } }, "node_modules/@smithy/credential-provider-imds": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.1.tgz", - "integrity": "sha512-l/qdInaDq1Zpznpmev/+52QomsJNZ3JkTl5yrTl02V6NBgJOQ4LY0SFw/8zsMwj3tLe8vqiIuwF6nxaEwgf6mg==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.4.tgz", + "integrity": "sha512-jN6M6zaGVyB8FmNGG+xOPQB4N89M1x97MMdMnm1ESjljLS3Qju/IegQizKujaNcy2vXAvrz0en8bobe6E55FEA==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -3103,13 +3189,13 @@ } }, "node_modules/@smithy/fetch-http-handler": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.1.tgz", - "integrity": "sha512-3aS+fP28urrMW2KTjb6z9iFow6jO8n3MFfineGbndvzGZit3taZhKWtTorf+Gp5RpFDDafeHlhfsGlDCXvUnJA==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.2.tgz", + "integrity": "sha512-+9Dz8sakS9pe7f2cBocpJXdeVjMopUDLgZs1yWeu7h++WqSbjUYv/JAJwKwXw1HV6gq1jyWjxuyn24E2GhoEcQ==", "dependencies": { - "@smithy/protocol-http": "^5.0.1", - "@smithy/querystring-builder": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/querystring-builder": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-base64": "^4.0.0", "tslib": "^2.6.2" }, @@ -3118,11 +3204,11 @@ } }, "node_modules/@smithy/hash-node": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.1.tgz", - "integrity": "sha512-TJ6oZS+3r2Xu4emVse1YPB3Dq3d8RkZDKcPr71Nj/lJsdAP1c7oFzYqEn1IBc915TsgLl2xIJNuxCz+gLbLE0w==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.2.tgz", + "integrity": "sha512-VnTpYPnRUE7yVhWozFdlxcYknv9UN7CeOqSrMH+V877v4oqtVYuoqhIhtSjmGPvYrYnAkaM61sLMKHvxL138yg==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-buffer-from": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -3132,11 +3218,11 @@ } }, "node_modules/@smithy/invalid-dependency": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.1.tgz", - "integrity": "sha512-gdudFPf4QRQ5pzj7HEnu6FhKRi61BfH/Gk5Yf6O0KiSbr1LlVhgjThcvjdu658VE6Nve8vaIWB8/fodmS1rBPQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.2.tgz", + "integrity": "sha512-GatB4+2DTpgWPday+mnUkoumP54u/MDM/5u44KF9hIu8jF0uafZtQLcdfIKkIcUNuF/fBojpLEHZS/56JqPeXQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3155,11 +3241,11 @@ } }, "node_modules/@smithy/md5-js": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.0.1.tgz", - "integrity": "sha512-HLZ647L27APi6zXkZlzSFZIjpo8po45YiyjMGJZM3gyDY8n7dPGdmxIIljLm4gPt/7rRvutLTTkYJpZVfG5r+A==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.0.2.tgz", + "integrity": "sha512-Hc0R8EiuVunUewCse2syVgA2AfSRco3LyAv07B/zCOMa+jpXI9ll+Q21Nc6FAlYPcpNcAXqBzMhNs1CD/pP2bA==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -3168,12 +3254,12 @@ } }, "node_modules/@smithy/middleware-content-length": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.1.tgz", - "integrity": "sha512-OGXo7w5EkB5pPiac7KNzVtfCW2vKBTZNuCctn++TTSOMpe6RZO/n6WEC1AxJINn3+vWLKW49uad3lo/u0WJ9oQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.2.tgz", + "integrity": "sha512-hAfEXm1zU+ELvucxqQ7I8SszwQ4znWMbNv6PLMndN83JJN41EPuS93AIyh2N+gJ6x8QFhzSO6b7q2e6oClDI8A==", "dependencies": { - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3181,17 +3267,17 @@ } }, "node_modules/@smithy/middleware-endpoint": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.0.3.tgz", - "integrity": "sha512-YdbmWhQF5kIxZjWqPIgboVfi8i5XgiYMM7GGKFMTvBei4XjNQfNv8sukT50ITvgnWKKKpOtp0C0h7qixLgb77Q==", + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.1.6.tgz", + "integrity": "sha512-Zdieg07c3ua3ap5ungdcyNnY1OsxmsXXtKDTk28+/YbwIPju0Z1ZX9X5AnkjmDE3+AbqgvhtC/ZuCMSr6VSfPw==", "dependencies": { - "@smithy/core": "^3.1.2", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", - "@smithy/util-middleware": "^4.0.1", + "@smithy/core": "^3.3.3", + "@smithy/middleware-serde": "^4.0.5", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -3199,17 +3285,17 @@ } }, "node_modules/@smithy/middleware-retry": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.0.4.tgz", - "integrity": "sha512-wmxyUBGHaYUqul0wZiset4M39SMtDBOtUr2KpDuftKNN74Do9Y36Go6Eqzj9tL0mIPpr31ulB5UUtxcsCeGXsQ==", + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.1.7.tgz", + "integrity": "sha512-lFIFUJ0E/4I0UaIDY5usNUzNKAghhxO0lDH4TZktXMmE+e4ActD9F154Si0Unc01aCPzcwd+NcOwQw6AfXXRRQ==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/service-error-classification": "^4.0.1", - "@smithy/smithy-client": "^4.1.3", - "@smithy/types": "^4.1.0", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/protocol-http": "^5.1.0", + "@smithy/service-error-classification": "^4.0.3", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.3", "tslib": "^2.6.2", "uuid": "^9.0.1" }, @@ -3218,11 +3304,12 @@ } }, "node_modules/@smithy/middleware-serde": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.2.tgz", - "integrity": "sha512-Sdr5lOagCn5tt+zKsaW+U2/iwr6bI9p08wOkCp6/eL6iMbgdtc2R5Ety66rf87PeohR0ExI84Txz9GYv5ou3iQ==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.5.tgz", + "integrity": "sha512-yREC3q/HXqQigq29xX3hiy6tFi+kjPKXoYUQmwQdgPORLbQ0n6V2Z/Iw9Nnlu66da9fM/WhDtGvYvqwecrCljQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3230,11 +3317,11 @@ } }, "node_modules/@smithy/middleware-stack": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.1.tgz", - "integrity": "sha512-dHwDmrtR/ln8UTHpaIavRSzeIk5+YZTBtLnKwDW3G2t6nAupCiQUvNzNoHBpik63fwUaJPtlnMzXbQrNFWssIA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.2.tgz", + "integrity": "sha512-eSPVcuJJGVYrFYu2hEq8g8WWdJav3sdrI4o2c6z/rjnYDd3xH9j9E7deZQCzFn4QvGPouLngH3dQ+QVTxv5bOQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3242,13 +3329,13 @@ } }, "node_modules/@smithy/node-config-provider": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.0.1.tgz", - "integrity": "sha512-8mRTjvCtVET8+rxvmzRNRR0hH2JjV0DFOmwXPrISmTIJEfnCBugpYYGAsCj8t41qd+RB5gbheSQ/6aKZCQvFLQ==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.1.1.tgz", + "integrity": "sha512-1slS5jf5icHETwl5hxEVBj+mh6B+LbVW4yRINsGtUKH+nxM5Pw2H59+qf+JqYFCHp9jssG4vX81f5WKnjMN3Vw==", "dependencies": { - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3256,14 +3343,14 @@ } }, "node_modules/@smithy/node-http-handler": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.2.tgz", - "integrity": "sha512-X66H9aah9hisLLSnGuzRYba6vckuFtGE+a5DcHLliI/YlqKrGoxhisD5XbX44KyoeRzoNlGr94eTsMVHFAzPOw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.4.tgz", + "integrity": "sha512-/mdqabuAT3o/ihBGjL94PUbTSPSRJ0eeVTdgADzow0wRJ0rN4A27EOrtlK56MYiO1fDvlO3jVTCxQtQmK9dZ1g==", "dependencies": { - "@smithy/abort-controller": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/querystring-builder": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/abort-controller": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/querystring-builder": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3271,11 +3358,11 @@ } }, "node_modules/@smithy/property-provider": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.1.tgz", - "integrity": "sha512-o+VRiwC2cgmk/WFV0jaETGOtX16VNPp2bSQEzu0whbReqE1BMqsP2ami2Vi3cbGVdKu1kq9gQkDAGKbt0WOHAQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.2.tgz", + "integrity": "sha512-wNRoQC1uISOuNc2s4hkOYwYllmiyrvVXWMtq+TysNRVQaHm4yoafYQyjN/goYZS+QbYlPIbb/QRjaUZMuzwQ7A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3283,11 +3370,11 @@ } }, "node_modules/@smithy/protocol-http": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.0.1.tgz", - "integrity": "sha512-TE4cpj49jJNB/oHyh/cRVEgNZaoPaxd4vteJNB0yGidOCVR0jCw/hjPVsT8Q8FRmj8Bd3bFZt8Dh7xGCT+xMBQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.1.0.tgz", + "integrity": "sha512-KxAOL1nUNw2JTYrtviRRjEnykIDhxc84qMBzxvu1MUfQfHTuBlCG7PA6EdVwqpJjH7glw7FqQoFxUJSyBQgu7g==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3295,11 +3382,11 @@ } }, "node_modules/@smithy/querystring-builder": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.1.tgz", - "integrity": "sha512-wU87iWZoCbcqrwszsOewEIuq+SU2mSoBE2CcsLwE0I19m0B2gOJr1MVjxWcDQYOzHbR1xCk7AcOBbGFUYOKvdg==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.2.tgz", + "integrity": "sha512-NTOs0FwHw1vimmQM4ebh+wFQvOwkEf/kQL6bSM1Lock+Bv4I89B3hGYoUEPkmvYPkDKyp5UdXJYu+PoTQ3T31Q==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-uri-escape": "^4.0.0", "tslib": "^2.6.2" }, @@ -3308,11 +3395,11 @@ } }, "node_modules/@smithy/querystring-parser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.1.tgz", - "integrity": "sha512-Ma2XC7VS9aV77+clSFylVUnPZRindhB7BbmYiNOdr+CHt/kZNJoPP0cd3QxCnCFyPXC4eybmyE98phEHkqZ5Jw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.2.tgz", + "integrity": "sha512-v6w8wnmZcVXjfVLjxw8qF7OwESD9wnpjp0Dqry/Pod0/5vcEA3qxCr+BhbOHlxS8O+29eLpT3aagxXGwIoEk7Q==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3320,22 +3407,22 @@ } }, "node_modules/@smithy/service-error-classification": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.1.tgz", - "integrity": "sha512-3JNjBfOWpj/mYfjXJHB4Txc/7E4LVq32bwzE7m28GN79+M1f76XHflUaSUkhOriprPDzev9cX/M+dEB80DNDKA==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.3.tgz", + "integrity": "sha512-FTbcajmltovWMjj3tksDQdD23b2w6gH+A0DYA1Yz3iSpjDj8fmkwy62UnXcWMy4d5YoMoSyLFHMfkEVEzbiN8Q==", "dependencies": { - "@smithy/types": "^4.1.0" + "@smithy/types": "^4.2.0" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/shared-ini-file-loader": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.1.tgz", - "integrity": "sha512-hC8F6qTBbuHRI/uqDgqqi6J0R4GtEZcgrZPhFQnMhfJs3MnUTGSnR1NSJCJs5VWlMydu0kJz15M640fJlRsIOw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.2.tgz", + "integrity": "sha512-J9/gTWBGVuFZ01oVA6vdb4DAjf1XbDhK6sLsu3OS9qmLrS6KB5ygpeHiM3miIbj1qgSJ96GYszXFWv6ErJ8QEw==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3343,15 +3430,15 @@ } }, "node_modules/@smithy/signature-v4": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.0.1.tgz", - "integrity": "sha512-nCe6fQ+ppm1bQuw5iKoeJ0MJfz2os7Ic3GBjOkLOPtavbD1ONoyE3ygjBfz2ythFWm4YnRm6OxW+8p/m9uCoIA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.1.0.tgz", + "integrity": "sha512-4t5WX60sL3zGJF/CtZsUQTs3UrZEDO2P7pEaElrekbLqkWPYkgqNW1oeiNYC6xXifBnT9dVBOnNQRvOE9riU9w==", "dependencies": { "@smithy/is-array-buffer": "^4.0.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-hex-encoding": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "@smithy/util-uri-escape": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -3361,16 +3448,16 @@ } }, "node_modules/@smithy/smithy-client": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.1.3.tgz", - "integrity": "sha512-A2Hz85pu8BJJaYFdX8yb1yocqigyqBzn+OVaVgm+Kwi/DkN8vhN2kbDVEfADo6jXf5hPKquMLGA3UINA64UZ7A==", + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.2.6.tgz", + "integrity": "sha512-WEqP0wQ1N/lVS4pwNK1Vk+0i6QIr66cq/xbu1dVy1tM0A0qYwAYyz0JhbquzM5pMa8s89lyDBtoGKxo7iG74GA==", "dependencies": { - "@smithy/core": "^3.1.2", - "@smithy/middleware-endpoint": "^4.0.3", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", - "@smithy/util-stream": "^4.0.2", + "@smithy/core": "^3.3.3", + "@smithy/middleware-endpoint": "^4.1.6", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", + "@smithy/util-stream": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3378,9 +3465,9 @@ } }, "node_modules/@smithy/types": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.1.0.tgz", - "integrity": "sha512-enhjdwp4D7CXmwLtD6zbcDMbo6/T6WtuuKCY49Xxc6OMOmUWlBEBDREsxxgV2LIdeQPW756+f97GzcgAwp3iLw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.2.0.tgz", + "integrity": "sha512-7eMk09zQKCO+E/ivsjQv+fDlOupcFUCSC/L2YUPgwhvowVGWbPQHjEFcmjt7QQ4ra5lyowS92SV53Zc6XD4+fg==", "dependencies": { "tslib": "^2.6.2" }, @@ -3389,12 +3476,12 @@ } }, "node_modules/@smithy/url-parser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.1.tgz", - "integrity": "sha512-gPXcIEUtw7VlK8f/QcruNXm7q+T5hhvGu9tl63LsJPZ27exB6dtNwvh2HIi0v7JcXJ5emBxB+CJxwaLEdJfA+g==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.2.tgz", + "integrity": "sha512-Bm8n3j2ScqnT+kJaClSVCMeiSenK6jVAzZCNewsYWuZtnBehEz4r2qP0riZySZVfzB+03XZHJeqfmJDkeeSLiQ==", "dependencies": { - "@smithy/querystring-parser": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/querystring-parser": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3460,13 +3547,13 @@ } }, "node_modules/@smithy/util-defaults-mode-browser": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.4.tgz", - "integrity": "sha512-Ej1bV5sbrIfH++KnWxjjzFNq9nyP3RIUq2c9Iqq7SmMO/idUR24sqvKH2LUQFTSPy/K7G4sB2m8n7YYlEAfZaw==", + "version": "4.0.14", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.14.tgz", + "integrity": "sha512-l7QnMX8VcDOH6n/fBRu4zqguSlOBZxFzWqp58dXFSARFBjNlmEDk5G/z4T7BMGr+rI0Pg8MkhmMUfEtHFgpy2g==", "dependencies": { - "@smithy/property-provider": "^4.0.1", - "@smithy/smithy-client": "^4.1.3", - "@smithy/types": "^4.1.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, @@ -3475,16 +3562,16 @@ } }, "node_modules/@smithy/util-defaults-mode-node": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.4.tgz", - "integrity": "sha512-HE1I7gxa6yP7ZgXPCFfZSDmVmMtY7SHqzFF55gM/GPegzZKaQWZZ+nYn9C2Cc3JltCMyWe63VPR3tSFDEvuGjw==", + "version": "4.0.14", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.14.tgz", + "integrity": "sha512-Ujs1gsWDo3m/T63VWBTBmHLTD2UlU6J6FEokLCEp7OZQv45jcjLHoxTwgWsi8ULpsYozvH4MTWkRP+bhwr0vDg==", "dependencies": { - "@smithy/config-resolver": "^4.0.1", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/smithy-client": "^4.1.3", - "@smithy/types": "^4.1.0", + "@smithy/config-resolver": "^4.1.2", + "@smithy/credential-provider-imds": "^4.0.4", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/property-provider": "^4.0.2", + "@smithy/smithy-client": "^4.2.6", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3492,12 +3579,12 @@ } }, "node_modules/@smithy/util-endpoints": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.1.tgz", - "integrity": "sha512-zVdUENQpdtn9jbpD9SCFK4+aSiavRb9BxEtw9ZGUR1TYo6bBHbIoi7VkrFQ0/RwZlzx0wRBaRmPclj8iAoJCLA==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.4.tgz", + "integrity": "sha512-VfFATC1bmZLV2858B/O1NpMcL32wYo8DPPhHxYxDCodDl3f3mSZ5oJheW1IF91A0EeAADz2WsakM/hGGPGNKLg==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/node-config-provider": "^4.1.1", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3516,11 +3603,11 @@ } }, "node_modules/@smithy/util-middleware": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.1.tgz", - "integrity": "sha512-HiLAvlcqhbzhuiOa0Lyct5IIlyIz0PQO5dnMlmQ/ubYM46dPInB+3yQGkfxsk6Q24Y0n3/JmcA1v5iEhmOF5mA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.2.tgz", + "integrity": "sha512-6GDamTGLuBQVAEuQ4yDQ+ti/YINf/MEmIegrEeg7DdB/sld8BX1lqt9RRuIcABOhAGTA50bRbPzErez7SlDtDQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3528,12 +3615,12 @@ } }, "node_modules/@smithy/util-retry": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.1.tgz", - "integrity": "sha512-WmRHqNVwn3kI3rKk1LsKcVgPBG6iLTBGC1iYOV3GQegwJ3E8yjzHytPt26VNzOWr1qu0xE03nK0Ug8S7T7oufw==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.3.tgz", + "integrity": "sha512-DPuYjZQDXmKr/sNvy9Spu8R/ESa2e22wXZzSAY6NkjOLj6spbIje/Aq8rT97iUMdDj0qHMRIe+bTxvlU74d9Ng==", "dependencies": { - "@smithy/service-error-classification": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/service-error-classification": "^4.0.3", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -3541,13 +3628,13 @@ } }, "node_modules/@smithy/util-stream": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.0.2.tgz", - "integrity": "sha512-0eZ4G5fRzIoewtHtwaYyl8g2C+osYOT4KClXgfdNEDAgkbe2TYPqcnw4GAWabqkZCax2ihRGPe9LZnsPdIUIHA==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.2.0.tgz", + "integrity": "sha512-Vj1TtwWnuWqdgQI6YTUF5hQ/0jmFiOYsc51CSMgj7QfyO+RF4EnT2HNjoviNlOOmgzgvf3f5yno+EiC4vrnaWQ==", "dependencies": { - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/node-http-handler": "^4.0.2", - "@smithy/types": "^4.1.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/types": "^4.2.0", "@smithy/util-base64": "^4.0.0", "@smithy/util-buffer-from": "^4.0.0", "@smithy/util-hex-encoding": "^4.0.0", @@ -3586,53 +3673,6 @@ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==" }, - "node_modules/@thi.ng/bitstream": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/@thi.ng/bitstream/-/bitstream-2.4.11.tgz", - "integrity": "sha512-7tXBVXQiJqVSVZLljnonXZOT9Zn6r7bc9X1GntDnNU/U8kW5DjAQmz0GvJxaIxRpZ+KqU1BvQVCfv3rH6f+TtA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/postspectacular" - }, - { - "type": "patreon", - "url": "https://patreon.com/thing_umbrella" - }, - { - "type": "liberapay", - "url": "https://liberapay.com/thi.ng" - } - ], - "dependencies": { - "@thi.ng/errors": "^2.5.25" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@thi.ng/errors": { - "version": "2.5.25", - "resolved": "https://registry.npmjs.org/@thi.ng/errors/-/errors-2.5.25.tgz", - "integrity": "sha512-PmK56hWGvRWr9Eq0V5xkV4tQvhjPtfvv6urFONP/D0gwFQXj+v6rcDYkAFLzOkbLqa0DYtkgvUsMklF/L53upA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/postspectacular" - }, - { - "type": "patreon", - "url": "https://patreon.com/thing_umbrella" - }, - { - "type": "liberapay", - "url": "https://liberapay.com/thi.ng" - } - ], - "engines": { - "node": ">=18" - } - }, "node_modules/@tokenizer/token": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", @@ -3690,17 +3730,17 @@ } }, "node_modules/@types/cors": { - "version": "2.8.17", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", - "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "version": "2.8.18", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.18.tgz", + "integrity": "sha512-nX3d0sxJW41CqQvfOzVG1NCTXfFDrDWIghCZncpHeWlVFd81zxB/DLhg7avFg6eHLCRX7ckBmoIIcqa++upvJA==", "dependencies": { "@types/node": "*" } }, "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==" + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz", + "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==" }, "node_modules/@types/express": { "version": "4.17.21", @@ -3774,11 +3814,11 @@ } }, "node_modules/@types/node": { - "version": "22.12.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.12.0.tgz", - "integrity": "sha512-Fll2FZ1riMjNmlmJOdAyY5pUbkftXslB5DgEzlIuNaiWhXd00FhWxVC/r4yV/4wBb9JfImTu+jiSvXTkJ7F/gA==", + "version": "22.15.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.18.tgz", + "integrity": "sha512-v1DKRfUdyW+jJhZNEI1PYy29S2YRxMV5AOO/x/SjKmW0acCIOqmbj6Haf9eHAhsPmrhlHSxEhv/1WszcLWV4cg==", "dependencies": { - "undici-types": "~6.20.0" + "undici-types": "~6.21.0" } }, "node_modules/@types/node-cron": { @@ -3842,9 +3882,9 @@ "dev": true }, "node_modules/@types/semver": { - "version": "7.5.8", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", - "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.0.tgz", + "integrity": "sha512-k107IF4+Xr7UHjwDc7Cfd6PRQfbdkiRabXGRjo07b4WyPahFBZCZ1sE+BNxYIJPPg73UkfOsVOLwqVc/6ETrIA==", "dev": true }, "node_modules/@types/send": { @@ -3906,9 +3946,9 @@ "dev": true }, "node_modules/@types/validator": { - "version": "13.12.2", - "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.12.2.tgz", - "integrity": "sha512-6SlHBzUW8Jhf3liqrGGXyTJSIFe4nqlJ5A5KaMZ2l/vbM3Wh3KSybots/wfWVzNLK4D1NZluDlSQIbIEPx6oyA==" + "version": "13.15.0", + "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.0.tgz", + "integrity": "sha512-nh7nrWhLr6CBq9ldtw0wx+z9wKnnv/uTVLA9g/3/TcOYxbpOSZE+MhKPmWqU+K0NvThjhv12uD8MuqijB0WzEA==" }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "6.21.0", @@ -4105,47 +4145,12 @@ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==" }, - "node_modules/@wasm-audio-decoders/common": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/common/-/common-9.0.5.tgz", - "integrity": "sha512-b9JNh9sPAvn8PVIizNh9D60WkfQong/u9ea873H47u7zvVDLctxYIp2aZw9CQqXaQdk7JB3MoU5UHiseO40swg==", - "dependencies": { - "@eshaz/web-worker": "1.2.2", - "simple-yenc": "^1.0.4" - } - }, - "node_modules/@wasm-audio-decoders/flac": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/flac/-/flac-0.2.5.tgz", - "integrity": "sha512-8M//CgB3PlkWwn47KcwD0tO6DZBA7/AGG0ukHSG0G97UbNEUNINvKDWAKPVWznzHsqeBP6axw+K/38dzng64JA==", - "dependencies": { - "@wasm-audio-decoders/common": "9.0.5", - "codec-parser": "2.5.0" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, - "node_modules/@wasm-audio-decoders/ogg-vorbis": { - "version": "0.1.16", - "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/ogg-vorbis/-/ogg-vorbis-0.1.16.tgz", - "integrity": "sha512-HcEx4LPZbbzjhs9bTXgMaXLVCSMSo/egY9paJxAnE9tsYbvseAaGtVddLYktl3Qi/G+nW/ZzUXg4144izJjqCw==", - "dependencies": { - "@wasm-audio-decoders/common": "9.0.5", - "codec-parser": "2.5.0" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, "node_modules/@whiskeysockets/eslint-config": { "version": "1.0.0", - "resolved": "git+ssh://git@github.com/whiskeysockets/eslint-config.git#326b55f2842668f4e11f471451c4e39819a0e1bf", + "resolved": "git+ssh://git@github.com/whiskeysockets/eslint-config.git#f264cd06d24a43f76e4ad2d81528f8485a1e7efe", "dependencies": { - "@typescript-eslint/eslint-plugin": "^7.15.0", - "@typescript-eslint/parser": "^7.15.0", + "@typescript-eslint/eslint-plugin": "^8.32.0", + "@typescript-eslint/parser": "^8.32.0", "eslint-plugin-simple-import-sort": "^12.1.1" }, "peerDependencies": { @@ -4154,74 +4159,66 @@ } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/eslint-plugin": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz", - "integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.32.1.tgz", + "integrity": "sha512-6u6Plg9nP/J1GRpe/vcjjabo6Uc5YQPAMxsgQyGC/I0RuukiG1wIe3+Vtg3IrSCVJDmqK3j8adrtzXSENRtFgg==", "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/type-utils": "7.18.0", - "@typescript-eslint/utils": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", + "@typescript-eslint/scope-manager": "8.32.1", + "@typescript-eslint/type-utils": "8.32.1", + "@typescript-eslint/utils": "8.32.1", + "@typescript-eslint/visitor-keys": "8.32.1", "graphemer": "^1.4.0", - "ignore": "^5.3.1", + "ignore": "^7.0.0", "natural-compare": "^1.4.0", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.1.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^7.0.0", - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/parser": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz", - "integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.32.1.tgz", + "integrity": "sha512-LKMrmwCPoLhM45Z00O1ulb6jwyVr2kr3XJp+G+tSEZcbauNnScewcQwtJqXDhXeYPDEjZ8C1SjXm015CirEmGg==", "dependencies": { - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", + "@typescript-eslint/scope-manager": "8.32.1", + "@typescript-eslint/types": "8.32.1", + "@typescript-eslint/typescript-estree": "8.32.1", + "@typescript-eslint/visitor-keys": "8.32.1", "debug": "^4.3.4" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/scope-manager": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz", - "integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.32.1.tgz", + "integrity": "sha512-7IsIaIDeZn7kffk7qXC3o6Z4UblZJKV3UBpkvRNpr5NSyLji7tvTcvmnMNYuYLyh26mN8W723xpo3i4MlD33vA==", "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0" + "@typescript-eslint/types": "8.32.1", + "@typescript-eslint/visitor-keys": "8.32.1" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -4229,37 +4226,33 @@ } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/type-utils": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.18.0.tgz", - "integrity": "sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.32.1.tgz", + "integrity": "sha512-mv9YpQGA8iIsl5KyUPi+FGLm7+bA4fgXaeRcFKRDRwDMu4iwrSHeDPipwueNXhdIIZltwCJv+NkxftECbIZWfA==", "dependencies": { - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/utils": "7.18.0", + "@typescript-eslint/typescript-estree": "8.32.1", + "@typescript-eslint/utils": "8.32.1", "debug": "^4.3.4", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.1.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/types": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.18.0.tgz", - "integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.32.1.tgz", + "integrity": "sha512-YmybwXUJcgGqgAp6bEsgpPXEg6dcCyPyCSr0CAAueacR/CCBi25G3V8gGQ2kRzQRBNol7VQknxMs9HvVa9Rvfg==", "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -4267,63 +4260,62 @@ } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/typescript-estree": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz", - "integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.32.1.tgz", + "integrity": "sha512-Y3AP9EIfYwBb4kWGb+simvPaqQoT5oJuzzj9m0i6FCY6SPvlomY2Ei4UEMm7+FXtlNJbor80ximyslzaQF6xhg==", "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", + "@typescript-eslint/types": "8.32.1", + "@typescript-eslint/visitor-keys": "8.32.1", "debug": "^4.3.4", - "globby": "^11.1.0", + "fast-glob": "^3.3.2", "is-glob": "^4.0.3", "minimatch": "^9.0.4", "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.1.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/utils": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.18.0.tgz", - "integrity": "sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==", - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^8.56.0" + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/utils": { + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.32.1.tgz", + "integrity": "sha512-DsSFNIgLSrc89gpq1LJB7Hm1YpuhK086DRDJSNrewcGvYloWW1vZLHBTIvarKZDcAORIy/uWNx8Gad+4oMpkSA==", + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.32.1", + "@typescript-eslint/types": "8.32.1", + "@typescript-eslint/typescript-estree": "8.32.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@whiskeysockets/eslint-config/node_modules/@typescript-eslint/visitor-keys": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz", - "integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==", + "version": "8.32.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.32.1.tgz", + "integrity": "sha512-ar0tjQfObzhSaW3C3QNmTc5ofj0hDoNQ5XWrCy6zDyabdr0TWhCkClp+rywGNj/odAFBVzzJrK4tEq5M4Hmu4w==", "dependencies": { - "@typescript-eslint/types": "7.18.0", - "eslint-visitor-keys": "^3.4.3" + "@typescript-eslint/types": "8.32.1", + "eslint-visitor-keys": "^4.2.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -4338,6 +4330,25 @@ "eslint": ">=5.0.0" } }, + "node_modules/@whiskeysockets/eslint-config/node_modules/eslint-visitor-keys": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", + "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@whiskeysockets/eslint-config/node_modules/ignore": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.4.tgz", + "integrity": "sha512-gJzzk+PQNznz8ysRrC0aOkBNVRBDtE1n53IqyqEf3PXrYwomFs5q4pGMizBMJF+ykh03insJ27hB8gSrD2Hn8A==", + "engines": { + "node": ">= 4" + } + }, "node_modules/@whiskeysockets/eslint-config/node_modules/minimatch": { "version": "9.0.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", @@ -4352,6 +4363,17 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/@whiskeysockets/eslint-config/node_modules/ts-api-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/@zxing/text-encoding": { "version": "0.9.0", "resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz", @@ -4390,9 +4412,9 @@ } }, "node_modules/acorn": { - "version": "8.14.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", - "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", + "version": "8.14.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", + "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", "bin": { "acorn": "bin/acorn" }, @@ -4463,11 +4485,10 @@ } }, "node_modules/amqplib": { - "version": "0.10.5", - "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.10.5.tgz", - "integrity": "sha512-Dx5zmy0Ur+Q7LPPdhz+jx5IzmJBoHd15tOeAfQ8SuvEtyPJ20hBemhOBA4b1WeORCRa0ENM/kHCzmem1w/zHvQ==", + "version": "0.10.8", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.10.8.tgz", + "integrity": "sha512-Tfn1O9sFgAP8DqeMEpt2IacsVTENBpblB3SqLdn0jK2AeX8iyCvbptBc8lyATT9bQ31MsjVwUSQ1g8f4jHOUfw==", "dependencies": { - "@acuminous/bitsyntax": "^0.1.2", "buffer-more-ints": "~1.0.0", "url-parse": "~1.5.10" }, @@ -4581,22 +4602,24 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, "engines": { "node": ">=8" } }, "node_modules/array.prototype.findlastindex": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz", - "integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", + "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", "dev": true, "dependencies": { - "call-bind": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", + "es-abstract": "^1.23.9", "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "es-shim-unscopables": "^1.0.2" + "es-object-atoms": "^1.1.1", + "es-shim-unscopables": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -4676,10 +4699,13 @@ "node": ">= 0.4" } }, - "node_modules/async-lock": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/async-lock/-/async-lock-1.4.1.tgz", - "integrity": "sha512-Az2ZTpuytrtqENulXwO3GGv1Bztugx6TT37NIo7imr/Qo0gsYiGtSdBa2B6fsXhTpVZDNfu1Qn3pk531e3q+nQ==" + "node_modules/async-mutex": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", + "integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==", + "dependencies": { + "tslib": "^2.4.0" + } }, "node_modules/asynckit": { "version": "0.4.0", @@ -4694,34 +4720,6 @@ "node": ">=8.0.0" } }, - "node_modules/audio-buffer": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/audio-buffer/-/audio-buffer-5.0.0.tgz", - "integrity": "sha512-gsDyj1wwUp8u7NBB+eW6yhLb9ICf+0eBmDX8NGaAS00w8/fLqFdxUlL5Ge/U8kB64DlQhdonxYC59dXy1J7H/w==" - }, - "node_modules/audio-decode": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/audio-decode/-/audio-decode-2.2.2.tgz", - "integrity": "sha512-xyh7z6dpRT+5Ez4ggV2cEkSShkDvvIBBmVPR3kYY7uIBqRO1BGNjofip6JnjBnvezhrU3ypBGZjepyKFDZWnDw==", - "dependencies": { - "@wasm-audio-decoders/flac": "^0.2.4", - "@wasm-audio-decoders/ogg-vorbis": "^0.1.15", - "audio-buffer": "^5.0.0", - "audio-type": "^2.2.1", - "mpg123-decoder": "^1.0.0", - "node-wav": "^0.0.2", - "ogg-opus-decoder": "^1.6.12", - "qoa-format": "^1.0.1" - } - }, - "node_modules/audio-type": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/audio-type/-/audio-type-2.2.1.tgz", - "integrity": "sha512-En9AY6EG1qYqEy5L/quryzbA4akBpJrnBZNxeKTqGHC2xT9Qc4aZ8b7CcbOMFTTc/MGdoNyp+SN4zInZNKxMYA==", - "engines": { - "node": ">=14" - } - }, "node_modules/available-typed-arrays": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", @@ -4737,9 +4735,9 @@ } }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", + "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -4752,43 +4750,41 @@ "integrity": "sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==" }, "node_modules/baileys": { - "version": "6.7.12", - "resolved": "git+ssh://git@github.com/EvolutionAPI/Baileys.git#2c69f65d4b6c4e779d6e3d2c0c32689a5425df95", + "version": "6.7.17", + "resolved": "git+ssh://git@github.com/EvolutionAPI/Baileys.git#f1142636fb6f0dd647de73d456f111a7a2d4e2ef", + "hasInstallScript": true, "dependencies": { - "@adiwajshing/keyed-db": "^0.2.4", + "@cacheable/node-cache": "^1.4.0", "@hapi/boom": "^9.1.3", "@whiskeysockets/eslint-config": "github:whiskeysockets/eslint-config", - "async-lock": "^1.4.1", - "audio-decode": "^2.1.3", + "async-mutex": "^0.5.0", "axios": "^1.6.0", - "cache-manager": "^5.7.6", - "futoin-hkdf": "^1.5.1", - "libphonenumber-js": "^1.10.20", "libsignal": "github:WhiskeySockets/libsignal-node", "lodash": "^4.17.21", "music-metadata": "^7.12.3", - "node-cache": "^5.1.2", - "pino": "^7.0.0", + "pino": "^9.6", "protobufjs": "^7.2.4", - "uuid": "^10.0.0", "ws": "^8.13.0" }, + "engines": { + "node": ">=20.0.0" + }, "peerDependencies": { + "audio-decode": "^2.1.3", "jimp": "^0.16.1", "link-preview-js": "^3.0.0", - "qrcode-terminal": "^0.12.0", "sharp": "^0.32.6" }, "peerDependenciesMeta": { + "audio-decode": { + "optional": true + }, "jimp": { "optional": true }, "link-preview-js": { "optional": true }, - "qrcode-terminal": { - "optional": true - }, "sharp": { "optional": true } @@ -4807,85 +4803,69 @@ "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==" }, - "node_modules/baileys/node_modules/on-exit-leak-free": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-0.2.0.tgz", - "integrity": "sha512-dqaz3u44QbRXQooZLTUKU41ZrzYrcvLISVgbrzbyCMxpmSLJvZ3ZamIJIZ29P6OhZIkNIQKosdeM6t1LYbA9hg==" - }, "node_modules/baileys/node_modules/pino": { - "version": "7.11.0", - "resolved": "https://registry.npmjs.org/pino/-/pino-7.11.0.tgz", - "integrity": "sha512-dMACeu63HtRLmCG8VKdy4cShCPKaYDR4youZqoSWLxl5Gu99HUw8bw75thbPv9Nip+H+QYX8o3ZJbTdVZZ2TVg==", + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-9.6.0.tgz", + "integrity": "sha512-i85pKRCt4qMjZ1+L7sy2Ag4t1atFcdbEt76+7iRJn1g2BvsnRMGu9p8pivl9fs63M2kF/A0OacFZhTub+m/qMg==", "dependencies": { "atomic-sleep": "^1.0.0", - "fast-redact": "^3.0.0", - "on-exit-leak-free": "^0.2.0", - "pino-abstract-transport": "v0.5.0", - "pino-std-serializers": "^4.0.0", - "process-warning": "^1.0.0", + "fast-redact": "^3.1.1", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^4.0.0", "quick-format-unescaped": "^4.0.3", - "real-require": "^0.1.0", - "safe-stable-stringify": "^2.1.0", - "sonic-boom": "^2.2.1", - "thread-stream": "^0.15.1" + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" }, "bin": { "pino": "bin.js" } }, "node_modules/baileys/node_modules/pino-abstract-transport": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-0.5.0.tgz", - "integrity": "sha512-+KAgmVeqXYbTtU2FScx1XS3kNyfZ5TrXY07V96QnUSFqo2gAqlvmaxH67Lj7SWazqsMabf+58ctdTcBgnOLUOQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", "dependencies": { - "duplexify": "^4.1.2", "split2": "^4.0.0" } }, "node_modules/baileys/node_modules/pino-std-serializers": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-4.0.0.tgz", - "integrity": "sha512-cK0pekc1Kjy5w9V2/n+8MkZwusa6EyyxfeQCB799CQRhRt/CqYKiWs5adeu8Shve2ZNffvfC/7J64A2PJo1W/Q==" + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz", + "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==" }, "node_modules/baileys/node_modules/process-warning": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-1.0.0.tgz", - "integrity": "sha512-du4wfLyj4yCZq1VupnVSZmRsPJsNuxoDQFdCFHLaYiEbFBD7QE0a+I4D7hOxrVnh78QE/YipFAj9lXHiXocV+Q==" - }, - "node_modules/baileys/node_modules/real-require": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.1.0.tgz", - "integrity": "sha512-r/H9MzAWtrv8aSVjPCMFpDMl5q66GqtmmRkRjpHTsp4zBAa+snZyiQNlMONiUmEJcsnaw0wCauJ2GWODr/aFkg==", - "engines": { - "node": ">= 12.13.0" - } + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz", + "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ] }, "node_modules/baileys/node_modules/sonic-boom": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-2.8.0.tgz", - "integrity": "sha512-kuonw1YOYYNOve5iHdSahXPOK49GqwA+LZhI6Wz/l0rP57iKyXXIHaRagOBHAPmGwJC6od2Z9zgvZ5loSgMlVg==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz", + "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==", "dependencies": { "atomic-sleep": "^1.0.0" } }, "node_modules/baileys/node_modules/thread-stream": { - "version": "0.15.2", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-0.15.2.tgz", - "integrity": "sha512-UkEhKIg2pD+fjkHQKyJO3yoIvAP3N6RlNFt2dUhcS1FGvCD1cQa1M/PGknCLFIyZdtJOWQjejp7bdNqmN7zwdA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", + "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==", "dependencies": { - "real-require": "^0.1.0" - } - }, - "node_modules/baileys/node_modules/uuid": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", - "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "bin": { - "uuid": "dist/bin/uuid" + "real-require": "^0.2.0" } }, "node_modules/balanced-match": { @@ -4900,26 +4880,34 @@ "optional": true }, "node_modules/bare-fs": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.0.1.tgz", - "integrity": "sha512-ilQs4fm/l9eMfWY2dY0WCIUplSUp7U0CT1vrqMg1MUdeZl4fypu5UP0XcDBK5WBQPJAKP1b7XEodISmekH/CEg==", + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz", + "integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==", "optional": true, "dependencies": { - "bare-events": "^2.0.0", + "bare-events": "^2.5.4", "bare-path": "^3.0.0", - "bare-stream": "^2.0.0" + "bare-stream": "^2.6.4" }, "engines": { - "bare": ">=1.7.0" + "bare": ">=1.16.0" + }, + "peerDependencies": { + "bare-buffer": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + } } }, "node_modules/bare-os": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.4.0.tgz", - "integrity": "sha512-9Ous7UlnKbe3fMi7Y+qh0DwAup6A1JkYgPnjvMDNOlmnxNRQvQ/7Nst+OnUQKzk0iAT0m9BisbDVp9gCv8+ETA==", + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz", + "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==", "optional": true, "engines": { - "bare": ">=1.6.0" + "bare": ">=1.14.0" } }, "node_modules/bare-path": { @@ -4932,9 +4920,9 @@ } }, "node_modules/bare-stream": { - "version": "2.6.4", - "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.4.tgz", - "integrity": "sha512-G6i3A74FjNq4nVrrSTUz5h3vgXzBJnjmWAVlBWaZETkgu+LgKd7AiyOml3EDJY1AHlIbBHKDXE+TUT53Ff8OaA==", + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz", + "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==", "optional": true, "dependencies": { "streamx": "^2.21.0" @@ -5123,6 +5111,11 @@ "node": ">=0.4.0" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -5174,18 +5167,13 @@ "node": ">=8" } }, - "node_modules/cache-manager": { - "version": "5.7.6", - "resolved": "https://registry.npmjs.org/cache-manager/-/cache-manager-5.7.6.tgz", - "integrity": "sha512-wBxnBHjDxF1RXpHCBD6HGvKER003Ts7IIm0CHpggliHzN1RZditb7rXoduE1rplc2DEFYKxhLKgFuchXMJje9w==", + "node_modules/cacheable": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-1.9.0.tgz", + "integrity": "sha512-8D5htMCxPDUULux9gFzv30f04Xo3wCnik0oOxKoRTPIBoqA7HtOcJ87uBhQTs3jCfZZTrUBGsYIZOgE0ZRgMAg==", "dependencies": { - "eventemitter3": "^5.0.1", - "lodash.clonedeep": "^4.5.0", - "lru-cache": "^10.2.2", - "promise-coalesce": "^1.1.2" - }, - "engines": { - "node": ">= 18" + "hookified": "^1.8.2", + "keyv": "^5.3.3" } }, "node_modules/call-bind": { @@ -5206,9 +5194,9 @@ } }, "node_modules/call-bind-apply-helpers": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz", - "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" @@ -5218,12 +5206,12 @@ } }, "node_modules/call-bound": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz", - "integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "get-intrinsic": "^1.2.6" + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" }, "engines": { "node": ">= 0.4" @@ -5355,12 +5343,12 @@ "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==" }, "node_modules/class-validator": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.1.tgz", - "integrity": "sha512-2VEG9JICxIqTpoK1eMzZqaV+u/EiwEJkMGzTrZf6sU/fwsnOITVgYJ8yojSy6CaXtO9V0Cc6ZQZ8h8m4UBuLwQ==", + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.2.tgz", + "integrity": "sha512-3kMVRF2io8N8pY1IFIXlho9r8IPUUIfHe2hYVtiebvAzU2XeQFXTv+XI4WX+TnXmtwXMDcjngcpkiPM0O9PvLw==", "dependencies": { "@types/validator": "^13.11.8", - "libphonenumber-js": "^1.10.53", + "libphonenumber-js": "^1.11.1", "validator": "^13.9.0" } }, @@ -5393,11 +5381,6 @@ "node": ">=0.10.0" } }, - "node_modules/codec-parser": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/codec-parser/-/codec-parser-2.5.0.tgz", - "integrity": "sha512-Ru9t80fV8B0ZiixQl8xhMTLru+dzuis/KQld32/x5T/+3LwZb0/YvQdSKytX9JqCnRdiupvAvyYJINKrXieziQ==" - }, "node_modules/color": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", @@ -5466,9 +5449,9 @@ } }, "node_modules/compression": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.5.tgz", - "integrity": "sha512-bQJ0YRck5ak3LgtnpKkiabX5pNF7tMUh1BSy2ZBOTh0Dim0BUu6aPPwByIns6/A5Prh8PufSPerMDUklpzes2Q==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.0.tgz", + "integrity": "sha512-k6WLKfunuqCYD3t6AsuPGvQWaKwuLLh2/xHNcX4qE+vIfDNXpSqnrhwA7O53R7WVQUnt8dVAIW+YHr7xTgOgGA==", "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", @@ -5495,25 +5478,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, - "node_modules/compression/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -5552,6 +5516,11 @@ "util-deprecate": "~1.0.1" } }, + "node_modules/concat-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, "node_modules/concat-stream/node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -5561,9 +5530,9 @@ } }, "node_modules/consola": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.0.tgz", - "integrity": "sha512-EiPU8G6dQG0GFHNR8ljnZFki/8a+cQwEQ+7wpxdChl02Q8HXlwEZWD5lqAF8vC2sEC3Tehr8hy7vErz88LHyUA==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", "engines": { "node": "^14.18.0 || >=16.10.0" } @@ -5579,25 +5548,6 @@ "node": ">= 0.6" } }, - "node_modules/content-disposition/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/content-type": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", @@ -5642,14 +5592,6 @@ "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "dev": true }, - "node_modules/cross-fetch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", - "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", - "dependencies": { - "node-fetch": "2.6.7" - } - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -5751,9 +5693,9 @@ "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==" }, "node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", "dependencies": { "ms": "^2.1.3" }, @@ -5868,9 +5810,9 @@ } }, "node_modules/detect-libc": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", - "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.4.tgz", + "integrity": "sha512-3UDv+G9CsCKO1WKMGw9fwq/SWJYbI0c5Y7LU1AXYoDdbhE2AHQ6N6Nb34sG8Fj7T5APy8qXDCKuuIHd1BR0tVA==", "engines": { "node": ">=8" } @@ -5893,6 +5835,7 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, "dependencies": { "path-type": "^4.0.0" }, @@ -5968,9 +5911,9 @@ } }, "node_modules/dotenv": { - "version": "16.4.7", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", - "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz", + "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==", "engines": { "node": ">=12" }, @@ -5991,17 +5934,6 @@ "node": ">= 0.4" } }, - "node_modules/duplexify": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", - "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", - "dependencies": { - "end-of-stream": "^1.4.1", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1", - "stream-shift": "^1.0.2" - } - }, "node_modules/dynamic-dedupe": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/dynamic-dedupe/-/dynamic-dedupe-0.3.0.tgz", @@ -6016,6 +5948,14 @@ "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -6268,7 +6208,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", @@ -6280,12 +6219,15 @@ } }, "node_modules/es-shim-unscopables": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz", - "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", "dev": true, "dependencies": { - "hasown": "^2.0.0" + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" } }, "node_modules/es-to-primitive": { @@ -6306,9 +6248,9 @@ } }, "node_modules/esbuild": { - "version": "0.24.2", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz", - "integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==", + "version": "0.25.4", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.4.tgz", + "integrity": "sha512-8pgjLUcUjcgDg+2Q4NYXnPbo/vncAY4UmyaCm0jZevERqCHZIaWwdJHkf8XQtu4AxSKCdvrUbT0XUr1IdZzI8Q==", "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" @@ -6317,31 +6259,31 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.24.2", - "@esbuild/android-arm": "0.24.2", - "@esbuild/android-arm64": "0.24.2", - "@esbuild/android-x64": "0.24.2", - "@esbuild/darwin-arm64": "0.24.2", - "@esbuild/darwin-x64": "0.24.2", - "@esbuild/freebsd-arm64": "0.24.2", - "@esbuild/freebsd-x64": "0.24.2", - "@esbuild/linux-arm": "0.24.2", - "@esbuild/linux-arm64": "0.24.2", - "@esbuild/linux-ia32": "0.24.2", - "@esbuild/linux-loong64": "0.24.2", - "@esbuild/linux-mips64el": "0.24.2", - "@esbuild/linux-ppc64": "0.24.2", - "@esbuild/linux-riscv64": "0.24.2", - "@esbuild/linux-s390x": "0.24.2", - "@esbuild/linux-x64": "0.24.2", - "@esbuild/netbsd-arm64": "0.24.2", - "@esbuild/netbsd-x64": "0.24.2", - "@esbuild/openbsd-arm64": "0.24.2", - "@esbuild/openbsd-x64": "0.24.2", - "@esbuild/sunos-x64": "0.24.2", - "@esbuild/win32-arm64": "0.24.2", - "@esbuild/win32-ia32": "0.24.2", - "@esbuild/win32-x64": "0.24.2" + "@esbuild/aix-ppc64": "0.25.4", + "@esbuild/android-arm": "0.25.4", + "@esbuild/android-arm64": "0.25.4", + "@esbuild/android-x64": "0.25.4", + "@esbuild/darwin-arm64": "0.25.4", + "@esbuild/darwin-x64": "0.25.4", + "@esbuild/freebsd-arm64": "0.25.4", + "@esbuild/freebsd-x64": "0.25.4", + "@esbuild/linux-arm": "0.25.4", + "@esbuild/linux-arm64": "0.25.4", + "@esbuild/linux-ia32": "0.25.4", + "@esbuild/linux-loong64": "0.25.4", + "@esbuild/linux-mips64el": "0.25.4", + "@esbuild/linux-ppc64": "0.25.4", + "@esbuild/linux-riscv64": "0.25.4", + "@esbuild/linux-s390x": "0.25.4", + "@esbuild/linux-x64": "0.25.4", + "@esbuild/netbsd-arm64": "0.25.4", + "@esbuild/netbsd-x64": "0.25.4", + "@esbuild/openbsd-arm64": "0.25.4", + "@esbuild/openbsd-x64": "0.25.4", + "@esbuild/sunos-x64": "0.25.4", + "@esbuild/win32-arm64": "0.25.4", + "@esbuild/win32-ia32": "0.25.4", + "@esbuild/win32-x64": "0.25.4" } }, "node_modules/escalade": { @@ -6591,13 +6533,13 @@ } }, "node_modules/eslint-plugin-prettier": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.3.tgz", - "integrity": "sha512-qJ+y0FfCp/mQYQ/vWQ3s7eUlFEL4PyKfAJxsnYTJ4YT73nsJBWqmEpFryxV9OeUiqmsTsYJ5Y+KDNaeP31wrRw==", + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.4.0.tgz", + "integrity": "sha512-BvQOvUhkVQM1i63iMETK9Hjud9QhqBnbtT1Zc642p9ynzBuCe5pybkOnvqZIBypXmMlsGcnU4HZ8sCTPfpAexA==", "dev": true, "dependencies": { "prettier-linter-helpers": "^1.0.0", - "synckit": "^0.9.1" + "synckit": "^0.11.0" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -6608,7 +6550,7 @@ "peerDependencies": { "@types/eslint": ">=8.0.0", "eslint": ">=8.0.0", - "eslint-config-prettier": "*", + "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", "prettier": ">=3.0.0" }, "peerDependenciesMeta": { @@ -6842,25 +6784,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, - "node_modules/express/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -6943,9 +6866,9 @@ } }, "node_modules/fastq": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.0.tgz", - "integrity": "sha512-7SFSRCNjBQIZH/xZR3iy5iQYR8aGBE0h3VG6/cwlbrpdciNYBMotQav8c1XI3HjHH+NikUpP53nPdlZSdWmFzA==", + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", "dependencies": { "reusify": "^1.0.4" } @@ -7054,10 +6977,18 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/flat-cache/node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dependencies": { + "json-buffer": "3.0.1" + } + }, "node_modules/flatted": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz", - "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==" + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==" }, "node_modules/fluent-ffmpeg": { "version": "2.1.3", @@ -7102,9 +7033,9 @@ } }, "node_modules/for-each": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.4.tgz", - "integrity": "sha512-kKaIINnFpzW6ffJNDjjyjrk21BkDx38c0xa/klsT8VzLCaMEefv4ZTacrcVR4DmgTeBra++jMDAfS/tS799YDw==", + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", "dependencies": { "is-callable": "^1.2.7" }, @@ -7116,11 +7047,11 @@ } }, "node_modules/foreground-child": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", - "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", "dependencies": { - "cross-spawn": "^7.0.0", + "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" }, "engines": { @@ -7131,12 +7062,13 @@ } }, "node_modules/form-data": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", - "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", + "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", "mime-types": "^2.1.12" }, "engines": { @@ -7241,14 +7173,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/futoin-hkdf": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/futoin-hkdf/-/futoin-hkdf-1.5.3.tgz", - "integrity": "sha512-SewY5KdMpaoCeh7jachEWFsh1nNlaDjNHZXWqL5IGwtpEYHTgkr2+AMCgNwKWkcc0wpSYrZfR7he4WdmHFtDxQ==", - "engines": { - "node": ">=8" - } - }, "node_modules/generic-pool": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz", @@ -7266,16 +7190,16 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.7.tgz", - "integrity": "sha512-VW6Pxhsrk0KAOqs3WEd0klDiF/+V7gQOpAvY1jVU/LHmaD/kQO4523aiJuikX/QAKYiW6x8Jh+RJej1almdtCA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "dependencies": { - "call-bind-apply-helpers": "^1.0.1", + "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", + "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", - "get-proto": "^1.0.0", + "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", @@ -7425,6 +7349,7 @@ "version": "11.1.0", "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, "dependencies": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", @@ -7538,6 +7463,11 @@ "node": ">= 0.4" } }, + "node_modules/hookified": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.9.0.tgz", + "integrity": "sha512-2yEEGqphImtKIe1NXWEhu6yD3hlFR4Mxk4Mtp3XEyScpSt4pQ4ymmXA1zzxZpj99QkFK+nN0nzjeb2+RUi/6CQ==" + }, "node_modules/htmlparser2": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", @@ -7665,9 +7595,9 @@ "integrity": "sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g==" }, "node_modules/import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -7680,11 +7610,11 @@ } }, "node_modules/import-in-the-middle": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.12.0.tgz", - "integrity": "sha512-yAgSE7GmtRcu4ZUSFX/4v69UGXwugFFSdIQJ14LHPOPPQrWv8Y7O9PHsw8Ovk7bKCLe4sjXMbZFqGFcLHpZ89w==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.13.2.tgz", + "integrity": "sha512-Yjp9X7s2eHSXvZYQ0aye6UvwYPrVB5C2k47fuXjFKnYinAByaDZjh4t9MT2wEga9775n6WaIqyHnQhBxYtX2mg==", "dependencies": { - "acorn": "^8.8.2", + "acorn": "^8.14.0", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", "module-details-from-path": "^1.0.3" @@ -7833,12 +7763,12 @@ } }, "node_modules/is-boolean-object": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.1.tgz", - "integrity": "sha512-l9qO6eFlUETHtuihLcYOaLKByJ1f+N4kthcU9YjHy3N+B3hWv0y/2Nd0mu/7lTFnRQHTrSdXF50HQ3bl5fEnng==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", "dev": true, "dependencies": { - "call-bound": "^1.0.2", + "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" }, "engines": { @@ -8118,12 +8048,12 @@ } }, "node_modules/is-weakref": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.0.tgz", - "integrity": "sha512-SXM8Nwyys6nT5WP6pltOwKytLV7FqQ4UiibxVmW+EIosHcmCqkkjViTb5SNssDlkCiEYRP1/pdWUKVvZBmsR2Q==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", "dev": true, "dependencies": { - "call-bound": "^1.0.2" + "call-bound": "^1.0.3" }, "engines": { "node": ">= 0.4" @@ -8185,10 +8115,13 @@ "regenerator-runtime": "^0.13.3" } }, - "node_modules/jimp/node_modules/regenerator-runtime": { - "version": "0.13.11", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", - "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" + "node_modules/jiti": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.4.2.tgz", + "integrity": "sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } }, "node_modules/joycon": { "version": "3.1.1", @@ -8254,12 +8187,52 @@ "node": "*" } }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", "dependencies": { - "json-buffer": "3.0.1" + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/keyv": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.3.3.tgz", + "integrity": "sha512-Rwu4+nXI9fqcxiEHtbkvoes2X+QfkTRo1TMkPfwzipGsJlJO/z69vqB4FNl9xJ3xCpAcbkvmEabZfPzrwN3+gQ==", + "dependencies": { + "@keyv/serialize": "^1.0.3" } }, "node_modules/levn": { @@ -8275,14 +8248,14 @@ } }, "node_modules/libphonenumber-js": { - "version": "1.11.19", - "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.11.19.tgz", - "integrity": "sha512-bW/Yp/9dod6fmyR+XqSUL1N5JE7QRxQ3KrBIbYS1FTv32e5i3SEtQVX+71CYNv8maWNSOgnlCoNp9X78f/cKiA==" + "version": "1.12.8", + "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.12.8.tgz", + "integrity": "sha512-f1KakiQJa9tdc7w1phC2ST+DyxWimy9c3g3yeF+84QtEanJr2K77wAmBPP22riU05xldniHsvXuflnLZ4oysqA==" }, "node_modules/libsignal": { "name": "@whiskeysockets/libsignal-node", "version": "2.0.1", - "resolved": "git+ssh://git@github.com/WhiskeySockets/libsignal-node.git#1bd9275d9e621d2ba899087ebdf548b3a5a4f05e", + "resolved": "git+ssh://git@github.com/WhiskeySockets/libsignal-node.git#d13b6622a208d3037a98b6f447bbde70261c39a9", "dependencies": { "curve25519-js": "^0.0.4", "protobufjs": "6.8.8" @@ -8340,14 +8313,15 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" }, "node_modules/link-preview-js": { - "version": "3.0.13", - "resolved": "https://registry.npmjs.org/link-preview-js/-/link-preview-js-3.0.13.tgz", - "integrity": "sha512-6WeGlt+jnh9s8mTl4fOBtAvb9JYHhIoPsB+sKZKE/cStaHyPRNN9Y8bKL3qKvBlVQEe8pZ+d49A6kJ89oclIvw==", + "version": "3.0.14", + "resolved": "https://registry.npmjs.org/link-preview-js/-/link-preview-js-3.0.14.tgz", + "integrity": "sha512-BAGZGCogqsWfF3msPt0c6DXr4+4zv7fregAxPioFYZJKoQEbKhJOhmu7VQjZmtKd1VRQ6CbL80Ok2KhpIuWJnQ==", "dependencies": { - "abort-controller": "^3.0.0", "cheerio": "1.0.0-rc.11", - "cross-fetch": "3.1.5", "url": "0.11.0" + }, + "engines": { + "node": ">=18" } }, "node_modules/load-bmfont": { @@ -8414,25 +8388,55 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, - "node_modules/lodash.clonedeep": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==" + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" + }, "node_modules/lodash.sortby": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", "integrity": "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==" }, "node_modules/long": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/long/-/long-5.2.4.tgz", - "integrity": "sha512-qtzLbJE8hq7VabR3mISmVGtoXP8KGc2Z/AT8OuqlYD7JTR3oqrgwdjnk07wpj1twXxYmgDXgoKVWUG/fReSzHg==" + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" }, "node_modules/lru-cache": { "version": "10.4.3", @@ -8462,9 +8466,9 @@ } }, "node_modules/mediainfo.js": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/mediainfo.js/-/mediainfo.js-0.3.4.tgz", - "integrity": "sha512-uTUlVqw9PcsuVt4DcXvqfQGKQBx3BCyQcDnJ68kSQyOxz0InIsCuykPShrYp+c5uDr6Mvhy5AfaboHn77xR7Ug==", + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/mediainfo.js/-/mediainfo.js-0.3.5.tgz", + "integrity": "sha512-frLJzKOoAUC0sbPzmg9VOR+WFbNj5CarbTuOzXeH9cOl33haU/CGcyXUTWK00HPXCVS2N5eT0o0dirVxaPIOIw==", "dependencies": { "yargs": "^17.7.2" }, @@ -8512,9 +8516,9 @@ } }, "node_modules/mime": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/mime/-/mime-4.0.6.tgz", - "integrity": "sha512-4rGt7rvQHBbaSOF9POGkk1ocRP16Md1x36Xma8sz8h8/vfCUI2OtEIeCqe4Ofes853x4xDoPiFLIT47J5fI/7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/mime/-/mime-4.0.7.tgz", + "integrity": "sha512-2OfDPL+e03E0LrXaGYOtTFIYhiuzep94NSsuhrNULq+stylcJedcHdzHtz0atMUuGwJfFYs0YL5xeC/Ca2x0eQ==", "funding": [ "https://github.com/sponsors/broofa" ], @@ -8526,9 +8530,9 @@ } }, "node_modules/mime-db": { - "version": "1.53.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.53.0.tgz", - "integrity": "sha512-oHlN/w+3MQ3rba9rqFr6V/ypF10LSkdwUysQL7GkXoTgIWeV+tcXGA852TBxH+gsh8UWoyhR1hKcoMJTuWflpg==", + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", "engines": { "node": ">= 0.6" } @@ -8595,9 +8599,9 @@ } }, "node_modules/minio": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/minio/-/minio-8.0.4.tgz", - "integrity": "sha512-GVW7y2PNbzjjFJ9opVMGKvDNuRkyz3bMt1q7UrHs7bsKFWLXbSvMPffjE/HkVYWUjlD8kQwMaeqiHhhvZJJOfQ==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/minio/-/minio-8.0.5.tgz", + "integrity": "sha512-/vAze1uyrK2R/DSkVutE4cjVoAowvIQ18RAwn7HrqnLecLlMazFnY0oNBqfuoAWvu7mZIGX75AzpuV05TJeoHg==", "dependencies": { "async": "^3.2.4", "block-stream2": "^2.1.0", @@ -8648,21 +8652,9 @@ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" }, "node_modules/module-details-from-path": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.3.tgz", - "integrity": "sha512-ySViT69/76t8VhE1xXHK6Ch4NcDd26gx0MzKXLO+F7NOtnqH68d9zF94nT8ZWSxXh8ELOERsnJO/sWt1xZYw5A==" - }, - "node_modules/mpg123-decoder": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mpg123-decoder/-/mpg123-decoder-1.0.0.tgz", - "integrity": "sha512-WV+pyuMUhRqv7s8S6p/Ii4KQHdBD1pb3yaABxcKJRsNp+HQ/Y6z2iIBIaOZu0JMHPTOoICYt0REDZ7XfLu+n/g==", - "dependencies": { - "@wasm-audio-decoders/common": "9.0.5" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==" }, "node_modules/ms": { "version": "2.1.3", @@ -8670,9 +8662,9 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, "node_modules/multer": { - "version": "1.4.5-lts.1", - "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz", - "integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==", + "version": "1.4.5-lts.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz", + "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==", "dependencies": { "append-field": "^1.0.0", "busboy": "^1.0.0", @@ -8722,6 +8714,17 @@ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==" }, + "node_modules/nats": { + "version": "2.29.3", + "resolved": "https://registry.npmjs.org/nats/-/nats-2.29.3.tgz", + "integrity": "sha512-tOQCRCwC74DgBTk4pWZ9V45sk4d7peoE2njVprMRCBXrhJ5q5cYM7i6W+Uvw2qUrcfOSnuisrX7bEx3b3Wx4QA==", + "dependencies": { + "nkeys.js": "1.1.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -8735,10 +8738,21 @@ "node": ">= 0.6" } }, + "node_modules/nkeys.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz", + "integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==", + "dependencies": { + "tweetnacl": "1.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/node-abi": { - "version": "3.73.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.73.0.tgz", - "integrity": "sha512-z8iYzQGBu35ZkTQ9mtR8RqugJZ9RCLn8fv3d7LsgDBzOijGQP3RdKTX4LA7LXw03ZhU5z0l4xfhIMgSES31+cg==", + "version": "3.75.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.75.0.tgz", + "integrity": "sha512-OhYaY5sDsIka7H7AtijtI9jwGYLyl29eQn/W623DiN/MIv5sUqc4g7BIDThX+gb7di9f6xK02nkp8sdfFWZLTg==", "dependencies": { "semver": "^7.3.5" }, @@ -8785,6 +8799,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", "funding": [ { "type": "github", @@ -8800,9 +8815,9 @@ } }, "node_modules/node-fetch": { - "version": "2.6.7", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", "dependencies": { "whatwg-url": "^5.0.0" }, @@ -8818,14 +8833,6 @@ } } }, - "node_modules/node-wav": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/node-wav/-/node-wav-0.0.2.tgz", - "integrity": "sha512-M6Rm/bbG6De/gKGxOpeOobx/dnGuP0dz40adqx38boqHhlWssBJZgLCPBNtb9NkrmnKYiV04xELq+R6PFOnoLA==", - "engines": { - "node": ">=4.4.0" - } - }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -8855,9 +8862,9 @@ } }, "node_modules/object-inspect": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", - "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", "engines": { "node": ">= 0.4" }, @@ -8944,20 +8951,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/ogg-opus-decoder": { - "version": "1.6.14", - "resolved": "https://registry.npmjs.org/ogg-opus-decoder/-/ogg-opus-decoder-1.6.14.tgz", - "integrity": "sha512-RQpk9yFl/mqXFwcgf1BrEYWL92HZk++aU1fOO8mPZ1+1DUYbJdpdUQEFfbPE1xcBkRGU3p75DjEO+EDMNeikFQ==", - "dependencies": { - "@wasm-audio-decoders/common": "9.0.5", - "codec-parser": "2.5.0", - "opus-decoder": "0.7.7" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, "node_modules/omggif": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz", @@ -8999,9 +8992,9 @@ } }, "node_modules/openai": { - "version": "4.81.0", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.81.0.tgz", - "integrity": "sha512-lXkFkV+He3O6RGnldHncRGef4uWHssDsAVwN5I3bWcgIdDPy/w8vgtIAwvZxAj49m4WiwWVD0+eGTJ9xOv/ISA==", + "version": "4.98.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.98.0.tgz", + "integrity": "sha512-TmDKur1WjxxMPQAtLG5sgBSCJmX7ynTsGmewKzoDwl1fRxtbLOsiR0FA/AOAAtYUmP6azal+MYQuOENfdU+7yg==", "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", @@ -9028,9 +9021,9 @@ } }, "node_modules/openai/node_modules/@types/node": { - "version": "18.19.74", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.74.tgz", - "integrity": "sha512-HMwEkkifei3L605gFdV+/UwtpxP6JSzM+xFk2Ia6DNFSwSVBRh9qp5Tgf4lNFOMfPVuU0WnkcWpXZpgn5ufO4A==", + "version": "18.19.100", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.100.tgz", + "integrity": "sha512-ojmMP8SZBKprc3qGrGk8Ujpo80AXkrP7G2tOT4VWr5jlr5DHjsJF+emXJz+Wm0glmy4Js62oKMdZZ6B9Y+tEcA==", "dependencies": { "undici-types": "~5.26.4" } @@ -9056,18 +9049,6 @@ "node": ">= 0.8.0" } }, - "node_modules/opus-decoder": { - "version": "0.7.7", - "resolved": "https://registry.npmjs.org/opus-decoder/-/opus-decoder-0.7.7.tgz", - "integrity": "sha512-KWDyCi/9aXnNN+jrjs+aaVdwiwzDdac81S9ul0iv1CTs4+5K4VDZKuJjIImrYOBA2oSNHDjVq4xzn6BE+XbI1A==", - "dependencies": { - "@wasm-audio-decoders/common": "9.0.5" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, "node_modules/own-keys": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz", @@ -9174,16 +9155,16 @@ } }, "node_modules/parse-headers": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.5.tgz", - "integrity": "sha512-ft3iAoLOB/MlwbNXgzy43SWGP6sQki2jQvAyBg/zDFAgr9bfNWZIUj42Kw2eJIl8kEi4PbgE6U1Zau/HwI75HA==" + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.6.tgz", + "integrity": "sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==" }, "node_modules/parse5": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.2.1.tgz", - "integrity": "sha512-BuBYQYlv1ckiPdQi/ohiivi9Sagc9JG+Ozs0r7b/0iK3sKmrb0b9FdWdBbOdx6hBCM/F9Ir82ofnBhtZOjCRPQ==", + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", "dependencies": { - "entities": "^4.5.0" + "entities": "^6.0.0" }, "funding": { "url": "https://github.com/inikulin/parse5?sponsor=1" @@ -9201,6 +9182,17 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.0.tgz", + "integrity": "sha512-aKstq2TDOndCn4diEyp9Uq/Flu2i1GlLkc6XIDQSDMuaFE3OPW5OphLCyQ5SpSJZTb4reN+kTcYru5yIfXoRPw==", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -9262,6 +9254,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, "engines": { "node": ">=8" } @@ -9279,21 +9272,21 @@ } }, "node_modules/pg": { - "version": "8.13.1", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.13.1.tgz", - "integrity": "sha512-OUir1A0rPNZlX//c7ksiu7crsGZTKSOXJPgtNiHGIlC9H0lO+NC6ZDYksSgBYY/thSWhnSRBv8w1lieNNGATNQ==", + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.16.0.tgz", + "integrity": "sha512-7SKfdvP8CTNXjMUzfcVTaI+TDzBEeaUnVwiVGZQD1Hh33Kpev7liQba9uLd4CfN8r9mCVsD0JIpq03+Unpz+kg==", "dependencies": { - "pg-connection-string": "^2.7.0", - "pg-pool": "^3.7.0", - "pg-protocol": "^1.7.0", - "pg-types": "^2.1.0", - "pgpass": "1.x" + "pg-connection-string": "^2.9.0", + "pg-pool": "^3.10.0", + "pg-protocol": "^1.10.0", + "pg-types": "2.2.0", + "pgpass": "1.0.5" }, "engines": { "node": ">= 8.0.0" }, "optionalDependencies": { - "pg-cloudflare": "^1.1.1" + "pg-cloudflare": "^1.2.5" }, "peerDependencies": { "pg-native": ">=3.0.1" @@ -9305,15 +9298,15 @@ } }, "node_modules/pg-cloudflare": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.1.1.tgz", - "integrity": "sha512-xWPagP/4B6BgFO+EKz3JONXv3YDgvkbVrGw2mTo3D6tVDQRh1e7cqVGvyR3BE+eQgAvx1XhW/iEASj4/jCWl3Q==", + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.2.5.tgz", + "integrity": "sha512-OOX22Vt0vOSRrdoUPKJ8Wi2OpE/o/h9T8X1s4qSkCedbNah9ei2W2765be8iMVxQUsvgT7zIAT2eIa9fs5+vtg==", "optional": true }, "node_modules/pg-connection-string": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.7.0.tgz", - "integrity": "sha512-PI2W9mv53rXJQEOb8xNR8lH7Hr+EKa6oJa38zsK0S/ky2er16ios1wLKhZyxzD7jUReiWokc9WK5nxSnC7W1TA==" + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.9.0.tgz", + "integrity": "sha512-P2DEBKuvh5RClafLngkAuGe9OUlFV7ebu8w1kmaaOgPcpJd1RIFh7otETfI6hAR8YupOLFTY7nuvvIn7PLciUQ==" }, "node_modules/pg-int8": { "version": "1.0.1", @@ -9324,17 +9317,17 @@ } }, "node_modules/pg-pool": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.7.0.tgz", - "integrity": "sha512-ZOBQForurqh4zZWjrgSwwAtzJ7QiRX0ovFkZr2klsen3Nm0aoh33Ls0fzfv3imeH/nw/O27cjdz5kzYJfeGp/g==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.10.0.tgz", + "integrity": "sha512-DzZ26On4sQ0KmqnO34muPcmKbhrjmyiO4lCCR0VwEd7MjmiKf5NTg/6+apUEu0NF7ESa37CGzFxH513CoUmWnA==", "peerDependencies": { "pg": ">=8.0" } }, "node_modules/pg-protocol": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.7.0.tgz", - "integrity": "sha512-hTK/mE36i8fDDhgDFjy6xNOG+LCorxLG3WO17tku+ij6sVHXh1jQUJ8hYAnRhNla4QVD2H8er/FOjc/+EgC6yQ==" + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.10.0.tgz", + "integrity": "sha512-IpdytjudNuLv8nhlHs/UrVBhU0e78J0oIS/0AVdTbWxSOkFUVdsHC/NrorO6nXsQNDTT1kzDSOMJubBQviX18Q==" }, "node_modules/pg-types": { "version": "2.2.0", @@ -9455,9 +9448,9 @@ "integrity": "sha512-cHjPPsE+vhj/tnhCy/wiMh3M3z3h/j15zHQX+S9GkTBgqJuTuJzYJ4gUyACLhDaJ7kk9ba9iRDmbH2tJU03OiA==" }, "node_modules/pirates": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", - "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", "engines": { "node": ">= 6" } @@ -9482,9 +9475,9 @@ } }, "node_modules/possible-typed-array-names": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", - "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", "engines": { "node": ">= 0.4" } @@ -9625,9 +9618,9 @@ } }, "node_modules/prettier": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", - "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz", + "integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==", "dev": true, "bin": { "prettier": "bin/prettier.cjs" @@ -9652,12 +9645,13 @@ } }, "node_modules/prisma": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.3.0.tgz", - "integrity": "sha512-y+Zh3Qg+xGCWyyrNUUNaFW/OltaV/yXYuTa0WRgYkz5LGyifmAsgpv94I47+qGRocZrMGcbF2A/78/oO2zgifA==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.8.1.tgz", + "integrity": "sha512-CLDiNk1vYWsa3ZIMZcttG3pzVaRK63yrtPBDMpzhsgI4MiahpCvdM72AAzQc/PElWENoBUx0JAF/UkIFhcmaJw==", "hasInstallScript": true, "dependencies": { - "@prisma/engines": "6.3.0" + "@prisma/config": "6.8.1", + "@prisma/engines": "6.8.1" }, "bin": { "prisma": "build/index.js" @@ -9665,9 +9659,6 @@ "engines": { "node": ">=18.18" }, - "optionalDependencies": { - "fsevents": "2.3.3" - }, "peerDependencies": { "typescript": ">=5.1.0" }, @@ -9695,18 +9686,10 @@ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz", "integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==" }, - "node_modules/promise-coalesce": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/promise-coalesce/-/promise-coalesce-1.1.2.tgz", - "integrity": "sha512-zLaJ9b8hnC564fnJH6NFSOGZYYdzrAJn2JUUIwzoQb32fG2QAakpDNM+CZo1km6keXkRXRM+hml1BFAPVnPkxg==", - "engines": { - "node": ">=16" - } - }, "node_modules/protobufjs": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.4.0.tgz", - "integrity": "sha512-mRUWCc3KUU4w1jU8sGxICXH/gNS94DvI1gxqDvBzhj1JpcsimQkYiOJfwsPUykUI5ZaspFbSgmBLER8IrQ3tqw==", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.2.tgz", + "integrity": "sha512-f2ls6rpO6G153Cy+o2XQ+Y0sARLOZ17+OGVLHrc3VUKcLHYKEKWbkSujdBWQXM7gKn5NTfp0XnRPZn1MIu8n9w==", "hasInstallScript": true, "dependencies": { "@protobufjs/aspromise": "^1.1.2", @@ -9784,14 +9767,6 @@ "node": ">= 4.0.0" } }, - "node_modules/qoa-format": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/qoa-format/-/qoa-format-1.0.1.tgz", - "integrity": "sha512-dMB0Z6XQjdpz/Cw4Rf6RiBpQvUSPCfYlQMWvmuWlWkAT7nDQD29cVZ1SwDUB6DYJSitHENwbt90lqfI+7bvMcw==", - "dependencies": { - "@thi.ng/bitstream": "^2.2.12" - } - }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -10060,11 +10035,11 @@ } }, "node_modules/readable-web-to-node-stream": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.2.tgz", - "integrity": "sha512-ePeK6cc1EcKLEhJFt/AebMCLL+GgSKhuygrZ/GLaKZYEecIgIECf4UaUuaByiGtzckwR4ain9VzUh95T1exYGw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.4.tgz", + "integrity": "sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw==", "dependencies": { - "readable-stream": "^3.6.0" + "readable-stream": "^4.7.0" }, "engines": { "node": ">=8" @@ -10074,6 +10049,44 @@ "url": "https://github.com/sponsors/Borewit" } }, + "node_modules/readable-web-to-node-stream/node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/readable-web-to-node-stream/node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -10095,15 +10108,15 @@ } }, "node_modules/redis": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/redis/-/redis-4.7.0.tgz", - "integrity": "sha512-zvmkHEAdGMn+hMRXuMBtu4Vo5P6rHQjLoHftu+lBqq8ZTA3RCVC/WzD790bkKKiNFp7d5/9PcSD19fJyyRvOdQ==", + "version": "4.7.1", + "resolved": "https://registry.npmjs.org/redis/-/redis-4.7.1.tgz", + "integrity": "sha512-S1bJDnqLftzHXHP8JsT5II/CtHWQrASX5K96REjWjlmWKrviSOLWmM7QnRLstAWsu1VBBV1ffV6DzCvxNP0UJQ==", "workspaces": [ "./packages/*" ], "dependencies": { "@redis/bloom": "1.2.0", - "@redis/client": "1.6.0", + "@redis/client": "1.6.1", "@redis/graph": "1.1.1", "@redis/json": "1.0.7", "@redis/search": "1.2.0", @@ -10133,9 +10146,9 @@ } }, "node_modules/regenerator-runtime": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", - "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==" + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" }, "node_modules/regexp.prototype.flags": { "version": "1.5.4", @@ -10166,9 +10179,9 @@ } }, "node_modules/require-in-the-middle": { - "version": "7.5.0", - "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.0.tgz", - "integrity": "sha512-/Tvpny/RVVicqlYTKwt/GtpZRsPG1CmJNhxVKGz+Sy/4MONfXCVNK69MFgGKdUt0/324q3ClI2dICcPgISrC8g==", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", + "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", "dependencies": { "debug": "^4.3.5", "module-details-from-path": "^1.0.3", @@ -10216,9 +10229,9 @@ } }, "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" @@ -10240,11 +10253,11 @@ } }, "node_modules/rollup": { - "version": "4.32.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.32.1.tgz", - "integrity": "sha512-z+aeEsOeEa3mEbS1Tjl6sAZ8NE3+AalQz1RJGj81M+fizusbdDMoEJwdJNHfaB40Scr4qNu+welOfes7maKonA==", + "version": "4.40.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.40.2.tgz", + "integrity": "sha512-tfUOg6DTP4rhQ3VjOO6B4wyrJnGOX85requAXvqYTHsOgb2TFJdZ3aWpT8W2kPoypSGP7dZUyzxJ9ee4buM5Fg==", "dependencies": { - "@types/estree": "1.0.6" + "@types/estree": "1.0.7" }, "bin": { "rollup": "dist/bin/rollup" @@ -10254,25 +10267,26 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.32.1", - "@rollup/rollup-android-arm64": "4.32.1", - "@rollup/rollup-darwin-arm64": "4.32.1", - "@rollup/rollup-darwin-x64": "4.32.1", - "@rollup/rollup-freebsd-arm64": "4.32.1", - "@rollup/rollup-freebsd-x64": "4.32.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.32.1", - "@rollup/rollup-linux-arm-musleabihf": "4.32.1", - "@rollup/rollup-linux-arm64-gnu": "4.32.1", - "@rollup/rollup-linux-arm64-musl": "4.32.1", - "@rollup/rollup-linux-loongarch64-gnu": "4.32.1", - "@rollup/rollup-linux-powerpc64le-gnu": "4.32.1", - "@rollup/rollup-linux-riscv64-gnu": "4.32.1", - "@rollup/rollup-linux-s390x-gnu": "4.32.1", - "@rollup/rollup-linux-x64-gnu": "4.32.1", - "@rollup/rollup-linux-x64-musl": "4.32.1", - "@rollup/rollup-win32-arm64-msvc": "4.32.1", - "@rollup/rollup-win32-ia32-msvc": "4.32.1", - "@rollup/rollup-win32-x64-msvc": "4.32.1", + "@rollup/rollup-android-arm-eabi": "4.40.2", + "@rollup/rollup-android-arm64": "4.40.2", + "@rollup/rollup-darwin-arm64": "4.40.2", + "@rollup/rollup-darwin-x64": "4.40.2", + "@rollup/rollup-freebsd-arm64": "4.40.2", + "@rollup/rollup-freebsd-x64": "4.40.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.40.2", + "@rollup/rollup-linux-arm-musleabihf": "4.40.2", + "@rollup/rollup-linux-arm64-gnu": "4.40.2", + "@rollup/rollup-linux-arm64-musl": "4.40.2", + "@rollup/rollup-linux-loongarch64-gnu": "4.40.2", + "@rollup/rollup-linux-powerpc64le-gnu": "4.40.2", + "@rollup/rollup-linux-riscv64-gnu": "4.40.2", + "@rollup/rollup-linux-riscv64-musl": "4.40.2", + "@rollup/rollup-linux-s390x-gnu": "4.40.2", + "@rollup/rollup-linux-x64-gnu": "4.40.2", + "@rollup/rollup-linux-x64-musl": "4.40.2", + "@rollup/rollup-win32-arm64-msvc": "4.40.2", + "@rollup/rollup-win32-ia32-msvc": "4.40.2", + "@rollup/rollup-win32-x64-msvc": "4.40.2", "fsevents": "~2.3.2" } }, @@ -10318,9 +10332,23 @@ } }, "node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, "node_modules/safe-push-apply": { "version": "1.0.0", @@ -10373,9 +10401,9 @@ "integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==" }, "node_modules/semver": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.0.tgz", - "integrity": "sha512-DrfFnPzblFmNrIZzg5RzHegbiRWg7KMR7btwi2yjHwx06zsUbO5g613sVwEV7FTwmzJu+Io0lJe2GJ3LxqpvBQ==", + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", "bin": { "semver": "bin/semver.js" }, @@ -10683,19 +10711,11 @@ "is-arrayish": "^0.3.1" } }, - "node_modules/simple-yenc": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/simple-yenc/-/simple-yenc-1.0.4.tgz", - "integrity": "sha512-5gvxpSd79e9a3V4QDYUqnqxeD4HGlhCakVpb6gMnDD7lexJggSBJRBO5h52y/iJrdXRilX9UCuDaIJhSWm5OWw==", - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, "node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, "engines": { "node": ">=8" } @@ -10900,11 +10920,6 @@ "stream-chain": "^2.2.5" } }, - "node_modules/stream-shift": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", - "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==" - }, "node_modules/streamsearch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", @@ -10941,25 +10956,6 @@ "safe-buffer": "~5.2.0" } }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -11087,9 +11083,15 @@ } }, "node_modules/strnum": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz", - "integrity": "sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] }, "node_modules/strtok3": { "version": "6.3.0", @@ -11184,19 +11186,19 @@ } }, "node_modules/synckit": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.9.2.tgz", - "integrity": "sha512-vrozgXDQwYO72vHjUb/HnFbQx1exDjoKzqx23aXEg2a9VIg2TSFZ8FmeZpTjUCFMYw7mpX4BE2SFu8wI7asYsw==", + "version": "0.11.5", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.5.tgz", + "integrity": "sha512-frqvfWyDA5VPVdrWfH24uM6SI/O8NLpVbIIJxb8t/a3YGsp4AW9CYgSKC0OaSEfexnp7Y1pVh2Y6IHO8ggGDmA==", "dev": true, "dependencies": { - "@pkgr/core": "^0.1.0", - "tslib": "^2.6.2" + "@pkgr/core": "^0.2.4", + "tslib": "^2.8.1" }, "engines": { "node": "^14.18.0 || >=16.0.0" }, "funding": { - "url": "https://opencollective.com/unts" + "url": "https://opencollective.com/synckit" } }, "node_modules/tar-fs": { @@ -11286,21 +11288,24 @@ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==" }, "node_modules/tinyglobby": { - "version": "0.2.10", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.10.tgz", - "integrity": "sha512-Zc+8eJlFMvgatPZTl6A9L/yht8QqdmUNtURHaKZLmKBE12hNPSrqNkUp2cs3M/UKmNVVAMFQYSjYIVHDjW5zew==", + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.13.tgz", + "integrity": "sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw==", "dependencies": { - "fdir": "^6.4.2", + "fdir": "^6.4.4", "picomatch": "^4.0.2" }, "engines": { "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" } }, "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.4.3", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.3.tgz", - "integrity": "sha512-PMXmW2y1hDDfTSRc9gaXIuCCRpuoz3Kaz8cUelp3smouvfT632ozg2vrT6lJsHKKOF59YLbOGfAWGUcKEfRMQw==", + "version": "6.4.4", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.4.tgz", + "integrity": "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==", "peerDependencies": { "picomatch": "^3 || ^4" }, @@ -11373,6 +11378,7 @@ "version": "1.4.3", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==", + "dev": true, "engines": { "node": ">=16" }, @@ -11528,25 +11534,25 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" }, "node_modules/tsup": { - "version": "8.3.6", - "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.3.6.tgz", - "integrity": "sha512-XkVtlDV/58S9Ye0JxUUTcrQk4S+EqlOHKzg6Roa62rdjL1nGWNUstG0xgI4vanHdfIpjP448J8vlN0oK6XOJ5g==", + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.4.0.tgz", + "integrity": "sha512-b+eZbPCjz10fRryaAA7C8xlIHnf8VnsaRqydheLIqwG/Mcpfk8Z5zp3HayX7GaTygkigHl5cBUs+IhcySiIexQ==", "dependencies": { - "bundle-require": "^5.0.0", + "bundle-require": "^5.1.0", "cac": "^6.7.14", - "chokidar": "^4.0.1", - "consola": "^3.2.3", - "debug": "^4.3.7", - "esbuild": "^0.24.0", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.25.0", "joycon": "^3.1.1", "picocolors": "^1.1.1", "postcss-load-config": "^6.0.1", "resolve-from": "^5.0.0", - "rollup": "^4.24.0", + "rollup": "^4.34.8", "source-map": "0.8.0-beta.0", "sucrase": "^3.35.0", - "tinyexec": "^0.3.1", - "tinyglobby": "^0.2.9", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", "tree-kill": "^1.2.2" }, "bin": { @@ -11592,9 +11598,9 @@ } }, "node_modules/tsup/node_modules/readdirp": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.1.tgz", - "integrity": "sha512-h80JrZu/MHUZCyHu5ciuoI0+WxsCxzxJTILn6Fs8rxSnFPh+UVHYfeIxK1nVGugMqkfC4vJcBOYbkfkwYK0+gw==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", "engines": { "node": ">= 14.18.0" }, @@ -11788,9 +11794,9 @@ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==" }, "node_modules/typescript": { - "version": "5.7.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", - "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -11818,9 +11824,9 @@ } }, "node_modules/undici-types": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", - "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==" + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==" }, "node_modules/unpipe": { "version": "1.0.0", @@ -11913,9 +11919,9 @@ "dev": true }, "node_modules/validator": { - "version": "13.12.0", - "resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz", - "integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==", + "version": "13.15.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.15.0.tgz", + "integrity": "sha512-36B2ryl4+oL5QxZ3AzD0t5SsMNGvTtQHpjgFO5tbNxfXbMFkY822ktCDe1MnlqV3301QQI9SLHDNJokDI+Z9pA==", "engines": { "node": ">= 0.10" } @@ -12045,14 +12051,15 @@ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==" }, "node_modules/which-typed-array": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.18.tgz", - "integrity": "sha512-qEcY+KJYlWyLH9vNbsr6/5j59AXk5ni5aakf8ldzBvGde6Iz4sxZGkJyWSAueTG7QhOvNRYb1lDdFmL5Td0QKA==", + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz", + "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==", "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "for-each": "^0.3.3", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" }, @@ -12110,9 +12117,9 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/ws": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", - "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==", "engines": { "node": ">=10.0.0" }, diff --git a/package.json b/package.json index 7e948028..de750887 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.3", + "version": "2.3.0", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -18,6 +18,7 @@ "db:studio": "node runWithProvider.js \"npx prisma studio --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"", "db:migrate:dev:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate dev --schema prisma\\DATABASE_PROVIDER-schema.prisma\"" + }, "repository": { "type": "git", @@ -41,7 +42,7 @@ ], "author": { "name": "Davidson Gomes", - "email": "contato@atendai.com" + "email": "contato@evolution-api.com" }, "license": "Apache-2.0", "bugs": { @@ -75,6 +76,7 @@ "jimp": "^0.16.13", "json-schema": "^0.4.0", "jsonschema": "^1.4.1", + "jsonwebtoken": "^9.0.2", "link-preview-js": "^3.0.13", "long": "^5.2.3", "mediainfo.js": "^0.3.4", @@ -82,6 +84,7 @@ "mime-types": "^2.1.35", "minio": "^8.0.3", "multer": "^1.4.5-lts.1", + "nats": "^2.29.1", "node-cache": "^5.1.2", "node-cron": "^3.0.3", "openai": "^4.77.3", diff --git a/prisma/mysql-migrations/1707735894523_add_wavoip_token_to_settings_table/migration.sql b/prisma/mysql-migrations/1707735894523_add_wavoip_token_to_settings_table/migration.sql new file mode 100644 index 00000000..2b634b17 --- /dev/null +++ b/prisma/mysql-migrations/1707735894523_add_wavoip_token_to_settings_table/migration.sql @@ -0,0 +1,9 @@ +/* + Warnings: + + - A unique constraint covering the columns `[remoteJid,instanceId]` on the table `Chat` will be added. If there are existing duplicate values, this will fail. +*/ + +-- AlterTable +ALTER TABLE `Setting` + ADD COLUMN IF NOT EXISTS `wavoipToken` VARCHAR(100); diff --git a/prisma/mysql-migrations/20250214181954_add_wavoip_token_column/migration.sql b/prisma/mysql-migrations/20250214181954_add_wavoip_token_column/migration.sql new file mode 100644 index 00000000..547111b6 --- /dev/null +++ b/prisma/mysql-migrations/20250214181954_add_wavoip_token_column/migration.sql @@ -0,0 +1,175 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Pusher` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Pusher` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - A unique constraint covering the columns `[instanceId,remoteJid]` on the table `Chat` will be added. If there are existing duplicate values, this will fail. + +*/ +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `IsOnWhatsapp` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Pusher` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` ADD COLUMN `wavoipToken` VARCHAR(100) NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateIndex +CREATE UNIQUE INDEX `Chat_instanceId_remoteJid_key` ON `Chat`(`instanceId`, `remoteJid`); diff --git a/prisma/mysql-migrations/20250510035200_add_wavoip_token_to_settings_table/migration.sql b/prisma/mysql-migrations/20250510035200_add_wavoip_token_to_settings_table/migration.sql new file mode 100644 index 00000000..11bdb5f5 --- /dev/null +++ b/prisma/mysql-migrations/20250510035200_add_wavoip_token_to_settings_table/migration.sql @@ -0,0 +1,26 @@ +/* +Warnings: + +- A unique constraint covering the columns `[remoteJid,instanceId]` on the table `Chat` will be added. If there are existing duplicate values, this will fail. + +*/ + +-- AlterTable +SET @column_exists := ( + SELECT COUNT(*) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'Setting' + AND column_name = 'wavoipToken' +); + +SET @sql := IF(@column_exists = 0, + 'ALTER TABLE Setting ADD COLUMN wavoipToken VARCHAR(100);', + 'SELECT "Column already exists";' +); + +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +ALTER TABLE Chat ADD CONSTRAINT unique_remote_instance UNIQUE (remoteJid, instanceId); diff --git a/prisma/mysql-migrations/migration_lock.toml b/prisma/mysql-migrations/migration_lock.toml index e5a788a7..8a21669a 100644 --- a/prisma/mysql-migrations/migration_lock.toml +++ b/prisma/mysql-migrations/migration_lock.toml @@ -1,3 +1,3 @@ # Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) +# It should be added in your version-control system (e.g., Git) provider = "mysql" \ No newline at end of file diff --git a/prisma/mysql-schema.prisma b/prisma/mysql-schema.prisma index a73ca069..782e4d85 100644 --- a/prisma/mysql-schema.prisma +++ b/prisma/mysql-schema.prisma @@ -86,6 +86,7 @@ model Instance { Proxy Proxy? Setting Setting? Rabbitmq Rabbitmq? + Nats Nats? Sqs Sqs? Websocket Websocket? Typebot Typebot[] @@ -99,12 +100,13 @@ model Instance { Template Template[] Dify Dify[] DifySetting DifySetting? - integrationSessions IntegrationSession[] + IntegrationSession IntegrationSession[] EvolutionBot EvolutionBot[] EvolutionBotSetting EvolutionBotSetting? Flowise Flowise[] FlowiseSetting FlowiseSetting? Pusher Pusher? + N8n N8n[] } model Session { @@ -116,18 +118,19 @@ model Session { } model Chat { - id String @id @default(cuid()) - remoteJid String @db.VarChar(100) - name String? @db.VarChar(100) - labels Json? @db.Json - createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp - updatedAt DateTime? @updatedAt @db.Timestamp - Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) - instanceId String + id String @id @default(cuid()) + remoteJid String @db.VarChar(100) + name String? @db.VarChar(100) + labels Json? @db.Json + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String unreadMessages Int @default(0) + + @@unique([instanceId, remoteJid]) @@index([instanceId]) @@index([remoteJid]) - @@unique([instanceId, remoteJid]) } model Contact { @@ -170,6 +173,7 @@ model Message { sessionId String? session IntegrationSession? @relation(fields: [sessionId], references: [id]) + @@index([instanceId]) } @@ -185,6 +189,7 @@ model MessageUpdate { messageId String Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + @@index([instanceId]) @@index([messageId]) } @@ -201,6 +206,7 @@ model Webhook { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -269,6 +275,7 @@ model Setting { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -282,6 +289,16 @@ model Rabbitmq { instanceId String @unique } +model Nats { + id String @id @default(cuid()) + enabled Boolean @default(false) + events Json @db.Json + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + model Sqs { id String @id @default(cuid()) enabled Boolean @default(false) @@ -382,7 +399,7 @@ model IntegrationSession { model Media { id String @id @default(cuid()) - fileName String @unique @db.VarChar(500) + fileName String @db.VarChar(500) type String @db.VarChar(100) mimetype String @db.VarChar(100) createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp @@ -627,3 +644,100 @@ model IsOnWhatsapp { createdAt DateTime @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp } + +model N8n { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + webhookUrl String? @db.VarChar(255) + basicAuthUser String? @db.VarChar(255) + basicAuthPass String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + N8nSetting N8nSetting[] +} + +model N8nSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback N8n? @relation(fields: [n8nIdFallback], references: [id]) + n8nIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Evoai { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + agentUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvoaiSetting EvoaiSetting[] +} + +model EvoaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Evoai? @relation(fields: [evoaiIdFallback], references: [id]) + evoaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} diff --git a/prisma/postgresql-migrations/20250225180031_add_nats_integration/migration.sql b/prisma/postgresql-migrations/20250225180031_add_nats_integration/migration.sql new file mode 100644 index 00000000..1e6c0e60 --- /dev/null +++ b/prisma/postgresql-migrations/20250225180031_add_nats_integration/migration.sql @@ -0,0 +1,17 @@ +-- CreateTable +CREATE TABLE "Nats" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT false, + "events" JSONB NOT NULL, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "Nats_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Nats_instanceId_key" ON "Nats"("instanceId"); + +-- AddForeignKey +ALTER TABLE "Nats" ADD CONSTRAINT "Nats_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20250514232744_add_n8n_table/migration.sql b/prisma/postgresql-migrations/20250514232744_add_n8n_table/migration.sql new file mode 100644 index 00000000..18a0d23d --- /dev/null +++ b/prisma/postgresql-migrations/20250514232744_add_n8n_table/migration.sql @@ -0,0 +1,62 @@ +-- CreateTable +CREATE TABLE "N8n" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "webhookUrl" VARCHAR(255), + "basicAuthUser" VARCHAR(255), + "basicAuthPass" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "N8n_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "N8nSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "n8nIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "N8nSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "N8nSetting_instanceId_key" ON "N8nSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "N8n" ADD CONSTRAINT "N8n_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "N8nSetting" ADD CONSTRAINT "N8nSetting_n8nIdFallback_fkey" FOREIGN KEY ("n8nIdFallback") REFERENCES "N8n"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "N8nSetting" ADD CONSTRAINT "N8nSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20250515211815_add_evoai_table/migration.sql b/prisma/postgresql-migrations/20250515211815_add_evoai_table/migration.sql new file mode 100644 index 00000000..1350d8eb --- /dev/null +++ b/prisma/postgresql-migrations/20250515211815_add_evoai_table/migration.sql @@ -0,0 +1,61 @@ +-- CreateTable +CREATE TABLE "Evoai" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "agentUrl" VARCHAR(255), + "apiKey" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "Evoai_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "EvoaiSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "evoaiIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "EvoaiSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "EvoaiSetting_instanceId_key" ON "EvoaiSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "Evoai" ADD CONSTRAINT "Evoai_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "EvoaiSetting" ADD CONSTRAINT "EvoaiSetting_evoaiIdFallback_fkey" FOREIGN KEY ("evoaiIdFallback") REFERENCES "Evoai"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "EvoaiSetting" ADD CONSTRAINT "EvoaiSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql b/prisma/postgresql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql new file mode 100644 index 00000000..25c1eda5 --- /dev/null +++ b/prisma/postgresql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql @@ -0,0 +1,2 @@ +-- DropIndex +DROP INDEX "Media_fileName_key"; diff --git a/prisma/postgresql-migrations/migration_lock.toml b/prisma/postgresql-migrations/migration_lock.toml index fbffa92c..648c57fd 100644 --- a/prisma/postgresql-migrations/migration_lock.toml +++ b/prisma/postgresql-migrations/migration_lock.toml @@ -1,3 +1,3 @@ # Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) +# It should be added in your version-control system (e.g., Git) provider = "postgresql" \ No newline at end of file diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index a9782ce5..a0a878df 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -86,6 +86,7 @@ model Instance { Proxy Proxy? Setting Setting? Rabbitmq Rabbitmq? + Nats Nats? Sqs Sqs? Websocket Websocket? Typebot Typebot[] @@ -99,12 +100,16 @@ model Instance { Template Template[] Dify Dify[] DifySetting DifySetting? - integrationSessions IntegrationSession[] + IntegrationSession IntegrationSession[] EvolutionBot EvolutionBot[] EvolutionBotSetting EvolutionBotSetting? Flowise Flowise[] FlowiseSetting FlowiseSetting? Pusher Pusher? + N8n N8n[] + N8nSetting N8nSetting[] + Evoai Evoai[] + EvoaiSetting EvoaiSetting? } model Session { @@ -125,6 +130,7 @@ model Chat { Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String unreadMessages Int @default(0) + @@index([instanceId]) @@index([remoteJid]) } @@ -168,6 +174,7 @@ model Message { sessionId String? session IntegrationSession? @relation(fields: [sessionId], references: [id]) + @@index([instanceId]) } @@ -183,6 +190,7 @@ model MessageUpdate { messageId String Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + @@index([instanceId]) @@index([messageId]) } @@ -199,6 +207,7 @@ model Webhook { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -269,6 +278,7 @@ model Setting { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -282,6 +292,16 @@ model Rabbitmq { instanceId String @unique } +model Nats { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + model Sqs { id String @id @default(cuid()) enabled Boolean @default(false) @db.Boolean @@ -363,7 +383,7 @@ model TypebotSetting { model Media { id String @id @default(cuid()) - fileName String @unique @db.VarChar(500) + fileName String @db.VarChar(500) type String @db.VarChar(100) mimetype String @db.VarChar(100) createdAt DateTime? @default(now()) @db.Date @@ -627,3 +647,100 @@ model IsOnWhatsapp { createdAt DateTime @default(now()) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp } + +model N8n { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + webhookUrl String? @db.VarChar(255) + basicAuthUser String? @db.VarChar(255) + basicAuthPass String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + N8nSetting N8nSetting[] +} + +model N8nSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback N8n? @relation(fields: [n8nIdFallback], references: [id]) + n8nIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Evoai { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + agentUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvoaiSetting EvoaiSetting[] +} + +model EvoaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Evoai? @relation(fields: [evoaiIdFallback], references: [id]) + evoaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} \ No newline at end of file diff --git a/src/api/controllers/business.controller.ts b/src/api/controllers/business.controller.ts new file mode 100644 index 00000000..3c7f166c --- /dev/null +++ b/src/api/controllers/business.controller.ts @@ -0,0 +1,15 @@ +import { getCatalogDto, getCollectionsDto } from '@api/dto/business.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; + +export class BusinessController { + constructor(private readonly waMonitor: WAMonitoringService) {} + + public async fetchCatalog({ instanceName }: InstanceDto, data: getCatalogDto) { + return await this.waMonitor.waInstances[instanceName].fetchCatalog(instanceName, data); + } + + public async fetchCollections({ instanceName }: InstanceDto, data: getCollectionsDto) { + return await this.waMonitor.waInstances[instanceName].fetchCollections(instanceName, data); + } +} diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index 874c7566..31441b42 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -170,6 +170,9 @@ export class InstanceController { rabbitmq: { enabled: instanceData?.rabbitmq?.enabled, }, + nats: { + enabled: instanceData?.nats?.enabled, + }, sqs: { enabled: instanceData?.sqs?.enabled, }, @@ -258,6 +261,9 @@ export class InstanceController { rabbitmq: { enabled: instanceData?.rabbitmq?.enabled, }, + nats: { + enabled: instanceData?.nats?.enabled, + }, sqs: { enabled: instanceData?.sqs?.enabled, }, diff --git a/src/api/controllers/sendMessage.controller.ts b/src/api/controllers/sendMessage.controller.ts index ac40562c..18339ce5 100644 --- a/src/api/controllers/sendMessage.controller.ts +++ b/src/api/controllers/sendMessage.controller.ts @@ -18,6 +18,14 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { BadRequestException } from '@exceptions'; import { isBase64, isURL } from 'class-validator'; +function isEmoji(str: string) { + if (str === '') return true; + + const emojiRegex = + /^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F000}-\u{1F02F}\u{1F0A0}-\u{1F0FF}\u{1F100}-\u{1F64F}\u{1F680}-\u{1F6FF}]$/u; + return emojiRegex.test(str); +} + export class SendMessageController { constructor(private readonly waMonitor: WAMonitoringService) {} @@ -81,8 +89,8 @@ export class SendMessageController { } public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) { - if (!data.reaction.match(/[^()\w\sà-ú"-+]+/)) { - throw new BadRequestException('"reaction" must be an emoji'); + if (!isEmoji(data.reaction)) { + throw new BadRequestException('Reaction must be a single emoji or empty string'); } return await this.waMonitor.waInstances[instanceName].reactionMessage(data); } diff --git a/src/api/dto/business.dto.ts b/src/api/dto/business.dto.ts new file mode 100644 index 00000000..d29b3cf9 --- /dev/null +++ b/src/api/dto/business.dto.ts @@ -0,0 +1,14 @@ +export class NumberDto { + number: string; +} + +export class getCatalogDto { + number?: string; + limit?: number; + cursor?: string; +} + +export class getCollectionsDto { + number?: string; + limit?: number; +} diff --git a/src/api/dto/sendMessage.dto.ts b/src/api/dto/sendMessage.dto.ts index 1c9b1154..ba9ecf52 100644 --- a/src/api/dto/sendMessage.dto.ts +++ b/src/api/dto/sendMessage.dto.ts @@ -44,6 +44,7 @@ export class Metadata { mentionsEveryOne?: boolean; mentioned?: string[]; encoding?: boolean; + notConvertSticker?: boolean; } export class SendTextDto extends Metadata { diff --git a/src/api/integrations/channel/evolution/evolution.channel.service.ts b/src/api/integrations/channel/evolution/evolution.channel.service.ts index dba02751..34c885d5 100644 --- a/src/api/integrations/channel/evolution/evolution.channel.service.ts +++ b/src/api/integrations/channel/evolution/evolution.channel.service.ts @@ -165,11 +165,7 @@ export class EvolutionStartupService extends ChannelStartupService { openAiDefaultSettings.speechToText && received?.message?.audioMessage ) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - received, - this.client.updateMediaMessage, - ); + messageRaw.message.speechToText = await this.openaiService.speechToText(received, this); } } diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 5360b9e4..9db19e84 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -192,17 +192,77 @@ export class BusinessStartupService extends ChannelStartupService { } private messageTextJson(received: any) { - let content: any; + // Verificar que received y received.messages existen + if (!received || !received.messages || received.messages.length === 0) { + this.logger.error('Error: received object or messages array is undefined or empty'); + return null; + } + const message = received.messages[0]; + let content: any; + + // Verificar si es un mensaje de tipo sticker, location u otro tipo que no tiene text + if (!message.text) { + // Si no hay texto, manejamos diferente según el tipo de mensaje + if (message.type === 'sticker') { + content = { stickerMessage: {} }; + } else if (message.type === 'location') { + content = { + locationMessage: { + degreesLatitude: message.location?.latitude, + degreesLongitude: message.location?.longitude, + name: message.location?.name, + address: message.location?.address, + }, + }; + } else { + // Para otros tipos de mensajes sin texto, creamos un contenido genérico + this.logger.log(`Mensaje de tipo ${message.type} sin campo text`); + content = { [message.type + 'Message']: message[message.type] || {} }; + } + + // Añadir contexto si existe + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } + + return content; + } + + // Si el mensaje tiene texto, procesamos normalmente + if (!received.metadata || !received.metadata.phone_number_id) { + this.logger.error('Error: metadata or phone_number_id is undefined'); + return null; + } + if (message.from === received.metadata.phone_number_id) { content = { extendedTextMessage: { text: message.text.body }, }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } } else { content = { conversation: message.text.body }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } } + + return content; + } + + private messageLocationJson(received: any) { + const message = received.messages[0]; + let content: any = { + locationMessage: { + degreesLatitude: message.location.latitude, + degreesLongitude: message.location.longitude, + name: message.location?.name, + address: message.location?.address, + }, + }; + message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; return content; } @@ -283,6 +343,12 @@ export class BusinessStartupService extends ChannelStartupService { case 'template': messageType = 'conversation'; break; + case 'location': + messageType = 'locationMessage'; + break; + case 'sticker': + messageType = 'stickerMessage'; + break; default: messageType = 'conversation'; break; @@ -299,12 +365,28 @@ export class BusinessStartupService extends ChannelStartupService { if (received.contacts) pushName = received.contacts[0].profile.name; if (received.messages) { + const message = received.messages[0]; // Añadir esta línea para definir message + const key = { - id: received.messages[0].id, + id: message.id, remoteJid: this.phoneNumber, - fromMe: received.messages[0].from === received.metadata.phone_number_id, + fromMe: message.from === received.metadata.phone_number_id, }; - if (this.isMediaMessage(received?.messages[0])) { + + if (message.type === 'sticker') { + this.logger.log('Procesando mensaje de tipo sticker'); + messageRaw = { + key, + pushName, + message: { + stickerMessage: message.sticker || {}, + }, + messageType: 'stickerMessage', + messageTimestamp: parseInt(message.timestamp) as number, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (this.isMediaMessage(message)) { messageRaw = { key, pushName, @@ -473,16 +555,12 @@ export class BusinessStartupService extends ChannelStartupService { openAiDefaultSettings.speechToText && audioMessage ) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - { - message: { - mediaUrl: messageRaw.message.mediaUrl, - ...messageRaw, - }, + messageRaw.message.speechToText = await this.openaiService.speechToText(openAiDefaultSettings.OpenaiCreds, { + message: { + mediaUrl: messageRaw.message.mediaUrl, + ...messageRaw, }, - () => {}, - ); + }); } } @@ -511,7 +589,7 @@ export class BusinessStartupService extends ChannelStartupService { } } - if (!this.isMediaMessage(received?.messages[0])) { + if (!this.isMediaMessage(message) && message.type !== 'sticker') { await this.prismaRepository.message.create({ data: messageRaw, }); @@ -714,17 +792,54 @@ export class BusinessStartupService extends ChannelStartupService { } protected async eventHandler(content: any) { - const database = this.configService.get('DATABASE'); - const settings = await this.findSettings(); + try { + // Registro para depuración + this.logger.log('Contenido recibido en eventHandler:'); + this.logger.log(JSON.stringify(content, null, 2)); - this.messageHandle(content, database, settings); + const database = this.configService.get('DATABASE'); + const settings = await this.findSettings(); + + // Si hay mensajes, verificar primero el tipo + if (content.messages && content.messages.length > 0) { + const message = content.messages[0]; + this.logger.log(`Tipo de mensaje recibido: ${message.type}`); + + // Verificamos el tipo de mensaje antes de procesarlo + if ( + message.type === 'text' || + message.type === 'image' || + message.type === 'video' || + message.type === 'audio' || + message.type === 'document' || + message.type === 'sticker' || + message.type === 'location' || + message.type === 'contacts' || + message.type === 'interactive' || + message.type === 'button' || + message.type === 'reaction' + ) { + // Procesar el mensaje normalmente + this.messageHandle(content, database, settings); + } else { + this.logger.warn(`Tipo de mensaje no reconocido: ${message.type}`); + } + } else if (content.statuses) { + // Procesar actualizaciones de estado + this.messageHandle(content, database, settings); + } else { + this.logger.warn('No se encontraron mensajes ni estados en el contenido recibido'); + } + } catch (error) { + this.logger.error('Error en eventHandler:'); + this.logger.error(error); + } } protected async sendMessageWithTyping(number: string, message: any, options?: Options, isIntegration = false) { try { let quoted: any; let webhookUrl: any; - const linkPreview = options?.linkPreview != false ? undefined : false; if (options?.quoted) { const m = options?.quoted; @@ -792,7 +907,7 @@ export class BusinessStartupService extends ChannelStartupService { to: number.replace(/\D/g, ''), text: { body: message['conversation'], - preview_url: linkPreview, + preview_url: Boolean(options?.linkPreview), }, }; quoted ? (content.context = { message_id: quoted.id }) : content; @@ -808,7 +923,7 @@ export class BusinessStartupService extends ChannelStartupService { to: number.replace(/\D/g, ''), [message['mediaType']]: { [message['type']]: message['id'], - preview_url: linkPreview, + preview_url: Boolean(options?.linkPreview), ...(message['fileName'] && !isImage && { filename: message['fileName'] }), caption: message['caption'], }, @@ -977,7 +1092,6 @@ export class BusinessStartupService extends ChannelStartupService { private async getIdMedia(mediaMessage: any) { const formData = new FormData(); - const fileStream = createReadStream(mediaMessage.media); formData.append('file', fileStream, { filename: 'media', contentType: mediaMessage.mimetype }); diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 10feb7ce..dbdd01d0 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1,3 +1,4 @@ +import { getCollectionsDto } from '@api/dto/business.dto'; import { OfferCallDto } from '@api/dto/call.dto'; import { ArchiveChatDto, @@ -54,7 +55,7 @@ import { import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper'; import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; import { ProviderFiles } from '@api/provider/sessions'; -import { PrismaRepository } from '@api/repository/repository.service'; +import { PrismaRepository, Query } from '@api/repository/repository.service'; import { chatbotController, waMonitor } from '@api/server.module'; import { CacheService } from '@api/services/cache.service'; import { ChannelStartupService } from '@api/services/channel.service'; @@ -77,7 +78,7 @@ import { BadRequestException, InternalServerErrorException, NotFoundException } import ffmpegPath from '@ffmpeg-installer/ffmpeg'; import { Boom } from '@hapi/boom'; import { createId as cuid } from '@paralleldrive/cuid2'; -import { Instance } from '@prisma/client'; +import { Instance, Message } from '@prisma/client'; import { createJid } from '@utils/createJid'; import { makeProxyAgent } from '@utils/makeProxyAgent'; import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache'; @@ -91,6 +92,7 @@ import makeWASocket, { BufferedEventData, BufferJSON, CacheStore, + CatalogCollection, Chat, ConnectionState, Contact, @@ -100,6 +102,7 @@ import makeWASocket, { fetchLatestBaileysVersion, generateWAMessageFromContent, getAggregateVotesInPollMessage, + GetCatalogOptions, getContentType, getDevice, GroupMetadata, @@ -113,6 +116,7 @@ import makeWASocket, { MiscMessageGenerationOptions, ParticipantAction, prepareWAMessageMedia, + Product, proto, UserFacingSocketConfig, WABrowserDescription, @@ -130,7 +134,6 @@ import { randomBytes } from 'crypto'; import EventEmitter2 from 'eventemitter2'; import ffmpeg from 'fluent-ffmpeg'; import FormData from 'form-data'; -import { readFileSync } from 'fs'; import Long from 'long'; import mimeTypes from 'mime-types'; import NodeCache from 'node-cache'; @@ -226,7 +229,10 @@ export class BaileysStartupService extends ChannelStartupService { private authStateProvider: AuthStateProvider; private readonly msgRetryCounterCache: CacheStore = new NodeCache(); - private readonly userDevicesCache: CacheStore = new NodeCache(); + private readonly userDevicesCache: CacheStore = new NodeCache({ + stdTTL: 300000, + useClones: false, + }); private endSession = false; private logBaileys = this.configService.get('LOG').BAILEYS; @@ -658,6 +664,10 @@ export class BaileysStartupService extends ChannelStartupService { qrTimeout: 45_000, emitOwnEvents: false, shouldIgnoreJid: (jid) => { + if (this.localSettings.syncFullHistory && isJidGroup(jid)) { + return false; + } + const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid); const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid); const isNewsletter = isJidNewsletter(jid); @@ -985,6 +995,17 @@ export class BaileysStartupService extends ChannelStartupService { } } + const contactsMap = new Map(); + + for (const contact of contacts) { + if (contact.id && (contact.notify || contact.name)) { + contactsMap.set(contact.id, { + name: contact.name ?? contact.notify, + jid: contact.id, + }); + } + } + const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = []; const chatsRepository = new Set( ( @@ -1056,6 +1077,15 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + if (!m.pushName && !m.key.fromMe) { + const participantJid = m.participant || m.key.participant || m.key.remoteJid; + if (participantJid && contactsMap.has(participantJid)) { + m.pushName = contactsMap.get(participantJid).name; + } else if (participantJid) { + m.pushName = participantJid.split('@')[0]; + } + } + messagesRaw.push(this.prepareMessage(m)); } @@ -1128,38 +1158,54 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { - const editedMessage = - received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; - if (editedMessage) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) - this.chatwootService.eventWhatsapp( - 'messages.edit', - { instanceName: this.instance.name, instanceId: this.instance.id }, - editedMessage, - ); + const editedMessage = + received?.message?.protocolMessage || received?.message?.editedMessage?.message?.protocolMessage; - await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage); + if (received.message?.protocolMessage?.editedMessage && editedMessage) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) + this.chatwootService.eventWhatsapp( + 'messages.edit', + { instanceName: this.instance.name, instanceId: this.instance.id }, + editedMessage, + ); + + await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage); + const oldMessage = await this.getMessage(editedMessage.key, true); + if ((oldMessage as any)?.id) { + const editedMessageTimestamp = Long.isLong(editedMessage?.timestampMs) + ? Math.floor(editedMessage.timestampMs.toNumber() / 1000) + : Math.floor((editedMessage.timestampMs as number) / 1000); + + await this.prismaRepository.message.update({ + where: { id: (oldMessage as any).id }, + data: { + message: editedMessage.editedMessage as any, + messageTimestamp: editedMessageTimestamp, + status: 'EDITED', + }, + }); + await this.prismaRepository.messageUpdate.create({ + data: { + fromMe: editedMessage.key.fromMe, + keyId: editedMessage.key.id, + remoteJid: editedMessage.key.remoteJid, + status: 'EDITED', + instanceId: this.instanceId, + messageId: (oldMessage as any).id, + }, + }); } } - if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') { - this.logger.info(`Recovering message lost messageId: ${received.key.id}`); - - await this.baileysCache.set(received.key.id, { - message: received, - retry: 0, - }); + const messageKey = `${this.instance.id}_${received.key.id}`; + const cached = await this.baileysCache.get(messageKey); + if (cached && !editedMessage) { + this.logger.info(`Message duplicated ignored: ${received.key.id}`); continue; } - const retryCache = (await this.baileysCache.get(received.key.id)) || null; - - if (retryCache) { - this.logger.info('Recovered message lost'); - await this.baileysCache.delete(received.key.id); - } + await this.baileysCache.set(messageKey, true, 5 * 60); if ( (type !== 'notify' && type !== 'append') || @@ -1177,6 +1223,7 @@ export class BaileysStartupService extends ChannelStartupService { if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) { continue; } + const existingChat = await this.prismaRepository.chat.findFirst({ where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid }, select: { id: true, name: true }, @@ -1186,7 +1233,9 @@ export class BaileysStartupService extends ChannelStartupService { existingChat && received.pushName && existingChat.name !== received.pushName && - received.pushName.trim().length > 0 + received.pushName.trim().length > 0 && + !received.key.fromMe && + !received.key.remoteJid.includes('@g.us') ) { this.sendDataWebhook(Events.CHATS_UPSERT, [{ ...existingChat, name: received.pushName }]); if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { @@ -1249,11 +1298,7 @@ export class BaileysStartupService extends ChannelStartupService { }); if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - received, - this.client.updateMediaMessage, - ); + messageRaw.message.speechToText = await this.openaiService.speechToText(received, this); } } @@ -1262,21 +1307,31 @@ export class BaileysStartupService extends ChannelStartupService { data: messageRaw, }); - if (received.key.fromMe === false) { - if (msg.status === status[3]) { - this.logger.log(`Update not read messages ${received.key.remoteJid}`); + const { remoteJid } = received.key; + const timestamp = msg.messageTimestamp; + const fromMe = received.key.fromMe.toString(); + const messageKey = `${remoteJid}_${timestamp}_${fromMe}`; - await this.updateChatUnreadMessages(received.key.remoteJid); - } else if (msg.status === status[4]) { - this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); + const cachedTimestamp = await this.baileysCache.get(messageKey); - await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + if (!cachedTimestamp) { + if (!received.key.fromMe) { + if (msg.status === status[3]) { + this.logger.log(`Update not read messages ${remoteJid}`); + await this.updateChatUnreadMessages(remoteJid); + } else if (msg.status === status[4]) { + this.logger.log(`Update readed messages ${remoteJid} - ${timestamp}`); + await this.updateMessagesReadedByTimestamp(remoteJid, timestamp); + } + } else { + // is send message by me + this.logger.log(`Update readed messages ${remoteJid} - ${timestamp}`); + await this.updateMessagesReadedByTimestamp(remoteJid, timestamp); } - } else { - // is send message by me - this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); - await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + await this.baileysCache.set(messageKey, true, 5 * 60); + } else { + this.logger.info(`Update readed messages duplicated ignored [avoid deadlock]: ${messageKey}`); } if (isMedia) { @@ -1292,7 +1347,12 @@ export class BaileysStartupService extends ChannelStartupService { const { buffer, mediaType, fileName, size } = media; const mimetype = mimeTypes.lookup(fileName).toString(); - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); + const fullName = join( + `${this.instance.id}`, + received.key.remoteJid, + mediaType, + `${Date.now()}_${fileName}`, + ); await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { 'Content-Type': mimetype, }); @@ -1335,7 +1395,24 @@ export class BaileysStartupService extends ChannelStartupService { }, ); - messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } else { + // retry to download media + const buffer = await downloadMediaMessage( + { key: received.key, message: received?.message }, + 'buffer', + {}, + { + logger: P({ level: 'error' }) as any, + reuploadRequest: this.client.updateMediaMessage, + }, + ); + + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } + } } catch (error) { this.logger.error(['Error converting media to base64', error?.message]); } @@ -1422,6 +1499,17 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + const updateKey = `${this.instance.id}_${key.id}_${update.status}`; + + const cached = await this.baileysCache.get(updateKey); + + if (cached) { + this.logger.info(`Message duplicated ignored [avoid deadlock]: ${updateKey}`); + continue; + } + + await this.baileysCache.set(updateKey, true, 30 * 60); + if (status[update.status] === 'READ' && key.fromMe) { if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( @@ -1432,7 +1520,7 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (key.remoteJid !== 'status@broadcast') { + if (key.remoteJid !== 'status@broadcast' && key.id !== undefined) { let pollUpdates: any; if (update.pollUpdates) { @@ -1460,19 +1548,20 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + const message: any = { + messageId: findMessage.id, + keyId: key.id, + remoteJid: key?.remoteJid, + fromMe: key.fromMe, + participant: key?.remoteJid, + status: status[update.status] ?? 'DELETED', + pollUpdates, + instanceId: this.instanceId, + }; + if (update.message === null && update.status === undefined) { this.sendDataWebhook(Events.MESSAGES_DELETE, key); - const message: any = { - messageId: findMessage.id, - keyId: key.id, - remoteJid: key.remoteJid, - fromMe: key.fromMe, - participant: key?.remoteJid, - status: 'DELETED', - instanceId: this.instanceId, - }; - if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) await this.prismaRepository.messageUpdate.create({ data: message, @@ -1491,29 +1580,32 @@ export class BaileysStartupService extends ChannelStartupService { if (!key.fromMe && key.remoteJid) { readChatToUpdate[key.remoteJid] = true; - if (status[update.status] === status[4]) { - this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`); - this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp); + const { remoteJid } = key; + const timestamp = findMessage.messageTimestamp; + const fromMe = key.fromMe.toString(); + const messageKey = `${remoteJid}_${timestamp}_${fromMe}`; + + const cachedTimestamp = await this.baileysCache.get(messageKey); + + if (!cachedTimestamp) { + if (status[update.status] === status[4]) { + this.logger.log(`Update as read in message.update ${remoteJid} - ${timestamp}`); + await this.updateMessagesReadedByTimestamp(remoteJid, timestamp); + await this.baileysCache.set(messageKey, true, 5 * 60); + } + + await this.prismaRepository.message.update({ + where: { id: findMessage.id }, + data: { status: status[update.status] }, + }); + } else { + this.logger.info( + `Update readed messages duplicated ignored in message.update [avoid deadlock]: ${messageKey}`, + ); } } - - await this.prismaRepository.message.update({ - where: { id: findMessage.id }, - data: { status: status[update.status] }, - }); } - const message: any = { - messageId: findMessage.id, - keyId: key.id, - remoteJid: key.remoteJid, - fromMe: key.fromMe, - participant: key?.remoteJid, - status: status[update.status], - pollUpdates, - instanceId: this.instanceId, - }; - this.sendDataWebhook(Events.MESSAGES_UPDATE, message); if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) @@ -1529,7 +1621,6 @@ export class BaileysStartupService extends ChannelStartupService { const chatToInsert = { remoteJid: message.remoteJid, instanceId: this.instanceId, - name: message.pushName || '', unreadMessages: 0, }; @@ -2233,11 +2324,7 @@ export class BaileysStartupService extends ChannelStartupService { }); if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - messageRaw, - this.client.updateMediaMessage, - ); + messageRaw.message.speechToText = await this.openaiService.speechToText(messageRaw, this); } } @@ -2309,7 +2396,24 @@ export class BaileysStartupService extends ChannelStartupService { }, ); - messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } else { + // retry to download media + const buffer = await downloadMediaMessage( + { key: messageRaw.key, message: messageRaw?.message }, + 'buffer', + {}, + { + logger: P({ level: 'error' }) as any, + reuploadRequest: this.client.updateMediaMessage, + }, + ); + + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } + } } catch (error) { this.logger.error(['Error converting media to base64', error?.message]); } @@ -2654,9 +2758,6 @@ export class BaileysStartupService extends ChannelStartupService { prepareMedia[mediaType].fileName = mediaMessage.fileName; if (mediaMessage.mediatype === 'video') { - prepareMedia[mediaType].jpegThumbnail = Uint8Array.from( - readFileSync(join(process.cwd(), 'public', 'images', 'video-cover.png')), - ); prepareMedia[mediaType].gifPlayback = false; } @@ -2703,21 +2804,43 @@ export class BaileysStartupService extends ChannelStartupService { imageBuffer = Buffer.from(response.data, 'binary'); } - const webpBuffer = await sharp(imageBuffer).webp().toBuffer(); + const isAnimated = this.isAnimated(image, imageBuffer); - return webpBuffer; + if (isAnimated) { + return await sharp(imageBuffer, { animated: true }).webp({ quality: 80 }).toBuffer(); + } else { + return await sharp(imageBuffer).webp().toBuffer(); + } } catch (error) { console.error('Erro ao converter a imagem para WebP:', error); throw error; } } + private isAnimatedWebp(buffer: Buffer): boolean { + if (buffer.length < 12) return false; + + return buffer.indexOf(Buffer.from('ANIM')) !== -1; + } + + private isAnimated(image: string, buffer: Buffer): boolean { + const lowerCaseImage = image.toLowerCase(); + + if (lowerCaseImage.includes('.gif')) return true; + + if (lowerCaseImage.includes('.webp')) return this.isAnimatedWebp(buffer); + + return false; + } + public async mediaSticker(data: SendStickerDto, file?: any) { const mediaData: SendStickerDto = { ...data }; if (file) mediaData.sticker = file.buffer.toString('base64'); - const convert = await this.convertToWebP(data.sticker); + const convert = data?.notConvertSticker + ? Buffer.from(data.sticker, 'base64') + : await this.convertToWebP(data.sticker); const gifPlayback = data.sticker.includes('.gif'); const result = await this.sendMessageWithTyping( data.number, @@ -2923,7 +3046,29 @@ export class BaileysStartupService extends ChannelStartupService { .noVideo() .audioCodec('libopus') .addOutputOptions('-avoid_negative_ts make_zero') + .audioBitrate('128k') + .audioFrequency(48000) .audioChannels(1) + .outputOptions([ + '-write_xing', + '0', + '-compression_level', + '10', + '-application', + 'voip', + '-fflags', + '+bitexact', + '-flags', + '+bitexact', + '-id3v2_version', + '0', + '-map_metadata', + '-1', + '-map_chapters', + '-1', + '-write_bext', + '0', + ]) .pipe(outputAudioStream, { end: true }) .on('error', function (error) { console.log('error', error); @@ -3573,6 +3718,18 @@ export class BaileysStartupService extends ChannelStartupService { status: 'DELETED', }, }); + const messageUpdate: any = { + messageId: message.id, + keyId: messageId, + remoteJid: response.key.remoteJid, + fromMe: response.key.fromMe, + participant: response.key?.remoteJid, + status: 'DELETED', + instanceId: this.instanceId, + }; + await this.prismaRepository.messageUpdate.create({ + data: messageUpdate, + }); } else { await this.prismaRepository.message.deleteMany({ where: { @@ -3618,6 +3775,10 @@ export class BaileysStartupService extends ChannelStartupService { } } + if ('messageContextInfo' in msg.message && Object.keys(msg.message).length === 1) { + throw 'The message is messageContextInfo'; + } + let mediaMessage: any; let mediaType: string; @@ -3899,13 +4060,84 @@ export class BaileysStartupService extends ChannelStartupService { } try { - return await this.client.sendMessage(jid, { + const oldMessage: any = await this.getMessage(data.key, true); + if (!oldMessage) throw new NotFoundException('Message not found'); + if (oldMessage?.key?.remoteJid !== jid) { + throw new BadRequestException('RemoteJid does not match'); + } + if (oldMessage?.messageTimestamp > Date.now() + 900000) { + // 15 minutes in milliseconds + throw new BadRequestException('Message is older than 15 minutes'); + } + + const messageSent = await this.client.sendMessage(jid, { ...(options as any), edit: data.key, }); + if (messageSent) { + const editedMessage = + messageSent?.message?.protocolMessage || messageSent?.message?.editedMessage?.message?.protocolMessage; + + if (editedMessage) { + this.sendDataWebhook(Events.SEND_MESSAGE_UPDATE, editedMessage); + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) + this.chatwootService.eventWhatsapp( + 'send.message.update', + { instanceName: this.instance.name, instanceId: this.instance.id }, + editedMessage, + ); + + const messageId = messageSent.message?.protocolMessage?.key?.id; + if (messageId) { + let message = await this.prismaRepository.message.findFirst({ + where: { + key: { + path: ['id'], + equals: messageId, + }, + }, + }); + if (!message) throw new NotFoundException('Message not found'); + + if (!(message.key.valueOf() as any).fromMe) { + new BadRequestException('You cannot edit others messages'); + } + if ((message.key.valueOf() as any)?.deleted) { + new BadRequestException('You cannot edit deleted messages'); + } + if (oldMessage.messageType === 'conversation' || oldMessage.messageType === 'extendedTextMessage') { + oldMessage.message.conversation = data.text; + } else { + oldMessage.message[oldMessage.messageType].caption = data.text; + } + message = await this.prismaRepository.message.update({ + where: { id: message.id }, + data: { + message: oldMessage.message, + status: 'EDITED', + messageTimestamp: Math.floor(Date.now() / 1000), // Convert to int32 by dividing by 1000 to get seconds + }, + }); + const messageUpdate: any = { + messageId: message.id, + keyId: messageId, + remoteJid: messageSent.key.remoteJid, + fromMe: messageSent.key.fromMe, + participant: messageSent.key?.remoteJid, + status: 'EDITED', + instanceId: this.instanceId, + }; + await this.prismaRepository.messageUpdate.create({ + data: messageUpdate, + }); + } + } + } + + return messageSent; } catch (error) { this.logger.error(error); - throw new BadRequestException(error.toString()); + throw error; } } @@ -4299,7 +4531,11 @@ export class BaileysStartupService extends ChannelStartupService { const messageRaw = { key: message.key, - pushName: message.pushName, + pushName: + message.pushName || + (message.key.fromMe + ? 'Você' + : message?.participant || (message.key?.participant ? message.key.participant.split('@')[0] : null)), status: status[message.status], message: { ...message.message }, contextInfo: contentMsg?.contextInfo, @@ -4534,4 +4770,245 @@ export class BaileysStartupService extends ChannelStartupService { return response; } + + //Business Controller + public async fetchCatalog(instanceName: string, data: getCollectionsDto) { + const jid = data.number ? createJid(data.number) : this.client?.user?.id; + const limit = data.limit || 10; + const cursor = null; + + const onWhatsapp = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + + if (!onWhatsapp.exists) { + throw new BadRequestException(onWhatsapp); + } + + try { + const info = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + const business = await this.fetchBusinessProfile(info?.jid); + + let catalog = await this.getCatalog({ jid: info?.jid, limit, cursor }); + let nextPageCursor = catalog.nextPageCursor; + let nextPageCursorJson = nextPageCursor ? JSON.parse(atob(nextPageCursor)) : null; + let pagination = nextPageCursorJson?.pagination_cursor + ? JSON.parse(atob(nextPageCursorJson.pagination_cursor)) + : null; + let fetcherHasMore = pagination?.fetcher_has_more === true ? true : false; + + let productsCatalog = catalog.products || []; + let countLoops = 0; + while (fetcherHasMore && countLoops < 4) { + catalog = await this.getCatalog({ jid: info?.jid, limit, cursor: nextPageCursor }); + nextPageCursor = catalog.nextPageCursor; + nextPageCursorJson = nextPageCursor ? JSON.parse(atob(nextPageCursor)) : null; + pagination = nextPageCursorJson?.pagination_cursor + ? JSON.parse(atob(nextPageCursorJson.pagination_cursor)) + : null; + fetcherHasMore = pagination?.fetcher_has_more === true ? true : false; + productsCatalog = [...productsCatalog, ...catalog.products]; + countLoops++; + } + + return { + wuid: info?.jid || jid, + numberExists: info?.exists, + isBusiness: business.isBusiness, + catalogLength: productsCatalog.length, + catalog: productsCatalog, + }; + } catch (error) { + console.log(error); + return { + wuid: jid, + name: null, + isBusiness: false, + }; + } + } + + public async getCatalog({ + jid, + limit, + cursor, + }: GetCatalogOptions): Promise<{ products: Product[]; nextPageCursor: string | undefined }> { + try { + jid = jid ? createJid(jid) : this.instance.wuid; + + const catalog = await this.client.getCatalog({ jid, limit: limit, cursor: cursor }); + + if (!catalog) { + return { + products: undefined, + nextPageCursor: undefined, + }; + } + + return catalog; + } catch (error) { + throw new InternalServerErrorException('Error getCatalog', error.toString()); + } + } + + public async fetchCollections(instanceName: string, data: getCollectionsDto) { + const jid = data.number ? createJid(data.number) : this.client?.user?.id; + const limit = data.limit <= 20 ? data.limit : 20; //(tem esse limite, não sei porque) + + const onWhatsapp = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + + if (!onWhatsapp.exists) { + throw new BadRequestException(onWhatsapp); + } + + try { + const info = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + const business = await this.fetchBusinessProfile(info?.jid); + const collections = await this.getCollections(info?.jid, limit); + + return { + wuid: info?.jid || jid, + name: info?.name, + numberExists: info?.exists, + isBusiness: business.isBusiness, + collectionsLength: collections?.length, + collections: collections, + }; + } catch (error) { + return { + wuid: jid, + name: null, + isBusiness: false, + }; + } + } + + public async getCollections(jid?: string | undefined, limit?: number): Promise { + try { + jid = jid ? createJid(jid) : this.instance.wuid; + + const result = await this.client.getCollections(jid, limit); + + if (!result) { + return [ + { + id: undefined, + name: undefined, + products: [], + status: undefined, + }, + ]; + } + + return result.collections; + } catch (error) { + throw new InternalServerErrorException('Error getCatalog', error.toString()); + } + } + + public async fetchMessages(query: Query) { + const keyFilters = query?.where?.key as { + id?: string; + fromMe?: boolean; + remoteJid?: string; + participants?: string; + }; + + const timestampFilter = {}; + if (query?.where?.messageTimestamp) { + if (query.where.messageTimestamp['gte'] && query.where.messageTimestamp['lte']) { + timestampFilter['messageTimestamp'] = { + gte: Math.floor(new Date(query.where.messageTimestamp['gte']).getTime() / 1000), + lte: Math.floor(new Date(query.where.messageTimestamp['lte']).getTime() / 1000), + }; + } + } + + const count = await this.prismaRepository.message.count({ + where: { + instanceId: this.instanceId, + id: query?.where?.id, + source: query?.where?.source, + messageType: query?.where?.messageType, + ...timestampFilter, + AND: [ + keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, + keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, + keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, + keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, + ], + }, + }); + + if (!query?.offset) { + query.offset = 50; + } + + if (!query?.page) { + query.page = 1; + } + + const messages = await this.prismaRepository.message.findMany({ + where: { + instanceId: this.instanceId, + id: query?.where?.id, + source: query?.where?.source, + messageType: query?.where?.messageType, + ...timestampFilter, + AND: [ + keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, + keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, + keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, + keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, + ], + }, + orderBy: { + messageTimestamp: 'desc', + }, + skip: query.offset * (query?.page === 1 ? 0 : (query?.page as number) - 1), + take: query.offset, + select: { + id: true, + key: true, + pushName: true, + messageType: true, + message: true, + messageTimestamp: true, + instanceId: true, + source: true, + contextInfo: true, + MessageUpdate: { + select: { + status: true, + }, + }, + }, + }); + + const formattedMessages = messages.map((message) => { + const messageKey = message.key as { fromMe: boolean; remoteJid: string; id: string; participant?: string }; + + if (!message.pushName) { + if (messageKey.fromMe) { + message.pushName = 'Você'; + } else if (message.contextInfo) { + const contextInfo = message.contextInfo as { participant?: string }; + if (contextInfo.participant) { + message.pushName = contextInfo.participant.split('@')[0]; + } else if (messageKey.participant) { + message.pushName = messageKey.participant.split('@')[0]; + } + } + } + + return message; + }); + + return { + messages: { + total: count, + pages: Math.ceil(count / query.offset), + currentPage: query.page, + records: formattedMessages, + }, + }; + } } diff --git a/src/api/integrations/chatbot/base-chatbot.controller.ts b/src/api/integrations/chatbot/base-chatbot.controller.ts new file mode 100644 index 00000000..dab51e25 --- /dev/null +++ b/src/api/integrations/chatbot/base-chatbot.controller.ts @@ -0,0 +1,929 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { TriggerOperator, TriggerType } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; + +import { BaseChatbotDto } from './base-chatbot.dto'; +import { ChatbotController, ChatbotControllerInterface, EmitData } from './chatbot.controller'; + +// Common settings interface for all chatbot integrations +export interface ChatbotSettings { + expire: number; + keywordFinish: string; + delayMessage: number; + unknownMessage: string; + listeningFromMe: boolean; + stopBotFromMe: boolean; + keepOpen: boolean; + debounceTime: number; + ignoreJids: string[]; + splitMessages: boolean; + timePerChar: number; + [key: string]: any; +} + +// Common bot properties for all chatbot integrations +export interface BaseBotData { + enabled?: boolean; + description: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType: string | TriggerType; + triggerOperator?: string | TriggerOperator; + triggerValue?: string; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; + [key: string]: any; +} + +export abstract class BaseChatbotController + extends ChatbotController + implements ChatbotControllerInterface +{ + public readonly logger: Logger; + + integrationEnabled: boolean; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Name of the integration, to be set by the derived class + protected abstract readonly integrationName: string; + + // Method to process bot-specific logic + protected abstract processBot( + waInstance: any, + remoteJid: string, + bot: BotType, + session: any, + settings: ChatbotSettings, + content: string, + pushName?: string, + msg?: any, + ): Promise; + + // Method to get the fallback bot ID from settings + protected abstract getFallbackBotId(settings: any): string | undefined; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + + this.sessionRepository = this.prismaRepository.integrationSession; + } + + // Base create bot implementation + public async createBot(instance: InstanceDto, data: BotData) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // Set default settings if not provided + if ( + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids || + !data.splitMessages || + !data.timePerChar + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck?.expire; + if (data.keywordFinish === undefined || data.keywordFinish === null) + data.keywordFinish = defaultSettingCheck?.keywordFinish; + if (data.delayMessage === undefined || data.delayMessage === null) + data.delayMessage = defaultSettingCheck?.delayMessage; + if (data.unknownMessage === undefined || data.unknownMessage === null) + data.unknownMessage = defaultSettingCheck?.unknownMessage; + if (data.listeningFromMe === undefined || data.listeningFromMe === null) + data.listeningFromMe = defaultSettingCheck?.listeningFromMe; + if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) + data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe; + if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck?.keepOpen; + if (data.debounceTime === undefined || data.debounceTime === null) + data.debounceTime = defaultSettingCheck?.debounceTime; + if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck?.ignoreJids; + if (data.splitMessages === undefined || data.splitMessages === null) + data.splitMessages = defaultSettingCheck?.splitMessages ?? false; + if (data.timePerChar === undefined || data.timePerChar === null) + data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error( + `You already have a ${this.integrationName} with an "All" trigger, you cannot have more bots while it is active`, + ); + } + + // Check for trigger keyword duplicates + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Check for trigger advanced duplicates + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Derived classes should implement the specific duplicate checking before calling this method + // and add bot-specific fields to the data object + + try { + const botData = { + enabled: data?.enabled, + description: data.description, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + ...this.getAdditionalBotData(data), + }; + + const bot = await this.botRepository.create({ + data: botData, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error(`Error creating ${this.integrationName}`); + } + } + + // Additional fields needed for specific bot types + protected abstract getAdditionalBotData(data: BotData): Record; + + // Common implementation for findBot + public async findBot(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + try { + const bots = await this.botRepository.findMany({ + where: { + instanceId: instanceId, + }, + }); + + return bots; + } catch (error) { + this.logger.error(error); + throw new Error(`Error finding ${this.integrationName}`); + } + } + + // Common implementation for fetchBot + public async fetchBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const bot = await this.botRepository.findUnique({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error(`${this.integrationName} not found`); + } + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error(`Error fetching ${this.integrationName}`); + } + } + + // Common implementation for settings + public async settings(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const existingSettings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + // Get the name of the fallback field for this integration type + const fallbackFieldName = this.getFallbackFieldName(); + + const settingsData = { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + [fallbackFieldName]: data.fallbackId, // Use the correct field name dynamically + }; + + if (existingSettings) { + const settings = await this.settingsRepository.update({ + where: { + id: existingSettings.id, + }, + data: settingsData, + }); + + // Map the specific fallback field to a generic 'fallbackId' in the response + return { + ...settings, + fallbackId: settings[fallbackFieldName], + }; + } else { + const settings = await this.settingsRepository.create({ + data: { + ...settingsData, + Instance: { + connect: { + id: instanceId, + }, + }, + }, + }); + + // Map the specific fallback field to a generic 'fallbackId' in the response + return { + ...settings, + fallbackId: settings[fallbackFieldName], + }; + } + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Abstract method to get the field name for the fallback ID + protected abstract getFallbackFieldName(): string; + + // Abstract method to get the integration type (dify, n8n, evoai, etc.) + protected abstract getIntegrationType(): string; + + // Common implementation for fetchSettings + public async fetchSettings(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + // Get the name of the fallback field for this integration type + const fallbackFieldName = this.getFallbackFieldName(); + + if (!settings) { + return { + expire: 300, + keywordFinish: 'bye', + delayMessage: 1000, + unknownMessage: 'Sorry, I dont understand', + listeningFromMe: true, + stopBotFromMe: true, + keepOpen: false, + debounceTime: 1, + ignoreJids: [], + splitMessages: false, + timePerChar: 0, + fallbackId: '', + fallback: null, + }; + } + + // Return with standardized fallbackId field + return { + ...settings, + fallbackId: settings[fallbackFieldName], + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching settings'); + } + } + + // Common implementation for changeStatus + public async changeStatus(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + const remoteJid = data.remoteJid; + const status = data.status; + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + + return { bot: { remoteJid: remoteJid, status: status } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + } + + return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; + } else { + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const botData = { + remoteJid: remoteJid, + status: status, + session, + }; + + return { bot: { ...instance, bot: botData } }; + } + } catch (error) { + this.logger.error(error); + throw new Error(`Error changing ${this.integrationName} status`); + } + } + + // Common implementation for fetchSessions + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (bot && bot.instanceId !== instanceId) { + throw new Error(`${this.integrationName} not found`); + } + + // Get the integration type (dify, n8n, evoai, etc.) + const integrationType = this.getIntegrationType(); + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: bot ? botId : { not: null }, + type: integrationType, + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + // Common implementation for ignoreJid + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Base implementation for updateBot + public async updateBot(instance: InstanceDto, botId: string, data: BotData) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error(`${this.integrationName} not found`); + } + + if (bot.instanceId !== instanceId) { + throw new Error(`${this.integrationName} not found`); + } + + // Check for "all" trigger type conflicts + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error( + `You already have a ${this.integrationName} with an "All" trigger, you cannot have more bots while it is active`, + ); + } + } + + // Let subclasses check for integration-specific duplicates + await this.validateNoDuplicatesOnUpdate(botId, instanceId, data); + + // Check for keyword trigger duplicates + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Check for advanced trigger duplicates + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Combine common fields with bot-specific fields + const updateData = { + enabled: data?.enabled, + description: data.description, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + ...this.getAdditionalUpdateFields(data), + }; + + const updatedBot = await this.botRepository.update({ + where: { + id: botId, + }, + data: updateData, + }); + + return updatedBot; + } catch (error) { + this.logger.error(error); + throw new Error(`Error updating ${this.integrationName}`); + } + } + + // Abstract method for validating bot-specific duplicates on update + protected abstract validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: BotData): Promise; + + // Abstract method for getting additional fields for update + protected abstract getAdditionalUpdateFields(data: BotData): Record; + + // Base implementation for deleteBot + public async deleteBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error(`${this.integrationName} not found`); + } + + if (bot.instanceId !== instanceId) { + throw new Error(`${this.integrationName} not found`); + } + + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { bot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error(`Error deleting ${this.integrationName} bot`); + } + } + + // Base implementation for emit + public async emit({ instance, remoteJid, msg }: EmitData) { + if (!this.integrationEnabled) return; + + try { + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; + + const session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + // Get integration type + // const integrationType = this.getIntegrationType(); + + // Find a bot for this message + let findBot: any = await this.findBotTrigger(this.botRepository, content, instance, session); + + // If no bot is found, try to use fallback + if (!findBot) { + const fallback = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + // Get the fallback ID for this integration type + const fallbackId = this.getFallbackBotId(fallback); + + if (fallbackId) { + const findFallback = await this.botRepository.findFirst({ + where: { + id: fallbackId, + }, + }); + + findBot = findFallback; + } else { + return; + } + } + + // If we still don't have a bot, return + if (!findBot) { + return; + } + + // Collect settings with fallbacks to default settings + let expire = findBot.expire; + let keywordFinish = findBot.keywordFinish; + let delayMessage = findBot.delayMessage; + let unknownMessage = findBot.unknownMessage; + let listeningFromMe = findBot.listeningFromMe; + let stopBotFromMe = findBot.stopBotFromMe; + let keepOpen = findBot.keepOpen; + let debounceTime = findBot.debounceTime; + let ignoreJids = findBot.ignoreJids; + let splitMessages = findBot.splitMessages; + let timePerChar = findBot.timePerChar; + + if (expire === undefined || expire === null) expire = settings.expire; + if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; + if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; + if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; + if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; + if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; + if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; + if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; + if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; + if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; + if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + // Handle stopping the bot if message is from me + if (stopBotFromMe && key.fromMe && session) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + return; + } + + // Skip if not listening to messages from me + if (!listeningFromMe && key.fromMe) { + return; + } + + // Skip if session exists but not awaiting user input + if (session && session.status === 'closed') { + return; + } + + // Merged settings + const mergedSettings = { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + splitMessages, + timePerChar, + }; + + // Process with debounce if needed + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + await this.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + mergedSettings, + debouncedContent, + msg?.pushName, + msg, + ); + }); + } else { + await this.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + mergedSettings, + content, + msg?.pushName, + msg, + ); + } + } catch (error) { + this.logger.error(error); + } + } +} diff --git a/src/api/integrations/chatbot/base-chatbot.dto.ts b/src/api/integrations/chatbot/base-chatbot.dto.ts new file mode 100644 index 00000000..7bc2e56a --- /dev/null +++ b/src/api/integrations/chatbot/base-chatbot.dto.ts @@ -0,0 +1,42 @@ +import { TriggerOperator, TriggerType } from '@prisma/client'; + +/** + * Base DTO for all chatbot integrations + * Contains common properties shared by all chatbot types + */ +export class BaseChatbotDto { + enabled?: boolean; + description: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType: TriggerType; + triggerOperator?: TriggerOperator; + triggerValue?: string; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; +} + +/** + * Base settings DTO for all chatbot integrations + */ +export class BaseChatbotSettingDto { + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + ignoreJids?: any; + splitMessages?: boolean; + timePerChar?: number; + fallbackId?: string; // Unified fallback ID field for all integrations +} diff --git a/src/api/integrations/chatbot/base-chatbot.service.ts b/src/api/integrations/chatbot/base-chatbot.service.ts new file mode 100644 index 00000000..f19cb9d4 --- /dev/null +++ b/src/api/integrations/chatbot/base-chatbot.service.ts @@ -0,0 +1,412 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { IntegrationSession } from '@prisma/client'; + +/** + * Base class for all chatbot service implementations + * Contains common methods shared across different chatbot integrations + */ +export abstract class BaseChatbotService { + protected readonly logger: Logger; + protected readonly waMonitor: WAMonitoringService; + protected readonly prismaRepository: PrismaRepository; + protected readonly configService?: ConfigService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + loggerName: string, + configService?: ConfigService, + ) { + this.waMonitor = waMonitor; + this.prismaRepository = prismaRepository; + this.logger = new Logger(loggerName); + this.configService = configService; + } + + /** + * Check if a message contains an image + */ + protected isImageMessage(content: string): boolean { + return content.includes('imageMessage'); + } + + /** + * Check if a message contains audio + */ + protected isAudioMessage(content: string): boolean { + return content.includes('audioMessage'); + } + + /** + * Check if a string is valid JSON + */ + protected isJSON(str: string): boolean { + try { + JSON.parse(str); + return true; + } catch (e) { + return false; + } + } + + /** + * Determine the media type from a URL based on its extension + */ + protected getMediaType(url: string): string | null { + const extension = url.split('.').pop()?.toLowerCase(); + const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; + const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; + const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; + const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; + + if (imageExtensions.includes(extension || '')) return 'image'; + if (audioExtensions.includes(extension || '')) return 'audio'; + if (videoExtensions.includes(extension || '')) return 'video'; + if (documentExtensions.includes(extension || '')) return 'document'; + return null; + } + + /** + * Create a new chatbot session + */ + public async createNewSession(instance: InstanceDto | any, data: any, type: string) { + try { + // Extract pushName safely - if data.pushName is an object with a pushName property, use that + const pushNameValue = + typeof data.pushName === 'object' && data.pushName?.pushName + ? data.pushName.pushName + : typeof data.pushName === 'string' + ? data.pushName + : null; + + // Extract remoteJid safely + const remoteJidValue = + typeof data.remoteJid === 'object' && data.remoteJid?.remoteJid ? data.remoteJid.remoteJid : data.remoteJid; + + const session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: remoteJidValue, + pushName: pushNameValue, + sessionId: remoteJidValue, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: type, + }, + }); + + return { session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + /** + * Standard implementation for processing incoming messages + * This handles the common workflow across all chatbot types: + * 1. Check for existing session or create new one + * 2. Handle message based on session state + */ + public async process( + instance: any, + remoteJid: string, + bot: BotType, + session: IntegrationSession, + settings: SettingsType, + content: string, + pushName?: string, + msg?: any, + ): Promise { + try { + // For new sessions or sessions awaiting initialization + if (!session) { + await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName, msg); + return; + } + + // If session is paused, ignore the message + if (session.status === 'paused') { + return; + } + + // For existing sessions, keywords might indicate the conversation should end + const keywordFinish = (settings as any)?.keywordFinish || ''; + const normalizedContent = content.toLowerCase().trim(); + if (keywordFinish.length > 0 && normalizedContent === keywordFinish.toLowerCase()) { + // Update session to closed and return + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + return; + } + + // Forward the message to the chatbot API + await this.sendMessageToBot(instance, session, settings, bot, remoteJid, pushName || '', content, msg); + + // Update session to indicate we're waiting for user response + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } catch (error) { + this.logger.error(`Error in process: ${error}`); + return; + } + } + + /** + * Standard implementation for sending messages to WhatsApp + * This handles common patterns like markdown links and formatting + */ + protected async sendMessageWhatsApp( + instance: any, + remoteJid: string, + message: string, + settings: SettingsType, + ): Promise { + if (!message) return; + + const linkRegex = /!?\[(.*?)\]\((.*?)\)/g; + let textBuffer = ''; + let lastIndex = 0; + let match: RegExpExecArray | null; + + const splitMessages = (settings as any)?.splitMessages ?? false; + + while ((match = linkRegex.exec(message)) !== null) { + const [fullMatch, altText, url] = match; + const mediaType = this.getMediaType(url); + const beforeText = message.slice(lastIndex, match.index); + + if (beforeText) { + textBuffer += beforeText; + } + + if (mediaType) { + // Send accumulated text before sending media + if (textBuffer.trim()) { + await this.sendFormattedText(instance, remoteJid, textBuffer.trim(), settings, splitMessages); + textBuffer = ''; + } + + // Handle sending the media + try { + if (mediaType === 'audio') { + await instance.audioWhatsapp({ + number: remoteJid.split('@')[0], + delay: (settings as any)?.delayMessage || 1000, + audio: url, + caption: altText, + }); + } else { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: (settings as any)?.delayMessage || 1000, + mediatype: mediaType, + media: url, + caption: altText, + fileName: mediaType === 'document' ? altText || 'document' : undefined, + }, + null, + false, + ); + } + } catch (error) { + this.logger.error(`Error sending media: ${error}`); + // If media fails, at least send the alt text and URL + textBuffer += `${altText}: ${url}`; + } + } else { + // It's a regular link, keep it in the text + textBuffer += fullMatch; + } + + lastIndex = linkRegex.lastIndex; + } + + // Add any remaining text after the last match + if (lastIndex < message.length) { + const remainingText = message.slice(lastIndex); + if (remainingText.trim()) { + textBuffer += remainingText; + } + } + + // Send any remaining text + if (textBuffer.trim()) { + await this.sendFormattedText(instance, remoteJid, textBuffer.trim(), settings, splitMessages); + } + } + + /** + * Helper method to send formatted text with proper typing indicators and delays + */ + private async sendFormattedText( + instance: any, + remoteJid: string, + text: string, + settings: any, + splitMessages: boolean, + ): Promise { + const timePerChar = settings?.timePerChar ?? 0; + const minDelay = 1000; + const maxDelay = 20000; + + if (splitMessages) { + const multipleMessages = text.split('\n\n'); + for (let index = 0; index < multipleMessages.length; index++) { + const message = multipleMessages[index]; + if (!message.trim()) continue; + + const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + await new Promise((resolve) => { + setTimeout(async () => { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: message, + }, + false, + ); + resolve(); + }, delay); + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); + } + } + } else { + const delay = Math.min(Math.max(text.length * timePerChar, minDelay), maxDelay); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + await new Promise((resolve) => { + setTimeout(async () => { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: text, + }, + false, + ); + resolve(); + }, delay); + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); + } + } + } + + /** + * Standard implementation for initializing a new session + * This method should be overridden if a subclass needs specific initialization + */ + protected async initNewSession( + instance: any, + remoteJid: string, + bot: BotType, + settings: SettingsType, + session: IntegrationSession, + content: string, + pushName?: string | any, + msg?: any, + ): Promise { + // Create a session if none exists + if (!session) { + // Extract pushName properly - if it's an object with pushName property, use that + const pushNameValue = + typeof pushName === 'object' && pushName?.pushName + ? pushName.pushName + : typeof pushName === 'string' + ? pushName + : null; + + const sessionResult = await this.createNewSession( + { + instanceName: instance.instanceName, + instanceId: instance.instanceId, + }, + { + remoteJid, + pushName: pushNameValue, + botId: (bot as any).id, + }, + this.getBotType(), + ); + + if (!sessionResult || !sessionResult.session) { + this.logger.error('Failed to create new session'); + return; + } + + session = sessionResult.session; + } + + // Update session status to opened + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + // Forward the message to the chatbot + await this.sendMessageToBot(instance, session, settings, bot, remoteJid, pushName || '', content, msg); + } + + /** + * Get the bot type identifier (e.g., 'dify', 'n8n', 'evoai') + * This should match the type field used in the IntegrationSession + */ + protected abstract getBotType(): string; + + /** + * Send a message to the chatbot API + * This is specific to each chatbot integration + */ + protected abstract sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: SettingsType, + bot: BotType, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise; +} diff --git a/src/api/integrations/chatbot/chatbot.controller.ts b/src/api/integrations/chatbot/chatbot.controller.ts index f99b4fae..ef9a2b38 100644 --- a/src/api/integrations/chatbot/chatbot.controller.ts +++ b/src/api/integrations/chatbot/chatbot.controller.ts @@ -2,8 +2,10 @@ import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { difyController, + evoaiController, evolutionBotController, flowiseController, + n8nController, openaiController, typebotController, } from '@api/server.module'; @@ -97,6 +99,10 @@ export class ChatbotController { await difyController.emit(emitData); + await n8nController.emit(emitData); + + await evoaiController.emit(emitData); + await flowiseController.emit(emitData); } @@ -173,7 +179,7 @@ export class ChatbotController { if (session) { if (session.status !== 'closed' && !session.botId) { this.logger.warn('Session is already opened in another integration'); - return; + return null; } else if (!session.botId) { session = null; } diff --git a/src/api/integrations/chatbot/chatbot.router.ts b/src/api/integrations/chatbot/chatbot.router.ts index 19fc74b7..10a52083 100644 --- a/src/api/integrations/chatbot/chatbot.router.ts +++ b/src/api/integrations/chatbot/chatbot.router.ts @@ -4,8 +4,10 @@ import { OpenaiRouter } from '@api/integrations/chatbot/openai/routes/openai.rou import { TypebotRouter } from '@api/integrations/chatbot/typebot/routes/typebot.router'; import { Router } from 'express'; +import { EvoaiRouter } from './evoai/routes/evoai.router'; import { EvolutionBotRouter } from './evolutionBot/routes/evolutionBot.router'; import { FlowiseRouter } from './flowise/routes/flowise.router'; +import { N8nRouter } from './n8n/routes/n8n.router'; export class ChatbotRouter { public readonly router: Router; @@ -19,5 +21,7 @@ export class ChatbotRouter { this.router.use('/openai', new OpenaiRouter(...guards).router); this.router.use('/dify', new DifyRouter(...guards).router); this.router.use('/flowise', new FlowiseRouter(...guards).router); + this.router.use('/n8n', new N8nRouter(...guards).router); + this.router.use('/evoai', new EvoaiRouter(...guards).router); } } diff --git a/src/api/integrations/chatbot/chatbot.schema.ts b/src/api/integrations/chatbot/chatbot.schema.ts index efc2388f..4712a70d 100644 --- a/src/api/integrations/chatbot/chatbot.schema.ts +++ b/src/api/integrations/chatbot/chatbot.schema.ts @@ -1,6 +1,8 @@ export * from '@api/integrations/chatbot/chatwoot/validate/chatwoot.schema'; export * from '@api/integrations/chatbot/dify/validate/dify.schema'; +export * from '@api/integrations/chatbot/evoai/validate/evoai.schema'; export * from '@api/integrations/chatbot/evolutionBot/validate/evolutionBot.schema'; export * from '@api/integrations/chatbot/flowise/validate/flowise.schema'; +export * from '@api/integrations/chatbot/n8n/validate/n8n.schema'; export * from '@api/integrations/chatbot/openai/validate/openai.schema'; export * from '@api/integrations/chatbot/typebot/validate/typebot.schema'; diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index 77b58bbe..d08079a4 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -543,216 +543,220 @@ export class ChatwootService { } public async createConversation(instance: InstanceDto, body: any) { + const remoteJid = body.key.remoteJid; + const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`; + const lockKey = `${instance.instanceName}:lock:createConversation-${remoteJid}`; + const maxWaitTime = 5000; // 5 secounds + try { - this.logger.verbose('--- Start createConversation ---'); + this.logger.verbose(`--- Start createConversation ---`); this.logger.verbose(`Instance: ${JSON.stringify(instance)}`); - const client = await this.clientCw(instance); - - if (!client) { - this.logger.warn(`Client not found for instance: ${JSON.stringify(instance)}`); - return null; - } - - const cacheKey = `${instance.instanceName}:createConversation-${body.key.remoteJid}`; - this.logger.verbose(`Cache key: ${cacheKey}`); - + // If it already exists in the cache, return conversationId if (await this.cache.has(cacheKey)) { - this.logger.verbose(`Cache hit for key: ${cacheKey}`); const conversationId = (await this.cache.get(cacheKey)) as number; - this.logger.verbose(`Cached conversation ID: ${conversationId}`); - let conversationExists: conversation | boolean; - try { - conversationExists = await client.conversations.get({ - accountId: this.provider.accountId, - conversationId: conversationId, - }); - this.logger.verbose(`Conversation exists: ${JSON.stringify(conversationExists)}`); - } catch (error) { - this.logger.error(`Error getting conversation: ${error}`); - conversationExists = false; - } - if (!conversationExists) { - this.logger.verbose('Conversation does not exist, re-calling createConversation'); - this.cache.delete(cacheKey); - return await this.createConversation(instance, body); - } - + this.logger.verbose(`Found conversation to: ${remoteJid}, conversation ID: ${conversationId}`); return conversationId; } - const isGroup = body.key.remoteJid.includes('@g.us'); - this.logger.verbose(`Is group: ${isGroup}`); - - const chatId = isGroup ? body.key.remoteJid : body.key.remoteJid.split('@')[0]; - this.logger.verbose(`Chat ID: ${chatId}`); - - let nameContact: string; - - nameContact = !body.key.fromMe ? body.pushName : chatId; - this.logger.verbose(`Name contact: ${nameContact}`); - - const filterInbox = await this.getInbox(instance); - - if (!filterInbox) { - this.logger.warn(`Inbox not found for instance: ${JSON.stringify(instance)}`); - return null; + // If lock already exists, wait until release or timeout + if (await this.cache.has(lockKey)) { + this.logger.verbose(`Operação de criação já em andamento para ${remoteJid}, aguardando resultado...`); + const start = Date.now(); + while (await this.cache.has(lockKey)) { + if (Date.now() - start > maxWaitTime) { + this.logger.warn(`Timeout aguardando lock para ${remoteJid}`); + break; + } + await new Promise((res) => setTimeout(res, 300)); + if (await this.cache.has(cacheKey)) { + const conversationId = (await this.cache.get(cacheKey)) as number; + this.logger.verbose(`Resolves creation of: ${remoteJid}, conversation ID: ${conversationId}`); + return conversationId; + } + } } - if (isGroup) { - this.logger.verbose('Processing group conversation'); - const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId); - this.logger.verbose(`Group metadata: ${JSON.stringify(group)}`); + // Adquire lock + await this.cache.set(lockKey, true, 30); + this.logger.verbose(`Bloqueio adquirido para: ${lockKey}`); - nameContact = `${group.subject} (GROUP)`; + try { + /* + Double check after lock + Utilizei uma nova verificação para evitar que outra thread execute entre o terminio do while e o set lock + */ + if (await this.cache.has(cacheKey)) { + return (await this.cache.get(cacheKey)) as number; + } - const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture( - body.key.participant.split('@')[0], - ); - this.logger.verbose(`Participant profile picture URL: ${JSON.stringify(picture_url)}`); + const client = await this.clientCw(instance); + if (!client) return null; - const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]); - this.logger.verbose(`Found participant: ${JSON.stringify(findParticipant)}`); + const isGroup = remoteJid.includes('@g.us'); + const chatId = isGroup ? remoteJid : remoteJid.split('@')[0]; + let nameContact = !body.key.fromMe ? body.pushName : chatId; + const filterInbox = await this.getInbox(instance); + if (!filterInbox) return null; - if (findParticipant) { - if (!findParticipant.name || findParticipant.name === chatId) { - await this.updateContact(instance, findParticipant.id, { - name: body.pushName, - avatar_url: picture_url.profilePictureUrl || null, - }); + if (isGroup) { + this.logger.verbose(`Processing group conversation`); + const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId); + this.logger.verbose(`Group metadata: ${JSON.stringify(group)}`); + + nameContact = `${group.subject} (GROUP)`; + + const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture( + body.key.participant.split('@')[0], + ); + this.logger.verbose(`Participant profile picture URL: ${JSON.stringify(picture_url)}`); + + const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]); + this.logger.verbose(`Found participant: ${JSON.stringify(findParticipant)}`); + + if (findParticipant) { + if (!findParticipant.name || findParticipant.name === chatId) { + await this.updateContact(instance, findParticipant.id, { + name: body.pushName, + avatar_url: picture_url.profilePictureUrl || null, + }); + } + } else { + await this.createContact( + instance, + body.key.participant.split('@')[0], + filterInbox.id, + false, + body.pushName, + picture_url.profilePictureUrl || null, + body.key.participant, + ); + } + } + + const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId); + this.logger.verbose(`Contact profile picture URL: ${JSON.stringify(picture_url)}`); + + let contact = await this.findContact(instance, chatId); + + if (contact) { + this.logger.verbose(`Found contact: ${JSON.stringify(contact)}`); + if (!body.key.fromMe) { + const waProfilePictureFile = + picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || ''; + const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || ''; + const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile; + const nameNeedsUpdate = + !contact.name || + contact.name === chatId || + (`+${chatId}`.startsWith('+55') + ? this.getNumbers(`+${chatId}`).some( + (v) => contact.name === v || contact.name === v.substring(3) || contact.name === v.substring(1), + ) + : false); + + this.logger.verbose(`Picture needs update: ${pictureNeedsUpdate}`); + this.logger.verbose(`Name needs update: ${nameNeedsUpdate}`); + + if (pictureNeedsUpdate || nameNeedsUpdate) { + contact = await this.updateContact(instance, contact.id, { + ...(nameNeedsUpdate && { name: nameContact }), + ...(waProfilePictureFile === '' && { avatar: null }), + ...(pictureNeedsUpdate && { avatar_url: picture_url?.profilePictureUrl }), + }); + } } } else { - await this.createContact( + const jid = body.key.remoteJid; + contact = await this.createContact( instance, - body.key.participant.split('@')[0], + chatId, filterInbox.id, - false, - body.pushName, + isGroup, + nameContact, picture_url.profilePictureUrl || null, - body.key.participant, + jid, ); } - } - const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId); - this.logger.verbose(`Contact profile picture URL: ${JSON.stringify(picture_url)}`); - - let contact = await this.findContact(instance, chatId); - this.logger.verbose(`Found contact: ${JSON.stringify(contact)}`); - - if (contact) { - if (!body.key.fromMe) { - const waProfilePictureFile = - picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || ''; - const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || ''; - const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile; - const nameNeedsUpdate = - !contact.name || - contact.name === chatId || - (`+${chatId}`.startsWith('+55') - ? this.getNumbers(`+${chatId}`).some( - (v) => contact.name === v || contact.name === v.substring(3) || contact.name === v.substring(1), - ) - : false); - - this.logger.verbose(`Picture needs update: ${pictureNeedsUpdate}`); - this.logger.verbose(`Name needs update: ${nameNeedsUpdate}`); - - if (pictureNeedsUpdate || nameNeedsUpdate) { - contact = await this.updateContact(instance, contact.id, { - ...(nameNeedsUpdate && { name: nameContact }), - ...(waProfilePictureFile === '' && { avatar: null }), - ...(pictureNeedsUpdate && { avatar_url: picture_url?.profilePictureUrl }), - }); - } + if (!contact) { + this.logger.warn(`Contact not created or found`); + return null; } - } else { - const jid = body.key.remoteJid; - contact = await this.createContact( - instance, - chatId, - filterInbox.id, - isGroup, - nameContact, - picture_url.profilePictureUrl || null, - jid, + + const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id; + this.logger.verbose(`Contact ID: ${contactId}`); + + const contactConversations = (await client.contacts.listConversations({ + accountId: this.provider.accountId, + id: contactId, + })) as any; + this.logger.verbose(`Contact conversations: ${JSON.stringify(contactConversations)}`); + + if (!contactConversations || !contactConversations.payload) { + this.logger.error(`No conversations found or payload is undefined`); + return null; + } + + let inboxConversation = contactConversations.payload.find( + (conversation) => conversation.inbox_id == filterInbox.id, ); - } + if (inboxConversation) { + if (this.provider.reopenConversation) { + this.logger.verbose(`Found conversation in reopenConversation mode: ${JSON.stringify(inboxConversation)}`); - if (!contact) { - this.logger.warn('Contact not created or found'); - return null; - } - - const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id; - this.logger.verbose(`Contact ID: ${contactId}`); - - const contactConversations = (await client.contacts.listConversations({ - accountId: this.provider.accountId, - id: contactId, - })) as any; - this.logger.verbose(`Contact conversations: ${JSON.stringify(contactConversations)}`); - - if (!contactConversations || !contactConversations.payload) { - this.logger.error('No conversations found or payload is undefined'); - return null; - } - - if (contactConversations.payload.length) { - let conversation: any; - if (this.provider.reopenConversation) { - conversation = contactConversations.payload.find((conversation) => conversation.inbox_id == filterInbox.id); - this.logger.verbose(`Found conversation in reopenConversation mode: ${JSON.stringify(conversation)}`); - - if (this.provider.conversationPending && conversation.status !== 'open') { - if (conversation) { + if (this.provider.conversationPending && inboxConversation.status !== 'open') { await client.conversations.toggleStatus({ accountId: this.provider.accountId, - conversationId: conversation.id, + conversationId: inboxConversation.id, data: { status: 'pending', }, }); } + } else { + inboxConversation = contactConversations.payload.find( + (conversation) => conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id, + ); + this.logger.verbose(`Found conversation: ${JSON.stringify(inboxConversation)}`); + } + + if (inboxConversation) { + this.logger.verbose(`Returning existing conversation ID: ${inboxConversation.id}`); + this.cache.set(cacheKey, inboxConversation.id); + return inboxConversation.id; } - } else { - conversation = contactConversations.payload.find( - (conversation) => conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id, - ); - this.logger.verbose(`Found conversation: ${JSON.stringify(conversation)}`); } - if (conversation) { - this.logger.verbose(`Returning existing conversation ID: ${conversation.id}`); - this.cache.set(cacheKey, conversation.id); - return conversation.id; + const data = { + contact_id: contactId.toString(), + inbox_id: filterInbox.id.toString(), + }; + + if (this.provider.conversationPending) { + data['status'] = 'pending'; } + + const conversation = await client.conversations.create({ + accountId: this.provider.accountId, + data, + }); + + if (!conversation) { + this.logger.warn(`Conversation not created or found`); + return null; + } + + this.logger.verbose(`New conversation created with ID: ${conversation.id}`); + this.cache.set(cacheKey, conversation.id); + return conversation.id; + } finally { + await this.cache.delete(lockKey); + this.logger.verbose(`Block released for: ${lockKey}`); } - - const data = { - contact_id: contactId.toString(), - inbox_id: filterInbox.id.toString(), - }; - - if (this.provider.conversationPending) { - data['status'] = 'pending'; - } - - const conversation = await client.conversations.create({ - accountId: this.provider.accountId, - data, - }); - - if (!conversation) { - this.logger.warn('Conversation not created or found'); - return null; - } - - this.logger.verbose(`New conversation created with ID: ${conversation.id}`); - this.cache.set(cacheKey, conversation.id); - return conversation.id; } catch (error) { this.logger.error(`Error in createConversation: ${error}`); + return null; } } @@ -931,7 +935,7 @@ export class ChatwootService { quotedMsg?: MessageModel, ) { if (sourceId && this.isImportHistoryAvailable()) { - const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]); + const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); if (messageAlreadySaved) { if (messageAlreadySaved.size > 0) { this.logger.warn('Message already saved on chatwoot'); @@ -1106,12 +1110,13 @@ export class ChatwootService { sendTelemetry('/message/sendWhatsAppAudio'); - const messageSent = await waInstance?.audioWhatsapp(data, true); + const messageSent = await waInstance?.audioWhatsapp(data, null, true); return messageSent; } - if (type === 'image' && parsedMedia && parsedMedia?.ext === '.gif') { + const documentExtensions = ['.gif', '.svg', '.tiff', '.tif']; + if (type === 'image' && parsedMedia && documentExtensions.includes(parsedMedia?.ext)) { type = 'document'; } @@ -1653,7 +1658,7 @@ export class ChatwootService { stickerMessage: undefined, documentMessage: msg.documentMessage?.caption, documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.caption, - audioMessage: msg.audioMessage?.caption, + audioMessage: msg.audioMessage ? (msg.audioMessage.caption ?? '') : undefined, contactMessage: msg.contactMessage?.vcard, contactsArrayMessage: msg.contactsArrayMessage, locationMessage: msg.locationMessage, @@ -1898,7 +1903,7 @@ export class ChatwootService { .replaceAll(/~((?!\s)([^\n~]+?)(?> { + public async getExistingSourceIds(sourceIds: string[], conversationId?: number): Promise> { try { const existingSourceIdsSet = new Set(); @@ -177,18 +177,25 @@ class ChatwootImport { return existingSourceIdsSet; } - const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); // Make sure the sourceId is always formatted as WAID:1234567890 - const query = 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; + // Ensure all sourceIds are consistently prefixed with 'WAID:' as required by downstream systems and database queries. + const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); const pgClient = postgresClient.getChatwootConnection(); - const result = await pgClient.query(query, [formattedSourceIds]); + const params = conversationId ? [formattedSourceIds, conversationId] : [formattedSourceIds]; + + const query = conversationId + ? 'SELECT source_id FROM messages WHERE source_id = ANY($1) AND conversation_id = $2' + : 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; + + const result = await pgClient.query(query, params); for (const row of result.rows) { existingSourceIdsSet.add(row.source_id); } return existingSourceIdsSet; } catch (error) { - return null; + this.logger.error(`Error on getExistingSourceIds: ${error.toString()}`); + return new Set(); } } @@ -499,25 +506,30 @@ class ChatwootImport { stickerMessage: msg.message.stickerMessage, templateMessage: msg.message.templateMessage?.hydratedTemplate?.hydratedContentText, }; - const typeKey = Object.keys(types).find((key) => types[key] !== undefined); + const typeKey = Object.keys(types).find((key) => types[key] !== undefined && types[key] !== null); switch (typeKey) { - case 'documentMessage': - return `__`; + case 'documentMessage': { + const doc = msg.message.documentMessage; + const fileName = doc?.fileName || 'document'; + const caption = doc?.caption ? ` ${doc.caption}` : ''; + return `__`; + } - case 'documentWithCaptionMessage': - return `__`; + case 'documentWithCaptionMessage': { + const doc = msg.message.documentWithCaptionMessage?.message?.documentMessage; + const fileName = doc?.fileName || 'document'; + const caption = doc?.caption ? ` ${doc.caption}` : ''; + return `__`; + } - case 'templateMessage': - return msg.message.templateMessage.hydratedTemplate.hydratedTitleText - ? `*${msg.message.templateMessage.hydratedTemplate.hydratedTitleText}*\\n` - : '' + msg.message.templateMessage.hydratedTemplate.hydratedContentText; + case 'templateMessage': { + const template = msg.message.templateMessage?.hydratedTemplate; + return ( + (template?.hydratedTitleText ? `*${template.hydratedTitleText}*\n` : '') + + (template?.hydratedContentText || '') + ); + } case 'imageMessage': return '__'; diff --git a/src/api/integrations/chatbot/dify/controllers/dify.controller.ts b/src/api/integrations/chatbot/dify/controllers/dify.controller.ts index 05834fb3..ebbf2b0d 100644 --- a/src/api/integrations/chatbot/dify/controllers/dify.controller.ts +++ b/src/api/integrations/chatbot/dify/controllers/dify.controller.ts @@ -1,4 +1,3 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { DifyDto } from '@api/integrations/chatbot/dify/dto/dify.dto'; import { DifyService } from '@api/integrations/chatbot/dify/services/dify.service'; @@ -7,12 +6,11 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { configService, Dify } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import { Dify as DifyModel } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { Dify as DifyModel, IntegrationSession } from '@prisma/client'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; -export class DifyController extends ChatbotController implements ChatbotControllerInterface { +export class DifyController extends BaseChatbotController { constructor( private readonly difyService: DifyService, prismaRepository: PrismaRepository, @@ -26,6 +24,7 @@ export class DifyController extends ChatbotController implements ChatbotControll } public readonly logger = new Logger('DifyController'); + protected readonly integrationName = 'Dify'; integrationEnabled = configService.get('DIFY').ENABLED; botRepository: any; @@ -33,261 +32,37 @@ export class DifyController extends ChatbotController implements ChatbotControll sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: DifyDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; - - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - instanceId: instanceId, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - }, - }); - - if (checkDuplicate) { - throw new Error('Dify already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating dify'); - } + protected getFallbackBotId(settings: any): string | undefined { + return settings?.fallbackId; } - public async findBot(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; + protected getFallbackFieldName(): string { + return 'difyIdFallback'; } - public async fetchBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Dify not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return bot; + protected getIntegrationType(): string { + return 'dify'; } - public async updateBot(instance: InstanceDto, botId: string, data: DifyDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + protected getAdditionalBotData(data: DifyDto): Record { + return { + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Dify not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - } + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: DifyDto): Record { + return { + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: DifyDto): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { id: { @@ -303,81 +78,10 @@ export class DifyController extends ChatbotController implements ChatbotControll if (checkDuplicate) { throw new Error('Dify already exists'); } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating dify'); - } } - public async deleteBot(instance: InstanceDto, botId: string) { + // Override createBot to add Dify-specific validation + public async createBot(instance: InstanceDto, data: DifyDto) { if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); const instanceId = await this.prismaRepository.instance @@ -388,501 +92,35 @@ export class DifyController extends ChatbotController implements ChatbotControll }) .then((instance) => instance.id); - const bot = await this.botRepository.findFirst({ + // Dify-specific duplicate check + const checkDuplicate = await this.botRepository.findFirst({ where: { - id: botId, + instanceId: instanceId, + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, }, }); - if (!bot) { - throw new Error('Dify not found'); + if (checkDuplicate) { + throw new Error('Dify already exists'); } - if (bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting dify bot'); - } + // Let the base class handle the rest + return super.createBot(instance, data); } - // Settings - public async settings(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - difyIdFallback: data.difyIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - difyIdFallback: updateSettings.difyIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - difyIdFallback: data.difyIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - difyIdFallback: newSetttings.difyIdFallback, - ignoreJids: newSetttings.ignoreJids, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - difyIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - difyIdFallback: settings.difyIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { bot: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - } - - return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const botData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { bot: { ...instance, bot: botData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (bot && bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: bot ? botId : { not: null }, - type: 'dify', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - // Emit - public async emit({ instance, remoteJid, msg }: EmitData) { - if (!this.integrationEnabled) return; - - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger(this.botRepository, content, instance, session)) as DifyModel; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.difyIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.difyIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.difyService.processDify( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - msg?.pushName, - ); - }); - } else { - await this.difyService.processDify( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - content, - msg?.pushName, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } + // Process Dify-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: DifyModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.difyService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); } } diff --git a/src/api/integrations/chatbot/dify/dto/dify.dto.ts b/src/api/integrations/chatbot/dify/dto/dify.dto.ts index ff9bba05..9e436705 100644 --- a/src/api/integrations/chatbot/dify/dto/dify.dto.ts +++ b/src/api/integrations/chatbot/dify/dto/dify.dto.ts @@ -1,38 +1,13 @@ -import { $Enums, TriggerOperator, TriggerType } from '@prisma/client'; +import { $Enums } from '@prisma/client'; -export class DifyDto { - enabled?: boolean; - description?: string; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; + +export class DifyDto extends BaseChatbotDto { botType?: $Enums.DifyBotType; apiUrl?: string; apiKey?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } -export class DifySettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class DifySettingDto extends BaseChatbotSettingDto { difyIdFallback?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/dify/services/dify.service.ts b/src/api/integrations/chatbot/dify/services/dify.service.ts index 348ee70c..773efe49 100644 --- a/src/api/integrations/chatbot/dify/services/dify.service.ts +++ b/src/api/integrations/chatbot/dify/services/dify.service.ts @@ -1,60 +1,34 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { Auth, ConfigService, HttpServer } from '@config/env.config'; -import { Logger } from '@config/logger.config'; +import { ConfigService, HttpServer } from '@config/env.config'; import { Dify, DifySetting, IntegrationSession } from '@prisma/client'; -import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; -import { Readable } from 'stream'; -export class DifyService { +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class DifyService extends BaseChatbotService { + private openaiService: OpenaiService; + constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private readonly logger = new Logger('DifyService'); - - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'dify', - }, - }); - - return { session }; - } catch (error) { - this.logger.error(error); - return; - } + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'DifyService', configService); + this.openaiService = openaiService; } - private isImageMessage(content: string) { - return content.includes('imageMessage'); + /** + * Return the bot type for Dify + */ + protected getBotType(): string { + return 'dify'; } - private isJSON(str: string): boolean { - try { - JSON.parse(str); - return true; - } catch (e) { - return false; - } - } - - private async sendMessageToBot( + protected async sendMessageToBot( instance: any, session: IntegrationSession, settings: DifySetting, @@ -62,10 +36,30 @@ export class DifyService { remoteJid: string, pushName: string, content: string, - ) { + msg?: any, + ): Promise { try { let endpoint: string = dify.apiUrl; + if (!endpoint) { + this.logger.error('No Dify endpoint defined'); + return; + } + + // Handle audio messages - transcribe using OpenAI Whisper + let processedContent = content; + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[Dify] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + processedContent = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[Dify] Failed to transcribe audio: ${err}`); + } + } + if (dify.botType === 'chatBot') { endpoint += '/chat-messages'; const payload: any = { @@ -74,17 +68,17 @@ export class DifyService { pushName: pushName, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, - query: content, + query: processedContent, response_mode: 'blocking', conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, user: remoteJid, }; + // Handle image messages if (this.isImageMessage(content)) { const contentSplit = content.split('|'); - payload.files = [ { type: 'image', @@ -112,7 +106,9 @@ export class DifyService { const message = response?.data?.answer; const conversationId = response?.data?.conversation_id; - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + if (message) { + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + } await this.prismaRepository.integrationSession.update({ where: { @@ -130,21 +126,21 @@ export class DifyService { endpoint += '/completion-messages'; const payload: any = { inputs: { - query: content, + query: processedContent, pushName: pushName, remoteJid: remoteJid, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, response_mode: 'blocking', conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, user: remoteJid, }; + // Handle image messages if (this.isImageMessage(content)) { const contentSplit = content.split('|'); - payload.files = [ { type: 'image', @@ -172,7 +168,9 @@ export class DifyService { const message = response?.data?.answer; const conversationId = response?.data?.conversation_id; - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + if (message) { + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + } await this.prismaRepository.integrationSession.update({ where: { @@ -194,17 +192,17 @@ export class DifyService { pushName: pushName, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, - query: content, + query: processedContent, response_mode: 'streaming', conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, user: remoteJid, }; + // Handle image messages if (this.isImageMessage(content)) { const contentSplit = content.split('|'); - payload.files = [ { type: 'image', @@ -230,7 +228,6 @@ export class DifyService { let answer = ''; const data = response.data.replaceAll('data: ', ''); - const events = data.split('\n').filter((line) => line.trim() !== ''); for (const eventString of events) { @@ -248,9 +245,9 @@ export class DifyService { if (instance.integration === Integration.WHATSAPP_BAILEYS) await instance.client.sendPresenceUpdate('paused', remoteJid); - const message = answer; - - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + if (answer) { + await this.sendMessageWhatsApp(instance, remoteJid, answer, settings); + } await this.prismaRepository.integrationSession.update({ where: { @@ -259,369 +256,13 @@ export class DifyService { data: { status: 'opened', awaitUser: true, - sessionId: conversationId, + sessionId: session.sessionId === remoteJid ? conversationId : session.sessionId, }, }); - - return; - } - - if (dify.botType === 'workflow') { - endpoint += '/workflows/run'; - const payload: any = { - inputs: { - query: content, - remoteJid: remoteJid, - pushName: pushName, - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - response_mode: 'blocking', - user: remoteJid, - }; - - if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - transfer_method: 'remote_url', - url: contentSplit[1].split('?')[0], - }, - ]; - payload.inputs.query = contentSplit[2] || content; - } - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.data.outputs.text; - - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - return; } } catch (error) { this.logger.error(error.response?.data || error); return; } } - - private async sendMessageWhatsApp(instance: any, remoteJid: string, message: string, settings: DifySetting) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - textBuffer = ''; - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; - } - - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - } - - sendTelemetry('/message/sendText'); - } - - private async initNewSession( - instance: any, - remoteJid: string, - dify: Dify, - settings: DifySetting, - session: IntegrationSession, - content: string, - pushName?: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - pushName, - botId: dify.id, - }); - - if (data.session) { - session = data.session; - } - - await this.sendMessageToBot(instance, session, settings, dify, remoteJid, pushName, content); - - return; - } - - public async processDify( - instance: any, - remoteJid: string, - dify: Dify, - session: IntegrationSession, - settings: DifySetting, - content: string, - pushName?: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: dify.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initNewSession(instance, remoteJid, dify, settings, session, content, pushName); - return; - } - } - - if (!session) { - await this.initNewSession(instance, remoteJid, dify, settings, session, content, pushName); - return; - } - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: dify.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - await this.sendMessageToBot(instance, session, settings, dify, remoteJid, pushName, content); - - return; - } } diff --git a/src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts b/src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts new file mode 100644 index 00000000..38ce433d --- /dev/null +++ b/src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts @@ -0,0 +1,122 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { EvoaiDto } from '@api/integrations/chatbot/evoai/dto/evoai.dto'; +import { EvoaiService } from '@api/integrations/chatbot/evoai/services/evoai.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Evoai } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { Evoai as EvoaiModel, IntegrationSession } from '@prisma/client'; + +import { BaseChatbotController } from '../../base-chatbot.controller'; + +export class EvoaiController extends BaseChatbotController { + constructor( + private readonly evoaiService: EvoaiService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.evoai; + this.settingsRepository = this.prismaRepository.evoaiSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('EvoaiController'); + protected readonly integrationName = 'Evoai'; + + integrationEnabled = configService.get('EVOAI').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + protected getFallbackBotId(settings: any): string | undefined { + return settings?.evoaiIdFallback; + } + + protected getFallbackFieldName(): string { + return 'evoaiIdFallback'; + } + + protected getIntegrationType(): string { + return 'evoai'; + } + + protected getAdditionalBotData(data: EvoaiDto): Record { + return { + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }; + } + + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: EvoaiDto): Record { + return { + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }; + } + + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: EvoaiDto): Promise { + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Evoai already exists'); + } + } + + // Override createBot to add EvoAI-specific validation + public async createBot(instance: InstanceDto, data: EvoaiDto) { + if (!this.integrationEnabled) throw new BadRequestException('Evoai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // EvoAI-specific duplicate check + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Evoai already exists'); + } + + // Let the base class handle the rest + return super.createBot(instance, data); + } + + // Process Evoai-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: EvoaiModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.evoaiService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } +} diff --git a/src/api/integrations/chatbot/evoai/dto/evoai.dto.ts b/src/api/integrations/chatbot/evoai/dto/evoai.dto.ts new file mode 100644 index 00000000..6043e765 --- /dev/null +++ b/src/api/integrations/chatbot/evoai/dto/evoai.dto.ts @@ -0,0 +1,10 @@ +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; + +export class EvoaiDto extends BaseChatbotDto { + agentUrl?: string; + apiKey?: string; +} + +export class EvoaiSettingDto extends BaseChatbotSettingDto { + evoaiIdFallback?: string; +} diff --git a/src/api/integrations/chatbot/evoai/routes/evoai.router.ts b/src/api/integrations/chatbot/evoai/routes/evoai.router.ts new file mode 100644 index 00000000..aadca01d --- /dev/null +++ b/src/api/integrations/chatbot/evoai/routes/evoai.router.ts @@ -0,0 +1,124 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { evoaiController } from '@api/server.module'; +import { + evoaiIgnoreJidSchema, + evoaiSchema, + evoaiSettingSchema, + evoaiStatusSchema, + instanceSchema, +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +import { EvoaiDto, EvoaiSettingDto } from '../dto/evoai.dto'; + +export class EvoaiRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiSchema, + ClassRef: EvoaiDto, + execute: (instance, data) => evoaiController.createBot(instance, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.findBot(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetch/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.fetchBot(instance, req.params.evoaiId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .put(this.routerPath('update/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiSchema, + ClassRef: EvoaiDto, + execute: (instance, data) => evoaiController.updateBot(instance, req.params.evoaiId, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .delete(this.routerPath('delete/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.deleteBot(instance, req.params.evoaiId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('settings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiSettingSchema, + ClassRef: EvoaiSettingDto, + execute: (instance, data) => evoaiController.settings(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSettings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.fetchSettings(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('changeStatus'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiStatusSchema, + ClassRef: InstanceDto, + execute: (instance, data) => evoaiController.changeStatus(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSessions/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.fetchSessions(instance, req.params.evoaiId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiIgnoreJidSchema, + ClassRef: IgnoreJidDto, + execute: (instance, data) => evoaiController.ignoreJid(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/chatbot/evoai/services/evoai.service.ts b/src/api/integrations/chatbot/evoai/services/evoai.service.ts new file mode 100644 index 00000000..c92835ae --- /dev/null +++ b/src/api/integrations/chatbot/evoai/services/evoai.service.ts @@ -0,0 +1,186 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { ConfigService, HttpServer } from '@config/env.config'; +import { Evoai, EvoaiSetting, IntegrationSession } from '@prisma/client'; +import axios from 'axios'; +import { downloadMediaMessage } from 'baileys'; +import { v4 as uuidv4 } from 'uuid'; + +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class EvoaiService extends BaseChatbotService { + private openaiService: OpenaiService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'EvoaiService', configService); + this.openaiService = openaiService; + } + + /** + * Return the bot type for EvoAI + */ + protected getBotType(): string { + return 'evoai'; + } + + /** + * Implement the abstract method to send message to EvoAI API + * Handles audio transcription, image processing, and complex JSON-RPC payload + */ + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: EvoaiSetting, + evoai: Evoai, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { + try { + this.logger.debug(`[EvoAI] Sending message to bot with content: ${content}`); + + let processedContent = content; + + // Handle audio messages - transcribe using OpenAI Whisper + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[EvoAI] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + processedContent = transcription; + } + } catch (err) { + this.logger.error(`[EvoAI] Failed to transcribe audio: ${err}`); + } + } + + const endpoint: string = evoai.agentUrl; + + if (!endpoint) { + this.logger.error('No EvoAI endpoint defined'); + return; + } + + const callId = `req-${uuidv4().substring(0, 8)}`; + const messageId = msg?.key?.id || uuidv4(); + + // Prepare message parts + const parts = [ + { + type: 'text', + text: processedContent, + }, + ]; + + // Handle image message if present + if (this.isImageMessage(content) && msg) { + const contentSplit = content.split('|'); + parts[0].text = contentSplit[2] || content; + + try { + // Download the image + const mediaBuffer = await downloadMediaMessage(msg, 'buffer', {}); + const fileContent = Buffer.from(mediaBuffer).toString('base64'); + const fileName = contentSplit[2] || `${msg.key?.id || 'image'}.jpg`; + + parts.push({ + type: 'file', + file: { + name: fileName, + mimeType: 'image/jpeg', + bytes: fileContent, + }, + } as any); + } catch (fileErr) { + this.logger.error(`[EvoAI] Failed to process image: ${fileErr}`); + } + } + + const payload = { + jsonrpc: '2.0', + id: callId, + method: 'message/send', + params: { + contextId: session.sessionId, + message: { + role: 'user', + parts, + messageId: messageId, + metadata: { + messageKey: msg?.key, + }, + }, + metadata: { + remoteJid: remoteJid, + pushName: pushName, + fromMe: msg?.key?.fromMe, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: instance.token, + }, + }, + }; + + this.logger.debug(`[EvoAI] Sending request to: ${endpoint}`); + // Redact base64 file bytes from payload log + const redactedPayload = JSON.parse(JSON.stringify(payload)); + if (redactedPayload?.params?.message?.parts) { + redactedPayload.params.message.parts = redactedPayload.params.message.parts.map((part) => { + if (part.type === 'file' && part.file && part.file.bytes) { + return { ...part, file: { ...part.file, bytes: '[base64 omitted]' } }; + } + return part; + }); + } + this.logger.debug(`[EvoAI] Payload: ${JSON.stringify(redactedPayload)}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await axios.post(endpoint, payload, { + headers: { + 'x-api-key': evoai.apiKey, + 'Content-Type': 'application/json', + }, + }); + + this.logger.debug(`[EvoAI] Response: ${JSON.stringify(response.data)}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + let message = undefined; + const result = response?.data?.result; + + // Extract message from artifacts array + if (result?.artifacts && Array.isArray(result.artifacts) && result.artifacts.length > 0) { + const artifact = result.artifacts[0]; + if (artifact?.parts && Array.isArray(artifact.parts)) { + const textPart = artifact.parts.find((p) => p.type === 'text' && p.text); + if (textPart) message = textPart.text; + } + } + + this.logger.debug(`[EvoAI] Extracted message to send: ${message}`); + + if (message) { + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + } + } catch (error) { + this.logger.error( + `[EvoAI] Error sending message: ${error?.response?.data ? JSON.stringify(error.response.data) : error}`, + ); + return; + } + } +} diff --git a/src/api/integrations/chatbot/evoai/validate/evoai.schema.ts b/src/api/integrations/chatbot/evoai/validate/evoai.schema.ts new file mode 100644 index 00000000..59a07038 --- /dev/null +++ b/src/api/integrations/chatbot/evoai/validate/evoai.schema.ts @@ -0,0 +1,115 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const evoaiSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + agentUrl: { type: 'string' }, + apiKey: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: ['enabled', 'agentUrl', 'triggerType'], + ...isNotEmpty('enabled', 'agentUrl', 'triggerType'), +}; + +export const evoaiStatusSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + status: { type: 'string', enum: ['opened', 'closed', 'paused', 'delete'] }, + }, + required: ['remoteJid', 'status'], + ...isNotEmpty('remoteJid', 'status'), +}; + +export const evoaiSettingSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + botIdFallback: { type: 'string' }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: [ + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ], + ...isNotEmpty( + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ), +}; + +export const evoaiIgnoreJidSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + action: { type: 'string', enum: ['add', 'remove'] }, + }, + required: ['remoteJid', 'action'], + ...isNotEmpty('remoteJid', 'action'), +}; diff --git a/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts b/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts index 0d5825de..13ec5330 100644 --- a/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts +++ b/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts @@ -1,16 +1,13 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Logger } from '@config/logger.config'; -import { EvolutionBot } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { EvolutionBot, IntegrationSession } from '@prisma/client'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; import { EvolutionBotDto } from '../dto/evolutionBot.dto'; import { EvolutionBotService } from '../services/evolutionBot.service'; -export class EvolutionBotController extends ChatbotController implements ChatbotControllerInterface { +export class EvolutionBotController extends BaseChatbotController { constructor( private readonly evolutionBotService: EvolutionBotService, prismaRepository: PrismaRepository, @@ -24,258 +21,49 @@ export class EvolutionBotController extends ChatbotController implements Chatbot } public readonly logger = new Logger('EvolutionBotController'); + protected readonly integrationName = 'EvolutionBot'; - integrationEnabled: boolean; + integrationEnabled = true; // Set to true by default or use config value if available botRepository: any; settingsRepository: any; sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: EvolutionBotDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); + // Implementation of abstract methods required by BaseChatbotController - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; - - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - instanceId: instanceId, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - }, - }); - - if (checkDuplicate) { - throw new Error('Dify already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating bot'); - } + protected getFallbackBotId(settings: any): string | undefined { + return settings?.botIdFallback; } - public async findBot(instance: InstanceDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; + protected getFallbackFieldName(): string { + return 'botIdFallback'; } - public async fetchBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - return bot; + protected getIntegrationType(): string { + return 'evolution'; } - public async updateBot(instance: InstanceDto, botId: string, data: EvolutionBotDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); + protected getAdditionalBotData(data: EvolutionBotDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error('You already have a bot with an "All" trigger, you cannot have more bots while it is active'); - } - } + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: EvolutionBotDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate( + botId: string, + instanceId: string, + data: EvolutionBotDto, + ): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { id: { @@ -288,573 +76,21 @@ export class EvolutionBotController extends ChatbotController implements Chatbot }); if (checkDuplicate) { - throw new Error('Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating bot'); + throw new Error('Evolution Bot already exists'); } } - public async deleteBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting bot'); - } - } - - // Settings - public async settings(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - botIdFallback: data.botIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - botIdFallback: updateSettings.botIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - botIdFallback: data.botIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - instanceId: instanceId, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - botIdFallback: newSetttings.botIdFallback, - ignoreJids: newSetttings.ignoreJids, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - botIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - botIdFallback: settings.botIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { bot: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - } - - return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const botData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { bot: { ...instance, bot: botData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (bot && bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: bot ? botId : { not: null }, - type: 'evolution', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - // Emit - public async emit({ instance, remoteJid, msg }: EmitData) { - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger(this.botRepository, content, instance, session)) as EvolutionBot; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.botIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.botIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.evolutionBotService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - msg?.pushName, - ); - }); - } else { - await this.evolutionBotService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - content, - msg?.pushName, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } + // Process bot-specific logic + protected async processBot( + instance: any, + remoteJid: string, + bot: EvolutionBot, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.evolutionBotService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); } } diff --git a/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts b/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts index de2d952c..dad8e559 100644 --- a/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts +++ b/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts @@ -1,37 +1,10 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; -export class EvolutionBotDto { - enabled?: boolean; - description?: string; - apiUrl?: string; - apiKey?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; +export class EvolutionBotDto extends BaseChatbotDto { + apiUrl: string; + apiKey: string; } -export class EvolutionBotSettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class EvolutionBotSettingDto extends BaseChatbotSettingDto { botIdFallback?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts index 5275f9e1..8f988991 100644 --- a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts +++ b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts @@ -1,428 +1,138 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { Auth, ConfigService, HttpServer } from '@config/env.config'; -import { Logger } from '@config/logger.config'; +import { ConfigService, HttpServer } from '@config/env.config'; import { EvolutionBot, EvolutionBotSetting, IntegrationSession } from '@prisma/client'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; -export class EvolutionBotService { +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class EvolutionBotService extends BaseChatbotService { + private openaiService: OpenaiService; + constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private readonly logger = new Logger('EvolutionBotService'); - - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'evolution', - }, - }); - - return { session }; - } catch (error) { - this.logger.error(error); - return; - } + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'EvolutionBotService', configService); + this.openaiService = openaiService; } - private isImageMessage(content: string) { - return content.includes('imageMessage'); + /** + * Get the bot type identifier + */ + protected getBotType(): string { + return 'evolution'; } - private async sendMessageToBot( + /** + * Send a message to the Evolution Bot API + */ + protected async sendMessageToBot( instance: any, session: IntegrationSession, + settings: EvolutionBotSetting, bot: EvolutionBot, remoteJid: string, pushName: string, content: string, - ) { - const payload: any = { - inputs: { - sessionId: session.id, - remoteJid: remoteJid, - pushName: pushName, - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - query: content, - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - url: contentSplit[1].split('?')[0], + msg?: any, + ): Promise { + try { + const payload: any = { + inputs: { + sessionId: session.id, + remoteJid: remoteJid, + pushName: pushName, + fromMe: msg?.key?.fromMe, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: instance.token, }, - ]; - payload.query = contentSplit[2] || content; - } - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - let headers: any = { - 'Content-Type': 'application/json', - }; - - if (bot.apiKey) { - headers = { - ...headers, - Authorization: `Bearer ${bot.apiKey}`, + query: content, + conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, + user: remoteJid, }; - } - const response = await axios.post(bot.apiUrl, payload, { - headers, - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.message; - - return message; - } - - private async sendMessageWhatsApp( - instance: any, - remoteJid: string, - session: IntegrationSession, - settings: EvolutionBotSetting, - message: string, - ) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[EvolutionBot] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + payload.query = transcription; + } + } catch (err) { + this.logger.error(`[EvolutionBot] Failed to transcribe audio: ${err}`); + } } - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - textBuffer = ''; - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; - } - - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( + payload.files = [ { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), + type: 'image', + url: contentSplit[1].split('?')[0], }, - false, - ); + ]; + payload.query = contentSplit[2] || content; } - textBuffer = ''; - } - sendTelemetry('/message/sendText'); + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - } + const endpoint = bot.apiUrl; - private async initNewSession( - instance: any, - remoteJid: string, - bot: EvolutionBot, - settings: EvolutionBotSetting, - session: IntegrationSession, - content: string, - pushName?: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - pushName, - botId: bot.id, - }); - - if (data.session) { - session = data.session; - } - - const message = await this.sendMessageToBot(instance, session, bot, remoteJid, pushName, content); - - if (!message) return; - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; - } - - public async processBot( - instance: any, - remoteJid: string, - bot: EvolutionBot, - session: IntegrationSession, - settings: EvolutionBotSetting, - content: string, - pushName?: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); + if (!endpoint) { + this.logger.error('No Evolution Bot endpoint defined'); return; } - } - if (!session) { - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; - } + let headers: any = { + 'Content-Type': 'application/json', + }; - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); + if (bot.apiKey) { + headers = { + ...headers, + Authorization: `Bearer ${bot.apiKey}`, + }; } - return; - } - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); + const response = await axios.post(endpoint, payload, { + headers, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); } + + let message = response?.data?.message; + + if (message && typeof message === 'string' && message.startsWith("'") && message.endsWith("'")) { + const innerContent = message.slice(1, -1); + if (!innerContent.includes("'")) { + message = innerContent; + } + } + + if (message) { + // Use the base class method to send the message to WhatsApp + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + } + + // Send telemetry + sendTelemetry('/message/sendText'); + } catch (error) { + this.logger.error(`Error in sendMessageToBot: ${error.message || JSON.stringify(error)}`); return; } - - const message = await this.sendMessageToBot(instance, session, bot, remoteJid, pushName, content); - - if (!message) return; - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; } } diff --git a/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts b/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts index c2d3300b..fbd9ea90 100644 --- a/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts +++ b/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts @@ -1,16 +1,16 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Flowise } from '@config/env.config'; import { Logger } from '@config/logger.config'; -import { Flowise } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { BadRequestException } from '@exceptions'; +import { Flowise as FlowiseModel, IntegrationSession } from '@prisma/client'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; import { FlowiseDto } from '../dto/flowise.dto'; import { FlowiseService } from '../services/flowise.service'; -export class FlowiseController extends ChatbotController implements ChatbotControllerInterface { +export class FlowiseController extends BaseChatbotController { constructor( private readonly flowiseService: FlowiseService, prismaRepository: PrismaRepository, @@ -24,15 +24,73 @@ export class FlowiseController extends ChatbotController implements ChatbotContr } public readonly logger = new Logger('FlowiseController'); + protected readonly integrationName = 'Flowise'; - integrationEnabled: boolean; + integrationEnabled = configService.get('FLOWISE').ENABLED; botRepository: any; settingsRepository: any; sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots + protected getFallbackBotId(settings: any): string | undefined { + return settings?.flowiseIdFallback; + } + + protected getFallbackFieldName(): string { + return 'flowiseIdFallback'; + } + + protected getIntegrationType(): string { + return 'flowise'; + } + + protected getAdditionalBotData(data: FlowiseDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + + protected getAdditionalUpdateFields(data: FlowiseDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: FlowiseDto): Promise { + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { not: botId }, + instanceId: instanceId, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Flowise already exists'); + } + } + + // Process Flowise-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: FlowiseModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.flowiseService.processBot(instance, remoteJid, bot, session, settings, content, pushName, msg); + } + + // Override createBot to add module availability check and Flowise-specific validation public async createBot(instance: InstanceDto, data: FlowiseDto) { + if (!this.integrationEnabled) throw new BadRequestException('Flowise is disabled'); + const instanceId = await this.prismaRepository.instance .findFirst({ where: { @@ -41,74 +99,7 @@ export class FlowiseController extends ChatbotController implements ChatbotContr }) .then((instance) => instance.id); - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; - - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a Flowise with an "All" trigger, you cannot have more bots while it is active'); - } - + // Flowise-specific duplicate check const checkDuplicate = await this.botRepository.findFirst({ where: { instanceId: instanceId, @@ -121,740 +112,7 @@ export class FlowiseController extends ChatbotController implements ChatbotContr throw new Error('Flowise already exists'); } - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating bot'); - } - } - - public async findBot(instance: InstanceDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; - } - - public async fetchBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - return bot; - } - - public async updateBot(instance: InstanceDto, botId: string, data: FlowiseDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error('You already have a bot with an "All" trigger, you cannot have more bots while it is active'); - } - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - id: { - not: botId, - }, - instanceId: instanceId, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - }, - }); - - if (checkDuplicate) { - throw new Error('Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating bot'); - } - } - - public async deleteBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting bot'); - } - } - - // Settings - public async settings(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - flowiseIdFallback: data.flowiseIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - flowiseIdFallback: updateSettings.flowiseIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - flowiseIdFallback: data.flowiseIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - flowiseIdFallback: newSetttings.flowiseIdFallback, - ignoreJids: newSetttings.ignoreJids, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - flowiseIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - flowiseIdFallback: settings.flowiseIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { bot: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - } - - return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const botData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { bot: { ...instance, bot: botData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (bot && bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: bot ? botId : { not: null }, - type: 'flowise', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - // Emit - public async emit({ instance, remoteJid, msg }: EmitData) { - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger(this.botRepository, content, instance, session)) as Flowise; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.flowiseIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.flowiseIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.flowiseService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - msg?.pushName, - ); - }); - } else { - await this.flowiseService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - content, - msg?.pushName, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } + // Let the base class handle the rest + return super.createBot(instance, data); } } diff --git a/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts b/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts index 98e612ad..4bbe1be3 100644 --- a/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts +++ b/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts @@ -1,37 +1,10 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; -export class FlowiseDto { - enabled?: boolean; - description?: string; - apiUrl?: string; +export class FlowiseDto extends BaseChatbotDto { + apiUrl: string; apiKey?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } -export class FlowiseSettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class FlowiseSettingDto extends BaseChatbotSettingDto { flowiseIdFallback?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/flowise/services/flowise.service.ts b/src/api/integrations/chatbot/flowise/services/flowise.service.ts index 6e4cdbd5..40dd2840 100644 --- a/src/api/integrations/chatbot/flowise/services/flowise.service.ts +++ b/src/api/integrations/chatbot/flowise/services/flowise.service.ts @@ -1,50 +1,57 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { Auth, ConfigService, HttpServer } from '@config/env.config'; -import { Logger } from '@config/logger.config'; -import { Flowise, FlowiseSetting, IntegrationSession } from '@prisma/client'; -import { sendTelemetry } from '@utils/sendTelemetry'; +import { ConfigService, HttpServer } from '@config/env.config'; +import { Flowise as FlowiseModel, IntegrationSession } from '@prisma/client'; import axios from 'axios'; -export class FlowiseService { +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class FlowiseService extends BaseChatbotService { + private openaiService: OpenaiService; + constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private readonly logger = new Logger('FlowiseService'); - - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'flowise', - }, - }); - - return { session }; - } catch (error) { - this.logger.error(error); - return; - } + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'FlowiseService', configService); + this.openaiService = openaiService; } - private isImageMessage(content: string) { - return content.includes('imageMessage'); + // Return the bot type for Flowise + protected getBotType(): string { + return 'flowise'; } - private async sendMessageToBot(instance: any, bot: Flowise, remoteJid: string, pushName: string, content: string) { + // Process Flowise-specific bot logic + public async processBot( + instance: any, + remoteJid: string, + bot: FlowiseModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } + + // Implement the abstract method to send message to Flowise API + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: any, + bot: FlowiseModel, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { const payload: any = { question: content, overrideConfig: { @@ -54,11 +61,24 @@ export class FlowiseService { pushName: pushName, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, }, }; + // Handle audio messages + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[Flowise] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + payload.question = transcription; + } + } catch (err) { + this.logger.error(`[Flowise] Failed to transcribe audio: ${err}`); + } + } + if (this.isImageMessage(content)) { const contentSplit = content.split('|'); @@ -91,335 +111,26 @@ export class FlowiseService { const endpoint = bot.apiUrl; - if (!endpoint) return null; + if (!endpoint) { + this.logger.error('No Flowise endpoint defined'); + return; + } const response = await axios.post(endpoint, payload, { headers, }); - if (instance.integration === Integration.WHATSAPP_BAILEYS) + if (instance.integration === Integration.WHATSAPP_BAILEYS) { await instance.client.sendPresenceUpdate('paused', remoteJid); + } const message = response?.data?.text; - return message; + if (message) { + // Use the base class method to send the message to WhatsApp + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + } } - private async sendMessageWhatsApp( - instance: any, - remoteJid: string, - session: IntegrationSession, - settings: FlowiseSetting, - message: string, - ) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - textBuffer = ''; - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; - } - - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - textBuffer = ''; - } - - sendTelemetry('/message/sendText'); - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - return; - } - - private async initNewSession( - instance: any, - remoteJid: string, - bot: Flowise, - settings: FlowiseSetting, - session: IntegrationSession, - content: string, - pushName?: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - pushName, - botId: bot.id, - }); - - if (data.session) { - session = data.session; - } - - const message = await this.sendMessageToBot(instance, bot, remoteJid, pushName, content); - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; - } - - public async processBot( - instance: any, - remoteJid: string, - bot: Flowise, - session: IntegrationSession, - settings: FlowiseSetting, - content: string, - pushName?: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; - } - } - - if (!session) { - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; - } - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - const message = await this.sendMessageToBot(instance, bot, remoteJid, pushName, content); - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; - } + // The service is now complete with just the abstract method implementations } diff --git a/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts b/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts index 83f9d1ea..3283d247 100644 --- a/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts +++ b/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts @@ -40,6 +40,8 @@ export const flowiseSchema: JSONSchema7 = { keepOpen: { type: 'boolean' }, debounceTime: { type: 'integer' }, ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, }, required: ['enabled', 'apiUrl', 'triggerType'], ...isNotEmpty('enabled', 'apiUrl', 'triggerType'), @@ -69,7 +71,9 @@ export const flowiseSettingSchema: JSONSchema7 = { keepOpen: { type: 'boolean' }, debounceTime: { type: 'integer' }, ignoreJids: { type: 'array', items: { type: 'string' } }, - botIdFallback: { type: 'string' }, + flowiseIdFallback: { type: 'string' }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, }, required: [ 'expire', diff --git a/src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts b/src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts new file mode 100644 index 00000000..0eb7f7a6 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts @@ -0,0 +1,127 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { N8nDto } from '@api/integrations/chatbot/n8n/dto/n8n.dto'; +import { N8nService } from '@api/integrations/chatbot/n8n/services/n8n.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { IntegrationSession, N8n as N8nModel } from '@prisma/client'; + +import { BaseChatbotController } from '../../base-chatbot.controller'; + +export class N8nController extends BaseChatbotController { + constructor( + private readonly n8nService: N8nService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.n8n; + this.settingsRepository = this.prismaRepository.n8nSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('N8nController'); + protected readonly integrationName = 'N8n'; + + integrationEnabled = configService.get('N8N').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + protected getFallbackBotId(settings: any): string | undefined { + return settings?.fallbackId; + } + + protected getFallbackFieldName(): string { + return 'n8nIdFallback'; + } + + protected getIntegrationType(): string { + return 'n8n'; + } + + protected getAdditionalBotData(data: N8nDto): Record { + return { + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }; + } + + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: N8nDto): Record { + return { + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }; + } + + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: N8nDto): Promise { + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }, + }); + + if (checkDuplicate) { + throw new Error('N8n already exists'); + } + } + + // Bots + public async createBot(instance: InstanceDto, data: N8nDto) { + if (!this.integrationEnabled) throw new BadRequestException('N8n is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // Check for N8n-specific duplicate + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }, + }); + + if (checkDuplicate) { + throw new Error('N8n already exists'); + } + + // Let the base class handle the rest of the bot creation process + return super.createBot(instance, data); + } + + // Process N8n-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: N8nModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + // Use the base class pattern instead of calling n8nService.process directly + await this.n8nService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } +} diff --git a/src/api/integrations/chatbot/n8n/dto/n8n.dto.ts b/src/api/integrations/chatbot/n8n/dto/n8n.dto.ts new file mode 100644 index 00000000..c844f76e --- /dev/null +++ b/src/api/integrations/chatbot/n8n/dto/n8n.dto.ts @@ -0,0 +1,17 @@ +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; + +export class N8nDto extends BaseChatbotDto { + // N8n specific fields + webhookUrl?: string; + basicAuthUser?: string; + basicAuthPass?: string; +} + +export class N8nSettingDto extends BaseChatbotSettingDto { + // N8n has no specific fields +} + +export class N8nMessageDto { + chatInput: string; + sessionId: string; +} diff --git a/src/api/integrations/chatbot/n8n/routes/n8n.router.ts b/src/api/integrations/chatbot/n8n/routes/n8n.router.ts new file mode 100644 index 00000000..1fbf50d2 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/routes/n8n.router.ts @@ -0,0 +1,114 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { n8nController } from '@api/server.module'; +import { + instanceSchema, + n8nIgnoreJidSchema, + n8nSchema, + n8nSettingSchema, + n8nStatusSchema, +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +import { N8nDto, N8nSettingDto } from '../dto/n8n.dto'; + +export class N8nRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nSchema, + ClassRef: N8nDto, + execute: (instance, data) => n8nController.createBot(instance, data), + }); + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.findBot(instance), + }); + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetch/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.fetchBot(instance, req.params.n8nId), + }); + res.status(HttpStatus.OK).json(response); + }) + .put(this.routerPath('update/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nSchema, + ClassRef: N8nDto, + execute: (instance, data) => n8nController.updateBot(instance, req.params.n8nId, data), + }); + res.status(HttpStatus.OK).json(response); + }) + .delete(this.routerPath('delete/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.deleteBot(instance, req.params.n8nId), + }); + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('settings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nSettingSchema, + ClassRef: N8nSettingDto, + execute: (instance, data) => n8nController.settings(instance, data), + }); + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSettings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.fetchSettings(instance), + }); + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('changeStatus'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nStatusSchema, + ClassRef: InstanceDto, + execute: (instance, data) => n8nController.changeStatus(instance, data), + }); + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSessions/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.fetchSessions(instance, req.params.n8nId), + }); + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nIgnoreJidSchema, + ClassRef: IgnoreJidDto, + execute: (instance, data) => n8nController.ignoreJid(instance, data), + }); + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/chatbot/n8n/services/n8n.service.ts b/src/api/integrations/chatbot/n8n/services/n8n.service.ts new file mode 100644 index 00000000..2d37dca0 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/services/n8n.service.ts @@ -0,0 +1,96 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { ConfigService, HttpServer } from '@config/env.config'; +import { IntegrationSession, N8n, N8nSetting } from '@prisma/client'; +import axios from 'axios'; + +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class N8nService extends BaseChatbotService { + private openaiService: OpenaiService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'N8nService', configService); + this.openaiService = openaiService; + } + + /** + * Return the bot type for N8n + */ + protected getBotType(): string { + return 'n8n'; + } + + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: N8nSetting, + n8n: N8n, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ) { + try { + if (!session) { + this.logger.error('Session is null in sendMessageToBot'); + return; + } + + const endpoint: string = n8n.webhookUrl; + const payload: any = { + chatInput: content, + sessionId: session.sessionId, + remoteJid: remoteJid, + pushName: pushName, + fromMe: msg?.key?.fromMe, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: instance.token, + }; + + // Handle audio messages + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[N8n] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + payload.chatInput = transcription; + } + } catch (err) { + this.logger.error(`[N8n] Failed to transcribe audio: ${err}`); + } + } + + const headers: Record = {}; + if (n8n.basicAuthUser && n8n.basicAuthPass) { + const auth = Buffer.from(`${n8n.basicAuthUser}:${n8n.basicAuthPass}`).toString('base64'); + headers['Authorization'] = `Basic ${auth}`; + } + const response = await axios.post(endpoint, payload, { headers }); + const message = response?.data?.output || response?.data?.answer; + + // Use base class method instead of custom implementation + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } catch (error) { + this.logger.error(error.response?.data || error); + return; + } + } +} diff --git a/src/api/integrations/chatbot/n8n/validate/n8n.schema.ts b/src/api/integrations/chatbot/n8n/validate/n8n.schema.ts new file mode 100644 index 00000000..b1382ac3 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/validate/n8n.schema.ts @@ -0,0 +1,116 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const n8nSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + webhookUrl: { type: 'string' }, + basicAuthUser: { type: 'string' }, + basicAuthPassword: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: ['enabled', 'webhookUrl', 'triggerType'], + ...isNotEmpty('enabled', 'webhookUrl', 'triggerType'), +}; + +export const n8nStatusSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + status: { type: 'string', enum: ['opened', 'closed', 'paused', 'delete'] }, + }, + required: ['remoteJid', 'status'], + ...isNotEmpty('remoteJid', 'status'), +}; + +export const n8nSettingSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + botIdFallback: { type: 'string' }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: [ + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ], + ...isNotEmpty( + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ), +}; + +export const n8nIgnoreJidSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + action: { type: 'string', enum: ['add', 'remove'] }, + }, + required: ['remoteJid', 'action'], + ...isNotEmpty('remoteJid', 'action'), +}; diff --git a/src/api/integrations/chatbot/openai/controllers/openai.controller.ts b/src/api/integrations/chatbot/openai/controllers/openai.controller.ts index 4bb2bcdb..1d9910d1 100644 --- a/src/api/integrations/chatbot/openai/controllers/openai.controller.ts +++ b/src/api/integrations/chatbot/openai/controllers/openai.controller.ts @@ -1,4 +1,3 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { OpenaiCredsDto, OpenaiDto } from '@api/integrations/chatbot/openai/dto/openai.dto'; import { OpenaiService } from '@api/integrations/chatbot/openai/services/openai.service'; @@ -7,13 +6,12 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { configService, Openai } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import { OpenaiBot } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { IntegrationSession, OpenaiBot } from '@prisma/client'; import OpenAI from 'openai'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; -export class OpenaiController extends ChatbotController implements ChatbotControllerInterface { +export class OpenaiController extends BaseChatbotController { constructor( private readonly openaiService: OpenaiService, prismaRepository: PrismaRepository, @@ -28,6 +26,7 @@ export class OpenaiController extends ChatbotController implements ChatbotContro } public readonly logger = new Logger('OpenaiController'); + protected readonly integrationName = 'Openai'; integrationEnabled = configService.get('OPENAI').ENABLED; botRepository: any; @@ -37,7 +36,191 @@ export class OpenaiController extends ChatbotController implements ChatbotContro private client: OpenAI; private credsRepository: any; - // Credentials + protected getFallbackBotId(settings: any): string | undefined { + return settings?.openaiIdFallback; + } + + protected getFallbackFieldName(): string { + return 'openaiIdFallback'; + } + + protected getIntegrationType(): string { + return 'openai'; + } + + protected getAdditionalBotData(data: OpenaiDto): Record { + return { + openaiCredsId: data.openaiCredsId, + botType: data.botType, + assistantId: data.assistantId, + functionUrl: data.functionUrl, + model: data.model, + systemMessages: data.systemMessages, + assistantMessages: data.assistantMessages, + userMessages: data.userMessages, + maxTokens: data.maxTokens, + }; + } + + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: OpenaiDto): Record { + return { + openaiCredsId: data.openaiCredsId, + botType: data.botType, + assistantId: data.assistantId, + functionUrl: data.functionUrl, + model: data.model, + systemMessages: data.systemMessages, + assistantMessages: data.assistantMessages, + userMessages: data.userMessages, + maxTokens: data.maxTokens, + }; + } + + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: OpenaiDto): Promise { + let whereDuplication: any = { + id: { + not: botId, + }, + instanceId: instanceId, + }; + + if (data.botType === 'assistant') { + if (!data.assistantId) throw new Error('Assistant ID is required'); + + whereDuplication = { + ...whereDuplication, + assistantId: data.assistantId, + botType: data.botType, + }; + } else if (data.botType === 'chatCompletion') { + if (!data.model) throw new Error('Model is required'); + if (!data.maxTokens) throw new Error('Max tokens is required'); + + whereDuplication = { + ...whereDuplication, + model: data.model, + maxTokens: data.maxTokens, + botType: data.botType, + }; + } else { + throw new Error('Bot type is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: whereDuplication, + }); + + if (checkDuplicate) { + throw new Error('OpenAI Bot already exists'); + } + } + + // Override createBot to handle OpenAI-specific credential logic + public async createBot(instance: InstanceDto, data: OpenaiDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // OpenAI specific validation + let whereDuplication: any = { + instanceId: instanceId, + }; + + if (data.botType === 'assistant') { + if (!data.assistantId) throw new Error('Assistant ID is required'); + + whereDuplication = { + ...whereDuplication, + assistantId: data.assistantId, + botType: data.botType, + }; + } else if (data.botType === 'chatCompletion') { + if (!data.model) throw new Error('Model is required'); + if (!data.maxTokens) throw new Error('Max tokens is required'); + + whereDuplication = { + ...whereDuplication, + model: data.model, + maxTokens: data.maxTokens, + botType: data.botType, + }; + } else { + throw new Error('Bot type is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: whereDuplication, + }); + + if (checkDuplicate) { + throw new Error('Openai Bot already exists'); + } + + // Check if settings exist and create them if not + const existingSettings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!existingSettings) { + // Create default settings with the OpenAI credentials + await this.settings(instance, { + openaiCredsId: data.openaiCredsId, + expire: data.expire || 300, + keywordFinish: data.keywordFinish || 'bye', + delayMessage: data.delayMessage || 1000, + unknownMessage: data.unknownMessage || 'Sorry, I dont understand', + listeningFromMe: data.listeningFromMe !== undefined ? data.listeningFromMe : true, + stopBotFromMe: data.stopBotFromMe !== undefined ? data.stopBotFromMe : true, + keepOpen: data.keepOpen !== undefined ? data.keepOpen : false, + debounceTime: data.debounceTime || 1, + ignoreJids: data.ignoreJids || [], + speechToText: false, + }); + } else if (!existingSettings.openaiCredsId && data.openaiCredsId) { + // Update settings with OpenAI credentials if they're missing + await this.settingsRepository.update({ + where: { + id: existingSettings.id, + }, + data: { + OpenaiCreds: { + connect: { + id: data.openaiCredsId, + }, + }, + }, + }); + } + + // Let the base class handle the rest of the bot creation process + return super.createBot(instance, data); + } + + // Process OpenAI-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: OpenaiBot, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.openaiService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } + + // Credentials - OpenAI specific functionality public async createOpenaiCreds(instance: InstanceDto, data: OpenaiCredsDto) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); @@ -49,8 +232,31 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - if (!data.apiKey) throw new Error('API Key is required'); - if (!data.name) throw new Error('Name is required'); + if (!data.apiKey) throw new BadRequestException('API Key is required'); + if (!data.name) throw new BadRequestException('Name is required'); + + // Check if API key already exists + const existingApiKey = await this.credsRepository.findFirst({ + where: { + apiKey: data.apiKey, + }, + }); + + if (existingApiKey) { + throw new BadRequestException('This API key is already registered. Please use a different API key.'); + } + + // Check if name already exists for this instance + const existingName = await this.credsRepository.findFirst({ + where: { + name: data.name, + instanceId: instanceId, + }, + }); + + if (existingName) { + throw new BadRequestException('This credential name is already in use. Please choose a different name.'); + } try { const creds = await this.credsRepository.create({ @@ -130,494 +336,7 @@ export class OpenaiController extends ChatbotController implements ChatbotContro } } - // Models - public async getModels(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if (!instanceId) throw new Error('Instance not found'); - - const defaultSettings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - OpenaiCreds: true, - }, - }); - - if (!defaultSettings) throw new Error('Settings not found'); - - const { apiKey } = defaultSettings.OpenaiCreds; - - try { - this.client = new OpenAI({ apiKey }); - - const models: any = await this.client.models.list(); - - return models?.body?.data; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching models'); - } - } - - // Bots - public async createBot(instance: InstanceDto, data: OpenaiDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.openaiCredsId || - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; - - if (!data.openaiCredsId) { - throw new Error('Openai Creds Id is required'); - } - - if (!defaultSettingCheck) { - await this.settings(instance, { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a openai with an "All" trigger, you cannot have more bots while it is active'); - } - - let whereDuplication: any = { - instanceId: instanceId, - }; - - if (data.botType === 'assistant') { - if (!data.assistantId) throw new Error('Assistant ID is required'); - - whereDuplication = { - ...whereDuplication, - assistantId: data.assistantId, - botType: data.botType, - }; - } else if (data.botType === 'chatCompletion') { - if (!data.model) throw new Error('Model is required'); - if (!data.maxTokens) throw new Error('Max tokens is required'); - - whereDuplication = { - ...whereDuplication, - model: data.model, - maxTokens: data.maxTokens, - botType: data.botType, - }; - } else { - throw new Error('Bot type is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: whereDuplication, - }); - - if (checkDuplicate) { - throw new Error('Openai Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - openaiCredsId: data.openaiCredsId, - botType: data.botType, - assistantId: data.assistantId, - functionUrl: data.functionUrl, - model: data.model, - systemMessages: data.systemMessages, - assistantMessages: data.assistantMessages, - userMessages: data.userMessages, - maxTokens: data.maxTokens, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating openai bot'); - } - } - - public async findBot(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; - } - - public async fetchBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Openai Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - return bot; - } - - public async updateBot(instance: InstanceDto, botId: string, data: OpenaiDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Openai Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error( - 'You already have a openai bot with an "All" trigger, you cannot have more bots while it is active', - ); - } - } - - let whereDuplication: any = { - id: { - not: botId, - }, - instanceId: instanceId, - }; - - if (data.botType === 'assistant') { - if (!data.assistantId) throw new Error('Assistant ID is required'); - - whereDuplication = { - ...whereDuplication, - assistantId: data.assistantId, - }; - } else if (data.botType === 'chatCompletion') { - if (!data.model) throw new Error('Model is required'); - if (!data.maxTokens) throw new Error('Max tokens is required'); - - whereDuplication = { - ...whereDuplication, - model: data.model, - maxTokens: data.maxTokens, - }; - } else { - throw new Error('Bot type is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: whereDuplication, - }); - - if (checkDuplicate) { - throw new Error('Openai Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - openaiCredsId: data.openaiCredsId, - botType: data.botType, - assistantId: data.assistantId, - functionUrl: data.functionUrl, - model: data.model, - systemMessages: data.systemMessages, - assistantMessages: data.assistantMessages, - userMessages: data.userMessages, - maxTokens: data.maxTokens, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating openai bot'); - } - } - - public async deleteBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Openai bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Openai bot not found'); - } - try { - await this.sessionRepository.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting openai bot'); - } - } - - // Settings + // Override the settings method to handle the OpenAI credentials public async settings(instance: InstanceDto, data: any) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); @@ -630,497 +349,134 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - const settings = await this.settingsRepository.findFirst({ + const existingSettings = await this.settingsRepository.findFirst({ where: { instanceId: instanceId, }, }); - if (settings) { - const updateSettings = await this.settingsRepository.update({ + // Convert keywordFinish to string if it's an array + const keywordFinish = data.keywordFinish; + + // Additional OpenAI-specific fields + const settingsData = { + expire: data.expire, + keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + openaiIdFallback: data.fallbackId, + OpenaiCreds: data.openaiCredsId + ? { + connect: { + id: data.openaiCredsId, + }, + } + : undefined, + speechToText: data.speechToText, + }; + + if (existingSettings) { + const settings = await this.settingsRepository.update({ where: { - id: settings.id, + id: existingSettings.id, }, + data: settingsData, + }); + + // Map the specific fallback field to a generic 'fallbackId' in the response + return { + ...settings, + fallbackId: settings.openaiIdFallback, + }; + } else { + const settings = await this.settingsRepository.create({ data: { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - speechToText: data.speechToText, - openaiIdFallback: data.openaiIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, + ...settingsData, + Instance: { + connect: { + id: instanceId, + }, + }, }, }); + // Map the specific fallback field to a generic 'fallbackId' in the response return { - openaiCredsId: updateSettings.openaiCredsId, - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - speechToText: updateSettings.speechToText, - openaiIdFallback: updateSettings.openaiIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, + ...settings, + fallbackId: settings.openaiIdFallback, }; } - - const newSetttings = await this.settingsRepository.create({ - data: { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - openaiIdFallback: data.openaiIdFallback, - ignoreJids: data.ignoreJids, - speechToText: data.speechToText, - instanceId: instanceId, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - openaiCredsId: newSetttings.openaiCredsId, - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - openaiIdFallback: newSetttings.openaiIdFallback, - ignoreJids: newSetttings.ignoreJids, - speechToText: newSetttings.speechToText, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; } catch (error) { this.logger.error(error); throw new Error('Error setting default settings'); } } - public async fetchSettings(instance: InstanceDto) { + // Models - OpenAI specific functionality + public async getModels(instance: InstanceDto, openaiCredsId?: string) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - try { - const instanceId = ( - await this.prismaRepository.instance.findFirst({ - select: { id: true }, - where: { - name: instance.instanceName, - }, - }) - )?.id; + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); - const settings = await this.settingsRepository.findFirst({ + if (!instanceId) throw new Error('Instance not found'); + + let apiKey: string; + + if (openaiCredsId) { + // Use specific credential ID if provided + const creds = await this.credsRepository.findFirst({ + where: { + id: openaiCredsId, + instanceId: instanceId, // Ensure the credential belongs to this instance + }, + }); + + if (!creds) throw new Error('OpenAI credentials not found for the provided ID'); + + apiKey = creds.apiKey; + } else { + // Use default credentials from settings if no ID provided + const defaultSettings = await this.settingsRepository.findFirst({ where: { instanceId: instanceId, }, include: { - Fallback: true, + OpenaiCreds: true, }, }); - if (!settings) { - return { - openaiCredsId: null, - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - openaiIdFallback: null, - speechToText: false, - fallback: null, - }; - } + if (!defaultSettings) throw new Error('Settings not found'); - return { - openaiCredsId: settings.openaiCredsId, - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - openaiIdFallback: settings.openaiIdFallback, - speechToText: settings.speechToText, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); + if (!defaultSettings.OpenaiCreds) + throw new Error( + 'OpenAI credentials not found. Please create credentials and associate them with the settings.', + ); + + apiKey = defaultSettings.OpenaiCreds.apiKey; } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); + this.client = new OpenAI({ apiKey }); - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); + const models: any = await this.client.models.list(); - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { openai: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - status: { not: 'closed' }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - }, - }); - } - - return { openai: { ...instance, openai: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const openaiData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { openai: { ...instance, openai: openaiData } }; - } + return models?.body?.data; } catch (error) { this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (openaiBot && openaiBot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: openaiBot ? botId : { not: null }, - type: 'openai', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - // Emit - public async emit({ instance, remoteJid, msg, pushName }: EmitData) { - if (!this.integrationEnabled) return; - - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - let session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger(this.botRepository, content, instance, session)) as OpenaiBot; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.openaiIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.openaiIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - session = await this.sessionRepository.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - if (findBot.botType === 'assistant') { - await this.openaiService.processOpenaiAssistant( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - key.fromMe, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - ); - } - - if (findBot.botType === 'chatCompletion') { - await this.openaiService.processOpenaiChatCompletion( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - ); - } - }); - } else { - if (findBot.botType === 'assistant') { - await this.openaiService.processOpenaiAssistant( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - key.fromMe, - findBot, - session, - settings, - content, - ); - } - - if (findBot.botType === 'chatCompletion') { - await this.openaiService.processOpenaiChatCompletion( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - findBot, - session, - settings, - content, - ); - } - } - - return; - } catch (error) { - this.logger.error(error); - return; + throw new Error('Error fetching models'); } } } diff --git a/src/api/integrations/chatbot/openai/dto/openai.dto.ts b/src/api/integrations/chatbot/openai/dto/openai.dto.ts index a8ac2e4d..9cea4ce5 100644 --- a/src/api/integrations/chatbot/openai/dto/openai.dto.ts +++ b/src/api/integrations/chatbot/openai/dto/openai.dto.ts @@ -1,15 +1,13 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; export class OpenaiCredsDto { name: string; apiKey: string; } -export class OpenaiDto { - enabled?: boolean; - description?: string; +export class OpenaiDto extends BaseChatbotDto { openaiCredsId: string; - botType?: string; + botType: string; assistantId?: string; functionUrl?: string; model?: string; @@ -17,35 +15,10 @@ export class OpenaiDto { assistantMessages?: string[]; userMessages?: string[]; maxTokens?: number; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } -export class OpenaiSettingDto { +export class OpenaiSettingDto extends BaseChatbotSettingDto { openaiCredsId?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; openaiIdFallback?: string; - ignoreJids?: any; speechToText?: boolean; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/openai/routes/openai.router.ts b/src/api/integrations/chatbot/openai/routes/openai.router.ts index ed55a4e7..262815d4 100644 --- a/src/api/integrations/chatbot/openai/routes/openai.router.ts +++ b/src/api/integrations/chatbot/openai/routes/openai.router.ts @@ -153,7 +153,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => openaiController.getModels(instance), + execute: (instance) => openaiController.getModels(instance, req.query.openaiCredsId as string), }); res.status(HttpStatus.OK).json(response); diff --git a/src/api/integrations/chatbot/openai/services/openai.service.ts b/src/api/integrations/chatbot/openai/services/openai.service.ts index 16f4ce80..dd00b04c 100644 --- a/src/api/integrations/chatbot/openai/services/openai.service.ts +++ b/src/api/integrations/chatbot/openai/services/openai.service.ts @@ -1,11 +1,8 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { ConfigService, Language } from '@config/env.config'; -import { Logger } from '@config/logger.config'; -import { IntegrationSession, OpenaiBot, OpenaiCreds, OpenaiSetting } from '@prisma/client'; +import { ConfigService, Language, Openai as OpenaiConfig } from '@config/env.config'; +import { IntegrationSession, OpenaiBot, OpenaiSetting } from '@prisma/client'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; import { downloadMediaMessage } from 'baileys'; @@ -13,104 +10,273 @@ import FormData from 'form-data'; import OpenAI from 'openai'; import P from 'pino'; -export class OpenaiService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} +import { BaseChatbotService } from '../../base-chatbot.service'; - private client: OpenAI; +/** + * OpenAI service that extends the common BaseChatbotService + * Handles both Assistant API and ChatCompletion API + */ +export class OpenaiService extends BaseChatbotService { + protected client: OpenAI; - private readonly logger = new Logger('OpenaiService'); - - private async sendMessageToBot(instance: any, openaiBot: OpenaiBot, remoteJid: string, content: string) { - const systemMessages: any = openaiBot.systemMessages; - - const messagesSystem: any[] = systemMessages.map((message) => { - return { - role: 'system', - content: message, - }; - }); - - const assistantMessages: any = openaiBot.assistantMessages; - - const messagesAssistant: any[] = assistantMessages.map((message) => { - return { - role: 'assistant', - content: message, - }; - }); - - const userMessages: any = openaiBot.userMessages; - - const messagesUser: any[] = userMessages.map((message) => { - return { - role: 'user', - content: message, - }; - }); - - const messageData: any = { - role: 'user', - content: [{ type: 'text', text: content }], - }; - - if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - const url = contentSplit[1].split('?')[0]; - - messageData.content = [ - { type: 'text', text: contentSplit[2] || content }, - { - type: 'image_url', - image_url: { - url: url, - }, - }, - ]; - } - - const messages: any[] = [...messagesSystem, ...messagesAssistant, ...messagesUser, messageData]; - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - const completions = await this.client.chat.completions.create({ - model: openaiBot.model, - messages: messages, - max_tokens: openaiBot.maxTokens, - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = completions.choices[0].message.content; - - return message; + constructor(waMonitor: WAMonitoringService, prismaRepository: PrismaRepository, configService: ConfigService) { + super(waMonitor, prismaRepository, 'OpenaiService', configService); } - private async sendMessageToAssistant( + /** + * Return the bot type for OpenAI + */ + protected getBotType(): string { + return 'openai'; + } + + /** + * Initialize the OpenAI client with the provided API key + */ + protected initClient(apiKey: string) { + this.client = new OpenAI({ apiKey }); + return this.client; + } + + /** + * Process a message based on the bot type (assistant or chat completion) + */ + public async process( instance: any, + remoteJid: string, + openaiBot: OpenaiBot, + session: IntegrationSession, + settings: OpenaiSetting, + content: string, + pushName?: string, + msg?: any, + ): Promise { + try { + this.logger.log(`Starting process for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`); + + // Handle audio message transcription + if (content.startsWith('audioMessage|') && msg) { + this.logger.log('Detected audio message, attempting to transcribe'); + + // Get OpenAI credentials for transcription + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); + + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`); + return; + } + + // Initialize OpenAI client for transcription + this.initClient(creds.apiKey); + + // Transcribe the audio + const transcription = await this.speechToText(msg, instance); + + if (transcription) { + this.logger.log(`Audio transcribed: ${transcription}`); + // Replace the audio message identifier with the transcription + content = transcription; + } else { + this.logger.error('Failed to transcribe audio'); + await this.sendMessageWhatsApp( + instance, + remoteJid, + "Sorry, I couldn't transcribe your audio message. Could you please type your message instead?", + settings, + ); + return; + } + } else { + // Get the OpenAI credentials + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); + + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`); + return; + } + + // Initialize OpenAI client + this.initClient(creds.apiKey); + } + + // Handle keyword finish + const keywordFinish = settings?.keywordFinish || ''; + const normalizedContent = content.toLowerCase().trim(); + if (keywordFinish.length > 0 && normalizedContent === keywordFinish.toLowerCase()) { + if (settings?.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.delete({ + where: { + id: session.id, + }, + }); + } + + await sendTelemetry('/openai/session/finish'); + return; + } + + // If session is new or doesn't exist + if (!session) { + const data = { + remoteJid, + pushName, + botId: openaiBot.id, + }; + + const createSession = await this.createNewSession( + { instanceName: instance.instanceName, instanceId: instance.instanceId }, + data, + this.getBotType(), + ); + + await this.initNewSession( + instance, + remoteJid, + openaiBot, + settings, + createSession.session, + content, + pushName, + msg, + ); + + await sendTelemetry('/openai/session/start'); + return; + } + + // If session exists but is paused + if (session.status === 'paused') { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + + return; + } + + // Process with the appropriate API based on bot type + await this.sendMessageToBot(instance, session, settings, openaiBot, remoteJid, pushName || '', content); + } catch (error) { + this.logger.error(`Error in process: ${error.message || JSON.stringify(error)}`); + return; + } + } + + /** + * Send message to OpenAI - this handles both Assistant API and ChatCompletion API + */ + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: OpenaiSetting, + openaiBot: OpenaiBot, + remoteJid: string, + pushName: string, + content: string, + ): Promise { + this.logger.log(`Sending message to bot for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`); + + if (!this.client) { + this.logger.log('Client not initialized, initializing now'); + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); + + if (!creds) { + this.logger.error(`OpenAI credentials not found in sendMessageToBot. CredsId: ${openaiBot.openaiCredsId}`); + return; + } + + this.initClient(creds.apiKey); + } + + try { + let message: string; + + // Handle different bot types + if (openaiBot.botType === 'assistant') { + this.logger.log('Processing with Assistant API'); + message = await this.processAssistantMessage( + instance, + session, + openaiBot, + remoteJid, + pushName, + false, // Not fromMe + content, + ); + } else { + this.logger.log('Processing with ChatCompletion API'); + message = await this.processChatCompletionMessage(instance, openaiBot, remoteJid, content); + } + + this.logger.log(`Got response from OpenAI: ${message?.substring(0, 50)}${message?.length > 50 ? '...' : ''}`); + + // Send the response + if (message) { + this.logger.log('Sending message to WhatsApp'); + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + } else { + this.logger.error('No message to send to WhatsApp'); + } + + // Update session status + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } catch (error) { + this.logger.error(`Error in sendMessageToBot: ${error.message || JSON.stringify(error)}`); + if (error.response) { + this.logger.error(`API Response data: ${JSON.stringify(error.response.data || {})}`); + } + return; + } + } + + /** + * Process message using the OpenAI Assistant API + */ + private async processAssistantMessage( + instance: any, + session: IntegrationSession, openaiBot: OpenaiBot, remoteJid: string, pushName: string, fromMe: boolean, content: string, - threadId: string, - ) { + ): Promise { const messageData: any = { role: fromMe ? 'assistant' : 'user', content: [{ type: 'text', text: content }], }; + // Handle image messages if (this.isImageMessage(content)) { const contentSplit = content.split('|'); - const url = contentSplit[1].split('?')[0]; messageData.content = [ @@ -124,13 +290,35 @@ export class OpenaiService { ]; } + // Get thread ID from session or create new thread + let threadId = session.sessionId; + + // Create a new thread if one doesn't exist or invalid format + if (!threadId || threadId === remoteJid) { + const newThread = await this.client.beta.threads.create(); + threadId = newThread.id; + + // Save the new thread ID to the session + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + sessionId: threadId, + }, + }); + this.logger.log(`Created new thread ID: ${threadId} for session: ${session.id}`); + } + + // Add message to thread await this.client.beta.threads.messages.create(threadId, messageData); if (fromMe) { sendTelemetry('/message/sendText'); - return; + return ''; } + // Run the assistant const runAssistant = await this.client.beta.threads.runs.create(threadId, { assistant_id: openaiBot.assistantId, }); @@ -140,190 +328,31 @@ export class OpenaiService { await instance.client.sendPresenceUpdate('composing', remoteJid); } + // Wait for the assistant to complete const response = await this.getAIResponse(threadId, runAssistant.id, openaiBot.functionUrl, remoteJid, pushName); - if (instance.integration === Integration.WHATSAPP_BAILEYS) + if (instance.integration === Integration.WHATSAPP_BAILEYS) { await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data[0].content[0].text.value; - - return message; - } - - private async sendMessageWhatsapp( - instance: any, - session: IntegrationSession, - remoteJid: string, - settings: OpenaiSetting, - message: string, - ) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - textBuffer = ''; - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; } - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); + // Extract the response text safely with type checking + let responseText = "I couldn't generate a proper response. Please try again."; + try { + const messages = response?.data || []; + if (messages.length > 0) { + const messageContent = messages[0]?.content || []; + if (messageContent.length > 0) { + const textContent = messageContent[0]; + if (textContent && 'text' in textContent && textContent.text && 'value' in textContent.text) { + responseText = textContent.text.value; } } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); } - textBuffer = ''; + } catch (error) { + this.logger.error(`Error extracting response text: ${error}`); } - sendTelemetry('/message/sendText'); - + // Update session with the thread ID to ensure continuity await this.prismaRepository.integrationSession.update({ where: { id: session.id, @@ -331,504 +360,322 @@ export class OpenaiService { data: { status: 'opened', awaitUser: true, + sessionId: threadId, // Ensure thread ID is saved consistently }, }); + + // Return fallback message if unable to extract text + return responseText; } - public async createAssistantNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; + /** + * Process message using the OpenAI ChatCompletion API + */ + private async processChatCompletionMessage( + instance: any, + openaiBot: OpenaiBot, + remoteJid: string, + content: string, + ): Promise { + this.logger.log('Starting processChatCompletionMessage'); - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: data.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - try { - this.client = new OpenAI({ - apiKey: creds.apiKey, + // Check if client is initialized + if (!this.client) { + this.logger.log('Client not initialized in processChatCompletionMessage, initializing now'); + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, }); - const threadId = (await this.client.beta.threads.create({})).id; - - let session = null; - if (threadId) { - session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: threadId, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'openai', - }, - }); + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`); + return 'Error: OpenAI credentials not found'; } - return { session }; - } catch (error) { - this.logger.error(error); - return; - } - } - private async initAssistantNewSession( - instance: any, - remoteJid: string, - pushName: string, - fromMe: boolean, - openaiBot: OpenaiBot, - settings: OpenaiSetting, - session: IntegrationSession, - content: string, - ) { - const data = await this.createAssistantNewSession(instance, { - remoteJid, - pushName, - openaiCredsId: openaiBot.openaiCredsId, - botId: openaiBot.id, + this.initClient(creds.apiKey); + } + + // Check if model is defined + if (!openaiBot.model) { + this.logger.error('OpenAI model not defined'); + return 'Error: OpenAI model not configured'; + } + + this.logger.log(`Using model: ${openaiBot.model}, max tokens: ${openaiBot.maxTokens || 500}`); + + // Get existing conversation history from the session + const session = await this.prismaRepository.integrationSession.findFirst({ + where: { + remoteJid, + botId: openaiBot.id, + status: 'opened', + }, }); - if (data.session) { - session = data.session; + let conversationHistory = []; + + if (session && session.context) { + try { + const sessionData = + typeof session.context === 'string' ? JSON.parse(session.context as string) : session.context; + + conversationHistory = sessionData.history || []; + this.logger.log(`Retrieved conversation history from session, ${conversationHistory.length} messages`); + } catch (error) { + this.logger.error(`Error parsing session context: ${error.message}`); + // Continue with empty history if we can't parse the session data + conversationHistory = []; + } } - const message = await this.sendMessageToAssistant( - instance, - openaiBot, - remoteJid, - pushName, - fromMe, - content, - session.sessionId, - ); + // Log bot data + this.logger.log(`Bot data - systemMessages: ${JSON.stringify(openaiBot.systemMessages || [])}`); + this.logger.log(`Bot data - assistantMessages: ${JSON.stringify(openaiBot.assistantMessages || [])}`); + this.logger.log(`Bot data - userMessages: ${JSON.stringify(openaiBot.userMessages || [])}`); - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); + // Prepare system messages + const systemMessages: any = openaiBot.systemMessages || []; + const messagesSystem: any[] = systemMessages.map((message) => { + return { + role: 'system', + content: message, + }; + }); - return; - } + // Prepare assistant messages + const assistantMessages: any = openaiBot.assistantMessages || []; + const messagesAssistant: any[] = assistantMessages.map((message) => { + return { + role: 'assistant', + content: message, + }; + }); - private isJSON(str: string): boolean { + // Prepare user messages + const userMessages: any = openaiBot.userMessages || []; + const messagesUser: any[] = userMessages.map((message) => { + return { + role: 'user', + content: message, + }; + }); + + // Prepare current message + const messageData: any = { + role: 'user', + content: [{ type: 'text', text: content }], + }; + + // Handle image messages + if (this.isImageMessage(content)) { + this.logger.log('Found image message'); + const contentSplit = content.split('|'); + const url = contentSplit[1].split('?')[0]; + + messageData.content = [ + { type: 'text', text: contentSplit[2] || content }, + { + type: 'image_url', + image_url: { + url: url, + }, + }, + ]; + } + + // Combine all messages: system messages, pre-defined messages, conversation history, and current message + const messages: any[] = [ + ...messagesSystem, + ...messagesAssistant, + ...messagesUser, + ...conversationHistory, + messageData, + ]; + + this.logger.log(`Final messages payload: ${JSON.stringify(messages)}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + this.logger.log('Setting typing indicator'); + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + // Send the request to OpenAI try { - JSON.parse(str); - return true; - } catch (e) { - return false; + this.logger.log('Sending request to OpenAI API'); + const completions = await this.client.chat.completions.create({ + model: openaiBot.model, + messages: messages, + max_tokens: openaiBot.maxTokens || 500, // Add default if maxTokens is missing + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); + } + + const responseContent = completions.choices[0].message.content; + this.logger.log(`Received response from OpenAI: ${JSON.stringify(completions.choices[0])}`); + + // Add the current exchange to the conversation history and update the session + conversationHistory.push(messageData); + conversationHistory.push({ + role: 'assistant', + content: responseContent, + }); + + // Limit history length to avoid token limits (keep last 10 messages) + if (conversationHistory.length > 10) { + conversationHistory = conversationHistory.slice(conversationHistory.length - 10); + } + + // Save the updated conversation history to the session + if (session) { + await this.prismaRepository.integrationSession.update({ + where: { id: session.id }, + data: { + context: JSON.stringify({ + history: conversationHistory, + }), + }, + }); + this.logger.log(`Updated session with conversation history, now ${conversationHistory.length} messages`); + } + + return responseContent; + } catch (error) { + this.logger.error(`Error calling OpenAI: ${error.message || JSON.stringify(error)}`); + if (error.response) { + this.logger.error(`API Response status: ${error.response.status}`); + this.logger.error(`API Response data: ${JSON.stringify(error.response.data || {})}`); + } + return `Sorry, there was an error: ${error.message || 'Unknown error'}`; } } + /** + * Wait for and retrieve the AI response + */ private async getAIResponse( threadId: string, runId: string, - functionUrl: string, + functionUrl: string | null, remoteJid: string, pushName: string, ) { - const getRun = await this.client.beta.threads.runs.retrieve(threadId, runId); - let toolCalls; - switch (getRun.status) { - case 'requires_action': - toolCalls = getRun?.required_action?.submit_tool_outputs?.tool_calls; + let status = await this.client.beta.threads.runs.retrieve(threadId, runId); - if (toolCalls) { - for (const toolCall of toolCalls) { - const id = toolCall.id; - const functionName = toolCall?.function?.name; - const functionArgument = this.isJSON(toolCall?.function?.arguments) - ? JSON.parse(toolCall?.function?.arguments) - : toolCall?.function?.arguments; + let maxRetries = 60; // 1 minute with 1s intervals + const checkInterval = 1000; // 1 second - let output = null; + while ( + status.status !== 'completed' && + status.status !== 'failed' && + status.status !== 'cancelled' && + status.status !== 'expired' && + maxRetries > 0 + ) { + await new Promise((resolve) => setTimeout(resolve, checkInterval)); + status = await this.client.beta.threads.runs.retrieve(threadId, runId); + // Handle tool calls + if (status.status === 'requires_action' && status.required_action?.type === 'submit_tool_outputs') { + const toolCalls = status.required_action.submit_tool_outputs.tool_calls; + const toolOutputs = []; + + for (const toolCall of toolCalls) { + if (functionUrl) { try { - const { data } = await axios.post(functionUrl, { - name: functionName, - arguments: { ...functionArgument, remoteJid, pushName }, + const payloadData = JSON.parse(toolCall.function.arguments); + + // Add context + payloadData.remoteJid = remoteJid; + payloadData.pushName = pushName; + + const response = await axios.post(functionUrl, { + functionName: toolCall.function.name, + functionArguments: payloadData, }); - output = JSON.stringify(data) - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t'); + toolOutputs.push({ + tool_call_id: toolCall.id, + output: JSON.stringify(response.data), + }); } catch (error) { - output = JSON.stringify(error) - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t'); + this.logger.error(`Error calling function: ${error}`); + toolOutputs.push({ + tool_call_id: toolCall.id, + output: JSON.stringify({ error: 'Function call failed' }), + }); } - - await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, { - tool_outputs: [ - { - tool_call_id: id, - output, - }, - ], + } else { + toolOutputs.push({ + tool_call_id: toolCall.id, + output: JSON.stringify({ error: 'No function URL configured' }), }); } } - return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); - case 'queued': - await new Promise((resolve) => setTimeout(resolve, 1000)); - return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); - case 'in_progress': - await new Promise((resolve) => setTimeout(resolve, 1000)); - return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); - case 'completed': - return await this.client.beta.threads.messages.list(threadId, { - run_id: runId, - limit: 1, + await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, { + tool_outputs: toolOutputs, }); + } + + maxRetries--; + } + + if (status.status === 'completed') { + const messages = await this.client.beta.threads.messages.list(threadId); + return messages; + } else { + this.logger.error(`Assistant run failed with status: ${status.status}`); + return { data: [{ content: [{ text: { value: 'Failed to get a response from the assistant.' } }] }] }; } } - private isImageMessage(content: string) { + protected isImageMessage(content: string): boolean { return content.includes('imageMessage'); } - public async processOpenaiAssistant( - instance: any, - remoteJid: string, - pushName: string, - fromMe: boolean, - openaiBot: OpenaiBot, - session: IntegrationSession, - settings: OpenaiSetting, - content: string, - ) { - if (session && session.status === 'closed') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initAssistantNewSession( - instance, - remoteJid, - pushName, - fromMe, - openaiBot, - settings, - session, - content, - ); - return; - } - } - - if (!session) { - await this.initAssistantNewSession(instance, remoteJid, pushName, fromMe, openaiBot, settings, session, content); - return; - } - - if (session.status !== 'paused') - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - const creds = await this.prismaRepository.openaiCreds.findFirst({ + /** + * Implementation of speech-to-text transcription for audio messages + */ + public async speechToText(msg: any, instance: any): Promise { + const settings = await this.prismaRepository.openaiSetting.findFirst({ where: { - id: openaiBot.openaiCredsId, + instanceId: instance.instanceId, }, }); - if (!creds) throw new Error('Openai Creds not found'); - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const threadId = session.sessionId; - - const message = await this.sendMessageToAssistant( - instance, - openaiBot, - remoteJid, - pushName, - fromMe, - content, - threadId, - ); - - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); - - return; - } - - public async createChatCompletionNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - - const id = Math.floor(Math.random() * 10000000000).toString(); - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: data.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: id, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'openai', - }, - }); - - return { session, creds }; - } catch (error) { - this.logger.error(error); - return; - } - } - - private async initChatCompletionNewSession( - instance: any, - remoteJid: string, - pushName: string, - openaiBot: OpenaiBot, - settings: OpenaiSetting, - session: IntegrationSession, - content: string, - ) { - const data = await this.createChatCompletionNewSession(instance, { - remoteJid, - pushName, - openaiCredsId: openaiBot.openaiCredsId, - botId: openaiBot.id, - }); - - session = data.session; - - const creds = data.creds; - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content); - - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); - - return; - } - - public async processOpenaiChatCompletion( - instance: any, - remoteJid: string, - pushName: string, - openaiBot: OpenaiBot, - session: IntegrationSession, - settings: OpenaiSetting, - content: string, - ) { - if (session && session.status !== 'opened') { - return; + if (!settings) { + this.logger.error(`OpenAI settings not found. InstanceId: ${instance.instanceId}`); + return null; } - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content); - return; - } - } - - if (!session) { - await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content); - return; - } - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: settings.openaiCredsId }, }); - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${settings.openaiCredsId}`); + return null; } - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } + let audio: Buffer; - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: openaiBot.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content); - - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); - - return; - } - - public async speechToText(creds: OpenaiCreds, msg: any, updateMediaMessage: any) { - let audio; - - if (msg?.message?.mediaUrl) { + if (msg.message.mediaUrl) { audio = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }).then((response) => { return Buffer.from(response.data, 'binary'); }); + } else if (msg.message.base64) { + audio = Buffer.from(msg.message.base64, 'base64'); } else { + // Fallback for raw WhatsApp audio messages that need downloadMediaMessage audio = await downloadMediaMessage( { key: msg.key, message: msg?.message }, 'buffer', {}, { logger: P({ level: 'error' }) as any, - reuploadRequest: updateMediaMessage, + reuploadRequest: instance, }, ); } @@ -838,15 +685,16 @@ export class OpenaiService { : this.configService.get('LANGUAGE'); const formData = new FormData(); - formData.append('file', audio, 'audio.ogg'); formData.append('model', 'whisper-1'); formData.append('language', lang); + const apiKey = creds?.apiKey || this.configService.get('OPENAI').API_KEY_GLOBAL; + const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, { headers: { 'Content-Type': 'multipart/form-data', - Authorization: `Bearer ${creds.apiKey}`, + Authorization: `Bearer ${apiKey}`, }, }); diff --git a/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts b/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts index 14975234..169850f9 100644 --- a/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts +++ b/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts @@ -1,4 +1,3 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { TypebotDto } from '@api/integrations/chatbot/typebot/dto/typebot.dto'; import { TypebotService } from '@api/integrations/chatbot/typebot/services/typebot.service'; @@ -8,13 +7,12 @@ import { Events } from '@api/types/wa.types'; import { configService, Typebot } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import { Typebot as TypebotModel } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { IntegrationSession, Typebot as TypebotModel } from '@prisma/client'; import axios from 'axios'; -import { ChatbotController, ChatbotControllerInterface } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; -export class TypebotController extends ChatbotController implements ChatbotControllerInterface { +export class TypebotController extends BaseChatbotController { constructor( private readonly typebotService: TypebotService, prismaRepository: PrismaRepository, @@ -28,6 +26,7 @@ export class TypebotController extends ChatbotController implements ChatbotContr } public readonly logger = new Logger('TypebotController'); + protected readonly integrationName = 'Typebot'; integrationEnabled = configService.get('TYPEBOT').ENABLED; botRepository: any; @@ -35,245 +34,35 @@ export class TypebotController extends ChatbotController implements ChatbotContr sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: TypebotDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; - if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR'; - if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; - if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi'; - if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; - if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; - if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; - if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; - if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; - - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a typebot with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - url: data.url, - typebot: data.typebot, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Typebot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - url: data.url, - typebot: data.typebot, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating typebot'); - } + protected getFallbackBotId(settings: any): string | undefined { + return settings?.typebotIdFallback; } - public async findBot(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; + protected getFallbackFieldName(): string { + return 'typebotIdFallback'; } - public async fetchBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Typebot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - return bot; + protected getIntegrationType(): string { + return 'typebot'; } - public async updateBot(instance: InstanceDto, botId: string, data: TypebotDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + protected getAdditionalBotData(data: TypebotDto): Record { + return { + url: data.url, + typebot: data.typebot, + }; + } - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error( - 'You already have a typebot with an "All" trigger, you cannot have more bots while it is active', - ); - } - } + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: TypebotDto): Record { + return { + url: data.url, + typebot: data.typebot, + }; + } + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: TypebotDto): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { url: data.url, @@ -288,263 +77,24 @@ export class TypebotController extends ChatbotController implements ChatbotContr if (checkDuplicate) { throw new Error('Typebot already exists'); } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - url: data.url, - typebot: data.typebot, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating typebot'); - } } - public async deleteBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { typebot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting typebot'); - } + // Process Typebot-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: TypebotModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + // Use the simplified service method that follows the base class pattern + await this.typebotService.processTypebot(instance, remoteJid, bot, session, settings, content, pushName, msg); } - // Settings - public async settings(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - typebotIdFallback: data.typebotIdFallback, - ignoreJids: data.ignoreJids, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - typebotIdFallback: updateSettings.typebotIdFallback, - ignoreJids: updateSettings.ignoreJids, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - typebotIdFallback: data.typebotIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - typebotIdFallback: newSetttings.typebotIdFallback, - ignoreJids: newSetttings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - typebotIdFallback: null, - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - typebotIdFallback: settings.typebotIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions + // TypeBot specific method for starting a bot from API public async startBot(instance: InstanceDto, data: any) { if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); @@ -552,7 +102,7 @@ export class TypebotController extends ChatbotController implements ChatbotContr const instanceData = await this.prismaRepository.instance.findFirst({ where: { - name: instance.instanceName, + id: instance.instanceId, }, }); @@ -661,22 +211,25 @@ export class TypebotController extends ChatbotController implements ChatbotContr }, }); - await this.typebotService.processTypebot( - instanceData, - remoteJid, - null, - null, - findBot, - url, + // Use the simplified service method instead of the complex one + const settings = { expire, - typebot, keywordFinish, delayMessage, unknownMessage, listeningFromMe, stopBotFromMe, keepOpen, + }; + + await this.typebotService.processTypebot( + instanceData, + remoteJid, + findBot, + null, // session + settings, 'init', + null, // pushName prefilledVariables, ); } else { @@ -722,7 +275,7 @@ export class TypebotController extends ChatbotController implements ChatbotContr request.data.clientSideActions, ); - this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, { + this.waMonitor.waInstances[instance.instanceId].sendDataWebhook(Events.TYPEBOT_START, { remoteJid: remoteJid, url: url, typebot: typebot, @@ -747,325 +300,4 @@ export class TypebotController extends ChatbotController implements ChatbotContr }, }; } - - public async changeStatus(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const remoteJid = data.remoteJid; - const status = data.status; - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - botId: { not: null }, - }, - }); - - return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - botId: { not: null }, - }, - }); - } - - return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; - } - - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const typebotData = { - remoteJid: remoteJid, - status: status, - session, - }; - - this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); - - return { typebot: { ...instance, typebot: typebotData } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (typebot && typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: botId ?? { not: null }, - type: 'typebot', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async emit({ - instance, - remoteJid, - msg, - }: { - instance: InstanceDto; - remoteJid: string; - msg: any; - pushName?: string; - }) { - if (!this.integrationEnabled) return; - - try { - const instanceData = await this.prismaRepository.instance.findFirst({ - where: { - name: instance.instanceName, - }, - }); - - if (!instanceData) throw new Error('Instance not found'); - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger(this.botRepository, content, instance, session)) as TypebotModel; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.typebotIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.typebotIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - const settings = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - const url = findBot?.url; - const typebot = findBot?.typebot; - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - - if (this.checkIgnoreJids(ignoreJids, remoteJid)) return; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.sessionRepository.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.typebotService.processTypebot( - instanceData, - remoteJid, - msg, - session, - findBot, - url, - expire, - typebot, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debouncedContent, - ); - }); - } else { - await this.typebotService.processTypebot( - instanceData, - remoteJid, - msg, - session, - findBot, - url, - expire, - typebot, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - content, - ); - } - - if (session && !session.awaitUser) return; - } catch (error) { - this.logger.error(error); - return; - } - } } diff --git a/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts b/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts index a7565236..a0c06ae4 100644 --- a/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts +++ b/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts @@ -1,4 +1,4 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; export class PrefilledVariables { remoteJid?: string; @@ -7,34 +7,11 @@ export class PrefilledVariables { additionalData?: { [key: string]: any }; } -export class TypebotDto { - enabled?: boolean; - description?: string; +export class TypebotDto extends BaseChatbotDto { url: string; - typebot?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; + typebot: string; } -export class TypebotSettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class TypebotSettingDto extends BaseChatbotSettingDto { typebotIdFallback?: string; - ignoreJids?: any; } diff --git a/src/api/integrations/chatbot/typebot/services/typebot.service.ts b/src/api/integrations/chatbot/typebot/services/typebot.service.ts index f0e4dc7f..dc17b925 100644 --- a/src/api/integrations/chatbot/typebot/services/typebot.service.ts +++ b/src/api/integrations/chatbot/typebot/services/typebot.service.ts @@ -1,96 +1,232 @@ import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Auth, ConfigService, HttpServer, Typebot } from '@config/env.config'; -import { Logger } from '@config/logger.config'; -import { Instance, IntegrationSession, Message, Typebot as TypebotModel } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; -import { sendTelemetry } from '@utils/sendTelemetry'; +import { IntegrationSession, Typebot as TypebotModel } from '@prisma/client'; import axios from 'axios'; -export class TypebotService { +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class TypebotService extends BaseChatbotService { + private openaiService: OpenaiService; + constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} + waMonitor: WAMonitoringService, + configService: ConfigService, + prismaRepository: PrismaRepository, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'TypebotService', configService); + this.openaiService = openaiService; + } - private readonly logger = new Logger('TypebotService'); + /** + * Get the bot type identifier + */ + protected getBotType(): string { + return 'typebot'; + } - public async createNewSession(instance: Instance, data: any) { - if (data.remoteJid === 'status@broadcast') return; + /** + * Send a message to the Typebot API + */ + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: any, + bot: TypebotModel, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { + try { + // Initialize a new session if needed or content is special command + if (!session || content === 'init') { + const prefilledVariables = content === 'init' ? msg : null; + await this.initTypebotSession(instance, session, bot, remoteJid, pushName, prefilledVariables); + return; + } + + // Handle keyword matching - if it's a keyword to finish + if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { id: session.id }, + data: { status: 'closed' }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { botId: bot.id, remoteJid: remoteJid }, + }); + } + return; + } + + // Continue an existing chat + const version = this.configService?.get('TYPEBOT').API_VERSION; + let url: string; + let reqData: any; + + if (version === 'latest') { + url = `${bot.url}/api/v1/sessions/${session.sessionId.split('-')[1]}/continueChat`; + reqData = { message: content }; + } else { + url = `${bot.url}/api/v1/sendMessage`; + reqData = { + message: content, + sessionId: session.sessionId.split('-')[1], + }; + } + + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[EvolutionBot] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + reqData.message = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[EvolutionBot] Failed to transcribe audio: ${err}`); + } + } + + const response = await axios.post(url, reqData); + + // Process the response and send the messages to WhatsApp + await this.sendWAMessage( + instance, + session, + settings, + remoteJid, + response?.data?.messages, + response?.data?.input, + response?.data?.clientSideActions, + ); + } catch (error) { + this.logger.error(`Error in sendMessageToBot for Typebot: ${error.message || JSON.stringify(error)}`); + } + } + + /** + * Initialize a new Typebot session + */ + private async initTypebotSession( + instance: any, + session: IntegrationSession, + bot: TypebotModel, + remoteJid: string, + pushName: string, + prefilledVariables?: any, + ): Promise { const id = Math.floor(Math.random() * 10000000000).toString(); try { - const version = this.configService.get('TYPEBOT').API_VERSION; + const version = this.configService?.get('TYPEBOT').API_VERSION; let url: string; let reqData: {}; - if (version === 'latest') { - url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; + if (version === 'latest') { + url = `${bot.url}/api/v1/typebots/${bot.typebot}/startChat`; reqData = { prefilledVariables: { - ...data.prefilledVariables, - remoteJid: data.remoteJid, - pushName: data.pushName || data.prefilledVariables?.pushName || '', + ...(prefilledVariables || {}), + remoteJid: remoteJid, + pushName: pushName || '', instanceName: instance.name, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + serverUrl: this.configService?.get('SERVER').URL, + apiKey: this.configService?.get('AUTHENTICATION').API_KEY.KEY, ownerJid: instance.number, }, }; } else { - url = `${data.url}/api/v1/sendMessage`; - + url = `${bot.url}/api/v1/sendMessage`; reqData = { startParams: { - publicId: data.typebot, + publicId: bot.typebot, prefilledVariables: { - ...data.prefilledVariables, - remoteJid: data.remoteJid, - pushName: data.pushName || data.prefilledVariables?.pushName || '', + ...(prefilledVariables || {}), + remoteJid: remoteJid, + pushName: pushName || '', instanceName: instance.name, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + serverUrl: this.configService?.get('SERVER').URL, + apiKey: this.configService?.get('AUTHENTICATION').API_KEY.KEY, ownerJid: instance.number, }, }, }; } + const request = await axios.post(url, reqData); - let session = null; + // Create or update session with the Typebot session ID + let updatedSession = session; if (request?.data?.sessionId) { - session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName || '', - sessionId: `${id}-${request.data.sessionId}`, - status: 'opened', - parameters: { - ...data.prefilledVariables, - remoteJid: data.remoteJid, - pushName: data.pushName || '', - instanceName: instance.name, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - ownerJid: instance.number, + if (session) { + updatedSession = await this.prismaRepository.integrationSession.update({ + where: { id: session.id }, + data: { + sessionId: `${id}-${request.data.sessionId}`, + status: 'opened', + awaitUser: false, }, - awaitUser: false, - botId: data.botId, - instanceId: instance.id, - type: 'typebot', - }, - }); + }); + } else { + updatedSession = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: remoteJid, + pushName: pushName || '', + sessionId: `${id}-${request.data.sessionId}`, + status: 'opened', + parameters: { + ...(prefilledVariables || {}), + remoteJid: remoteJid, + pushName: pushName || '', + instanceName: instance.name, + serverUrl: this.configService?.get('SERVER').URL, + apiKey: this.configService?.get('AUTHENTICATION').API_KEY.KEY, + ownerJid: instance.number, + }, + awaitUser: false, + botId: bot.id, + instanceId: instance.id, + type: 'typebot', + }, + }); + } + } + + if (request?.data?.messages?.length > 0) { + // Process the response and send the messages to WhatsApp + await this.sendWAMessage( + instance, + updatedSession, + { + expire: bot.expire, + keywordFinish: bot.keywordFinish, + delayMessage: bot.delayMessage, + unknownMessage: bot.unknownMessage, + listeningFromMe: bot.listeningFromMe, + stopBotFromMe: bot.stopBotFromMe, + keepOpen: bot.keepOpen, + }, + remoteJid, + request.data.messages, + request.data.input, + request.data.clientSideActions, + ); } - return { ...request.data, session }; } catch (error) { - this.logger.error(error); - return; + this.logger.error(`Error initializing Typebot session: ${error.message || JSON.stringify(error)}`); } } + /** + * Send WhatsApp message with Typebot responses + * This handles the specific formatting and structure of Typebot responses + */ public async sendWAMessage( - instance: Instance, + instance: any, session: IntegrationSession, settings: { expire: number; @@ -106,848 +242,297 @@ export class TypebotService { input: any, clientSideActions: any, ) { - processMessages( - this.waMonitor.waInstances[instance.name], - session, - settings, - messages, - input, - clientSideActions, - applyFormatting, - this.prismaRepository, - ).catch((err) => { - console.error('Erro ao processar mensagens:', err); - }); - - function findItemAndGetSecondsToWait(array, targetId) { - if (!array) return null; - - for (const item of array) { - if (item.lastBubbleBlockId === targetId) { - return item.wait?.secondsToWaitFor; - } - } - return null; + if (!messages || messages.length === 0) { + return; } - function applyFormatting(element) { - let text = ''; + try { + await this.processTypebotMessages(instance, session, settings, remoteJid, messages, input, clientSideActions); + } catch (err) { + this.logger.error(`Error processing Typebot messages: ${err}`); + } + } - if (element.text) { - text += element.text; - } + /** + * Process Typebot-specific message formats and send to WhatsApp + */ + private async processTypebotMessages( + instance: any, + session: IntegrationSession, + settings: { + expire: number; + keywordFinish: string; + delayMessage: number; + unknownMessage: string; + listeningFromMe: boolean; + stopBotFromMe: boolean; + keepOpen: boolean; + }, + remoteJid: string, + messages: any, + input: any, + clientSideActions: any, + ) { + // Helper to find an item in an array and calculate wait time based on delay settings + const findItemAndGetSecondsToWait = (array, targetId) => { + const index = array.findIndex((item) => item.id === targetId); + if (index === -1) return 0; + return index * (settings.delayMessage || 0); + }; - if (element.children && element.type !== 'a') { - for (const child of element.children) { - text += applyFormatting(child); - } - } + // Helper to apply formatting to message content + const applyFormatting = (element) => { + if (!element) return ''; - if (element.type === 'p' && element.type !== 'inline-variable') { - text = text.trim() + '\n'; - } + let formattedText = ''; - if (element.type === 'inline-variable') { - text = text.trim(); - } + if (typeof element === 'string') { + formattedText = element; + } else if (element.text) { + formattedText = element.text; + } else if (element.type === 'text' && element.content) { + formattedText = element.content.text || ''; + } else if (element.content && element.content.richText) { + // Handle Typebot's rich text format + formattedText = element.content.richText.reduce((acc, item) => { + let text = item.text || ''; - if (element.type === 'ol') { - text = - '\n' + - text - .split('\n') - .map((line, index) => (line ? `${index + 1}. ${line}` : '')) - .join('\n'); - } + // Apply bold formatting + if (item.bold) text = `*${text}*`; - if (element.type === 'li') { - text = text - .split('\n') - .map((line) => (line ? ` ${line}` : '')) - .join('\n'); - } + // Apply italic formatting + if (item.italic) text = `_${text}_`; - let formats = ''; + // Apply strikethrough formatting (if supported) + if (item.strikethrough) text = `~${text}~`; - if (element.bold) { - formats += '*'; - } + // Apply URL if present (convert to Markdown style link) + if (item.url) text = `[${text}](${item.url})`; - if (element.italic) { - formats += '_'; - } - - if (element.underline) { - formats += '~'; - } - - let formattedText = `${formats}${text}${formats.split('').reverse().join('')}`; - - if (element.url) { - formattedText = element.children[0]?.text ? `[${formattedText}]\n(${element.url})` : `${element.url}`; + return acc + text; + }, ''); } return formattedText; - } + }; - async function processMessages( - instance: any, - session: IntegrationSession, - settings: { - expire: number; - keywordFinish: string; - delayMessage: number; - unknownMessage: string; - listeningFromMe: boolean; - stopBotFromMe: boolean; - keepOpen: boolean; - }, - messages: any, - input: any, - clientSideActions: any, - applyFormatting: any, - prismaRepository: PrismaRepository, - ) { - for (const message of messages) { - if (message.type === 'text') { - let formattedText = ''; + // Process each message + for (const message of messages) { + // Handle text type messages + if (message.type === 'text') { + const wait = findItemAndGetSecondsToWait(messages, message.id); + const content = applyFormatting(message); - for (const richText of message.content.richText) { - for (const element of richText.children) { - formattedText += applyFormatting(element); - } - formattedText += '\n'; - } + // Skip empty messages + if (!content) continue; - formattedText = formattedText.replace(/\*\*/g, '').replace(/__/, '').replace(/~~/, '').replace(/\n$/, ''); + // Check for WhatsApp list format + const listMatch = content.match(/\[list:(.+?)\]\[(.*?)\]/s); + if (listMatch) { + const { sections, buttonText } = this.parseListFormat(content); - formattedText = formattedText.replace(/\n$/, ''); + if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait * 1000)); - if (formattedText.includes('[list]')) { - const listJson = { - number: remoteJid.split('@')[0], - title: '', - description: '', - buttonText: '', - footerText: '', - sections: [], - }; - - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[buttonText\])/); - const buttonTextMatch = formattedText.match(/\[buttonText\]([\s\S]*?)(?=\[footerText\])/); - const footerTextMatch = formattedText.match(/\[footerText\]([\s\S]*?)(?=\[menu\])/); - - if (titleMatch) listJson.title = titleMatch[1].trim(); - if (descriptionMatch) listJson.description = descriptionMatch[1].trim(); - if (buttonTextMatch) listJson.buttonText = buttonTextMatch[1].trim(); - if (footerTextMatch) listJson.footerText = footerTextMatch[1].trim(); - - const menuContent = formattedText.match(/\[menu\]([\s\S]*?)\[\/menu\]/)?.[1]; - if (menuContent) { - const sections = menuContent.match(/\[section\]([\s\S]*?)(?=\[section\]|\[\/section\]|\[\/menu\])/g); - if (sections) { - sections.forEach((section) => { - const sectionTitle = section.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(); - const rows = section.match(/\[row\]([\s\S]*?)(?=\[row\]|\[\/row\]|\[\/section\]|\[\/menu\])/g); - - const sectionData = { - title: sectionTitle, - rows: - rows?.map((row) => ({ - title: row.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(), - description: row.match(/description: (.*?)(?:\n|$)/)?.[1]?.trim(), - rowId: row.match(/rowId: (.*?)(?:\n|$)/)?.[1]?.trim(), - })) || [], - }; - - listJson.sections.push(sectionData); - }); - } - } - - await instance.listMessage(listJson); - } else if (formattedText.includes('[buttons]')) { - const buttonJson = { - number: remoteJid.split('@')[0], - thumbnailUrl: undefined, - title: '', - description: '', - footer: '', - buttons: [], - }; - - const thumbnailUrlMatch = formattedText.match(/\[thumbnailUrl\]([\s\S]*?)(?=\[title\])/); - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[footer\])/); - const footerMatch = formattedText.match(/\[footer\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url))/); - - if (titleMatch) buttonJson.title = titleMatch[1].trim(); - if (thumbnailUrlMatch) buttonJson.thumbnailUrl = thumbnailUrlMatch[1].trim(); - if (descriptionMatch) buttonJson.description = descriptionMatch[1].trim(); - if (footerMatch) buttonJson.footer = footerMatch[1].trim(); - - const buttonTypes = { - reply: /\[reply\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - pix: /\[pix\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - copy: /\[copy\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - call: /\[call\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - url: /\[url\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - }; - - for (const [type, pattern] of Object.entries(buttonTypes)) { - let match; - while ((match = pattern.exec(formattedText)) !== null) { - const content = match[1].trim(); - const button: any = { type }; - - switch (type) { - case 'pix': - button.currency = content.match(/currency: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.name = content.match(/name: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.keyType = content.match(/keyType: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.key = content.match(/key: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'reply': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.id = content.match(/id: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'copy': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.copyCode = content.match(/copyCode: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'call': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.phoneNumber = content.match(/phone: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'url': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.url = content.match(/url: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - } - - if (Object.keys(button).length > 1) { - buttonJson.buttons.push(button); - } - } - } - - await instance.buttonMessage(buttonJson); - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: formattedText, - }, - false, - ); - } - - sendTelemetry('/message/sendText'); - } - - if (message.type === 'image') { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: 'image', - media: message.content.url, - }, - null, - false, - ); - - sendTelemetry('/message/sendMedia'); - } - - if (message.type === 'video') { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: 'video', - media: message.content.url, - }, - null, - false, - ); - - sendTelemetry('/message/sendMedia'); - } - - if (message.type === 'audio') { - await instance.audioWhatsapp( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - encoding: true, - audio: message.content.url, - }, - false, - ); - - sendTelemetry('/message/sendWhatsAppAudio'); - } - - const wait = findItemAndGetSecondsToWait(clientSideActions, message.id); - - if (wait) { - await new Promise((resolve) => setTimeout(resolve, wait * 1000)); - } - } - - console.log('input', input); - if (input) { - if (input.type === 'choice input') { - let formattedText = ''; - - const items = input.items; - - for (const item of items) { - formattedText += `▶️ ${item.content}\n`; - } - - formattedText = formattedText.replace(/\n$/, ''); - - if (formattedText.includes('[list]')) { - const listJson = { - number: remoteJid.split('@')[0], - title: '', - description: '', - buttonText: '', - footerText: '', - sections: [], - }; - - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[buttonText\])/); - const buttonTextMatch = formattedText.match(/\[buttonText\]([\s\S]*?)(?=\[footerText\])/); - const footerTextMatch = formattedText.match(/\[footerText\]([\s\S]*?)(?=\[menu\])/); - - if (titleMatch) listJson.title = titleMatch[1].trim(); - if (descriptionMatch) listJson.description = descriptionMatch[1].trim(); - if (buttonTextMatch) listJson.buttonText = buttonTextMatch[1].trim(); - if (footerTextMatch) listJson.footerText = footerTextMatch[1].trim(); - - const menuContent = formattedText.match(/\[menu\]([\s\S]*?)\[\/menu\]/)?.[1]; - if (menuContent) { - const sections = menuContent.match(/\[section\]([\s\S]*?)(?=\[section\]|\[\/section\]|\[\/menu\])/g); - if (sections) { - sections.forEach((section) => { - const sectionTitle = section.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(); - const rows = section.match(/\[row\]([\s\S]*?)(?=\[row\]|\[\/row\]|\[\/section\]|\[\/menu\])/g); - - const sectionData = { - title: sectionTitle, - rows: - rows?.map((row) => ({ - title: row.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(), - description: row.match(/description: (.*?)(?:\n|$)/)?.[1]?.trim(), - rowId: row.match(/rowId: (.*?)(?:\n|$)/)?.[1]?.trim(), - })) || [], - }; - - listJson.sections.push(sectionData); - }); - } - } - - await instance.listMessage(listJson); - } else if (formattedText.includes('[buttons]')) { - const buttonJson = { - number: remoteJid.split('@')[0], - thumbnailUrl: undefined, - title: '', - description: '', - footer: '', - buttons: [], - }; - - const thumbnailUrlMatch = formattedText.match(/\[thumbnailUrl\]([\s\S]*?)(?=\[title\])/); - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[footer\])/); - const footerMatch = formattedText.match(/\[footer\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url))/); - - if (titleMatch) buttonJson.title = titleMatch[1].trim(); - if (thumbnailUrlMatch) buttonJson.thumbnailUrl = thumbnailUrlMatch[1].trim(); - if (descriptionMatch) buttonJson.description = descriptionMatch[1].trim(); - if (footerMatch) buttonJson.footer = footerMatch[1].trim(); - - const buttonTypes = { - reply: /\[reply\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - pix: /\[pix\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - copy: /\[copy\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - call: /\[call\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - url: /\[url\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - }; - - for (const [type, pattern] of Object.entries(buttonTypes)) { - let match; - while ((match = pattern.exec(formattedText)) !== null) { - const content = match[1].trim(); - const button: any = { type }; - - switch (type) { - case 'pix': - button.currency = content.match(/currency: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.name = content.match(/name: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.keyType = content.match(/keyType: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.key = content.match(/key: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'reply': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.id = content.match(/id: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'copy': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.copyCode = content.match(/copyCode: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'call': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.phoneNumber = content.match(/phone: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'url': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.url = content.match(/url: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - } - - if (Object.keys(button).length > 1) { - buttonJson.buttons.push(button); - } - } - } - - await instance.buttonMessage(buttonJson); - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: formattedText, - }, - false, - ); - } - - sendTelemetry('/message/sendText'); - } - - await prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - awaitUser: true, - }, - }); - } else { - if (!settings?.keepOpen) { - await prismaRepository.integrationSession.deleteMany({ - where: { - id: session.id, - }, - }); - } else { - await prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } - } - } - } - - public async processTypebot( - instance: Instance, - remoteJid: string, - msg: Message, - session: IntegrationSession, - findTypebot: TypebotModel, - url: string, - expire: number, - typebot: string, - keywordFinish: string, - delayMessage: number, - unknownMessage: string, - listeningFromMe: boolean, - stopBotFromMe: boolean, - keepOpen: boolean, - content: string, - prefilledVariables?: any, - ) { - if (session && expire && expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > expire) { - if (keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - - const data = await this.createNewSession(instance, { - enabled: findTypebot?.enabled, - url: url, - typebot: typebot, - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - remoteJid: remoteJid, - pushName: msg.pushName, - botId: findTypebot.id, - prefilledVariables: prefilledVariables, - }); - - if (data.session) { - session = data.session; - } - - if (data.messages.length === 0) { - const content = getConversationMessage(msg.message); - - if (!content) { - if (unknownMessage) { - this.waMonitor.waInstances[instance.name].textMessage( - { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { - if (keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - try { - const version = this.configService.get('TYPEBOT').API_VERSION; - let urlTypebot: string; - let reqData: {}; - if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; - reqData = { - message: content, - }; - } else { - urlTypebot = `${url}/api/v1/sendMessage`; - reqData = { - message: content, - sessionId: data.sessionId, - }; - } - - const request = await axios.post(urlTypebot, reqData); - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, - ); - } catch (error) { - this.logger.error(error); - return; - } - } - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - data.messages, - data.input, - data.clientSideActions, - ); - - return; - } - } - - if (session && session.status !== 'opened') { - return; - } - - if (!session) { - const data = await this.createNewSession(instance, { - enabled: findTypebot?.enabled, - url: url, - typebot: typebot, - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - remoteJid: remoteJid, - pushName: msg?.pushName, - botId: findTypebot.id, - prefilledVariables: prefilledVariables, - }); - - if (data?.session) { - session = data.session; - } - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - data?.messages, - data?.input, - data?.clientSideActions, - ); - - if (data.messages.length === 0) { - if (!content) { - if (unknownMessage) { - this.waMonitor.waInstances[instance.name].textMessage( - { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { - if (keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - - return; - } - - let request: any; - try { - const version = this.configService.get('TYPEBOT').API_VERSION; - let urlTypebot: string; - let reqData: {}; - if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; - reqData = { - message: content, - }; - } else { - urlTypebot = `${url}/api/v1/sendMessage`; - reqData = { - message: content, - sessionId: data.sessionId, - }; - } - request = await axios.post(urlTypebot, reqData); - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, - ); - } catch (error) { - this.logger.error(error); - return; - } - } - return; - } - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (unknownMessage) { - this.waMonitor.waInstances[instance.name].textMessage( - { + // Send as WhatsApp list + // Using instance directly since waMonitor might not have sendListMessage + await instance.sendListMessage({ number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, - }, - false, - ); + sections, + buttonText, + }); + continue; + } - sendTelemetry('/message/sendText'); + // Check for WhatsApp button format + const buttonMatch = content.match(/\[button:(.+?)\]/); + if (buttonMatch) { + const { text, buttons } = this.parseButtonFormat(content); + + if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait * 1000)); + + // Send as WhatsApp buttons + await instance.sendButtonMessage({ + number: remoteJid.split('@')[0], + text, + buttons, + }); + continue; + } + + // Process for standard text messages + if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait * 1000)); + await this.sendMessageWhatsApp(instance, remoteJid, content, settings); + } + + // Handle image type messages + else if (message.type === 'image') { + const url = message.content?.url || message.content?.imageUrl || ''; + if (!url) continue; + + const caption = message.content?.caption || ''; + const wait = findItemAndGetSecondsToWait(messages, message.id); + + if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait * 1000)); + + // Send image to WhatsApp + await instance.sendMediaMessage({ + number: remoteJid.split('@')[0], + type: 'image', + media: url, + caption, + }); + } + + // Handle other media types (video, audio, etc.) + else if (['video', 'audio', 'file'].includes(message.type)) { + const mediaType = message.type; + const url = message.content?.url || ''; + if (!url) continue; + + const caption = message.content?.caption || ''; + const wait = findItemAndGetSecondsToWait(messages, message.id); + + if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait * 1000)); + + // Send media to WhatsApp + await instance.sendMediaMessage({ + number: remoteJid.split('@')[0], + type: mediaType, + media: url, + caption, + }); } - return; } - if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { - if (keepOpen) { + // Check if we need to update the session status based on input/client actions + if (input && input.type === 'choice input') { + await this.prismaRepository.integrationSession.update({ + where: { id: session.id }, + data: { awaitUser: true }, + }); + } else if (!input && !clientSideActions) { + // If no input or actions, close the session or keep it open based on settings + if (settings.keepOpen) { await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, + where: { id: session.id }, + data: { status: 'closed' }, }); } else { await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: findTypebot.id, - remoteJid: remoteJid, - }, + where: { id: session.id }, }); } - return; } + } - const version = this.configService.get('TYPEBOT').API_VERSION; - let urlTypebot: string; - let reqData: {}; - if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${session.sessionId.split('-')[1]}/continueChat`; - reqData = { - message: content, - }; - } else { - urlTypebot = `${url}/api/v1/sendMessage`; - reqData = { - message: content, - sessionId: session.sessionId.split('-')[1], - }; + /** + * Parse WhatsApp list format from Typebot text + */ + private parseListFormat(text: string): { sections: any[]; buttonText: string } { + try { + const regex = /\[list:(.+?)\]\[(.*?)\]/s; + const match = regex.exec(text); + + if (!match) return { sections: [], buttonText: 'Menu' }; + + const listContent = match[1]; + const buttonText = match[2] || 'Menu'; + + // Parse list sections from content + const sectionStrings = listContent.split(/(?=\{section:)/s); + const sections = []; + + for (const sectionString of sectionStrings) { + if (!sectionString.trim()) continue; + + const sectionMatch = sectionString.match(/\{section:(.+?)\}\[(.*?)\]/s); + if (!sectionMatch) continue; + + const title = sectionMatch[1]; + const rowsContent = sectionMatch[2]; + + const rows = rowsContent + .split(/(?=\[row:)/s) + .map((rowString) => { + const rowMatch = rowString.match(/\[row:(.+?)\]\[(.+?)\]/); + if (!rowMatch) return null; + + return { + title: rowMatch[1], + id: rowMatch[2], + description: '', + }; + }) + .filter(Boolean); + + if (rows.length > 0) { + sections.push({ + title, + rows, + }); + } + } + + return { sections, buttonText }; + } catch (error) { + this.logger.error(`Error parsing list format: ${error}`); + return { sections: [], buttonText: 'Menu' }; } - const request = await axios.post(urlTypebot, reqData); + } - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request?.data?.messages, - request?.data?.input, - request?.data?.clientSideActions, - ); + /** + * Parse WhatsApp button format from Typebot text + */ + private parseButtonFormat(text: string): { text: string; buttons: any[] } { + try { + const regex = /\[button:(.+?)\]/g; + let match; + const buttons = []; + let cleanedText = text; - return; + // Extract all button definitions and build buttons array + while ((match = regex.exec(text)) !== null) { + const buttonParts = match[1].split('|'); + if (buttonParts.length >= 1) { + const buttonText = buttonParts[0].trim(); + const buttonId = buttonParts.length > 1 ? buttonParts[1].trim() : buttonText; + + buttons.push({ + buttonId, + buttonText: { displayText: buttonText }, + type: 1, + }); + + // Remove button definition from clean text + cleanedText = cleanedText.replace(match[0], ''); + } + } + + cleanedText = cleanedText.trim(); + + return { + text: cleanedText, + buttons, + }; + } catch (error) { + this.logger.error(`Error parsing button format: ${error}`); + return { text, buttons: [] }; + } + } + /** + * Simplified method that matches the base class pattern + * This should be the preferred way for the controller to call + */ + public async processTypebot( + instance: any, + remoteJid: string, + bot: TypebotModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ): Promise { + return this.process(instance, remoteJid, bot, session, settings, content, pushName, msg); } } diff --git a/src/api/integrations/event/event.controller.ts b/src/api/integrations/event/event.controller.ts index 2e6a2330..7df3de92 100644 --- a/src/api/integrations/event/event.controller.ts +++ b/src/api/integrations/event/event.controller.ts @@ -132,6 +132,7 @@ export class EventController { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', @@ -151,5 +152,8 @@ export class EventController { 'TYPEBOT_CHANGE_STATUS', 'REMOVE_INSTANCE', 'LOGOUT_INSTANCE', + 'INSTANCE_CREATE', + 'INSTANCE_DELETE', + 'STATUS_INSTANCE', ]; } diff --git a/src/api/integrations/event/event.dto.ts b/src/api/integrations/event/event.dto.ts index eaa7cc40..84426764 100644 --- a/src/api/integrations/event/event.dto.ts +++ b/src/api/integrations/event/event.dto.ts @@ -26,6 +26,11 @@ export class EventDto { events?: string[]; }; + nats?: { + enabled?: boolean; + events?: string[]; + }; + pusher?: { enabled?: boolean; appId?: string; @@ -63,6 +68,11 @@ export function EventInstanceMixin(Base: TBase) { events?: string[]; }; + nats?: { + enabled?: boolean; + events?: string[]; + }; + pusher?: { enabled?: boolean; appId?: string; diff --git a/src/api/integrations/event/event.manager.ts b/src/api/integrations/event/event.manager.ts index 9df96f9f..4b4a310c 100644 --- a/src/api/integrations/event/event.manager.ts +++ b/src/api/integrations/event/event.manager.ts @@ -1,3 +1,4 @@ +import { NatsController } from '@api/integrations/event/nats/nats.controller'; import { PusherController } from '@api/integrations/event/pusher/pusher.controller'; import { RabbitmqController } from '@api/integrations/event/rabbitmq/rabbitmq.controller'; import { SqsController } from '@api/integrations/event/sqs/sqs.controller'; @@ -13,6 +14,7 @@ export class EventManager { private websocketController: WebsocketController; private webhookController: WebhookController; private rabbitmqController: RabbitmqController; + private natsController: NatsController; private sqsController: SqsController; private pusherController: PusherController; @@ -23,6 +25,7 @@ export class EventManager { this.websocket = new WebsocketController(prismaRepository, waMonitor); this.webhook = new WebhookController(prismaRepository, waMonitor); this.rabbitmq = new RabbitmqController(prismaRepository, waMonitor); + this.nats = new NatsController(prismaRepository, waMonitor); this.sqs = new SqsController(prismaRepository, waMonitor); this.pusher = new PusherController(prismaRepository, waMonitor); } @@ -67,6 +70,14 @@ export class EventManager { return this.rabbitmqController; } + public set nats(nats: NatsController) { + this.natsController = nats; + } + + public get nats() { + return this.natsController; + } + public set sqs(sqs: SqsController) { this.sqsController = sqs; } @@ -85,6 +96,7 @@ export class EventManager { public init(httpServer: Server): void { this.websocket.init(httpServer); this.rabbitmq.init(); + this.nats.init(); this.sqs.init(); this.pusher.init(); } @@ -103,6 +115,7 @@ export class EventManager { }): Promise { await this.websocket.emit(eventData); await this.rabbitmq.emit(eventData); + await this.nats.emit(eventData); await this.sqs.emit(eventData); await this.webhook.emit(eventData); await this.pusher.emit(eventData); @@ -125,6 +138,14 @@ export class EventManager { }, }); + if (data.nats) + await this.nats.set(instanceName, { + nats: { + enabled: true, + events: data.nats?.events, + }, + }); + if (data.sqs) await this.sqs.set(instanceName, { sqs: { diff --git a/src/api/integrations/event/event.router.ts b/src/api/integrations/event/event.router.ts index 580b0324..49a6ec60 100644 --- a/src/api/integrations/event/event.router.ts +++ b/src/api/integrations/event/event.router.ts @@ -1,3 +1,4 @@ +import { NatsRouter } from '@api/integrations/event/nats/nats.router'; import { PusherRouter } from '@api/integrations/event/pusher/pusher.router'; import { RabbitmqRouter } from '@api/integrations/event/rabbitmq/rabbitmq.router'; import { SqsRouter } from '@api/integrations/event/sqs/sqs.router'; @@ -14,6 +15,7 @@ export class EventRouter { this.router.use('/webhook', new WebhookRouter(configService, ...guards).router); this.router.use('/websocket', new WebsocketRouter(...guards).router); this.router.use('/rabbitmq', new RabbitmqRouter(...guards).router); + this.router.use('/nats', new NatsRouter(...guards).router); this.router.use('/pusher', new PusherRouter(...guards).router); this.router.use('/sqs', new SqsRouter(...guards).router); } diff --git a/src/api/integrations/event/event.schema.ts b/src/api/integrations/event/event.schema.ts index 5ec8866f..464ee02b 100644 --- a/src/api/integrations/event/event.schema.ts +++ b/src/api/integrations/event/event.schema.ts @@ -16,6 +16,9 @@ export const eventSchema: JSONSchema7 = { rabbitmq: { $ref: '#/$defs/event', }, + nats: { + $ref: '#/$defs/event', + }, sqs: { $ref: '#/$defs/event', }, diff --git a/src/api/integrations/event/nats/nats.controller.ts b/src/api/integrations/event/nats/nats.controller.ts new file mode 100644 index 00000000..09b59779 --- /dev/null +++ b/src/api/integrations/event/nats/nats.controller.ts @@ -0,0 +1,161 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Log, Nats } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { connect, NatsConnection, StringCodec } from 'nats'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class NatsController extends EventController implements EventControllerInterface { + public natsClient: NatsConnection | null = null; + private readonly logger = new Logger('NatsController'); + private readonly sc = StringCodec(); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, configService.get('NATS')?.ENABLED, 'nats'); + } + + public async init(): Promise { + if (!this.status) { + return; + } + + try { + const uri = configService.get('NATS').URI; + + this.natsClient = await connect({ servers: uri }); + + this.logger.info('NATS initialized'); + + if (configService.get('NATS')?.GLOBAL_ENABLED) { + await this.initGlobalSubscriptions(); + } + } catch (error) { + this.logger.error('Failed to connect to NATS:'); + this.logger.error(error); + throw error; + } + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + integration, + }: EmitData): Promise { + if (integration && !integration.includes('nats')) { + return; + } + + if (!this.status || !this.natsClient) { + return; + } + + const instanceNats = await this.get(instanceName); + const natsLocal = instanceNats?.events; + const natsGlobal = configService.get('NATS').GLOBAL_ENABLED; + const natsEvents = configService.get('NATS').EVENTS; + const prefixKey = configService.get('NATS').PREFIX_KEY; + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + const logEnabled = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + + const message = { + event, + instance: instanceName, + data, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + }; + + // Instância específica + if (instanceNats?.enabled) { + if (Array.isArray(natsLocal) && natsLocal.includes(we)) { + const subject = `${instanceName}.${event.toLowerCase()}`; + + try { + this.natsClient.publish(subject, this.sc.encode(JSON.stringify(message))); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-NATS`, + ...message, + }; + this.logger.log(logData); + } + } catch (error) { + this.logger.error(`Failed to publish to NATS (instance): ${error}`); + } + } + } + + // Global + if (natsGlobal && natsEvents[we]) { + try { + const subject = prefixKey ? `${prefixKey}.${event.toLowerCase()}` : event.toLowerCase(); + + this.natsClient.publish(subject, this.sc.encode(JSON.stringify(message))); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-NATS-Global`, + ...message, + }; + this.logger.log(logData); + } + } catch (error) { + this.logger.error(`Failed to publish to NATS (global): ${error}`); + } + } + } + + private async initGlobalSubscriptions(): Promise { + this.logger.info('Initializing global subscriptions'); + + const events = configService.get('NATS').EVENTS; + const prefixKey = configService.get('NATS').PREFIX_KEY; + + if (!events) { + this.logger.warn('No events to initialize on NATS'); + return; + } + + const eventKeys = Object.keys(events); + + for (const event of eventKeys) { + if (events[event] === false) continue; + + const subject = prefixKey ? `${prefixKey}.${event.toLowerCase()}` : event.toLowerCase(); + + // Criar uma subscription para cada evento + try { + const subscription = this.natsClient.subscribe(subject); + this.logger.info(`Subscribed to: ${subject}`); + + // Processar mensagens (exemplo básico) + (async () => { + for await (const msg of subscription) { + try { + const data = JSON.parse(this.sc.decode(msg.data)); + // Aqui você pode adicionar a lógica de processamento + this.logger.debug(`Received message on ${subject}:`); + this.logger.debug(data); + } catch (error) { + this.logger.error(`Error processing message on ${subject}:`); + this.logger.error(error); + } + } + })(); + } catch (error) { + this.logger.error(`Failed to subscribe to ${subject}:`); + this.logger.error(error); + } + } + } +} diff --git a/src/api/integrations/event/nats/nats.router.ts b/src/api/integrations/event/nats/nats.router.ts new file mode 100644 index 00000000..945b75f3 --- /dev/null +++ b/src/api/integrations/event/nats/nats.router.ts @@ -0,0 +1,36 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { eventSchema, instanceSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class NatsRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: eventSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.nats.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.nats.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts index 22defde5..07694f5f 100644 --- a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts +++ b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts @@ -21,9 +21,21 @@ export class RabbitmqController extends EventController implements EventControll await new Promise((resolve, reject) => { const uri = configService.get('RABBITMQ').URI; + const frameMax = configService.get('RABBITMQ').FRAME_MAX; const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; - amqp.connect(uri, (error, connection) => { + const url = new URL(uri); + const connectionOptions = { + protocol: url.protocol.slice(0, -1), + hostname: url.hostname, + port: url.port || 5672, + username: url.username || 'guest', + password: url.password || 'guest', + vhost: url.pathname.slice(1) || '/', + frameMax: frameMax, + }; + + amqp.connect(connectionOptions, (error, connection) => { if (error) { reject(error); diff --git a/src/api/integrations/event/sqs/sqs.controller.ts b/src/api/integrations/event/sqs/sqs.controller.ts index 1d60fb7b..05bf618b 100644 --- a/src/api/integrations/event/sqs/sqs.controller.ts +++ b/src/api/integrations/event/sqs/sqs.controller.ts @@ -1,10 +1,11 @@ import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; -import { SQS } from '@aws-sdk/client-sqs'; +import { CreateQueueCommand, DeleteQueueCommand, ListQueuesCommand, SQS } from '@aws-sdk/client-sqs'; import { configService, Log, Sqs } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { EmitData, EventController, EventControllerInterface } from '../event.controller'; +import { EventDto } from '../event.dto'; export class SqsController extends EventController implements EventControllerInterface { private sqs: SQS; @@ -45,6 +46,39 @@ export class SqsController extends EventController implements EventControllerInt return this.sqs; } + override async set(instanceName: string, data: EventDto): Promise { + if (!this.status) { + return; + } + + if (!data[this.name]?.enabled) { + data[this.name].events = []; + } else { + if (0 === data[this.name].events.length) { + data[this.name].events = EventController.events; + } + } + + await this.saveQueues(instanceName, data[this.name].events, data[this.name]?.enabled); + + const payload: any = { + where: { + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + update: { + enabled: data[this.name]?.enabled, + events: data[this.name].events, + }, + create: { + enabled: data[this.name]?.enabled, + events: data[this.name].events, + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + }; + console.log('*** payload: ', payload); + return this.prisma[this.name].upsert(payload); + } + public async emit({ instanceName, origin, @@ -121,70 +155,92 @@ export class SqsController extends EventController implements EventControllerInt } } - public async initQueues(instanceName: string, events: string[]) { - if (!events || !events.length) return; + private async saveQueues(instanceName: string, events: string[], enable: boolean) { + if (enable) { + const eventsFinded = await this.listQueuesByInstance(instanceName); + console.log('eventsFinded', eventsFinded); - const queues = events.map((event) => { - return `${event.replace(/_/g, '_').toLowerCase()}`; - }); + for (const event of events) { + const normalizedEvent = event.toLowerCase(); - queues.forEach((event) => { - const queueName = `${instanceName}_${event}.fifo`; + if (eventsFinded.includes(normalizedEvent)) { + this.logger.info(`A queue para o evento "${normalizedEvent}" já existe. Ignorando criação.`); + continue; + } - this.sqs.createQueue( - { - QueueName: queueName, - Attributes: { - FifoQueue: 'true', - }, - }, - (err, data) => { - if (err) { - this.logger.error(`Error creating queue ${queueName}: ${err.message}`); - } else { - this.logger.info(`Queue ${queueName} created: ${data.QueueUrl}`); - } - }, - ); - }); + const queueName = `${instanceName}_${normalizedEvent}.fifo`; + + try { + const createCommand = new CreateQueueCommand({ + QueueName: queueName, + Attributes: { + FifoQueue: 'true', + }, + }); + const data = await this.sqs.send(createCommand); + this.logger.info(`Queue ${queueName} criada: ${data.QueueUrl}`); + } catch (err: any) { + this.logger.error(`Erro ao criar queue ${queueName}: ${err.message}`); + } + } + } } - public async removeQueues(instanceName: string, events: any) { - const eventsArray = Array.isArray(events) ? events.map((event) => String(event)) : []; - if (!events || !eventsArray.length) return; + private async listQueuesByInstance(instanceName: string) { + let existingQueues: string[] = []; + try { + const listCommand = new ListQueuesCommand({ + QueueNamePrefix: `${instanceName}_`, + }); + const listData = await this.sqs.send(listCommand); + if (listData.QueueUrls && listData.QueueUrls.length > 0) { + // Extrai o nome da fila a partir da URL + existingQueues = listData.QueueUrls.map((queueUrl) => { + const parts = queueUrl.split('/'); + return parts[parts.length - 1]; + }); + } + } catch (error: any) { + this.logger.error(`Erro ao listar filas para a instância ${instanceName}: ${error.message}`); + return; + } - const queues = eventsArray.map((event) => { - return `${event.replace(/_/g, '_').toLowerCase()}`; - }); + // Mapeia os eventos já existentes nas filas: remove o prefixo e o sufixo ".fifo" + return existingQueues + .map((queueName) => { + // Espera-se que o nome seja `${instanceName}_${event}.fifo` + if (queueName.startsWith(`${instanceName}_`) && queueName.endsWith('.fifo')) { + return queueName.substring(instanceName.length + 1, queueName.length - 5).toLowerCase(); + } + return ''; + }) + .filter((event) => event !== ''); + } - queues.forEach((event) => { - const queueName = `${instanceName}_${event}.fifo`; + // Para uma futura feature de exclusão forçada das queues + private async removeQueuesByInstance(instanceName: string) { + try { + const listCommand = new ListQueuesCommand({ + QueueNamePrefix: `${instanceName}_`, + }); + const listData = await this.sqs.send(listCommand); - this.sqs.getQueueUrl( - { - QueueName: queueName, - }, - (err, data) => { - if (err) { - this.logger.error(`Error getting queue URL for ${queueName}: ${err.message}`); - } else { - const queueUrl = data.QueueUrl; + if (!listData.QueueUrls || listData.QueueUrls.length === 0) { + this.logger.info(`No queues found for instance ${instanceName}`); + return; + } - this.sqs.deleteQueue( - { - QueueUrl: queueUrl, - }, - (deleteErr) => { - if (deleteErr) { - this.logger.error(`Error deleting queue ${queueName}: ${deleteErr.message}`); - } else { - this.logger.info(`Queue ${queueName} deleted`); - } - }, - ); - } - }, - ); - }); + for (const queueUrl of listData.QueueUrls) { + try { + const deleteCommand = new DeleteQueueCommand({ QueueUrl: queueUrl }); + await this.sqs.send(deleteCommand); + this.logger.info(`Queue ${queueUrl} deleted`); + } catch (err: any) { + this.logger.error(`Error deleting queue ${queueUrl}: ${err.message}`); + } + } + } catch (err: any) { + this.logger.error(`Error listing queues for instance ${instanceName}: ${err.message}`); + } } } diff --git a/src/api/integrations/event/webhook/webhook.controller.ts b/src/api/integrations/event/webhook/webhook.controller.ts index ce709c3d..a204f8f7 100644 --- a/src/api/integrations/event/webhook/webhook.controller.ts +++ b/src/api/integrations/event/webhook/webhook.controller.ts @@ -6,7 +6,7 @@ import { configService, Log, Webhook } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; import axios, { AxiosInstance } from 'axios'; -import { isURL } from 'class-validator'; +import * as jwt from 'jsonwebtoken'; import { EmitData, EventController, EventControllerInterface } from '../event.controller'; @@ -18,7 +18,7 @@ export class WebhookController extends EventController implements EventControlle } override async set(instanceName: string, data: EventDto): Promise { - if (!isURL(data.webhook.url, { require_tld: false })) { + if (!/^(https?:\/\/)/.test(data.webhook.url)) { throw new BadRequestException('Invalid "url" property'); } @@ -74,10 +74,20 @@ export class WebhookController extends EventController implements EventControlle const webhookConfig = configService.get('WEBHOOK'); const webhookLocal = instance?.events; - const webhookHeaders = instance?.headers; + const webhookHeaders = { ...((instance?.headers as Record) || {}) }; + + if (webhookHeaders && 'jwt_key' in webhookHeaders) { + const jwtKey = webhookHeaders['jwt_key']; + const jwtToken = this.generateJwtToken(jwtKey); + webhookHeaders['Authorization'] = `Bearer ${jwtToken}`; + + delete webhookHeaders['jwt_key']; + } + const we = event.replace(/[.-]/gm, '_').toUpperCase(); const transformedWe = we.replace(/_/gm, '-').toLowerCase(); const enabledLog = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + const regex = /^(https?:\/\/)/; const webhookData = { event, @@ -111,10 +121,11 @@ export class WebhookController extends EventController implements EventControlle } try { - if (instance?.enabled && isURL(instance.url, { require_tld: false })) { + if (instance?.enabled && regex.test(instance.url)) { const httpService = axios.create({ baseURL, headers: webhookHeaders as Record | undefined, + timeout: webhookConfig.REQUEST?.TIMEOUT_MS ?? 30000, }); await this.retryWebhookRequest(httpService, webhookData, `${origin}.sendData-Webhook`, baseURL, serverUrl); @@ -155,8 +166,11 @@ export class WebhookController extends EventController implements EventControlle } try { - if (isURL(globalURL)) { - const httpService = axios.create({ baseURL: globalURL }); + if (regex.test(globalURL)) { + const httpService = axios.create({ + baseURL: globalURL, + timeout: webhookConfig.REQUEST?.TIMEOUT_MS ?? 30000, + }); await this.retryWebhookRequest( httpService, @@ -190,12 +204,20 @@ export class WebhookController extends EventController implements EventControlle origin: string, baseURL: string, serverUrl: string, - maxRetries = 10, - delaySeconds = 30, + maxRetries?: number, + delaySeconds?: number, ): Promise { + const webhookConfig = configService.get('WEBHOOK'); + const maxRetryAttempts = maxRetries ?? webhookConfig.RETRY?.MAX_ATTEMPTS ?? 10; + const initialDelay = delaySeconds ?? webhookConfig.RETRY?.INITIAL_DELAY_SECONDS ?? 5; + const useExponentialBackoff = webhookConfig.RETRY?.USE_EXPONENTIAL_BACKOFF ?? true; + const maxDelay = webhookConfig.RETRY?.MAX_DELAY_SECONDS ?? 300; + const jitterFactor = webhookConfig.RETRY?.JITTER_FACTOR ?? 0.2; + const nonRetryableStatusCodes = webhookConfig.RETRY?.NON_RETRYABLE_STATUS_CODES ?? [400, 401, 403, 404, 422]; + let attempts = 0; - while (attempts < maxRetries) { + while (attempts < maxRetryAttempts) { try { await httpService.post('', webhookData); if (attempts > 0) { @@ -209,12 +231,27 @@ export class WebhookController extends EventController implements EventControlle } catch (error) { attempts++; + const isTimeout = error.code === 'ECONNABORTED'; + + if (error?.response?.status && nonRetryableStatusCodes.includes(error.response.status)) { + this.logger.error({ + local: `${origin}`, + message: `Erro não recuperável (${error.response.status}): ${error?.message}. Cancelando retentativas.`, + statusCode: error?.response?.status, + url: baseURL, + server_url: serverUrl, + }); + throw error; + } + this.logger.error({ local: `${origin}`, - message: `Tentativa ${attempts}/${maxRetries} falhou: ${error?.message}`, + message: `Tentativa ${attempts}/${maxRetryAttempts} falhou: ${isTimeout ? 'Timeout da requisição' : error?.message}`, hostName: error?.hostname, syscall: error?.syscall, code: error?.code, + isTimeout, + statusCode: error?.response?.status, error: error?.errno, stack: error?.stack, name: error?.name, @@ -222,12 +259,46 @@ export class WebhookController extends EventController implements EventControlle server_url: serverUrl, }); - if (attempts === maxRetries) { + if (attempts === maxRetryAttempts) { throw error; } - await new Promise((resolve) => setTimeout(resolve, delaySeconds * 1000)); + let nextDelay = initialDelay; + if (useExponentialBackoff) { + nextDelay = Math.min(initialDelay * Math.pow(2, attempts - 1), maxDelay); + + const jitter = nextDelay * jitterFactor * (Math.random() * 2 - 1); + nextDelay = Math.max(initialDelay, nextDelay + jitter); + } + + this.logger.log({ + local: `${origin}`, + message: `Aguardando ${nextDelay.toFixed(1)} segundos antes da próxima tentativa`, + url: baseURL, + }); + + await new Promise((resolve) => setTimeout(resolve, nextDelay * 1000)); } } } + + private generateJwtToken(authToken: string): string { + try { + const payload = { + iat: Math.floor(Date.now() / 1000), + exp: Math.floor(Date.now() / 1000) + 600, // 10 min expiration + app: 'evolution', + action: 'webhook', + }; + + const token = jwt.sign(payload, authToken, { algorithm: 'HS256' }); + return token; + } catch (error) { + this.logger.error({ + local: 'WebhookController.generateJwtToken', + message: `JWT generation failed: ${error?.message}`, + }); + throw error; + } + } } diff --git a/src/api/integrations/event/websocket/websocket.controller.ts b/src/api/integrations/event/websocket/websocket.controller.ts index f6d152ff..a1cef2db 100644 --- a/src/api/integrations/event/websocket/websocket.controller.ts +++ b/src/api/integrations/event/websocket/websocket.controller.ts @@ -1,6 +1,6 @@ import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; -import { configService, Cors, Log, Websocket } from '@config/env.config'; +import { Auth, configService, Cors, Log, Websocket } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { Server } from 'http'; import { Server as SocketIO } from 'socket.io'; @@ -24,8 +24,40 @@ export class WebsocketController extends EventController implements EventControl } this.socket = new SocketIO(httpServer, { - cors: { - origin: this.cors, + cors: { origin: this.cors }, + allowRequest: async (req, callback) => { + try { + const url = new URL(req.url || '', 'http://localhost'); + const params = new URLSearchParams(url.search); + + // Permite conexões internas do Socket.IO (EIO=4 é o Engine.IO v4) + if (params.has('EIO')) { + return callback(null, true); + } + + const apiKey = params.get('apikey') || (req.headers.apikey as string); + + if (!apiKey) { + this.logger.error('Connection rejected: apiKey not provided'); + return callback('apiKey is required', false); + } + + const instance = await this.prismaRepository.instance.findFirst({ where: { token: apiKey } }); + + if (!instance) { + const globalToken = configService.get('AUTHENTICATION').API_KEY.KEY; + if (apiKey !== globalToken) { + this.logger.error('Connection rejected: invalid global token'); + return callback('Invalid global token', false); + } + } + + callback(null, true); + } catch (error) { + this.logger.error('Authentication error:'); + this.logger.error(error); + callback('Authentication error', false); + } }, }); @@ -101,10 +133,7 @@ export class WebsocketController extends EventController implements EventControl this.socket.emit(event, message); if (logEnabled) { - this.logger.log({ - local: `${origin}.sendData-WebsocketGlobal`, - ...message, - }); + this.logger.log({ local: `${origin}.sendData-WebsocketGlobal`, ...message }); } } @@ -119,10 +148,7 @@ export class WebsocketController extends EventController implements EventControl this.socket.of(`/${instanceName}`).emit(event, message); if (logEnabled) { - this.logger.log({ - local: `${origin}.sendData-Websocket`, - ...message, - }); + this.logger.log({ local: `${origin}.sendData-Websocket`, ...message }); } } } catch (err) { diff --git a/src/api/integrations/storage/s3/libs/minio.server.ts b/src/api/integrations/storage/s3/libs/minio.server.ts index 5a66305c..30c81876 100644 --- a/src/api/integrations/storage/s3/libs/minio.server.ts +++ b/src/api/integrations/storage/s3/libs/minio.server.ts @@ -63,9 +63,9 @@ const createBucket = async () => { if (!exists) { await minioClient.makeBucket(bucketName); } - - await setBucketPolicy(); - + if (!BUCKET.SKIP_POLICY) { + await setBucketPolicy(); + } logger.info(`S3 Bucket ${bucketName} - ON`); return true; } catch (error) { diff --git a/src/api/provider/sessions.ts b/src/api/provider/sessions.ts index 05668232..e211ecdc 100644 --- a/src/api/provider/sessions.ts +++ b/src/api/provider/sessions.ts @@ -1,7 +1,7 @@ import { Auth, ConfigService, ProviderSession } from '@config/env.config'; import { Logger } from '@config/logger.config'; import axios from 'axios'; -import { execSync } from 'child_process'; +import { execFileSync } from 'child_process'; type ResponseSuccess = { status: number; data?: any }; type ResponseProvider = Promise<[ResponseSuccess?, Error?]>; @@ -36,7 +36,7 @@ export class ProviderFiles { } catch (error) { this.logger.error(['Failed to connect to the file server', error?.message, error?.stack]); const pid = process.pid; - execSync(`kill -9 ${pid}`); + execFileSync('kill', ['-9', `${pid}`]); } } } diff --git a/src/api/routes/business.router.ts b/src/api/routes/business.router.ts new file mode 100644 index 00000000..1e510a4f --- /dev/null +++ b/src/api/routes/business.router.ts @@ -0,0 +1,37 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { NumberDto } from '@api/dto/chat.dto'; +import { businessController } from '@api/server.module'; +import { catalogSchema, collectionsSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +import { HttpStatus } from './index.router'; + +export class BusinessRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('getCatalog'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: catalogSchema, + ClassRef: NumberDto, + execute: (instance, data) => businessController.fetchCatalog(instance, data), + }); + + return res.status(HttpStatus.OK).json(response); + }) + + .post(this.routerPath('getCollections'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: collectionsSchema, + ClassRef: NumberDto, + execute: (instance, data) => businessController.fetchCollections(instance, data), + }); + + return res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/routes/chat.router.ts b/src/api/routes/chat.router.ts index 20126c1a..5c556705 100644 --- a/src/api/routes/chat.router.ts +++ b/src/api/routes/chat.router.ts @@ -207,7 +207,6 @@ export class ChatRouter extends RouterBroker { return res.status(HttpStatus.OK).json(response); }) - .post(this.routerPath('updateProfileName'), ...guards, async (req, res) => { const response = await this.dataValidate({ request: req, diff --git a/src/api/routes/index.router.ts b/src/api/routes/index.router.ts index a4a7c071..9c0ecd13 100644 --- a/src/api/routes/index.router.ts +++ b/src/api/routes/index.router.ts @@ -11,6 +11,7 @@ import fs from 'fs'; import mimeTypes from 'mime-types'; import path from 'path'; +import { BusinessRouter } from './business.router'; import { CallRouter } from './call.router'; import { ChatRouter } from './chat.router'; import { GroupRouter } from './group.router'; @@ -82,6 +83,7 @@ router .use('/message', new MessageRouter(...guards).router) .use('/call', new CallRouter(...guards).router) .use('/chat', new ChatRouter(...guards).router) + .use('/business', new BusinessRouter(...guards).router) .use('/group', new GroupRouter(...guards).router) .use('/template', new TemplateRouter(configService, ...guards).router) .use('/settings', new SettingsRouter(...guards).router) diff --git a/src/api/routes/instance.router.ts b/src/api/routes/instance.router.ts index dd990c3b..3559893e 100644 --- a/src/api/routes/instance.router.ts +++ b/src/api/routes/instance.router.ts @@ -15,7 +15,6 @@ export class InstanceRouter extends RouterBroker { super(); this.router .post('/create', ...guards, async (req, res) => { - console.log('create instance', req.body); const response = await this.dataValidate({ request: req, schema: instanceSchema, diff --git a/src/api/server.module.ts b/src/api/server.module.ts index 49fc5695..385fe17b 100644 --- a/src/api/server.module.ts +++ b/src/api/server.module.ts @@ -3,6 +3,7 @@ import { Chatwoot, configService, ProviderSession } from '@config/env.config'; import { eventEmitter } from '@config/event.config'; import { Logger } from '@config/logger.config'; +import { BusinessController } from './controllers/business.controller'; import { CallController } from './controllers/call.controller'; import { ChatController } from './controllers/chat.controller'; import { GroupController } from './controllers/group.controller'; @@ -21,10 +22,14 @@ import { ChatwootController } from './integrations/chatbot/chatwoot/controllers/ import { ChatwootService } from './integrations/chatbot/chatwoot/services/chatwoot.service'; import { DifyController } from './integrations/chatbot/dify/controllers/dify.controller'; import { DifyService } from './integrations/chatbot/dify/services/dify.service'; +import { EvoaiController } from './integrations/chatbot/evoai/controllers/evoai.controller'; +import { EvoaiService } from './integrations/chatbot/evoai/services/evoai.service'; import { EvolutionBotController } from './integrations/chatbot/evolutionBot/controllers/evolutionBot.controller'; import { EvolutionBotService } from './integrations/chatbot/evolutionBot/services/evolutionBot.service'; import { FlowiseController } from './integrations/chatbot/flowise/controllers/flowise.controller'; import { FlowiseService } from './integrations/chatbot/flowise/services/flowise.service'; +import { N8nController } from './integrations/chatbot/n8n/controllers/n8n.controller'; +import { N8nService } from './integrations/chatbot/n8n/services/n8n.service'; import { OpenaiController } from './integrations/chatbot/openai/controllers/openai.controller'; import { OpenaiService } from './integrations/chatbot/openai/services/openai.service'; import { TypebotController } from './integrations/chatbot/typebot/controllers/typebot.controller'; @@ -98,6 +103,7 @@ export const instanceController = new InstanceController( export const sendMessageController = new SendMessageController(waMonitor); export const callController = new CallController(waMonitor); export const chatController = new ChatController(waMonitor); +export const businessController = new BusinessController(waMonitor); export const groupController = new GroupController(waMonitor); export const labelController = new LabelController(waMonitor); @@ -109,20 +115,27 @@ export const channelController = new ChannelController(prismaRepository, waMonit export const evolutionController = new EvolutionController(prismaRepository, waMonitor); export const metaController = new MetaController(prismaRepository, waMonitor); export const baileysController = new BaileysController(waMonitor); -// chatbots -const typebotService = new TypebotService(waMonitor, configService, prismaRepository); -export const typebotController = new TypebotController(typebotService, prismaRepository, waMonitor); -const openaiService = new OpenaiService(waMonitor, configService, prismaRepository); +const openaiService = new OpenaiService(waMonitor, prismaRepository, configService); export const openaiController = new OpenaiController(openaiService, prismaRepository, waMonitor); -const difyService = new DifyService(waMonitor, configService, prismaRepository); +// chatbots +const typebotService = new TypebotService(waMonitor, configService, prismaRepository, openaiService); +export const typebotController = new TypebotController(typebotService, prismaRepository, waMonitor); + +const difyService = new DifyService(waMonitor, prismaRepository, configService, openaiService); export const difyController = new DifyController(difyService, prismaRepository, waMonitor); -const evolutionBotService = new EvolutionBotService(waMonitor, configService, prismaRepository); +const evolutionBotService = new EvolutionBotService(waMonitor, prismaRepository, configService, openaiService); export const evolutionBotController = new EvolutionBotController(evolutionBotService, prismaRepository, waMonitor); -const flowiseService = new FlowiseService(waMonitor, configService, prismaRepository); +const flowiseService = new FlowiseService(waMonitor, prismaRepository, configService, openaiService); export const flowiseController = new FlowiseController(flowiseService, prismaRepository, waMonitor); +const n8nService = new N8nService(waMonitor, prismaRepository, configService, openaiService); +export const n8nController = new N8nController(n8nService, prismaRepository, waMonitor); + +const evoaiService = new EvoaiService(waMonitor, prismaRepository, configService, openaiService); +export const evoaiController = new EvoaiController(evoaiService, prismaRepository, waMonitor); + logger.info('Module - ON'); diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index 0f30f0c9..3d52f620 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -45,11 +45,11 @@ export class ChannelStartupService { this.chatwootCache, ); - public typebotService = new TypebotService(waMonitor, this.configService, this.prismaRepository); + public openaiService = new OpenaiService(waMonitor, this.prismaRepository, this.configService); - public openaiService = new OpenaiService(waMonitor, this.configService, this.prismaRepository); + public typebotService = new TypebotService(waMonitor, this.configService, this.prismaRepository, this.openaiService); - public difyService = new DifyService(waMonitor, this.configService, this.prismaRepository); + public difyService = new DifyService(waMonitor, this.prismaRepository, this.configService, this.openaiService); public setInstance(instance: InstanceDto) { this.logger.setInstance(instance.instanceName); @@ -503,8 +503,29 @@ export class ChannelStartupService { where['remoteJid'] = remoteJid; } - return await this.prismaRepository.contact.findMany({ + const contactFindManyArgs: Prisma.ContactFindManyArgs = { where, + }; + + if (query.offset) contactFindManyArgs.take = query.offset; + if (query.page) { + const validPage = Math.max(query.page as number, 1); + contactFindManyArgs.skip = query.offset * (validPage - 1); + } + + const contacts = await this.prismaRepository.contact.findMany(contactFindManyArgs); + + return contacts.map((contact) => { + const remoteJid = contact.remoteJid; + const isGroup = remoteJid.endsWith('@g.us'); + const isSaved = !!contact.pushName || !!contact.profilePicUrl; + const type = isGroup ? 'group' : isSaved ? 'contact' : 'group_member'; + return { + ...contact, + isGroup, + isSaved, + type, + }; }); } @@ -685,88 +706,100 @@ export class ChannelStartupService { const timestampFilter = query?.where?.messageTimestamp?.gte && query?.where?.messageTimestamp?.lte ? Prisma.sql` - AND "Message"."messageTimestamp" >= ${Math.floor(new Date(query.where.messageTimestamp.gte).getTime() / 1000)} - AND "Message"."messageTimestamp" <= ${Math.floor(new Date(query.where.messageTimestamp.lte).getTime() / 1000)}` + AND "Message"."messageTimestamp" >= ${Math.floor(new Date(query.where.messageTimestamp.gte).getTime() / 1000)} + AND "Message"."messageTimestamp" <= ${Math.floor(new Date(query.where.messageTimestamp.lte).getTime() / 1000)}` : Prisma.sql``; + const limit = query?.take ? Prisma.sql`LIMIT ${query.take}` : Prisma.sql``; + const offset = query?.skip ? Prisma.sql`OFFSET ${query.skip}` : Prisma.sql``; + const results = await this.prismaRepository.$queryRaw` - WITH rankedMessages AS ( - SELECT DISTINCT ON ("Contact"."remoteJid") - "Contact"."id", - "Contact"."remoteJid", - "Contact"."pushName", - "Contact"."profilePicUrl", - COALESCE( - to_timestamp("Message"."messageTimestamp"::double precision), - "Contact"."updatedAt" - ) as "updatedAt", - "Chat"."createdAt" as "windowStart", - "Chat"."createdAt" + INTERVAL '24 hours' as "windowExpires", - CASE - WHEN "Chat"."createdAt" + INTERVAL '24 hours' > NOW() THEN true - ELSE false - END as "windowActive", - "Message"."id" AS lastMessageId, - "Message"."key" AS lastMessage_key, - "Message"."pushName" AS lastMessagePushName, - "Message"."participant" AS lastMessageParticipant, - "Message"."messageType" AS lastMessageMessageType, - "Message"."message" AS lastMessageMessage, - "Message"."contextInfo" AS lastMessageContextInfo, - "Message"."source" AS lastMessageSource, - "Message"."messageTimestamp" AS lastMessageMessageTimestamp, - "Message"."instanceId" AS lastMessageInstanceId, - "Message"."sessionId" AS lastMessageSessionId, - "Message"."status" AS lastMessageStatus - FROM "Contact" - INNER JOIN "Message" ON "Message"."key"->>'remoteJid' = "Contact"."remoteJid" - LEFT JOIN "Chat" ON "Chat"."remoteJid" = "Contact"."remoteJid" - AND "Chat"."instanceId" = "Contact"."instanceId" - WHERE - "Contact"."instanceId" = ${this.instanceId} - AND "Message"."instanceId" = ${this.instanceId} - ${remoteJid ? Prisma.sql`AND "Contact"."remoteJid" = ${remoteJid}` : Prisma.sql``} - ${timestampFilter} - ORDER BY - "Contact"."remoteJid", - "Message"."messageTimestamp" DESC - ) - SELECT * FROM rankedMessages - ORDER BY "updatedAt" DESC NULLS LAST; + WITH rankedMessages AS ( + SELECT DISTINCT ON ("Message"."key"->>'remoteJid') + "Contact"."id" as "contactId", + "Message"."key"->>'remoteJid' as "remoteJid", + CASE + WHEN "Message"."key"->>'remoteJid' LIKE '%@g.us' THEN COALESCE("Chat"."name", "Contact"."pushName") + ELSE COALESCE("Contact"."pushName", "Message"."pushName") + END as "pushName", + "Contact"."profilePicUrl", + COALESCE( + to_timestamp("Message"."messageTimestamp"::double precision), + "Contact"."updatedAt" + ) as "updatedAt", + "Chat"."name" as "pushName", + "Chat"."createdAt" as "windowStart", + "Chat"."createdAt" + INTERVAL '24 hours' as "windowExpires", + CASE WHEN "Chat"."createdAt" + INTERVAL '24 hours' > NOW() THEN true ELSE false END as "windowActive", + "Message"."id" AS lastMessageId, + "Message"."key" AS lastMessage_key, + CASE + WHEN "Message"."key"->>'fromMe' = 'true' THEN 'Você' + ELSE "Message"."pushName" + END AS lastMessagePushName, + "Message"."participant" AS lastMessageParticipant, + "Message"."messageType" AS lastMessageMessageType, + "Message"."message" AS lastMessageMessage, + "Message"."contextInfo" AS lastMessageContextInfo, + "Message"."source" AS lastMessageSource, + "Message"."messageTimestamp" AS lastMessageMessageTimestamp, + "Message"."instanceId" AS lastMessageInstanceId, + "Message"."sessionId" AS lastMessageSessionId, + "Message"."status" AS lastMessageStatus + FROM "Message" + LEFT JOIN "Contact" ON "Contact"."remoteJid" = "Message"."key"->>'remoteJid' AND "Contact"."instanceId" = "Message"."instanceId" + LEFT JOIN "Chat" ON "Chat"."remoteJid" = "Message"."key"->>'remoteJid' AND "Chat"."instanceId" = "Message"."instanceId" + WHERE "Message"."instanceId" = ${this.instanceId} + ${remoteJid ? Prisma.sql`AND "Message"."key"->>'remoteJid' = ${remoteJid}` : Prisma.sql``} + ${timestampFilter} + ORDER BY "Message"."key"->>'remoteJid', "Message"."messageTimestamp" DESC + ) + SELECT * FROM rankedMessages + ORDER BY "updatedAt" DESC NULLS LAST + ${limit} + ${offset}; `; if (results && isArray(results) && results.length > 0) { const mappedResults = results.map((contact) => { - const lastMessage = contact.lastMessageId + const lastMessage = contact.lastmessageid ? { - id: contact.lastMessageId, - key: contact.lastMessageKey, - pushName: contact.lastMessagePushName, - participant: contact.lastMessageParticipant, - messageType: contact.lastMessageMessageType, - message: contact.lastMessageMessage, - contextInfo: contact.lastMessageContextInfo, - source: contact.lastMessageSource, - messageTimestamp: contact.lastMessageMessageTimestamp, - instanceId: contact.lastMessageInstanceId, - sessionId: contact.lastMessageSessionId, - status: contact.lastMessageStatus, + id: contact.lastmessageid, + key: contact.lastmessage_key, + pushName: contact.lastmessagepushname, + participant: contact.lastmessageparticipant, + messageType: contact.lastmessagemessagetype, + message: contact.lastmessagemessage, + contextInfo: contact.lastmessagecontextinfo, + source: contact.lastmessagesource, + messageTimestamp: contact.lastmessagemessagetimestamp, + instanceId: contact.lastmessageinstanceid, + sessionId: contact.lastmessagesessionid, + status: contact.lastmessagestatus, } : undefined; return { - id: contact.id, - remoteJid: contact.remoteJid, - pushName: contact.pushName, - profilePicUrl: contact.profilePicUrl, - updatedAt: contact.updatedAt, - windowStart: contact.windowStart, - windowExpires: contact.windowExpires, - windowActive: contact.windowActive, + id: contact.contactid || null, + remoteJid: contact.remotejid, + pushName: contact.pushname, + profilePicUrl: contact.profilepicurl, + updatedAt: contact.updatedat, + windowStart: contact.windowstart, + windowExpires: contact.windowexpires, + windowActive: contact.windowactive, lastMessage: lastMessage ? this.cleanMessageData(lastMessage) : undefined, + unreadCount: 0, + isSaved: !!contact.contactid, }; }); + if (query?.take && query?.skip) { + const skip = query.skip || 0; + const take = query.take || 20; + return mappedResults.slice(skip, skip + take); + } + return mappedResults; } diff --git a/src/api/services/monitor.service.ts b/src/api/services/monitor.service.ts index af775f1f..90962dcb 100644 --- a/src/api/services/monitor.service.ts +++ b/src/api/services/monitor.service.ts @@ -7,7 +7,7 @@ import { CacheConf, Chatwoot, ConfigService, Database, DelInstance, ProviderSess import { Logger } from '@config/logger.config'; import { INSTANCE_DIR, STORE_DIR } from '@config/path.config'; import { NotFoundException } from '@exceptions'; -import { execSync } from 'child_process'; +import { execFileSync } from 'child_process'; import EventEmitter2 from 'eventemitter2'; import { rmSync } from 'fs'; import { join } from 'path'; @@ -91,6 +91,7 @@ export class WAMonitoringService { Chatwoot: true, Proxy: true, Rabbitmq: true, + Nats: true, Sqs: true, Websocket: true, Setting: true, @@ -168,7 +169,8 @@ export class WAMonitoringService { public async cleaningStoreData(instanceName: string) { if (this.configService.get('CHATWOOT').ENABLED) { - execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`); + const instancePath = join(STORE_DIR, 'chatwoot', instanceName); + execFileSync('rm', ['-rf', instancePath]); } const instance = await this.prismaRepository.instance.findFirst({ @@ -190,6 +192,7 @@ export class WAMonitoringService { await this.prismaRepository.chatwoot.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.proxy.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.rabbitmq.deleteMany({ where: { instanceId: instance.id } }); + await this.prismaRepository.nats.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.sqs.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.integrationSession.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.typebot.deleteMany({ where: { instanceId: instance.id } }); diff --git a/src/api/types/wa.types.ts b/src/api/types/wa.types.ts index 0aad0696..2bb3dc1e 100644 --- a/src/api/types/wa.types.ts +++ b/src/api/types/wa.types.ts @@ -15,6 +15,7 @@ export enum Events { MESSAGES_UPDATE = 'messages.update', MESSAGES_DELETE = 'messages.delete', SEND_MESSAGE = 'send.message', + SEND_MESSAGE_UPDATE = 'send.message.update', CONTACTS_SET = 'contacts.set', CONTACTS_UPSERT = 'contacts.upsert', CONTACTS_UPDATE = 'contacts.update', diff --git a/src/config/env.config.ts b/src/config/env.config.ts index 78ca891c..8c253163 100644 --- a/src/config/env.config.ts +++ b/src/config/env.config.ts @@ -72,6 +72,7 @@ export type EventsRabbitmq = { MESSAGES_UPDATE: boolean; MESSAGES_DELETE: boolean; SEND_MESSAGE: boolean; + SEND_MESSAGE_UPDATE: boolean; CONTACTS_SET: boolean; CONTACTS_UPDATE: boolean; CONTACTS_UPSERT: boolean; @@ -94,10 +95,20 @@ export type EventsRabbitmq = { export type Rabbitmq = { ENABLED: boolean; URI: string; + FRAME_MAX: number; EXCHANGE_NAME: string; GLOBAL_ENABLED: boolean; EVENTS: EventsRabbitmq; - PREFIX_KEY: string; + PREFIX_KEY?: string; +}; + +export type Nats = { + ENABLED: boolean; + URI: string; + EXCHANGE_NAME: string; + GLOBAL_ENABLED: boolean; + EVENTS: EventsRabbitmq; + PREFIX_KEY?: string; }; export type Sqs = { @@ -131,6 +142,7 @@ export type EventsWebhook = { MESSAGES_UPDATE: boolean; MESSAGES_DELETE: boolean; SEND_MESSAGE: boolean; + SEND_MESSAGE_UPDATE: boolean; CONTACTS_SET: boolean; CONTACTS_UPDATE: boolean; CONTACTS_UPSERT: boolean; @@ -163,6 +175,7 @@ export type EventsPusher = { MESSAGES_UPDATE: boolean; MESSAGES_DELETE: boolean; SEND_MESSAGE: boolean; + SEND_MESSAGE_UPDATE: boolean; CONTACTS_SET: boolean; CONTACTS_UPDATE: boolean; CONTACTS_UPSERT: boolean; @@ -220,7 +233,21 @@ export type CacheConfLocal = { TTL: number; }; export type SslConf = { PRIVKEY: string; FULLCHAIN: string }; -export type Webhook = { GLOBAL?: GlobalWebhook; EVENTS: EventsWebhook }; +export type Webhook = { + GLOBAL?: GlobalWebhook; + EVENTS: EventsWebhook; + REQUEST?: { + TIMEOUT_MS?: number; + }; + RETRY?: { + MAX_ATTEMPTS?: number; + INITIAL_DELAY_SECONDS?: number; + USE_EXPONENTIAL_BACKOFF?: boolean; + MAX_DELAY_SECONDS?: number; + JITTER_FACTOR?: number; + NON_RETRYABLE_STATUS_CODES?: number[]; + }; +}; export type Pusher = { ENABLED: boolean; GLOBAL?: GlobalPusher; EVENTS: EventsPusher }; export type ConfigSessionPhone = { CLIENT: string; NAME: string; VERSION: string }; export type QrCode = { LIMIT: number; COLOR: string }; @@ -241,6 +268,9 @@ export type Chatwoot = { }; export type Openai = { ENABLED: boolean; API_KEY_GLOBAL?: string }; export type Dify = { ENABLED: boolean }; +export type N8n = { ENABLED: boolean }; +export type Evoai = { ENABLED: boolean }; +export type Flowise = { ENABLED: boolean }; export type S3 = { ACCESS_KEY: string; @@ -251,6 +281,7 @@ export type S3 = { PORT?: number; USE_SSL?: boolean; REGION?: string; + SKIP_POLICY?: boolean; }; export type CacheConf = { REDIS: CacheConfRedis; LOCAL: CacheConfLocal }; @@ -263,6 +294,7 @@ export interface Env { PROVIDER: ProviderSession; DATABASE: Database; RABBITMQ: Rabbitmq; + NATS: Nats; SQS: Sqs; WEBSOCKET: Websocket; WA_BUSINESS: WaBusiness; @@ -278,6 +310,9 @@ export interface Env { CHATWOOT: Chatwoot; OPENAI: Openai; DIFY: Dify; + N8N: N8n; + EVOAI: Evoai; + FLOWISE: Flowise; CACHE: CacheConf; S3?: S3; AUTHENTICATION: Auth; @@ -356,9 +391,10 @@ export class ConfigService { RABBITMQ: { ENABLED: process.env?.RABBITMQ_ENABLED === 'true', GLOBAL_ENABLED: process.env?.RABBITMQ_GLOBAL_ENABLED === 'true', - PREFIX_KEY: process.env?.RABBITMQ_PREFIX_KEY || 'evolution', + PREFIX_KEY: process.env?.RABBITMQ_PREFIX_KEY, EXCHANGE_NAME: process.env?.RABBITMQ_EXCHANGE_NAME || 'evolution_exchange', URI: process.env.RABBITMQ_URI || '', + FRAME_MAX: Number.parseInt(process.env.RABBITMQ_FRAME_MAX) || 8192, EVENTS: { APPLICATION_STARTUP: process.env?.RABBITMQ_EVENTS_APPLICATION_STARTUP === 'true', INSTANCE_CREATE: process.env?.RABBITMQ_EVENTS_INSTANCE_CREATE === 'true', @@ -370,6 +406,7 @@ export class ConfigService { MESSAGES_UPDATE: process.env?.RABBITMQ_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_DELETE: process.env?.RABBITMQ_EVENTS_MESSAGES_DELETE === 'true', SEND_MESSAGE: process.env?.RABBITMQ_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.RABBITMQ_EVENTS_SEND_MESSAGE_UPDATE === 'true', CONTACTS_SET: process.env?.RABBITMQ_EVENTS_CONTACTS_SET === 'true', CONTACTS_UPDATE: process.env?.RABBITMQ_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPSERT: process.env?.RABBITMQ_EVENTS_CONTACTS_UPSERT === 'true', @@ -389,6 +426,43 @@ export class ConfigService { TYPEBOT_CHANGE_STATUS: process.env?.RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS === 'true', }, }, + NATS: { + ENABLED: process.env?.NATS_ENABLED === 'true', + GLOBAL_ENABLED: process.env?.NATS_GLOBAL_ENABLED === 'true', + PREFIX_KEY: process.env?.NATS_PREFIX_KEY, + EXCHANGE_NAME: process.env?.NATS_EXCHANGE_NAME || 'evolution_exchange', + URI: process.env.NATS_URI || '', + EVENTS: { + APPLICATION_STARTUP: process.env?.NATS_EVENTS_APPLICATION_STARTUP === 'true', + INSTANCE_CREATE: process.env?.NATS_EVENTS_INSTANCE_CREATE === 'true', + INSTANCE_DELETE: process.env?.NATS_EVENTS_INSTANCE_DELETE === 'true', + QRCODE_UPDATED: process.env?.NATS_EVENTS_QRCODE_UPDATED === 'true', + MESSAGES_SET: process.env?.NATS_EVENTS_MESSAGES_SET === 'true', + MESSAGES_UPSERT: process.env?.NATS_EVENTS_MESSAGES_UPSERT === 'true', + MESSAGES_EDITED: process.env?.NATS_EVENTS_MESSAGES_EDITED === 'true', + MESSAGES_UPDATE: process.env?.NATS_EVENTS_MESSAGES_UPDATE === 'true', + MESSAGES_DELETE: process.env?.NATS_EVENTS_MESSAGES_DELETE === 'true', + SEND_MESSAGE: process.env?.NATS_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.NATS_EVENTS_SEND_MESSAGE_UPDATE === 'true', + CONTACTS_SET: process.env?.NATS_EVENTS_CONTACTS_SET === 'true', + CONTACTS_UPDATE: process.env?.NATS_EVENTS_CONTACTS_UPDATE === 'true', + CONTACTS_UPSERT: process.env?.NATS_EVENTS_CONTACTS_UPSERT === 'true', + PRESENCE_UPDATE: process.env?.NATS_EVENTS_PRESENCE_UPDATE === 'true', + CHATS_SET: process.env?.NATS_EVENTS_CHATS_SET === 'true', + CHATS_UPDATE: process.env?.NATS_EVENTS_CHATS_UPDATE === 'true', + CHATS_UPSERT: process.env?.NATS_EVENTS_CHATS_UPSERT === 'true', + CHATS_DELETE: process.env?.NATS_EVENTS_CHATS_DELETE === 'true', + CONNECTION_UPDATE: process.env?.NATS_EVENTS_CONNECTION_UPDATE === 'true', + LABELS_EDIT: process.env?.NATS_EVENTS_LABELS_EDIT === 'true', + LABELS_ASSOCIATION: process.env?.NATS_EVENTS_LABELS_ASSOCIATION === 'true', + GROUPS_UPSERT: process.env?.NATS_EVENTS_GROUPS_UPSERT === 'true', + GROUP_UPDATE: process.env?.NATS_EVENTS_GROUPS_UPDATE === 'true', + GROUP_PARTICIPANTS_UPDATE: process.env?.NATS_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true', + CALL: process.env?.NATS_EVENTS_CALL === 'true', + TYPEBOT_START: process.env?.NATS_EVENTS_TYPEBOT_START === 'true', + TYPEBOT_CHANGE_STATUS: process.env?.NATS_EVENTS_TYPEBOT_CHANGE_STATUS === 'true', + }, + }, SQS: { ENABLED: process.env?.SQS_ENABLED === 'true', ACCESS_KEY_ID: process.env.SQS_ACCESS_KEY_ID || '', @@ -421,6 +495,7 @@ export class ConfigService { MESSAGES_UPDATE: process.env?.PUSHER_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_DELETE: process.env?.PUSHER_EVENTS_MESSAGES_DELETE === 'true', SEND_MESSAGE: process.env?.PUSHER_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.PUSHER_EVENTS_SEND_MESSAGE_UPDATE === 'true', CONTACTS_SET: process.env?.PUSHER_EVENTS_CONTACTS_SET === 'true', CONTACTS_UPDATE: process.env?.PUSHER_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPSERT: process.env?.PUSHER_EVENTS_CONTACTS_UPSERT === 'true', @@ -477,6 +552,7 @@ export class ConfigService { MESSAGES_UPDATE: process.env?.WEBHOOK_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_DELETE: process.env?.WEBHOOK_EVENTS_MESSAGES_DELETE === 'true', SEND_MESSAGE: process.env?.WEBHOOK_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE === 'true', CONTACTS_SET: process.env?.WEBHOOK_EVENTS_CONTACTS_SET === 'true', CONTACTS_UPDATE: process.env?.WEBHOOK_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPSERT: process.env?.WEBHOOK_EVENTS_CONTACTS_UPSERT === 'true', @@ -497,6 +573,19 @@ export class ConfigService { ERRORS: process.env?.WEBHOOK_EVENTS_ERRORS === 'true', ERRORS_WEBHOOK: process.env?.WEBHOOK_EVENTS_ERRORS_WEBHOOK || '', }, + REQUEST: { + TIMEOUT_MS: Number.parseInt(process.env?.WEBHOOK_REQUEST_TIMEOUT_MS) || 30000, + }, + RETRY: { + MAX_ATTEMPTS: Number.parseInt(process.env?.WEBHOOK_RETRY_MAX_ATTEMPTS) || 10, + INITIAL_DELAY_SECONDS: Number.parseInt(process.env?.WEBHOOK_RETRY_INITIAL_DELAY_SECONDS) || 5, + USE_EXPONENTIAL_BACKOFF: process.env?.WEBHOOK_RETRY_USE_EXPONENTIAL_BACKOFF !== 'false', + MAX_DELAY_SECONDS: Number.parseInt(process.env?.WEBHOOK_RETRY_MAX_DELAY_SECONDS) || 300, + JITTER_FACTOR: Number.parseFloat(process.env?.WEBHOOK_RETRY_JITTER_FACTOR) || 0.2, + NON_RETRYABLE_STATUS_CODES: process.env?.WEBHOOK_RETRY_NON_RETRYABLE_STATUS_CODES?.split(',').map(Number) || [ + 400, 401, 403, 404, 422, + ], + }, }, CONFIG_SESSION_PHONE: { CLIENT: process.env?.CONFIG_SESSION_PHONE_CLIENT || 'Evolution API', @@ -533,6 +622,15 @@ export class ConfigService { DIFY: { ENABLED: process.env?.DIFY_ENABLED === 'true', }, + N8N: { + ENABLED: process.env?.N8N_ENABLED === 'true', + }, + EVOAI: { + ENABLED: process.env?.EVOAI_ENABLED === 'true', + }, + FLOWISE: { + ENABLED: process.env?.FLOWISE_ENABLED === 'true', + }, CACHE: { REDIS: { ENABLED: process.env?.CACHE_REDIS_ENABLED === 'true', @@ -555,6 +653,7 @@ export class ConfigService { PORT: Number.parseInt(process.env?.S3_PORT || '9000'), USE_SSL: process.env?.S3_USE_SSL === 'true', REGION: process.env?.S3_REGION, + SKIP_POLICY: process.env?.S3_SKIP_POLICY === 'true', }, AUTHENTICATION: { API_KEY: { diff --git a/src/main.ts b/src/main.ts index 938d51d2..cf787f32 100644 --- a/src/main.ts +++ b/src/main.ts @@ -128,7 +128,15 @@ async function bootstrap() { const httpServer = configService.get('SERVER'); ServerUP.app = app; - const server = ServerUP[httpServer.TYPE]; + let server = ServerUP[httpServer.TYPE]; + + if (server === null) { + logger.warn('SSL cert load failed — falling back to HTTP.'); + logger.info("Ensure 'SSL_CONF_PRIVKEY' and 'SSL_CONF_FULLCHAIN' env vars point to valid certificate files."); + + httpServer.TYPE = 'http'; + server = ServerUP[httpServer.TYPE]; + } eventManager.init(server); diff --git a/src/utils/getConversationMessage.ts b/src/utils/getConversationMessage.ts index b2522ab0..a7650968 100644 --- a/src/utils/getConversationMessage.ts +++ b/src/utils/getConversationMessage.ts @@ -3,19 +3,19 @@ import { configService, S3 } from '@config/env.config'; const getTypeMessage = (msg: any) => { let mediaId: string; - if (configService.get('S3').ENABLE) mediaId = msg.message.mediaUrl; - else mediaId = msg.key.id; + if (configService.get('S3').ENABLE) mediaId = msg.message?.mediaUrl; + else mediaId = msg.key?.id; const types = { conversation: msg?.message?.conversation, extendedTextMessage: msg?.message?.extendedTextMessage?.text, contactMessage: msg?.message?.contactMessage?.displayName, - locationMessage: msg?.message?.locationMessage?.degreesLatitude, + locationMessage: msg?.message?.locationMessage?.degreesLatitude.toString(), viewOnceMessageV2: msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, - listResponseMessage: msg?.message?.listResponseMessage?.title, + listResponseMessage: msg?.message?.listResponseMessage?.title || msg?.listResponseMessage?.title, responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, templateButtonReplyMessage: msg?.message?.templateButtonReplyMessage?.selectedId || msg?.message?.buttonsResponseMessage?.selectedButtonId, diff --git a/src/validate/business.schema.ts b/src/validate/business.schema.ts new file mode 100644 index 00000000..91ad17b2 --- /dev/null +++ b/src/validate/business.schema.ts @@ -0,0 +1,17 @@ +import { JSONSchema7 } from 'json-schema'; + +export const catalogSchema: JSONSchema7 = { + type: 'object', + properties: { + number: { type: 'string' }, + limit: { type: 'number' }, + }, +}; + +export const collectionsSchema: JSONSchema7 = { + type: 'object', + properties: { + number: { type: 'string' }, + limit: { type: 'number' }, + }, +}; diff --git a/src/validate/instance.schema.ts b/src/validate/instance.schema.ts index 06c34df9..a0553b66 100644 --- a/src/validate/instance.schema.ts +++ b/src/validate/instance.schema.ts @@ -68,6 +68,7 @@ export const instanceSchema: JSONSchema7 = { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', @@ -104,6 +105,44 @@ export const instanceSchema: JSONSchema7 = { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', + 'CONTACTS_SET', + 'CONTACTS_UPSERT', + 'CONTACTS_UPDATE', + 'PRESENCE_UPDATE', + 'CHATS_SET', + 'CHATS_UPSERT', + 'CHATS_UPDATE', + 'CHATS_DELETE', + 'GROUPS_UPSERT', + 'GROUP_UPDATE', + 'GROUP_PARTICIPANTS_UPDATE', + 'CONNECTION_UPDATE', + 'LABELS_EDIT', + 'LABELS_ASSOCIATION', + 'CALL', + 'TYPEBOT_START', + 'TYPEBOT_CHANGE_STATUS', + ], + }, + }, + // NATS + natsEnabled: { type: 'boolean' }, + natsEvents: { + type: 'array', + minItems: 0, + items: { + type: 'string', + enum: [ + 'APPLICATION_STARTUP', + 'QRCODE_UPDATED', + 'MESSAGES_SET', + 'MESSAGES_UPSERT', + 'MESSAGES_EDITED', + 'MESSAGES_UPDATE', + 'MESSAGES_DELETE', + 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', @@ -140,6 +179,7 @@ export const instanceSchema: JSONSchema7 = { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', diff --git a/src/validate/validate.schema.ts b/src/validate/validate.schema.ts index cf3d7828..4577eae3 100644 --- a/src/validate/validate.schema.ts +++ b/src/validate/validate.schema.ts @@ -1,4 +1,5 @@ // Integrations Schema +export * from './business.schema'; export * from './chat.schema'; export * from './group.schema'; export * from './instance.schema'; diff --git a/tsup.config.ts b/tsup.config.ts index 2450b52f..f09ecd87 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -15,5 +15,6 @@ export default defineConfig({ }, loader: { '.json': 'file', + '.yml': 'file', }, });