UNPKG

vlibras-player-webjs

Version:

Biblioteca JavaScript moderna para integração do VLibras Player com React, Vue, Angular e vanilla JS

1 lines 44.6 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.VLibras=t():e.VLibras=t()}(this,function(){return function(){"use strict";var e,t,r={};(t=e||(e={})).IDLE="idle",t.INITIALIZING="initializing",t.LOADING_ASSETS="loading_assets",t.READY="ready",t.TRANSLATING="translating",t.PLAYING="playing",t.PAUSED="paused",t.COMPLETED="completed",t.ERROR="error";class n{constructor(e={}){this.callbacks={},this.config={autoSetup:!0,logCalls:!1,prefix:"VLibras",...e}}static setupAutomatically(e){return n.isSetup||(n.instance=new n(e),"undefined"!=typeof window&&(n.instance.registerGlobalFunctions(),n.isSetup=!0)),n.instance}setCallbacks(e){this.callbacks={...this.callbacks,...e}}registerGlobalFunctions(){const e=window,t=this.config.prefix,r=(e,...r)=>{this.config.logCalls&&console.log(`[${t}Bridge] ${e}:`,...r)};e[`${t}_onPlayingStateChange`]=e=>{r("onPlayingStateChange",e),this.callbacks.onPlayingStateChange?.(e)},e[`${t}_GetAvatar`]=e=>{r("GetAvatar",e),this.callbacks.GetAvatar?.(e)},e[`${t}_onLoadPlayer`]=()=>{r("onLoadPlayer"),this.callbacks.onLoadPlayer?.()},e[`${t}_onProgress`]=e=>{r("onProgress",e),this.callbacks.onProgress?.(e)},e[`${t}_onCounterGloss`]=(e,t)=>{r("onCounterGloss",e,t),this.callbacks.onCounterGloss?.(e,t)},e[`${t}_onFinishWelcome`]=e=>{r("onFinishWelcome",e),this.callbacks.onFinishWelcome?.(e)},e[`${t}_onError`]=e=>{r("onError",e),this.callbacks.onError?.(e)},this.setupLegacyCompatibility(e)}setupLegacyCompatibility(e){const t=this.config.prefix;e.onPlayingStateChange=e[`${t}_onPlayingStateChange`],e.GetAvatar=e[`${t}_GetAvatar`],e.onLoadPlayer=e[`${t}_onLoadPlayer`],e.onProgress=e[`${t}_onProgress`],e.onCounterGloss=e[`${t}_onCounterGloss`],e.onFinishWelcome=e[`${t}_onFinishWelcome`],e.onError=e[`${t}_onError`]}cleanup(){if("undefined"==typeof window)return;const e=window,t=this.config.prefix;delete e[`${t}_onPlayingStateChange`],delete e[`${t}_GetAvatar`],delete e[`${t}_onLoadPlayer`],delete e[`${t}_onProgress`],delete e[`${t}_onCounterGloss`],delete e[`${t}_onFinishWelcome`],delete e[`${t}_onError`],delete e.onPlayingStateChange,delete e.GetAvatar,delete e.onLoadPlayer,delete e.onProgress,delete e.onCounterGloss,delete e.onFinishWelcome,delete e.onError,n.isSetup=!1}static isConfigured(){return n.isSetup}static getInstance(){return n.instance||null}}n.isSetup=!1;class a{static injectOptimizedCSS(e=".vlibras-container",t={},r){if("undefined"==typeof document)return;a.removeInjectedCSS();const n={fillContainer:!0,aspectRatio:"auto",scaleMode:"cover",removeBlackBorders:!0,backgroundColor:"transparent",borderRadius:"8px",...t},s=a.generateOptimizedCSS(e,n,r),o=document.createElement("style");o.id=a.injectedStyleId,o.textContent=s,document.head.appendChild(o),a.cssInjected=!0,console.log("[VLibras CSS] CSS otimizado injetado automaticamente")}static generateOptimizedCSS(e,t,r){let n=`\n/* VLibras Player - CSS Automático Otimizado */\n${e} {\n position: relative;\n overflow: hidden;\n ${t.borderRadius?`border-radius: ${t.borderRadius};`:""}\n ${t.backgroundColor?`background-color: ${t.backgroundColor};`:""}\n ${t.fillContainer?"width: 100%; height: 100%;":""}\n}\n\n${e} canvas {\n display: block;\n ${t.fillContainer?"width: 100% !important; height: 100% !important;":""}\n ${t.customWidth?`width: ${t.customWidth} !important;`:""}\n ${t.customHeight?`height: ${t.customHeight} !important;`:""}\n ${t.backgroundColor?`background-color: ${t.backgroundColor};`:""}\n ${t.borderRadius?`border-radius: ${t.borderRadius};`:""}\n \n /* Remove bordas pretas do Unity */\n ${t.removeBlackBorders?"transform: scale(1.05);":""}\n \n /* Modo de escala */\n object-fit: ${"stretch"===t.scaleMode?"fill":"cover"===t.scaleMode?"cover":"contain"===t.scaleMode?"contain":"none"};\n}\n\n/* Proporção de aspecto */\n${a.generateAspectRatioCSS(e,t.aspectRatio)}\n\n/* Container para centralizar o canvas */\n${e} .unity-container {\n position: relative;\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n/* Loading state styling */\n${e} .vlibras-loading {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 10;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 12px;\n}\n\n/* Estados visuais */\n${e}[data-state="loading"] {\n background: linear-gradient(45deg, #f0f0f0 25%, transparent 25%), \n linear-gradient(-45deg, #f0f0f0 25%, transparent 25%), \n linear-gradient(45deg, transparent 75%, #f0f0f0 75%), \n linear-gradient(-45deg, transparent 75%, #f0f0f0 75%);\n background-size: 20px 20px;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0px;\n animation: vlibras-loading-bg 2s linear infinite;\n}\n\n${e}[data-state="error"] {\n background-color: #fee;\n border: 2px solid #fcc;\n}\n\n${e}[data-state="ready"] {\n background-color: #efe;\n border: 2px solid #cfc;\n}\n\n@keyframes vlibras-loading-bg {\n 0% { background-position: 0 0, 0 10px, 10px -10px, -10px 0px; }\n 100% { background-position: 20px 20px, 20px 30px, 30px 10px, 10px 20px; }\n}\n\n/* Animações suaves */\n${e} canvas {\n transition: transform 0.3s ease, opacity 0.3s ease;\n}\n\n${e}[data-state="playing"] canvas {\n transform: scale(${t.removeBlackBorders?"1.05":"1"});\n opacity: 1;\n}\n\n${e}[data-state="loading"] canvas {\n opacity: 0.7;\n}\n`;return r?.enabled&&(n+=a.generateResponsiveCSS(e,r)),n}static generateAspectRatioCSS(e,t){if(!t||"auto"===t)return"";const r={"16:9":"56.25%","4:3":"75%","1:1":"100%"}[t];return r?`\n${e}::before {\n content: '';\n display: block;\n padding-top: ${r};\n}\n\n${e} .unity-container {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n}\n`:""}static generateResponsiveCSS(e,t){return`\n/* Mobile */\n@media (max-width: ${t.breakpoints.mobile.maxWidth}) {\n ${e} {\n ${a.configToCSS(t.breakpoints.mobile.config)}\n }\n}\n\n/* Tablet */\n@media (min-width: calc(${t.breakpoints.mobile.maxWidth} + 1px)) and (max-width: ${t.breakpoints.tablet.maxWidth}) {\n ${e} {\n ${a.configToCSS(t.breakpoints.tablet.config)}\n }\n}\n\n/* Desktop */\n@media (min-width: ${t.breakpoints.desktop.minWidth}) {\n ${e} {\n ${a.configToCSS(t.breakpoints.desktop.config)}\n }\n}\n`}static configToCSS(e){let t="";return e.customWidth&&(t+=`width: ${e.customWidth} !important; `),e.customHeight&&(t+=`height: ${e.customHeight} !important; `),e.backgroundColor&&(t+=`background-color: ${e.backgroundColor}; `),e.borderRadius&&(t+=`border-radius: ${e.borderRadius}; `),t}static removeInjectedCSS(){if("undefined"==typeof document)return;const e=document.getElementById(a.injectedStyleId);e&&(e.remove(),a.cssInjected=!1)}static isCSSInjected(){return a.cssInjected}static setContainerState(e,t){e&&e.setAttribute("data-state",t)}static getDefaultResponsiveConfig(){return{enabled:!0,breakpoints:{mobile:{maxWidth:"768px",config:{customHeight:"200px",removeBlackBorders:!0,borderRadius:"4px"}},tablet:{maxWidth:"1024px",config:{customHeight:"300px",removeBlackBorders:!0,borderRadius:"6px"}},desktop:{minWidth:"1025px",config:{fillContainer:!0,removeBlackBorders:!0,borderRadius:"8px"}}}}}}a.injectedStyleId="vlibras-auto-css",a.cssInjected=!1,new class{constructor(){this.listeners=new Map,this.onceListeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}once(e,t){return this.onceListeners.has(e)||this.onceListeners.set(e,[]),this.onceListeners.get(e).push(t),()=>this.off(e,t)}off(e,t){const r=this.listeners.get(e);if(r){const e=r.indexOf(t);-1!==e&&r.splice(e,1)}const n=this.onceListeners.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}emit(e,t){const r=this.listeners.get(e);r&&r.forEach(r=>{try{r(t)}catch(t){console.error(`Erro no listener do evento ${e}:`,t)}});const n=this.onceListeners.get(e);n&&(n.forEach(r=>{try{r(t)}catch(t){console.error(`Erro no listener once do evento ${e}:`,t)}}),this.onceListeners.set(e,[]))}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){return(this.listeners.get(e)?.length||0)+(this.onceListeners.get(e)?.length||0)}eventNames(){const e=new Set;for(const t of this.listeners.keys())e.add(t);for(const t of this.onceListeners.keys())e.add(t);return Array.from(e)}};class s{static enableDebugMode(){this.isDebugMode=!0,console.log("🔧 VLibras Debug Mode ativado"),this.injectDebugStyles(),this.startAutoPerformanceMonitoring()}static disableDebugMode(){this.isDebugMode=!1,console.log("🔧 VLibras Debug Mode desativado")}static isDebugEnabled(){return this.isDebugMode}static async runDiagnostics(){console.log("🔍 Executando diagnósticos do VLibras...");const e=this.checkWebGL(),t=await this.checkAssets(),r=this.checkPerformance(),n=this.checkCompatibility(),a={webgl:e,assets:t,performance:r,compatibility:n,recommendations:this.generateRecommendations(e,t,r,n)};return console.log("✅ Diagnósticos concluídos:",a),a}static startProfiling(){this.performanceData=[],this.profilingStartTime=performance.now(),console.log("📊 Profiling iniciado")}static stopProfiling(){if(!this.profilingStartTime)throw new Error("Profiling não foi iniciado");const e={operations:[...this.performanceData],summary:{totalOperations:this.performanceData.length,averageDuration:this.performanceData.reduce((e,t)=>e+t.duration,0)/this.performanceData.length||0,slowestOperation:this.performanceData.reduce((e,t)=>t.duration>e.duration?t:e,this.performanceData[0]||{name:"none",duration:0,timestamp:0}).name,memoryPeak:Math.max(...this.performanceData.map(e=>e.memory||0))}};return console.log("📊 Profiling concluído:",e),this.profilingStartTime=null,e}static recordOperation(e,t,r){this.profilingStartTime&&this.performanceData.push({name:e,duration:t,timestamp:performance.now(),memory:r}),this.isDebugMode&&console.log(`⏱️ ${e}: ${t.toFixed(2)}ms`)}static getDebugInfo(){return{version:"2.4.0",buildTime:(new Date).toISOString(),environment:"production",features:["UnityBridge","VLibrasPresets","VLibrasCSS","VLibrasEvents","VLibrasDevTools","ReactHooks","AccessibilitySupport","PerformanceMonitoring"],configuration:{debugMode:this.isDebugMode,profilingActive:null!==this.profilingStartTime,operationsRecorded:this.performanceData.length}}}static async clearCache(){console.log("🗑️ Limpando cache..."),localStorage.removeItem("vlibras-cache"),console.log("✅ Cache limpo")}static getCacheInfo(){return{size:0,entries:0,hitRate:0,missRate:0,storage:"memory"}}static checkWebGL(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{supported:!1,version:"Not supported",renderer:"Unknown",vendor:"Unknown"};const r=t.getExtension("WEBGL_debug_renderer_info");return{supported:!0,version:t.getParameter(t.VERSION),renderer:r?t.getParameter(r.UNMASKED_RENDERER_WEBGL):"Unknown",vendor:r?t.getParameter(r.UNMASKED_VENDOR_WEBGL):"Unknown"}}catch(e){return{supported:!1,version:"Error checking",renderer:"Error",vendor:"Error"}}}static async checkAssets(){const e=performance.now();try{const t=["/target/playerweb.wasm.code.unityweb","/target/playerweb.wasm.framework.unityweb","/target/playerweb.data.unityweb"];let r=0,n=0;for(const e of t)try{const t=await fetch(e,{method:"HEAD"});if(t.ok){n++;const e=t.headers.get("content-length");e&&(r+=parseInt(e,10))}}catch{}const a=performance.now()-e;return{available:n===t.length,size:r,version:"2.1.0",loadTime:a}}catch(t){return{available:!1,size:0,version:"Unknown",loadTime:performance.now()-e}}}static checkPerformance(){const e=performance.memory;return{loadTime:performance.now(),memoryUsage:e?e.usedJSHeapSize:0,fps:this.estimateFPS()}}static checkCompatibility(){const e=navigator.userAgent;let t="Unknown",r="Unknown",n=!1;if(e.includes("Chrome")){t="Chrome";const a=e.match(/Chrome\/(\d+)/);r=a?a[1]:"Unknown",n=parseInt(r)>=80}else if(e.includes("Firefox")){t="Firefox";const a=e.match(/Firefox\/(\d+)/);r=a?a[1]:"Unknown",n=parseInt(r)>=75}else if(e.includes("Safari")&&!e.includes("Chrome")){t="Safari";const a=e.match(/Version\/(\d+)/);r=a?a[1]:"Unknown",n=parseInt(r)>=13}else if(e.includes("Edge")){t="Edge";const a=e.match(/Edge\/(\d+)/);r=a?a[1]:"Unknown",n=parseInt(r)>=79}return{browser:t,version:r,supported:n,userAgent:e}}static generateRecommendations(e,t,r,n){const a=[];return e.supported||a.push("WebGL não é suportado. Considere usar um browser mais recente ou habilitar aceleração de hardware."),t.available||a.push("Assets do VLibras não estão disponíveis. Verifique se os arquivos estão no caminho correto."),t.loadTime>3e3&&a.push("Tempo de carregamento de assets está alto. Considere usar CDN ou otimizar assets."),r.memoryUsage>104857600&&a.push("Uso de memória está alto. Considere otimizar o código ou limpar cache."),r.fps<30&&a.push("FPS está baixo. Verifique a performance do dispositivo."),n.supported||a.push(`Browser ${n.browser} ${n.version} pode não ser totalmente compatível. Atualize para uma versão mais recente.`),0===a.length&&a.push("Sistema está funcionando corretamente! 🎉"),a}static estimateFPS(){return 60}static injectDebugStyles(){const e=document.createElement("style");e.id="vlibras-debug-styles",e.textContent="\n .vlibras-debug-overlay {\n position: fixed;\n top: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.8);\n color: white;\n padding: 10px;\n border-radius: 5px;\n font-family: monospace;\n font-size: 12px;\n z-index: 9999;\n max-width: 300px;\n }\n \n .vlibras-debug-item {\n margin: 2px 0;\n }\n \n .vlibras-debug-warning {\n color: #ff9800;\n }\n \n .vlibras-debug-error {\n color: #f44336;\n }\n \n .vlibras-debug-success {\n color: #4caf50;\n }\n ",document.head.appendChild(e)}static startAutoPerformanceMonitoring(){this.isDebugMode&&setInterval(()=>{const e=performance.memory;e&&e.usedJSHeapSize>52428800&&console.warn("⚠️ Alto uso de memória detectado:",e.usedJSHeapSize/1048576,"MB")},5e3)}}s.isDebugMode=!1,s.performanceData=[],s.profilingStartTime=null;const o={assetsPath:"/target",defaultRegion:"BR",theme:"auto",language:"pt-BR",enableStats:!1,debug:!1,autoRetry:!0,retryAttempts:3,performance:{preloadAssets:!1,cacheEnabled:!0,maxCacheSize:50,enableGPUAcceleration:!0,lowLatencyMode:!1},analytics:{enabled:!1,anonymizeData:!0,respectDoNotTrack:!0},accessibility:{announceStateChanges:!0,keyboardNavigation:!0,reduceMotion:!1,highContrastMode:!1,screenReaderSupport:!0},experimental:{enableWorkers:!1,enableOfflineMode:!1,enablePredictiveCache:!1,enableAutoScale:!0}};class i{static configure(e){const t={...this.config};this.config=this.deepMerge(this.config,e),this.saveToStorage(),this.applyConfiguration(),this.notifyListeners(),this.isInitialized=!0,console.log("🔧 VLibras configurado:",{previous:t,current:this.config,changes:this.getChanges(t,this.config)})}static getConfig(){return{...this.config}}static get(e){return this.config[e]}static set(e,t){this.configure({[e]:t})}static reset(){this.config={...o},this.saveToStorage(),this.applyConfiguration(),this.notifyListeners(),console.log("🔄 VLibras resetado para configuração padrão")}static loadFromStorage(){try{const e=localStorage.getItem("vlibras-global-config");if(e){const t=JSON.parse(e);return this.configure(t),!0}}catch(e){console.warn("⚠️ Erro ao carregar configuração do storage:",e)}return!1}static saveToStorage(){try{localStorage.setItem("vlibras-global-config",JSON.stringify(this.config))}catch(e){console.warn("⚠️ Erro ao salvar configuração no storage:",e)}}static onChange(e){return this.listeners.push(e),()=>{const t=this.listeners.indexOf(e);-1!==t&&this.listeners.splice(t,1)}}static isConfigured(){return this.isInitialized}static createPlayerConfig(e){return{targetPath:this.config.assetsPath,...e}}static getEnvironmentConfig(){const e="undefined"!=typeof process&&!1,t="undefined"!=typeof process&&!0;return e?{debug:!0,enableStats:!0,performance:{...o.performance,preloadAssets:!1}}:t?{debug:!1,enableStats:!1,performance:{...o.performance,preloadAssets:!0}}:{}}static autoConfigureForEnvironment(){const e=this.getEnvironmentConfig();this.configure(e)}static validateConfig(e){const t=[];return e.performance?.maxCacheSize&&e.performance.maxCacheSize<0&&t.push("maxCacheSize deve ser maior ou igual a 0"),e.retryAttempts&&e.retryAttempts<0&&t.push("retryAttempts deve ser maior ou igual a 0"),e.assetsPath&&!e.assetsPath.trim()&&t.push("assetsPath não pode estar vazio"),{valid:0===t.length,errors:t}}static applyConfiguration(){this.applyTheme(),this.applyAccessibilitySettings(),this.applyPerformanceSettings()}static applyTheme(){const{theme:e}=this.config,t=document.documentElement;if("auto"===e)if("undefined"!=typeof window&&window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)").matches;t.setAttribute("data-vlibras-theme",e?"dark":"light")}else t.setAttribute("data-vlibras-theme","light");else t.setAttribute("data-vlibras-theme",e)}static applyAccessibilitySettings(){const{accessibility:e}=this.config,t=document.documentElement;e.reduceMotion&&t.style.setProperty("--vlibras-animation-duration","0.01ms"),e.highContrastMode&&t.setAttribute("data-vlibras-contrast","high")}static applyPerformanceSettings(){const{performance:e}=this.config;e.enableGPUAcceleration,e.lowLatencyMode}static notifyListeners(){this.listeners.forEach(e=>{try{e(this.config)}catch(e){console.error("Erro no listener de configuração:",e)}})}static deepMerge(e,t){const r={...e};for(const n in t)void 0!==t[n]&&(this.isObject(t[n])&&this.isObject(e[n])?r[n]=this.deepMerge(e[n],t[n]):r[n]=t[n]);return r}static isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}static getChanges(e,t){const r={};for(const n in t)JSON.stringify(e[n])!==JSON.stringify(t[n])&&(r[n]={from:e[n],to:t[n]});return r}}i.config={...o},i.listeners=[],i.isInitialized=!1,"undefined"!=typeof window&&(i.loadFromStorage(),i.isConfigured()||i.autoConfigureForEnvironment(),"undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{"auto"===i.get("theme")&&i.configure({})}));class c{constructor(e){this.memoryCache=new Map,this.stats={hits:0,misses:0,totalRequests:0,hitRate:0,currentSize:0,maxSize:0,entries:0,oldestEntry:0,newestEntry:0},this.strategy=e,this.stats.maxSize=1024*e.maxSize*1024}static getInstance(e){return this.instance||(this.instance=new c(e||{type:"hybrid",maxSize:50,ttl:3600,compression:!0,maxEntries:1e3})),this.instance}static configure(e){const t=this.getInstance();t.strategy={...t.strategy,...e},t.stats.maxSize=1024*t.strategy.maxSize*1024}async set(e,t,r){const n={key:e,data:t,timestamp:Date.now(),ttl:r||this.strategy.ttl,size:this.calculateSize(t),accessCount:0,lastAccess:Date.now()};await this.ensureSpace(n.size),await this.storeEntry(n),this.updateStats()}async get(e){this.stats.totalRequests++;const t=await this.retrieveEntry(e);return t?this.isExpired(t)?(await this.delete(e),this.stats.misses++,this.updateHitRate(),null):(t.accessCount++,t.lastAccess=Date.now(),await this.storeEntry(t),this.stats.hits++,this.updateHitRate(),t.data):(this.stats.misses++,this.updateHitRate(),null)}async delete(e){const t=await this.deleteEntry(e);return t&&this.updateStats(),t}async clear(){this.memoryCache.clear(),"localStorage"!==this.strategy.type&&"hybrid"!==this.strategy.type||this.clearLocalStorage(),"indexedDB"!==this.strategy.type&&"hybrid"!==this.strategy.type||await this.clearIndexedDB(),this.resetStats()}async has(e){const t=await this.retrieveEntry(e);return null!==t&&!this.isExpired(t)}getStats(){return this.updateStats(),{...this.stats}}async preloadCommonWords(e){console.log(`📦 Preload de ${e.length} palavras comuns...`);for(const t of e)if(!await this.has(`gloss:${t}`)){const e=`gloss_data_for_${t}`;await this.set(`gloss:${t}`,e,2*this.strategy.ttl)}console.log("✅ Preload concluído")}async enablePredictiveCache(e){e.enabled&&console.log("🤖 Cache preditivo ativado")}async preloadForContext(e){const t={dictionary:["olá","obrigado","por favor","com licença","desculpa"],quiz:["correto","errado","parabéns","tente novamente","próxima"],tutorial:["início","continuar","próximo","anterior","fim"]}[e]||[];await this.preloadCommonWords(t)}calculateSize(e){try{return 2*JSON.stringify(e).length}catch{return 1024}}isExpired(e){return Date.now()>e.timestamp+1e3*e.ttl}async ensureSpace(e){if(this.stats.currentSize+e<=this.stats.maxSize)return;const t=Array.from(this.memoryCache.values()).sort((e,t)=>e.lastAccess-t.lastAccess);let r=0;for(const n of t){if(r>=e)break;await this.delete(n.key),r+=n.size}}async storeEntry(e){switch(this.strategy.type){case"memory":this.memoryCache.set(e.key,e);break;case"localStorage":await this.storeInLocalStorage(e);break;case"indexedDB":await this.storeInIndexedDB(e);break;case"hybrid":e.size<10240?this.memoryCache.set(e.key,e):await this.storeInIndexedDB(e)}}async retrieveEntry(e){const t=this.memoryCache.get(e);if(t)return t;if("localStorage"===this.strategy.type||"hybrid"===this.strategy.type){const t=await this.retrieveFromLocalStorage(e);if(t)return t}if("indexedDB"===this.strategy.type||"hybrid"===this.strategy.type){const t=await this.retrieveFromIndexedDB(e);if(t)return t}return null}async deleteEntry(e){let t=!1;if(this.memoryCache.has(e)&&(this.memoryCache.delete(e),t=!0),"localStorage"===this.strategy.type||"hybrid"===this.strategy.type)try{localStorage.removeItem(`vlibras:${e}`),t=!0}catch{}if("indexedDB"===this.strategy.type||"hybrid"===this.strategy.type)try{await this.deleteFromIndexedDB(e),t=!0}catch{}return t}async storeInLocalStorage(e){try{const t=this.strategy.compression?this.compress(JSON.stringify(e)):JSON.stringify(e);localStorage.setItem(`vlibras:${e.key}`,t)}catch(e){console.warn("Erro ao armazenar no localStorage:",e)}}async retrieveFromLocalStorage(e){try{const t=localStorage.getItem(`vlibras:${e}`);return t?this.strategy.compression?JSON.parse(this.decompress(t)):JSON.parse(t):null}catch{return null}}deleteFromLocalStorage(e){try{const t=`vlibras:${e}`;return!!localStorage.getItem(t)&&(localStorage.removeItem(t),!0)}catch(e){return console.warn("Erro ao remover do localStorage:",e),!1}}async storeInIndexedDB(e){try{const t=(await this.openIndexedDB()).transaction(["vlibras_cache"],"readwrite").objectStore("vlibras_cache");await new Promise((r,n)=>{const a=t.put(e,e.key);a.onsuccess=()=>r(),a.onerror=()=>n(a.error)})}catch(t){console.warn("Erro ao armazenar no IndexedDB:",t),await this.storeInLocalStorage(e)}}async retrieveFromIndexedDB(e){try{const t=(await this.openIndexedDB()).transaction(["vlibras_cache"],"readonly").objectStore("vlibras_cache");return new Promise((r,n)=>{const a=t.get(e);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}catch(t){return console.warn("Erro ao recuperar do IndexedDB:",t),this.retrieveFromLocalStorage(e)}}async deleteFromIndexedDB(e){try{const t=(await this.openIndexedDB()).transaction(["vlibras_cache"],"readwrite").objectStore("vlibras_cache");await new Promise((r,n)=>{const a=t.delete(e);a.onsuccess=()=>r(),a.onerror=()=>n(a.error)})}catch(t){console.warn("Erro ao remover do IndexedDB:",t),this.deleteFromLocalStorage(e)}}async openIndexedDB(){return new Promise((e,t)=>{const r=indexedDB.open("vlibras_cache_db",1);r.onupgradeneeded=e=>{const t=e.target.result;if(!t.objectStoreNames.contains("vlibras_cache")){const e=t.createObjectStore("vlibras_cache");e.createIndex("timestamp","timestamp",{unique:!1}),e.createIndex("ttl","ttl",{unique:!1})}},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}clearLocalStorage(){Object.keys(localStorage).forEach(e=>{e.startsWith("vlibras:")&&localStorage.removeItem(e)})}async clearIndexedDB(){}compress(e){return btoa(e)}decompress(e){try{return atob(e)}catch{return e}}updateStats(){if(this.stats.entries=this.memoryCache.size,this.stats.currentSize=Array.from(this.memoryCache.values()).reduce((e,t)=>e+t.size,0),this.stats.entries>0){const e=Array.from(this.memoryCache.values()).map(e=>e.timestamp);this.stats.oldestEntry=Math.min(...e),this.stats.newestEntry=Math.max(...e)}}updateHitRate(){this.stats.hitRate=this.stats.totalRequests>0?this.stats.hits/this.stats.totalRequests:0}resetStats(){this.stats={hits:0,misses:0,totalRequests:0,hitRate:0,currentSize:0,maxSize:this.stats.maxSize,entries:0,oldestEntry:0,newestEntry:0}}}c.getInstance();const l={name:"light",displayName:"Claro",description:"Tema claro padrão com alta legibilidade",colors:{primary:"#2563eb",secondary:"#64748b",background:"#ffffff",surface:"#f8fafc",error:"#dc2626",success:"#16a34a",warning:"#d97706",info:"#0284c7",text:"#1e293b",textSecondary:"#64748b",border:"#e2e8f0",shadow:"rgba(0, 0, 0, 0.1)"},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{light:300,normal:400,medium:500,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{none:"none",sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px -5px rgba(0, 0, 0, 0.1)"},animation:{duration:{fast:"150ms",normal:"300ms",slow:"500ms"},easing:{ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out"}},vlibras:{playerBackground:"#ffffff",controlsBackground:"#f8fafc",progressBarColor:"#2563eb",loadingSpinnerColor:"#2563eb",errorColor:"#dc2626",successColor:"#16a34a"}},d={...l,name:"dark",displayName:"Escuro",description:"Tema escuro para reduzir fadiga visual",colors:{primary:"#3b82f6",secondary:"#94a3b8",background:"#0f172a",surface:"#1e293b",error:"#ef4444",success:"#22c55e",warning:"#f59e0b",info:"#06b6d4",text:"#f1f5f9",textSecondary:"#94a3b8",border:"#334155",shadow:"rgba(0, 0, 0, 0.25)"},vlibras:{playerBackground:"#1e293b",controlsBackground:"#0f172a",progressBarColor:"#3b82f6",loadingSpinnerColor:"#3b82f6",errorColor:"#ef4444",successColor:"#22c55e"}},m={...l,name:"high-contrast",displayName:"Alto Contraste",description:"Tema com alto contraste para acessibilidade",colors:{primary:"#000000",secondary:"#333333",background:"#ffffff",surface:"#f0f0f0",error:"#cc0000",success:"#008800",warning:"#ff8800",info:"#0066cc",text:"#000000",textSecondary:"#333333",border:"#000000",shadow:"rgba(0, 0, 0, 0.5)"},vlibras:{playerBackground:"#ffffff",controlsBackground:"#f0f0f0",progressBarColor:"#000000",loadingSpinnerColor:"#000000",errorColor:"#cc0000",successColor:"#008800"}},g={...l,name:"compact",displayName:"Compacto",description:"Tema otimizado para espaços reduzidos",spacing:{xs:"0.125rem",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",xl:"1rem"},typography:{...l.typography,fontSize:{xs:"0.625rem",sm:"0.75rem",md:"0.875rem",lg:"1rem",xl:"1.125rem"}},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}};class p{constructor(){this.themes=new Map,this.currentTheme=l,this.styleElement=null,this.registerTheme(l),this.registerTheme(d),this.registerTheme(m),this.registerTheme(g),this.detectSystemPreference()}static getInstance(){return p.instance||(p.instance=new p),p.instance}registerTheme(e){this.themes.set(e.name,e),console.log(`🎨 Tema '${e.displayName}' registrado`)}getAvailableThemes(){return Array.from(this.themes.values())}getTheme(e){return this.themes.get(e)}getCurrentTheme(){return this.currentTheme}applyTheme(e){const t=this.themes.get(e);t?(this.currentTheme=t,this.injectCSS(t),["light","dark","high-contrast","auto"].includes(e)&&i.configure({theme:e}),localStorage.setItem("vlibras-theme",e),document.dispatchEvent(new CustomEvent("vlibras:theme-changed",{detail:{theme:t}})),console.log(`🎨 Tema '${t.displayName}' aplicado`)):console.error(`Tema '${e}' não encontrado`)}detectSystemPreference(){"undefined"!=typeof window&&window.matchMedia&&(window.matchMedia("(prefers-color-scheme: dark)").matches?this.applyTheme("dark"):this.applyTheme("light"),window.matchMedia("(prefers-contrast: high)").matches&&this.applyTheme("high-contrast"),window.matchMedia("(prefers-reduced-motion: reduce)").matches&&this.updateAnimations(!1),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{e.matches?this.applyTheme("dark"):this.applyTheme("light")}))}injectCSS(e){this.styleElement&&this.styleElement.remove(),this.styleElement=document.createElement("style"),this.styleElement.id="vlibras-theme";const t=this.generateCSS(e);this.styleElement.textContent=t,document.head.appendChild(this.styleElement)}generateCSS(e){return`\n :root {\n /* Cores */\n --vlibras-primary: ${e.colors.primary};\n --vlibras-secondary: ${e.colors.secondary};\n --vlibras-background: ${e.colors.background};\n --vlibras-surface: ${e.colors.surface};\n --vlibras-error: ${e.colors.error};\n --vlibras-success: ${e.colors.success};\n --vlibras-warning: ${e.colors.warning};\n --vlibras-info: ${e.colors.info};\n --vlibras-text: ${e.colors.text};\n --vlibras-text-secondary: ${e.colors.textSecondary};\n --vlibras-border: ${e.colors.border};\n --vlibras-shadow: ${e.colors.shadow};\n \n /* Espaçamentos */\n --vlibras-spacing-xs: ${e.spacing.xs};\n --vlibras-spacing-sm: ${e.spacing.sm};\n --vlibras-spacing-md: ${e.spacing.md};\n --vlibras-spacing-lg: ${e.spacing.lg};\n --vlibras-spacing-xl: ${e.spacing.xl};\n \n /* Tipografia */\n --vlibras-font-family: ${e.typography.fontFamily};\n --vlibras-font-size-xs: ${e.typography.fontSize.xs};\n --vlibras-font-size-sm: ${e.typography.fontSize.sm};\n --vlibras-font-size-md: ${e.typography.fontSize.md};\n --vlibras-font-size-lg: ${e.typography.fontSize.lg};\n --vlibras-font-size-xl: ${e.typography.fontSize.xl};\n \n /* Border radius */\n --vlibras-radius-none: ${e.borderRadius.none};\n --vlibras-radius-sm: ${e.borderRadius.sm};\n --vlibras-radius-md: ${e.borderRadius.md};\n --vlibras-radius-lg: ${e.borderRadius.lg};\n --vlibras-radius-full: ${e.borderRadius.full};\n \n /* Sombras */\n --vlibras-shadow-none: ${e.shadows.none};\n --vlibras-shadow-sm: ${e.shadows.sm};\n --vlibras-shadow-md: ${e.shadows.md};\n --vlibras-shadow-lg: ${e.shadows.lg};\n --vlibras-shadow-xl: ${e.shadows.xl};\n \n /* Animações */\n --vlibras-duration-fast: ${e.animation.duration.fast};\n --vlibras-duration-normal: ${e.animation.duration.normal};\n --vlibras-duration-slow: ${e.animation.duration.slow};\n \n /* VLibras específico */\n --vlibras-player-bg: ${e.vlibras.playerBackground};\n --vlibras-controls-bg: ${e.vlibras.controlsBackground};\n --vlibras-progress-color: ${e.vlibras.progressBarColor};\n --vlibras-loading-color: ${e.vlibras.loadingSpinnerColor};\n --vlibras-error-color: ${e.vlibras.errorColor};\n --vlibras-success-color: ${e.vlibras.successColor};\n }\n\n .vlibras-player {\n font-family: var(--vlibras-font-family);\n background-color: var(--vlibras-player-bg);\n color: var(--vlibras-text);\n border: 1px solid var(--vlibras-border);\n border-radius: var(--vlibras-radius-md);\n box-shadow: var(--vlibras-shadow-md);\n }\n\n .vlibras-controls {\n background-color: var(--vlibras-controls-bg);\n border-top: 1px solid var(--vlibras-border);\n padding: var(--vlibras-spacing-sm);\n border-radius: 0 0 var(--vlibras-radius-md) var(--vlibras-radius-md);\n }\n\n .vlibras-button {\n background-color: var(--vlibras-primary);\n color: white;\n border: none;\n padding: var(--vlibras-spacing-sm) var(--vlibras-spacing-md);\n border-radius: var(--vlibras-radius-sm);\n font-size: var(--vlibras-font-size-sm);\n cursor: pointer;\n transition: background-color var(--vlibras-duration-normal);\n }\n\n .vlibras-button:hover {\n background-color: color-mix(in srgb, var(--vlibras-primary) 80%, black);\n }\n\n .vlibras-button:disabled {\n background-color: var(--vlibras-secondary);\n cursor: not-allowed;\n opacity: 0.6;\n }\n\n .vlibras-progress {\n width: 100%;\n height: 4px;\n background-color: var(--vlibras-border);\n border-radius: var(--vlibras-radius-full);\n overflow: hidden;\n }\n\n .vlibras-progress-bar {\n height: 100%;\n background-color: var(--vlibras-progress-color);\n transition: width var(--vlibras-duration-normal);\n }\n\n .vlibras-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--vlibras-loading-color);\n padding: var(--vlibras-spacing-lg);\n }\n\n .vlibras-error {\n color: var(--vlibras-error-color);\n background-color: color-mix(in srgb, var(--vlibras-error-color) 10%, transparent);\n border: 1px solid var(--vlibras-error-color);\n border-radius: var(--vlibras-radius-sm);\n padding: var(--vlibras-spacing-md);\n }\n\n .vlibras-success {\n color: var(--vlibras-success-color);\n background-color: color-mix(in srgb, var(--vlibras-success-color) 10%, transparent);\n border: 1px solid var(--vlibras-success-color);\n border-radius: var(--vlibras-radius-sm);\n padding: var(--vlibras-spacing-md);\n }\n\n @media (prefers-reduced-motion: reduce) {\n .vlibras-player * {\n animation-duration: 0.01ms !important;\n animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important;\n }\n }\n `}updateAnimations(e){document.documentElement.style.setProperty("--vlibras-animations-enabled",e?"1":"0")}createCustomTheme(e,t){const r=this.themes.get(e);if(!r)throw new Error(`Tema base '${e}' não encontrado`);const n={...r,...t,name:t.name||`custom-${Date.now()}`,colors:{...r.colors,...t.colors},spacing:{...r.spacing,...t.spacing},typography:{...r.typography,...t.typography,fontSize:{...r.typography.fontSize,...t.typography?.fontSize}},vlibras:{...r.vlibras,...t.vlibras}};return this.registerTheme(n),n}removeTheme(e){["light","dark","high-contrast","compact"].includes(e)?console.warn("Não é possível remover temas padrão"):(this.themes.delete(e),console.log(`🗑️ Tema '${e}' removido`))}}p.instance=null,p.getInstance();class h{static applyCanvasConfig(e,t){const r={...this.defaultConfig,...t},n=e.parentElement?.id||"unknown";this.appliedConfigs.set(n,r),this.applyBasicStyles(e,r),this.applyAspectRatio(e,r),this.applyScaleMode(e,r),this.applyQualitySettings(e,r),r.responsive&&this.setupResponsive(e,r),console.log("🎨 Canvas configurado com:",r)}static applyBasicStyles(e,t){const r=e.style;t.fillContainer&&(r.width="100%",r.height="100%"),t.backgroundColor&&(r.backgroundColor=t.backgroundColor),t.borderRadius&&(r.borderRadius=t.borderRadius),t.maxWidth&&(r.maxWidth=t.maxWidth),t.maxHeight&&(r.maxHeight=t.maxHeight),t.minWidth&&(r.minWidth=t.minWidth),t.minHeight&&(r.minHeight=t.minHeight),t.removeBlackBorders&&(r.transform="scale(1.05)",r.overflow="hidden"),r.display="block",r.objectFit=t.scaleMode||"contain"}static applyAspectRatio(e,t){if("auto"===t.aspectRatio)return;const r=e.parentElement;if(!r)return;const n=t.aspectRatio?{"16:9":16/9,"4:3":4/3,"1:1":1,"3:2":1.5,"21:9":21/9,"9:16":9/16}[t.aspectRatio]:null;if(!n)return;let a=r.querySelector(".vlibras-aspect-wrapper");a||(a=document.createElement("div"),a.className="vlibras-aspect-wrapper",a.style.cssText=`\n position: relative;\n width: 100%;\n height: 0;\n padding-bottom: ${1/n*100}%;\n overflow: hidden;\n `,r.insertBefore(a,e),a.appendChild(e)),e.style.cssText+="\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n "}static applyScaleMode(e,t){const r={stretch:"fill",cover:"cover",contain:"contain",fill:"fill"}[t.scaleMode||"contain"];r&&(e.style.objectFit=r)}static applyQualitySettings(e,t){(e.getContext("webgl")||e.getContext("webgl2"))&&t.enableAntialiasing&&(e.style.imageRendering="high"===t.quality||"ultra"===t.quality?"crisp-edges":"auto"),t.enableHardwareAcceleration&&(e.style.willChange="transform",e.style.backfaceVisibility="hidden");const r={low:{filter:"none"},medium:{filter:"none"},high:{filter:"contrast(1.1) brightness(1.05)"},ultra:{filter:"contrast(1.15) brightness(1.1) saturate(1.05)"}}[t.quality||"medium"];r.filter&&(e.style.filter=r.filter)}static setupResponsive(e,t){const r=()=>{const r=window.innerWidth;let n={...t};n=r<=768?{...n,scaleMode:"cover",removeBlackBorders:!0,quality:"medium"}:r<=1024?{...n,quality:"medium"}:{...n,quality:t.quality||"high"},this.applyBasicStyles(e,n)};if(r(),window.addEventListener("resize",r),"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(()=>{r()});e.parentElement&&t.observe(e.parentElement)}}static applyPreset(e,t){const r=this.presets[t];if(!r)throw new Error(`Preset '${t}' não encontrado`);this.applyCanvasConfig(e,r),console.log(`✅ Preset '${t}' aplicado ao canvas`)}static autoDetectAndApply(e){const t=e.parentElement;if(!t)return;const r=t.offsetWidth,n=t.offsetHeight,a=r/n;let s={...this.defaultConfig};s=r<300||n<200?this.presets.compact:a>1.5?this.presets.presentation:a<.8?this.presets.mobile:this.presets.dictionary,this.applyCanvasConfig(e,s),console.log("🔍 Auto-detectado e aplicado configuração baseada no contexto:",s)}static injectGlobalCSS(){if("undefined"==typeof document)return;if(document.getElementById("vlibras-canvas-config"))return;const e=document.createElement("style");e.id="vlibras-canvas-config",e.textContent="\n .vlibras-canvas-container {\n position: relative;\n overflow: hidden;\n }\n \n .vlibras-aspect-wrapper {\n position: relative;\n width: 100%;\n overflow: hidden;\n }\n \n .vlibras-canvas-optimized {\n image-rendering: optimizeSpeed;\n image-rendering: -moz-crisp-edges;\n image-rendering: -webkit-optimize-contrast;\n image-rendering: optimize-contrast;\n image-rendering: pixelated;\n ms-interpolation-mode: nearest-neighbor;\n }\n \n @media (max-width: 768px) {\n .vlibras-canvas-container {\n width: 100%;\n height: auto;\n }\n }\n \n @media (prefers-reduced-motion: reduce) {\n .vlibras-canvas-container canvas {\n animation: none !important;\n transition: none !important;\n }\n }\n ",document.head.appendChild(e),console.log("🎨 CSS global do VLibras Canvas Config injetado")}static removeConfig(e){this.appliedConfigs.delete(e)}static getAppliedConfig(e){return this.appliedConfigs.get(e)}}h.defaultConfig={fillContainer:!0,aspectRatio:"auto",scaleMode:"contain",removeBlackBorders:!0,backgroundColor:"transparent",responsive:!0,quality:"medium",enableAntialiasing:!0,enableHardwareAcceleration:!0},h.appliedConfigs=new Map,h.presets={dictionary:{fillContainer:!0,aspectRatio:"4:3",scaleMode:"contain",removeBlackBorders:!0,backgroundColor:"#f8f9fa",borderRadius:"8px",responsive:!0,quality:"high"},quiz:{fillContainer:!0,aspectRatio:"16:9",scaleMode:"cover",removeBlackBorders:!0,backgroundColor:"transparent",responsive:!0,quality:"medium"},compact:{fillContainer:!0,aspectRatio:"1:1",scaleMode:"cover",removeBlackBorders:!0,backgroundColor:"transparent",maxWidth:"200px",maxHeight:"200px",quality:"medium"},presentation:{fillContainer:!0,aspectRatio:"16:9",scaleMode:"contain",removeBlackBorders:!1,backgroundColor:"#000000",responsive:!0,quality:"ultra",enableHardwareAcceleration:!0},mobile:{fillContainer:!0,aspectRatio:"9:16",scaleMode:"cover",removeBlackBorders:!0,backgroundColor:"transparent",responsive:!0,quality:"medium"}},"undefined"!=typeof document&&h.injectGlobalCSS();class u{constructor(){this.events=new Map}emit(e,t){(this.events.get(e)||[]).forEach(r=>{try{r(t)}catch(t){console.error(`Erro em listener do evento ${e}:`,t)}})}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e).push(t)}off(e,t){const r=this.events.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}}class f{constructor(){this.plugins=new Map,this.eventEmitter=new u}static getInstance(){return f.instance||(f.instance=new f),f.instance}async register(e,t){const r=this.validatePlugin(e);if(!r.valid)throw new Error(`Plugin inválido: ${r.errors.join(", ")}`);await this.checkDependencies(e);const n={plugin:e,config:t,active:!1,errorCount:0};this.plugins.set(e.name,n),this.eventEmitter.emit("plugin:registered",{name:e.name,version:e.version}),console.log(`✅ Plugin '${e.name}' registrado com sucesso`)}async activate(e,t){const r=this.plugins.get(e);if(!r)throw new Error(`Plugin '${e}' não encontrado`);if(r.active)console.warn(`Plugin '${e}' já está ativo`);else try{const n=performance.now();await r.plugin.setup(t,r.config);const a=performance.now()-n;r.setupTime=a,r.active=!0,r.plugin.onPlayerReady&&t.on("player:ready",()=>r.plugin.onPlayerReady(t)),r.plugin.onTranslation&&t.on("translation:start",({text:e})=>r.plugin.onTranslation(e,t)),r.plugin.onError&&t.on("player:error",({error:e})=>r.plugin.onError(e,t)),this.eventEmitter.emit("plugin:activated",{name:e,setupTime:a}),console.log(`🚀 Plugin '${e}' ativado (${a.toFixed(2)}ms)`)}catch(t){throw r.errorCount++,r.lastError=t,this.eventEmitter.emit("plugin:error",{name:e,error:t}),new Error(`Erro ao ativar plugin '${e}': ${t.message}`)}}async deactivate(e,t){const r=this.plugins.get(e);if(!r)throw new Error(`Plugin '${e}' não encontrado`);if(r.active)try{r.plugin.teardown&&await r.plugin.teardown(t),r.active=!1,this.eventEmitter.emit("plugin:deactivated",{name:e}),console.log(`🛑 Plugin '${e}' desativado`)}catch(t){throw r.errorCount++,r.lastError=t,new Error(`Erro ao desativar plugin '${e}': ${t.message}`)}else console.warn(`Plugin '${e}' já está inativo`)}list(){return Array.from(this.plugins.values())}listByCategory(e){return this.list().filter(t=>t.plugin.category===e)}getPluginInfo(e){return this.plugins.get(e)}validatePlugin(e){const t=[],r=[];return e.name&&""!==e.name.trim()||t.push("Nome do plugin é obrigatório"),e.version&&""!==e.version.trim()||t.push("Versão do plugin é obrigatória"),"function"!=typeof e.setup&&t.push("Método setup é obrigatório"),e.description||r.push("Descrição do plugin é recomendada"),e.category||r.push("Categoria do plugin é recomendada"),this.plugins.has(e.name)&&t.push(`Já existe plugin com nome '${e.name}'`),{valid:0===t.length,errors:t,warnings:r}}async checkDependencies(e){if(!e.dependencies||0===e.dependencies.length)return;const t=[];for(const r of e.dependencies)this.plugins.has(r)||t.push(r);if(t.length>0)throw new Error(`Dependências não encontradas para plugin '${e.name}': ${t.join(", ")}`)}async autoActivate(e,t={}){const{enabledPlugins:r=[]}=t;for(const t of r)try{await this.activate(t,e)}catch(e){console.error(`Erro ao ativar plugin '${t}':`,e.message)}}getStats(){const e=this.list();return{total:e.length,active:e.filter(e=>e.active).length,inactive:e.filter(e=>!e.active).length,withErrors:e.filter(e=>e.errorCount>0).length,byCategory:e.reduce((e,t)=>{const r=t.plugin.category||"unknown";return e[r]=(e[r]||0)+1,e},{}),avgSetupTime:e.filter(e=>e.setupTime).reduce((e,t,r,n)=>e+t.setupTime/n.length,0)}}on(e,t){this.eventEmitter.on(e,t)}clear(){this.plugins.clear()}}var b;return f.instance=null,f.getInstance(),function(e){e.IDLE="idle",e.INITIALIZING="initializing",e.LOADING_ASSETS="loading_assets",e.READY="ready",e.TRANSLATING="translating",e.PLAYING="playing",e.PAUSED="paused",e.COMPLETED="completed",e.ERROR="error"}(b||(b={})),b.IDLE,b.INITIALIZING,b.LOADING_ASSETS,b.READY,b.TRANSLATING,b.PLAYING,b.PAUSED,b.COMPLETED,b.ERROR,r.default}()});