// ==UserScript== // @name [VOT] - Voice Over Translation // @name:de [VOT] - Voice-Over-Video-Übersetzung // @name:es [VOT] - Traducción de vídeo en off // @name:fr [VOT] - Traduction vidéo voix-off // @name:it [VOT] - Traduzione Video fuori campo // @name:ru [VOT] - Закадровый перевод видео // @name:zh [VOT] - 画外音视频翻译 // @namespace vot // @version 1.11.1 // @author Toil, SashaXser, MrSoczekXD, mynovelhost, sodapng // @description A small extension that adds a Yandex Browser video translation to other browsers // @description:de Eine kleine Erweiterung, die eine Voice-over-Übersetzung von Videos aus dem Yandex-Browser zu anderen Browsern hinzufügt // @description:es Una pequeña extensión que agrega una traducción de voz en off de un video de Yandex Browser a otros navegadores // @description:fr Une petite extension qui ajoute la traduction vocale de la vidéo du Navigateur Yandex à d'autres navigateurs // @description:it Una piccola estensione che aggiunge la traduzione vocale del video dal browser Yandex ad altri browser // @description:ru Небольшое расширение, которое добавляет закадровый перевод видео из Яндекс Браузера в другие браузеры // @description:zh 一个小扩展,它增加了视频从Yandex浏览器到其他浏览器的画外音翻译 // @license MIT // @icon https://translate.yandex.ru/icons/favicon.ico // @homepageURL https://github.com/ilyhalight/voice-over-translation // @source https://github.com/ilyhalight/voice-over-translation.git // @supportURL https://github.com/ilyhalight/voice-over-translation/issues // @downloadURL https://raw.githubusercontent.com/ilyhalight/voice-over-translation/master/dist/vot-min.user.js // @updateURL https://raw.githubusercontent.com/ilyhalight/voice-over-translation/master/dist/vot-min.user.js // @match *://*.youtube.com/* // @match *://*.youtube-nocookie.com/* // @match *://*.youtubekids.com/* // @match *://*.twitch.tv/* // @match *://*.xvideos.com/* // @match *://*.xvideos-ar.com/* // @match *://*.xvideos005.com/* // @match *://*.xv-ru.com/* // @match *://*.xhamster.com/* // @match *://*.xhamster.desi/* // @match *://*.xhvid.com/* // @match *://*.spankbang.com/* // @match *://*.rule34video.com/* // @match *://*.picarto.tv/* // @match *://*.olympics.com/* // @match *://*.pornhub.com/* // @match *://*.pornhub.org/* // @match *://*.vk.com/* // @match *://*.vkvideo.ru/* // @match *://*.vk.ru/* // @match *://*.vimeo.com/* // @match *://*.imdb.com/* // @match *://*.9gag.com/* // @match *://*.twitter.com/* // @match *://*.x.com/* // @match *://*.facebook.com/* // @match *://*.rutube.ru/* // @match *://*.bilibili.com/* // @match *://*.bilibili.tv/* // @match *://my.mail.ru/* // @match *://*.bitchute.com/* // @match *://*.coursera.org/* // @match *://*.udemy.com/course/* // @match *://*.tiktok.com/* // @match *://*.douyin.com/* // @match *://rumble.com/* // @match *://*.eporner.com/* // @match *://*.dailymotion.com/* // @match *://*.ok.ru/* // @match *://trovo.live/* // @match *://disk.yandex.ru/* // @match *://disk.yandex.kz/* // @match *://disk.yandex.com/* // @match *://disk.yandex.com.am/* // @match *://disk.yandex.com.ge/* // @match *://disk.yandex.com.tr/* // @match *://disk.yandex.by/* // @match *://disk.yandex.az/* // @match *://disk.yandex.co.il/* // @match *://disk.yandex.ee/* // @match *://disk.yandex.lt/* // @match *://disk.yandex.lv/* // @match *://disk.yandex.md/* // @match *://disk.yandex.net/* // @match *://disk.yandex.tj/* // @match *://disk.yandex.tm/* // @match *://disk.yandex.uz/* // @match *://disk.360.yandex.ru/* // @match *://youtube.googleapis.com/embed/* // @match *://*.banned.video/* // @match *://*.madmaxworld.tv/* // @match *://*.weverse.io/* // @match *://*.newgrounds.com/* // @match *://*.egghead.io/* // @match *://*.youku.com/* // @match *://*.archive.org/* // @match *://*.patreon.com/* // @match *://*.reddit.com/* // @match *://*.kodik.info/* // @match *://*.kodik.biz/* // @match *://*.kodik.cc/* // @match *://*.kick.com/* // @match *://developer.apple.com/* // @match *://dev.epicgames.com/* // @match *://*.rapid-cloud.co/* // @match *://odysee.com/* // @match *://learning.sap.com/* // @match *://*.watchporn.to/* // @match *://*.linkedin.com/* // @match *://*.incestflix.net/* // @match *://*.incestflix.to/* // @match *://*.porntn.com/* // @match *://*.dzen.ru/* // @match *://*.cloudflarestream.com/* // @match *://*.loom.com/* // @match *://*.artstation.com/learning/* // @match *://*.rt.com/* // @match *://*.bitview.net/* // @match *://*.kickstarter.com/* // @match *://*.thisvid.com/* // @match *://*.ign.com/* // @match *://*.bunkr.site/* // @match *://*.bunkr.black/* // @match *://*.bunkr.cat/* // @match *://*.bunkr.media/* // @match *://*.bunkr.red/* // @match *://*.bunkr.ws/* // @match *://*.bunkr.org/* // @match *://*.bunkr.sk/* // @match *://*.bunkr.si/* // @match *://*.bunkr.su/* // @match *://*.bunkr.ci/* // @match *://*.bunkr.cr/* // @match *://*.bunkr.fi/* // @match *://*.bunkr.ph/* // @match *://*.bunkr.pk/* // @match *://*.bunkr.ps/* // @match *://*.bunkr.ru/* // @match *://*.bunkr.la/* // @match *://*.bunkr.is/* // @match *://*.bunkr.to/* // @match *://*.bunkr.ac/* // @match *://*.bunkr.ax/* // @match *://web.telegram.org/k/* // @match *://t2mc.toil.cc/* // @match *://mylearn.oracle.com/* // @match *://learn.deeplearning.ai/* // @match *://learn-staging.deeplearning.ai/* // @match *://learn-dev.deeplearning.ai/* // @match *://*.netacad.com/content/i2cs/* // @match *://*.nicovideo.jp/* // @match *://*.zdf.de/* // @match *://*.weibo.com/* // @match *://*/*.mp4* // @match *://*/*.webm* // @match *://*.yewtu.be/* // @match *://inv.nadeko.net/* // @match *://invidious.nerdvpn.de/* // @match *://invidious.protokolla.fi/* // @match *://invidious.materialio.us/* // @match *://iv.melmac.space/* // @match *://*.piped.video/* // @match *://piped.kavin.rocks/* // @match *://piped.private.coffee/* // @match *://proxitok.pabloferreiro.es/* // @match *://proxitok.pussthecat.org/* // @match *://tok.habedieeh.re/* // @match *://proxitok.esmailelbob.xyz/* // @match *://proxitok.privacydev.net/* // @match *://tok.artemislena.eu/* // @match *://tok.adminforge.de/* // @match *://tt.vern.cc/* // @match *://cringe.whatever.social/* // @match *://proxitok.lunar.icu/* // @match *://proxitok.privacy.com.de/* // @match *://peertube.tmp.rcp.tf/* // @match *://*.dalek.zone/* // @match *://video.sadmin.io/* // @match *://videos.viorsan.com/* // @match *://peertube.1312.media/* // @match *://tube.shanti.cafe/* // @match *://*.bee-tube.fr/* // @match *://video.blender.org/* // @match *://*.beetoons.tv/* // @match *://*.makertube.net/* // @match *://*.peertube.tv/* // @match *://*.framatube.org/* // @match *://*.tilvids.com/* // @match *://*.diode.zone/* // @match *://*.fedimovie.com/* // @match *://video.hardlimit.com/* // @match *://*.share.tube/* // @match *://*.peervideo.club/* // @match *://*.coursehunter.net/* // @match *://*.coursetrain.net/* // @exclude file://*/*.mp4* // @exclude file://*/*.webm* // @exclude *://accounts.youtube.com/* // @require https://gist.githubusercontent.com/ilyhalight/6eb5bb4dffc7ca9e3c57d6933e2452f3/raw/7ab38af2228d0bed13912e503bc8a9ee4b11828d/gm-addstyle-polyfill.js // @connect yandex.ru // @connect disk.yandex.kz // @connect disk.yandex.com // @connect disk.yandex.com.am // @connect disk.yandex.com.ge // @connect disk.yandex.com.tr // @connect disk.yandex.by // @connect disk.yandex.az // @connect disk.yandex.co.il // @connect disk.yandex.ee // @connect disk.yandex.lt // @connect disk.yandex.lv // @connect disk.yandex.md // @connect disk.yandex.net // @connect disk.yandex.tj // @connect disk.yandex.tm // @connect disk.yandex.uz // @connect disk.360.yandex.ru // @connect yandex.net // @connect timeweb.cloud // @connect raw.githubusercontent.com // @connect vimeo.com // @connect toil.cc // @connect deno.dev // @connect onrender.com // @connect workers.dev // @connect cloudflare-dns.com // @connect porntn.com // @connect googlevideo.com // @grant GM.deleteValue // @grant GM.getValue // @grant GM.getValues // @grant GM.listValues // @grant GM.setValue // @grant GM_addStyle // @grant GM_deleteValue // @grant GM_getValue // @grant GM_info // @grant GM_listValues // @grant GM_notification // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant unsafeWindow // @grant window.focus // ==/UserScript== !function(){function e(e,t){return(t||"")+" (SystemJS Error#"+e+" https://github.com/systemjs/systemjs/blob/main/docs/errors.md#"+e+")"}function t(e,t){if(-1!==e.indexOf("\\")&&(e=e.replace(j,"/")),"/"===e[0]&&"/"===e[1])return t.slice(0,t.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){var n,r=t.slice(0,t.indexOf(":")+1);if(n="/"===t[r.length+1]?"file:"!==r?(n=t.slice(r.length+2)).slice(n.indexOf("/")+1):t.slice(8):t.slice(r.length+("/"===t[r.length])),"/"===e[0])return t.slice(0,t.length-n.length-1)+e;for(var i=n.slice(0,n.lastIndexOf("/")+1)+e,o=[],s=-1,u=0;un.length&&"/"!==r[r.length-1]))return r+e.slice(n.length);u("W2",n,r,"should have a trailing '/'")}}function u(t,n,r,i){console.warn(e(t,"Package target "+i+", resolving target '"+r+"' for "+n))}function c(e,t,n){for(var r=e.scopes,i=n&&o(n,r);i;){var u=s(t,r[i]);if(u)return u;i=o(i.slice(0,i.lastIndexOf("/")),r)}return s(t,e.imports)||-1!==t.indexOf(":")&&t}function a(){this[M]={}}function f(e){return e.id}function l(e,t,n,r){if(e.onload(n,t.id,t.d&&t.d.map(f),!!r),n)throw n}function d(t,n,r,i){var o=t[M][n];if(o)return o;var s=[],u=Object.create(null);P&&Object.defineProperty(u,P,{value:"Module"});var c=Promise.resolve().then((function(){return t.instantiate(n,r,i)})).then((function(r){if(!r)throw Error(e(2,"Module "+n+" did not instantiate"));var i=r[1]((function(e,t){o.h=!0;var n=!1;if("string"==typeof e)e in u&&u[e]===t||(u[e]=t,n=!0);else{for(var r in e)t=e[r],r in u&&u[r]===t||(u[r]=t,n=!0);e&&e.__esModule&&(u.__esModule=e.__esModule)}if(n)for(var i=0;i-1){var n=document.createEvent("Event");n.initEvent("error",!1,!1),t.dispatchEvent(n)}return Promise.reject(e)}))}else if("systemjs-importmap"===t.type){t.sp=!0;var r=t.src?(System.fetch||fetch)(t.src,{integrity:t.integrity,priority:t.fetchPriority,passThrough:!0}).then((function(e){if(!e.ok)throw Error("Invalid status code: "+e.status);return e.text()})).catch((function(n){return n.message=e("W4","Error fetching systemjs-import map "+t.src)+"\n"+n.message,console.warn(n),"function"==typeof t.onerror&&t.onerror(),"{}"})):t.innerHTML;W=W.then((function(){return r})).then((function(n){!function(t,n,r){var o={};try{o=JSON.parse(n)}catch(s){console.warn(Error(e("W5","systemjs-importmap contains invalid JSON")+"\n\n"+n+"\n"))}i(o,r,t)}(N,n,t.src||g)}))}}))}var g,y="undefined"!=typeof Symbol,b="undefined"!=typeof self,S="undefined"!=typeof document,w=b?self:global;if(S){var O=document.querySelector("base[href]");O&&(g=O.href)}if(!g&&"undefined"!=typeof location){var E=(g=location.href.split("#")[0].split("?")[0]).lastIndexOf("/");-1!==E&&(g=g.slice(0,E+1))}var x,j=/\\/g,P=y&&Symbol.toStringTag,M=y?Symbol():"@",I=a.prototype;I.import=function(e,t,n){var r=this;return t&&"object"==typeof t&&(n=t,t=void 0),Promise.resolve(r.prepareImport()).then((function(){return r.resolve(e,t,n)})).then((function(e){var t=d(r,e,void 0,n);return t.C||p(r,t)}))},I.createContext=function(e){var t=this;return{url:e,resolve:function(n,r){return Promise.resolve(t.resolve(n,r||e))}}},I.onload=function(){},I.register=function(e,t,n){x=[e,t,n]},I.getRegister=function(){var e=x;return x=void 0,e};var L=Object.freeze(Object.create(null));w.System=new a;var C,R,W=Promise.resolve(),N={imports:{},scopes:{},depcache:{},integrity:{}},T=S;if(I.prepareImport=function(e){return(T||e)&&(m(),T=!1),W},I.getImportMap=function(){return JSON.parse(JSON.stringify(N))},S&&(m(),window.addEventListener("DOMContentLoaded",m)),I.addImportMap=function(e,t){i(e,t||g,N)},S){window.addEventListener("error",(function(e){J=e.filename,_=e.error}));var A=location.origin}I.createScript=function(e){var t=document.createElement("script");t.async=!0,e.indexOf(A+"/")&&(t.crossOrigin="anonymous");var n=N.integrity[e];return n&&(t.integrity=n),t.src=e,t};var J,_,k={},U=I.register;I.register=function(e,t){if(S&&"loading"===document.readyState&&"string"!=typeof e){var n=document.querySelectorAll("script[src]"),r=n[n.length-1];if(r){C=e;var i=this;R=setTimeout((function(){k[r.src]=[e,t],i.import(r.src)}))}}else C=void 0;return U.call(this,e,t)},I.instantiate=function(t,n){var r=k[t];if(r)return delete k[t],r;var i=this;return Promise.resolve(I.createScript(t)).then((function(r){return new Promise((function(o,s){r.addEventListener("error",(function(){s(Error(e(3,"Error loading "+t+(n?" from "+n:""))))})),r.addEventListener("load",(function(){if(document.head.removeChild(r),J===t)s(_);else{var e=i.getRegister(t);e&&e[0]===C&&clearTimeout(R),o(e)}})),document.head.appendChild(r)}))}))},I.shouldFetch=function(){return!1},"undefined"!=typeof fetch&&(I.fetch=fetch);var $=I.instantiate,B=/^(text|application)\/(x-)?javascript(;|$)/;I.instantiate=function(t,n,r){var i=this;return this.shouldFetch(t,n,r)?this.fetch(t,{credentials:"same-origin",integrity:N.integrity[t],meta:r}).then((function(r){if(!r.ok)throw Error(e(7,r.status+" "+r.statusText+", loading "+t+(n?" from "+n:"")));var o=r.headers.get("content-type");if(!o||!B.test(o))throw Error(e(4,'Unknown Content-Type "'+o+'", loading '+t+(n?" from "+n:"")));return r.text().then((function(e){return e.indexOf("//# sourceURL=")<0&&(e+="\n//# sourceURL="+t),(0,eval)(e),i.getRegister(t)}))})):$.apply(this,arguments)},I.resolve=function(n,r){return c(N,t(n,r=r||g)||n,r)||function(t,n){throw Error(e(8,"Unable to resolve bare specifier '"+t+(n?"' from "+n:"'")))}(n,r)};var F=I.instantiate;I.instantiate=function(e,t,n){var r=N.depcache[e];if(r)for(var i=0;i{t.has(e)||(t.add(e),(a=>GM_addStyle(a))(e));}; const K={host:"api.browser.yandex.ru",hostVOT:"vot.toil.cc/v1",hostWorker:"vot-worker.toil.cc",mediaProxy:"media-proxy.toil.cc",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 YaBrowser/25.12.0.0 Safari/537.36",componentVersion:"25.12.4.1198",hmac:"bt8xH3VOlb4mqf0nqAibnDOoiPlXsisf",defaultDuration:343,minChunkSize:5295308,loggerLevel:1,version:"2.4.14"};function Ls(){let e=0,t=0;for(let i=0;i<28;i+=7){let o=this.buf[this.pos++];if(e|=(o&127)<>4,(n&128)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let o=this.buf[this.pos++];if(t|=(o&127)<>>r,a=!(!(s>>>7)&&t==0),l=(a?s|128:s)&255;if(n.push(l),!a)return}const i=e>>>28&15|(t&7)<<4,o=t>>3!=0;if(n.push((o?i|128:i)&255),!!o){for(let r=3;r<31;r=r+7){const s=t>>>r,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(t>>>31&1);}}const Se=4294967296;function Xn(e){const t=e[0]==="-";t&&(e=e.slice(1));const n=1e6;let i=0,o=0;function r(s,a){const l=Number(e.slice(s,a));o*=n,i=i*n+l,i>=Se&&(o=o+(i/Se|0),i=i%Se);}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?Oo(i,o):An(i,o)}function Is(e,t){let n=An(e,t);const i=n.hi&2147483648;i&&(n=Oo(n.lo,n.hi));const o=_o(n.lo,n.hi);return i?"-"+o:o}function _o(e,t){if({lo:e,hi:t}=Ps(e,t),t<=2097151)return String(Se*t+e);const n=e&16777215,i=(e>>>24|t<<8)&16777215,o=t>>16&65535;let r=n+i*6777216+o*6710656,s=i+o*8147497,a=o*2;const l=1e7;return r>=l&&(s+=Math.floor(r/l),r%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+jn(s)+jn(r)}function Ps(e,t){return {lo:e>>>0,hi:t>>>0}}function An(e,t){return {lo:e|0,hi:t|0}}function Oo(e,t){return t=~t,e?e=~e+1:t+=1,An(e,t)}const jn=e=>{const t=String(e);return "0000000".slice(t.length)+t};function Zn(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e=e>>>7;t.push(e);}else {for(let n=0;n<9;n++)t.push(e&127|128),e=e>>7;t.push(1);}}function Cs(){let e=this.buf[this.pos++],t=e&127;if((e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<7,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<14,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<21,(e&128)==0)return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let n=5;(e&128)!==0&&n<10;n++)e=this.buf[this.pos++];if((e&128)!=0)throw new Error("invalid varint");return this.assertBounds(),t>>>0}var Qn={};const ct=Es();function Es(){const e=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof e.getBigInt64=="function"&&typeof e.getBigUint64=="function"&&typeof e.setBigInt64=="function"&&typeof e.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof Qn!="object"||Qn.BUF_BIGINT_DISABLE!=="1")){const n=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),o=BigInt("0"),r=BigInt("18446744073709551615");return {zero:BigInt(0),supported:true,parse(s){const a=typeof s=="bigint"?s:BigInt(s);if(a>i||ar||a>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(ni(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return qe(t),Zn(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let n=this.encodeUtf8(t);return this.uint32(n.byteLength),this.raw(n)}float(t){Bs(t);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,t,true),this.raw(n)}double(t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,true),this.raw(n)}fixed32(t){ni(t);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,true),this.raw(n)}sfixed32(t){qe(t);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,t,true),this.raw(n)}sint32(t){return qe(t),t=(t<<1^t>>31)>>>0,Zn(t,this.buf),this}sfixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),o=ct.enc(t);return i.setInt32(0,o.lo,true),i.setInt32(4,o.hi,true),this.raw(n)}fixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),o=ct.uEnc(t);return i.setInt32(0,o.lo,true),i.setInt32(4,o.hi,true),this.raw(n)}int64(t){let n=ct.enc(t);return We(n.lo,n.hi,this.buf),this}sint64(t){const n=ct.enc(t),i=n.hi>>31,o=n.lo<<1^i,r=(n.hi<<1|n.lo>>>31)^i;return We(o,r,this.buf),this}uint64(t){const n=ct.uEnc(t);return We(n.lo,n.hi,this.buf),this}}class V{constructor(t,n=Do().decodeUtf8){this.decodeUtf8=n,this.varint64=Ls,this.uint32=Cs,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength);}tag(){let t=this.uint32(),n=t>>>3,i=t&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return [n,i]}skip(t,n){let i=this.pos;switch(t){case gt.Varint:for(;this.buf[this.pos++]&128;);break;case gt.Bit64:this.pos+=4;case gt.Bit32:this.pos+=4;break;case gt.LengthDelimited:let o=this.uint32();this.pos+=o;break;case gt.StartGroup:for(;;){const[r,s]=this.tag();if(s===gt.EndGroup){if(n!==void 0&&r!==n)throw new Error("invalid end group tag");break}this.skip(s,r);}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return ct.dec(...this.varint64())}uint64(){return ct.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),i=-(t&1);return t=(t>>>1|(n&1)<<31)^i,n=n>>>1^i,ct.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,true)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,true)}fixed64(){return ct.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ct.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,true)}double(){return this.view.getFloat64((this.pos+=8)-8,true)}bytes(){let t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(){return this.decodeUtf8(this.bytes())}}function qe(e){if(typeof e=="string")e=Number(e);else if(typeof e!="number")throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>Os||e_s||e<0)throw new Error("invalid uint32: "+e)}function Bs(e){if(typeof e=="string"){const t=e;if(e=Number(e),Number.isNaN(e)&&t!=="NaN")throw new Error("invalid float32: "+t)}else if(typeof e!="number")throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>Vs||e>>3){case 1:{if(r!==10)break;o.target=n.string();continue}case 2:{if(r!==18)break;o.targetUrl=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {target:S(e.target)?globalThis.String(e.target):"",targetUrl:S(e.targetUrl)?globalThis.String(e.targetUrl):""}},toJSON(e){const t={};return e.target!==""&&(t.target=e.target),e.targetUrl!==""&&(t.targetUrl=e.targetUrl),t},create(e){return Bt.fromPartial(e??{})},fromPartial(e){const t=ii();return t.target=e.target??"",t.targetUrl=e.targetUrl??"",t}};function oi(){return {url:"",deviceId:void 0,firstRequest:false,duration:0,unknown0:0,language:"",forceSourceLang:false,unknown1:0,translationHelp:[],wasStream:false,responseLanguage:"",unknown2:0,unknown3:0,bypassCache:false,useLivelyVoice:false,videoTitle:""}}const Bo={encode(e,t=new H){e.url!==""&&t.uint32(26).string(e.url),e.deviceId!==void 0&&t.uint32(34).string(e.deviceId),e.firstRequest!==false&&t.uint32(40).bool(e.firstRequest),e.duration!==0&&t.uint32(49).double(e.duration),e.unknown0!==0&&t.uint32(56).int32(e.unknown0),e.language!==""&&t.uint32(66).string(e.language),e.forceSourceLang!==false&&t.uint32(72).bool(e.forceSourceLang),e.unknown1!==0&&t.uint32(80).int32(e.unknown1);for(const n of e.translationHelp)Bt.encode(n,t.uint32(90).fork()).join();return e.wasStream!==false&&t.uint32(104).bool(e.wasStream),e.responseLanguage!==""&&t.uint32(114).string(e.responseLanguage),e.unknown2!==0&&t.uint32(120).int32(e.unknown2),e.unknown3!==0&&t.uint32(128).int32(e.unknown3),e.bypassCache!==false&&t.uint32(136).bool(e.bypassCache),e.useLivelyVoice!==false&&t.uint32(144).bool(e.useLivelyVoice),e.videoTitle!==""&&t.uint32(154).string(e.videoTitle),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=oi();for(;n.pos>>3){case 3:{if(r!==26)break;o.url=n.string();continue}case 4:{if(r!==34)break;o.deviceId=n.string();continue}case 5:{if(r!==40)break;o.firstRequest=n.bool();continue}case 6:{if(r!==49)break;o.duration=n.double();continue}case 7:{if(r!==56)break;o.unknown0=n.int32();continue}case 8:{if(r!==66)break;o.language=n.string();continue}case 9:{if(r!==72)break;o.forceSourceLang=n.bool();continue}case 10:{if(r!==80)break;o.unknown1=n.int32();continue}case 11:{if(r!==90)break;o.translationHelp.push(Bt.decode(n,n.uint32()));continue}case 13:{if(r!==104)break;o.wasStream=n.bool();continue}case 14:{if(r!==114)break;o.responseLanguage=n.string();continue}case 15:{if(r!==120)break;o.unknown2=n.int32();continue}case 16:{if(r!==128)break;o.unknown3=n.int32();continue}case 17:{if(r!==136)break;o.bypassCache=n.bool();continue}case 18:{if(r!==144)break;o.useLivelyVoice=n.bool();continue}case 19:{if(r!==154)break;o.videoTitle=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {url:S(e.url)?globalThis.String(e.url):"",deviceId:S(e.deviceId)?globalThis.String(e.deviceId):void 0,firstRequest:S(e.firstRequest)?globalThis.Boolean(e.firstRequest):false,duration:S(e.duration)?globalThis.Number(e.duration):0,unknown0:S(e.unknown0)?globalThis.Number(e.unknown0):0,language:S(e.language)?globalThis.String(e.language):"",forceSourceLang:S(e.forceSourceLang)?globalThis.Boolean(e.forceSourceLang):false,unknown1:S(e.unknown1)?globalThis.Number(e.unknown1):0,translationHelp:globalThis.Array.isArray(e?.translationHelp)?e.translationHelp.map(t=>Bt.fromJSON(t)):[],wasStream:S(e.wasStream)?globalThis.Boolean(e.wasStream):false,responseLanguage:S(e.responseLanguage)?globalThis.String(e.responseLanguage):"",unknown2:S(e.unknown2)?globalThis.Number(e.unknown2):0,unknown3:S(e.unknown3)?globalThis.Number(e.unknown3):0,bypassCache:S(e.bypassCache)?globalThis.Boolean(e.bypassCache):false,useLivelyVoice:S(e.useLivelyVoice)?globalThis.Boolean(e.useLivelyVoice):false,videoTitle:S(e.videoTitle)?globalThis.String(e.videoTitle):""}},toJSON(e){const t={};return e.url!==""&&(t.url=e.url),e.deviceId!==void 0&&(t.deviceId=e.deviceId),e.firstRequest!==false&&(t.firstRequest=e.firstRequest),e.duration!==0&&(t.duration=e.duration),e.unknown0!==0&&(t.unknown0=Math.round(e.unknown0)),e.language!==""&&(t.language=e.language),e.forceSourceLang!==false&&(t.forceSourceLang=e.forceSourceLang),e.unknown1!==0&&(t.unknown1=Math.round(e.unknown1)),e.translationHelp?.length&&(t.translationHelp=e.translationHelp.map(n=>Bt.toJSON(n))),e.wasStream!==false&&(t.wasStream=e.wasStream),e.responseLanguage!==""&&(t.responseLanguage=e.responseLanguage),e.unknown2!==0&&(t.unknown2=Math.round(e.unknown2)),e.unknown3!==0&&(t.unknown3=Math.round(e.unknown3)),e.bypassCache!==false&&(t.bypassCache=e.bypassCache),e.useLivelyVoice!==false&&(t.useLivelyVoice=e.useLivelyVoice),e.videoTitle!==""&&(t.videoTitle=e.videoTitle),t},create(e){return Bo.fromPartial(e??{})},fromPartial(e){const t=oi();return t.url=e.url??"",t.deviceId=e.deviceId??void 0,t.firstRequest=e.firstRequest??false,t.duration=e.duration??0,t.unknown0=e.unknown0??0,t.language=e.language??"",t.forceSourceLang=e.forceSourceLang??false,t.unknown1=e.unknown1??0,t.translationHelp=e.translationHelp?.map(n=>Bt.fromPartial(n))||[],t.wasStream=e.wasStream??false,t.responseLanguage=e.responseLanguage??"",t.unknown2=e.unknown2??0,t.unknown3=e.unknown3??0,t.bypassCache=e.bypassCache??false,t.useLivelyVoice=e.useLivelyVoice??false,t.videoTitle=e.videoTitle??"",t}};function ri(){return {url:void 0,duration:void 0,status:0,remainingTime:void 0,unknown0:void 0,translationId:"",language:void 0,message:void 0,isLivelyVoice:false,unknown2:void 0,shouldRetry:void 0,unknown3:void 0}}const Ro={encode(e,t=new H){return e.url!==void 0&&t.uint32(10).string(e.url),e.duration!==void 0&&t.uint32(17).double(e.duration),e.status!==0&&t.uint32(32).int32(e.status),e.remainingTime!==void 0&&t.uint32(40).int32(e.remainingTime),e.unknown0!==void 0&&t.uint32(48).int32(e.unknown0),e.translationId!==""&&t.uint32(58).string(e.translationId),e.language!==void 0&&t.uint32(66).string(e.language),e.message!==void 0&&t.uint32(74).string(e.message),e.isLivelyVoice!==false&&t.uint32(80).bool(e.isLivelyVoice),e.unknown2!==void 0&&t.uint32(88).int32(e.unknown2),e.shouldRetry!==void 0&&t.uint32(96).int32(e.shouldRetry),e.unknown3!==void 0&&t.uint32(104).int32(e.unknown3),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=ri();for(;n.pos>>3){case 1:{if(r!==10)break;o.url=n.string();continue}case 2:{if(r!==17)break;o.duration=n.double();continue}case 4:{if(r!==32)break;o.status=n.int32();continue}case 5:{if(r!==40)break;o.remainingTime=n.int32();continue}case 6:{if(r!==48)break;o.unknown0=n.int32();continue}case 7:{if(r!==58)break;o.translationId=n.string();continue}case 8:{if(r!==66)break;o.language=n.string();continue}case 9:{if(r!==74)break;o.message=n.string();continue}case 10:{if(r!==80)break;o.isLivelyVoice=n.bool();continue}case 11:{if(r!==88)break;o.unknown2=n.int32();continue}case 12:{if(r!==96)break;o.shouldRetry=n.int32();continue}case 13:{if(r!==104)break;o.unknown3=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {url:S(e.url)?globalThis.String(e.url):void 0,duration:S(e.duration)?globalThis.Number(e.duration):void 0,status:S(e.status)?globalThis.Number(e.status):0,remainingTime:S(e.remainingTime)?globalThis.Number(e.remainingTime):void 0,unknown0:S(e.unknown0)?globalThis.Number(e.unknown0):void 0,translationId:S(e.translationId)?globalThis.String(e.translationId):"",language:S(e.language)?globalThis.String(e.language):void 0,message:S(e.message)?globalThis.String(e.message):void 0,isLivelyVoice:S(e.isLivelyVoice)?globalThis.Boolean(e.isLivelyVoice):false,unknown2:S(e.unknown2)?globalThis.Number(e.unknown2):void 0,shouldRetry:S(e.shouldRetry)?globalThis.Number(e.shouldRetry):void 0,unknown3:S(e.unknown3)?globalThis.Number(e.unknown3):void 0}},toJSON(e){const t={};return e.url!==void 0&&(t.url=e.url),e.duration!==void 0&&(t.duration=e.duration),e.status!==0&&(t.status=Math.round(e.status)),e.remainingTime!==void 0&&(t.remainingTime=Math.round(e.remainingTime)),e.unknown0!==void 0&&(t.unknown0=Math.round(e.unknown0)),e.translationId!==""&&(t.translationId=e.translationId),e.language!==void 0&&(t.language=e.language),e.message!==void 0&&(t.message=e.message),e.isLivelyVoice!==false&&(t.isLivelyVoice=e.isLivelyVoice),e.unknown2!==void 0&&(t.unknown2=Math.round(e.unknown2)),e.shouldRetry!==void 0&&(t.shouldRetry=Math.round(e.shouldRetry)),e.unknown3!==void 0&&(t.unknown3=Math.round(e.unknown3)),t},create(e){return Ro.fromPartial(e??{})},fromPartial(e){const t=ri();return t.url=e.url??void 0,t.duration=e.duration??void 0,t.status=e.status??0,t.remainingTime=e.remainingTime??void 0,t.unknown0=e.unknown0??void 0,t.translationId=e.translationId??"",t.language=e.language??void 0,t.message=e.message??void 0,t.isLivelyVoice=e.isLivelyVoice??false,t.unknown2=e.unknown2??void 0,t.shouldRetry=e.shouldRetry??void 0,t.unknown3=e.unknown3??void 0,t}};function si(){return {status:0,remainingTime:void 0,message:void 0,unknown0:void 0}}const st={encode(e,t=new H){return e.status!==0&&t.uint32(8).int32(e.status),e.remainingTime!==void 0&&t.uint32(16).int32(e.remainingTime),e.message!==void 0&&t.uint32(26).string(e.message),e.unknown0!==void 0&&t.uint32(32).int32(e.unknown0),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=si();for(;n.pos>>3){case 1:{if(r!==8)break;o.status=n.int32();continue}case 2:{if(r!==16)break;o.remainingTime=n.int32();continue}case 3:{if(r!==26)break;o.message=n.string();continue}case 4:{if(r!==32)break;o.unknown0=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {status:S(e.status)?globalThis.Number(e.status):0,remainingTime:S(e.remainingTime)?globalThis.Number(e.remainingTime):void 0,message:S(e.message)?globalThis.String(e.message):void 0,unknown0:S(e.unknown0)?globalThis.Number(e.unknown0):void 0}},toJSON(e){const t={};return e.status!==0&&(t.status=Math.round(e.status)),e.remainingTime!==void 0&&(t.remainingTime=Math.round(e.remainingTime)),e.message!==void 0&&(t.message=e.message),e.unknown0!==void 0&&(t.unknown0=Math.round(e.unknown0)),t},create(e){return st.fromPartial(e??{})},fromPartial(e){const t=si();return t.status=e.status??0,t.remainingTime=e.remainingTime??void 0,t.message=e.message??void 0,t.unknown0=e.unknown0??void 0,t}};function ai(){return {url:"",duration:0,language:"",responseLanguage:""}}const No={encode(e,t=new H){return e.url!==""&&t.uint32(10).string(e.url),e.duration!==0&&t.uint32(17).double(e.duration),e.language!==""&&t.uint32(26).string(e.language),e.responseLanguage!==""&&t.uint32(34).string(e.responseLanguage),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=ai();for(;n.pos>>3){case 1:{if(r!==10)break;o.url=n.string();continue}case 2:{if(r!==17)break;o.duration=n.double();continue}case 3:{if(r!==26)break;o.language=n.string();continue}case 4:{if(r!==34)break;o.responseLanguage=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {url:S(e.url)?globalThis.String(e.url):"",duration:S(e.duration)?globalThis.Number(e.duration):0,language:S(e.language)?globalThis.String(e.language):"",responseLanguage:S(e.responseLanguage)?globalThis.String(e.responseLanguage):""}},toJSON(e){const t={};return e.url!==""&&(t.url=e.url),e.duration!==0&&(t.duration=e.duration),e.language!==""&&(t.language=e.language),e.responseLanguage!==""&&(t.responseLanguage=e.responseLanguage),t},create(e){return No.fromPartial(e??{})},fromPartial(e){const t=ai();return t.url=e.url??"",t.duration=e.duration??0,t.language=e.language??"",t.responseLanguage=e.responseLanguage??"",t}};function li(){return {default:void 0,cloning:void 0}}const Fo={encode(e,t=new H){return e.default!==void 0&&st.encode(e.default,t.uint32(10).fork()).join(),e.cloning!==void 0&&st.encode(e.cloning,t.uint32(18).fork()).join(),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=li();for(;n.pos>>3){case 1:{if(r!==10)break;o.default=st.decode(n,n.uint32());continue}case 2:{if(r!==18)break;o.cloning=st.decode(n,n.uint32());continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {default:S(e.default)?st.fromJSON(e.default):void 0,cloning:S(e.cloning)?st.fromJSON(e.cloning):void 0}},toJSON(e){const t={};return e.default!==void 0&&(t.default=st.toJSON(e.default)),e.cloning!==void 0&&(t.cloning=st.toJSON(e.cloning)),t},create(e){return Fo.fromPartial(e??{})},fromPartial(e){const t=li();return t.default=e.default!==void 0&&e.default!==null?st.fromPartial(e.default):void 0,t.cloning=e.cloning!==void 0&&e.cloning!==null?st.fromPartial(e.cloning):void 0,t}};function ci(){return {audioFile:new Uint8Array(0),fileId:""}}const Rt={encode(e,t=new H){return e.audioFile.length!==0&&t.uint32(18).bytes(e.audioFile),e.fileId!==""&&t.uint32(10).string(e.fileId),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=ci();for(;n.pos>>3){case 2:{if(r!==18)break;o.audioFile=n.bytes();continue}case 1:{if(r!==10)break;o.fileId=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {audioFile:S(e.audioFile)?Yo(e.audioFile):new Uint8Array(0),fileId:S(e.fileId)?globalThis.String(e.fileId):""}},toJSON(e){const t={};return e.audioFile.length!==0&&(t.audioFile=Jo(e.audioFile)),e.fileId!==""&&(t.fileId=e.fileId),t},create(e){return Rt.fromPartial(e??{})},fromPartial(e){const t=ci();return t.audioFile=e.audioFile??new Uint8Array(0),t.fileId=e.fileId??"",t}};function di(){return {audioFile:new Uint8Array(0),chunkId:0}}const Nt={encode(e,t=new H){return e.audioFile.length!==0&&t.uint32(18).bytes(e.audioFile),e.chunkId!==0&&t.uint32(8).int32(e.chunkId),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=di();for(;n.pos>>3){case 2:{if(r!==18)break;o.audioFile=n.bytes();continue}case 1:{if(r!==8)break;o.chunkId=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {audioFile:S(e.audioFile)?Yo(e.audioFile):new Uint8Array(0),chunkId:S(e.chunkId)?globalThis.Number(e.chunkId):0}},toJSON(e){const t={};return e.audioFile.length!==0&&(t.audioFile=Jo(e.audioFile)),e.chunkId!==0&&(t.chunkId=Math.round(e.chunkId)),t},create(e){return Nt.fromPartial(e??{})},fromPartial(e){const t=di();return t.audioFile=e.audioFile??new Uint8Array(0),t.chunkId=e.chunkId??0,t}};function ui(){return {audioBuffer:void 0,audioPartsLength:0,fileId:"",version:0}}const Ft={encode(e,t=new H){return e.audioBuffer!==void 0&&Nt.encode(e.audioBuffer,t.uint32(10).fork()).join(),e.audioPartsLength!==0&&t.uint32(16).int32(e.audioPartsLength),e.fileId!==""&&t.uint32(26).string(e.fileId),e.version!==0&&t.uint32(32).int32(e.version),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=ui();for(;n.pos>>3){case 1:{if(r!==10)break;o.audioBuffer=Nt.decode(n,n.uint32());continue}case 2:{if(r!==16)break;o.audioPartsLength=n.int32();continue}case 3:{if(r!==26)break;o.fileId=n.string();continue}case 4:{if(r!==32)break;o.version=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {audioBuffer:S(e.audioBuffer)?Nt.fromJSON(e.audioBuffer):void 0,audioPartsLength:S(e.audioPartsLength)?globalThis.Number(e.audioPartsLength):0,fileId:S(e.fileId)?globalThis.String(e.fileId):"",version:S(e.version)?globalThis.Number(e.version):0}},toJSON(e){const t={};return e.audioBuffer!==void 0&&(t.audioBuffer=Nt.toJSON(e.audioBuffer)),e.audioPartsLength!==0&&(t.audioPartsLength=Math.round(e.audioPartsLength)),e.fileId!==""&&(t.fileId=e.fileId),e.version!==0&&(t.version=Math.round(e.version)),t},create(e){return Ft.fromPartial(e??{})},fromPartial(e){const t=ui();return t.audioBuffer=e.audioBuffer!==void 0&&e.audioBuffer!==null?Nt.fromPartial(e.audioBuffer):void 0,t.audioPartsLength=e.audioPartsLength??0,t.fileId=e.fileId??"",t.version=e.version??0,t}};function hi(){return {translationId:"",url:"",partialAudioInfo:void 0,audioInfo:void 0}}const un={encode(e,t=new H){return e.translationId!==""&&t.uint32(10).string(e.translationId),e.url!==""&&t.uint32(18).string(e.url),e.partialAudioInfo!==void 0&&Ft.encode(e.partialAudioInfo,t.uint32(34).fork()).join(),e.audioInfo!==void 0&&Rt.encode(e.audioInfo,t.uint32(50).fork()).join(),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=hi();for(;n.pos>>3){case 1:{if(r!==10)break;o.translationId=n.string();continue}case 2:{if(r!==18)break;o.url=n.string();continue}case 4:{if(r!==34)break;o.partialAudioInfo=Ft.decode(n,n.uint32());continue}case 6:{if(r!==50)break;o.audioInfo=Rt.decode(n,n.uint32());continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {translationId:S(e.translationId)?globalThis.String(e.translationId):"",url:S(e.url)?globalThis.String(e.url):"",partialAudioInfo:S(e.partialAudioInfo)?Ft.fromJSON(e.partialAudioInfo):void 0,audioInfo:S(e.audioInfo)?Rt.fromJSON(e.audioInfo):void 0}},toJSON(e){const t={};return e.translationId!==""&&(t.translationId=e.translationId),e.url!==""&&(t.url=e.url),e.partialAudioInfo!==void 0&&(t.partialAudioInfo=Ft.toJSON(e.partialAudioInfo)),e.audioInfo!==void 0&&(t.audioInfo=Rt.toJSON(e.audioInfo)),t},create(e){return un.fromPartial(e??{})},fromPartial(e){const t=hi();return t.translationId=e.translationId??"",t.url=e.url??"",t.partialAudioInfo=e.partialAudioInfo!==void 0&&e.partialAudioInfo!==null?Ft.fromPartial(e.partialAudioInfo):void 0,t.audioInfo=e.audioInfo!==void 0&&e.audioInfo!==null?Rt.fromPartial(e.audioInfo):void 0,t}};function fi(){return {status:0,remainingChunks:[]}}const Ho={encode(e,t=new H){e.status!==0&&t.uint32(8).int32(e.status);for(const n of e.remainingChunks)t.uint32(18).string(n);return t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=fi();for(;n.pos>>3){case 1:{if(r!==8)break;o.status=n.int32();continue}case 2:{if(r!==18)break;o.remainingChunks.push(n.string());continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {status:S(e.status)?globalThis.Number(e.status):0,remainingChunks:globalThis.Array.isArray(e?.remainingChunks)?e.remainingChunks.map(t=>globalThis.String(t)):[]}},toJSON(e){const t={};return e.status!==0&&(t.status=Math.round(e.status)),e.remainingChunks?.length&&(t.remainingChunks=e.remainingChunks),t},create(e){return Ho.fromPartial(e??{})},fromPartial(e){const t=fi();return t.status=e.status??0,t.remainingChunks=e.remainingChunks?.map(n=>n)||[],t}};function pi(){return {language:"",url:"",unknown0:0,translatedLanguage:"",translatedUrl:"",unknown1:0,unknown2:0}}const Ht={encode(e,t=new H){return e.language!==""&&t.uint32(10).string(e.language),e.url!==""&&t.uint32(18).string(e.url),e.unknown0!==0&&t.uint32(24).int32(e.unknown0),e.translatedLanguage!==""&&t.uint32(34).string(e.translatedLanguage),e.translatedUrl!==""&&t.uint32(42).string(e.translatedUrl),e.unknown1!==0&&t.uint32(48).int32(e.unknown1),e.unknown2!==0&&t.uint32(56).int32(e.unknown2),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=pi();for(;n.pos>>3){case 1:{if(r!==10)break;o.language=n.string();continue}case 2:{if(r!==18)break;o.url=n.string();continue}case 3:{if(r!==24)break;o.unknown0=n.int32();continue}case 4:{if(r!==34)break;o.translatedLanguage=n.string();continue}case 5:{if(r!==42)break;o.translatedUrl=n.string();continue}case 6:{if(r!==48)break;o.unknown1=n.int32();continue}case 7:{if(r!==56)break;o.unknown2=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {language:S(e.language)?globalThis.String(e.language):"",url:S(e.url)?globalThis.String(e.url):"",unknown0:S(e.unknown0)?globalThis.Number(e.unknown0):0,translatedLanguage:S(e.translatedLanguage)?globalThis.String(e.translatedLanguage):"",translatedUrl:S(e.translatedUrl)?globalThis.String(e.translatedUrl):"",unknown1:S(e.unknown1)?globalThis.Number(e.unknown1):0,unknown2:S(e.unknown2)?globalThis.Number(e.unknown2):0}},toJSON(e){const t={};return e.language!==""&&(t.language=e.language),e.url!==""&&(t.url=e.url),e.unknown0!==0&&(t.unknown0=Math.round(e.unknown0)),e.translatedLanguage!==""&&(t.translatedLanguage=e.translatedLanguage),e.translatedUrl!==""&&(t.translatedUrl=e.translatedUrl),e.unknown1!==0&&(t.unknown1=Math.round(e.unknown1)),e.unknown2!==0&&(t.unknown2=Math.round(e.unknown2)),t},create(e){return Ht.fromPartial(e??{})},fromPartial(e){const t=pi();return t.language=e.language??"",t.url=e.url??"",t.unknown0=e.unknown0??0,t.translatedLanguage=e.translatedLanguage??"",t.translatedUrl=e.translatedUrl??"",t.unknown1=e.unknown1??0,t.unknown2=e.unknown2??0,t}};function gi(){return {url:"",language:""}}const $o={encode(e,t=new H){return e.url!==""&&t.uint32(10).string(e.url),e.language!==""&&t.uint32(18).string(e.language),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=gi();for(;n.pos>>3){case 1:{if(r!==10)break;o.url=n.string();continue}case 2:{if(r!==18)break;o.language=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {url:S(e.url)?globalThis.String(e.url):"",language:S(e.language)?globalThis.String(e.language):""}},toJSON(e){const t={};return e.url!==""&&(t.url=e.url),e.language!==""&&(t.language=e.language),t},create(e){return $o.fromPartial(e??{})},fromPartial(e){const t=gi();return t.url=e.url??"",t.language=e.language??"",t}};function mi(){return {waiting:false,subtitles:[]}}const Uo={encode(e,t=new H){e.waiting!==false&&t.uint32(8).bool(e.waiting);for(const n of e.subtitles)Ht.encode(n,t.uint32(18).fork()).join();return t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=mi();for(;n.pos>>3){case 1:{if(r!==8)break;o.waiting=n.bool();continue}case 2:{if(r!==18)break;o.subtitles.push(Ht.decode(n,n.uint32()));continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {waiting:S(e.waiting)?globalThis.Boolean(e.waiting):false,subtitles:globalThis.Array.isArray(e?.subtitles)?e.subtitles.map(t=>Ht.fromJSON(t)):[]}},toJSON(e){const t={};return e.waiting!==false&&(t.waiting=e.waiting),e.subtitles?.length&&(t.subtitles=e.subtitles.map(n=>Ht.toJSON(n))),t},create(e){return Uo.fromPartial(e??{})},fromPartial(e){const t=mi();return t.waiting=e.waiting??false,t.subtitles=e.subtitles?.map(n=>Ht.fromPartial(n))||[],t}};function vi(){return {url:"",timestamp:""}}const $t={encode(e,t=new H){return e.url!==""&&t.uint32(10).string(e.url),e.timestamp!==""&&t.uint32(18).string(e.timestamp),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=vi();for(;n.pos>>3){case 1:{if(r!==10)break;o.url=n.string();continue}case 2:{if(r!==18)break;o.timestamp=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {url:S(e.url)?globalThis.String(e.url):"",timestamp:S(e.timestamp)?globalThis.String(e.timestamp):""}},toJSON(e){const t={};return e.url!==""&&(t.url=e.url),e.timestamp!==""&&(t.timestamp=e.timestamp),t},create(e){return $t.fromPartial(e??{})},fromPartial(e){const t=vi();return t.url=e.url??"",t.timestamp=e.timestamp??"",t}};function bi(){return {url:"",language:"",responseLanguage:"",unknown0:0,unknown1:0}}const Wo={encode(e,t=new H){return e.url!==""&&t.uint32(10).string(e.url),e.language!==""&&t.uint32(18).string(e.language),e.responseLanguage!==""&&t.uint32(26).string(e.responseLanguage),e.unknown0!==0&&t.uint32(40).int32(e.unknown0),e.unknown1!==0&&t.uint32(48).int32(e.unknown1),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=bi();for(;n.pos>>3){case 1:{if(r!==10)break;o.url=n.string();continue}case 2:{if(r!==18)break;o.language=n.string();continue}case 3:{if(r!==26)break;o.responseLanguage=n.string();continue}case 5:{if(r!==40)break;o.unknown0=n.int32();continue}case 6:{if(r!==48)break;o.unknown1=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {url:S(e.url)?globalThis.String(e.url):"",language:S(e.language)?globalThis.String(e.language):"",responseLanguage:S(e.responseLanguage)?globalThis.String(e.responseLanguage):"",unknown0:S(e.unknown0)?globalThis.Number(e.unknown0):0,unknown1:S(e.unknown1)?globalThis.Number(e.unknown1):0}},toJSON(e){const t={};return e.url!==""&&(t.url=e.url),e.language!==""&&(t.language=e.language),e.responseLanguage!==""&&(t.responseLanguage=e.responseLanguage),e.unknown0!==0&&(t.unknown0=Math.round(e.unknown0)),e.unknown1!==0&&(t.unknown1=Math.round(e.unknown1)),t},create(e){return Wo.fromPartial(e??{})},fromPartial(e){const t=bi();return t.url=e.url??"",t.language=e.language??"",t.responseLanguage=e.responseLanguage??"",t.unknown0=e.unknown0??0,t.unknown1=e.unknown1??0,t}};function yi(){return {interval:0,translatedInfo:void 0,pingId:void 0}}const zo={encode(e,t=new H){return e.interval!==0&&t.uint32(8).int32(e.interval),e.translatedInfo!==void 0&&$t.encode(e.translatedInfo,t.uint32(18).fork()).join(),e.pingId!==void 0&&t.uint32(24).int32(e.pingId),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=yi();for(;n.pos>>3){case 1:{if(r!==8)break;o.interval=n.int32();continue}case 2:{if(r!==18)break;o.translatedInfo=$t.decode(n,n.uint32());continue}case 3:{if(r!==24)break;o.pingId=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {interval:S(e.interval)?Rs(e.interval):0,translatedInfo:S(e.translatedInfo)?$t.fromJSON(e.translatedInfo):void 0,pingId:S(e.pingId)?globalThis.Number(e.pingId):void 0}},toJSON(e){const t={};return e.interval!==0&&(t.interval=Ns(e.interval)),e.translatedInfo!==void 0&&(t.translatedInfo=$t.toJSON(e.translatedInfo)),e.pingId!==void 0&&(t.pingId=Math.round(e.pingId)),t},create(e){return zo.fromPartial(e??{})},fromPartial(e){const t=yi();return t.interval=e.interval??0,t.translatedInfo=e.translatedInfo!==void 0&&e.translatedInfo!==null?$t.fromPartial(e.translatedInfo):void 0,t.pingId=e.pingId??void 0,t}};function wi(){return {pingId:0}}const qo={encode(e,t=new H){return e.pingId!==0&&t.uint32(8).int32(e.pingId),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=wi();for(;n.pos>>3){case 1:{if(r!==8)break;o.pingId=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {pingId:S(e.pingId)?globalThis.Number(e.pingId):0}},toJSON(e){const t={};return e.pingId!==0&&(t.pingId=Math.round(e.pingId)),t},create(e){return qo.fromPartial(e??{})},fromPartial(e){const t=wi();return t.pingId=e.pingId??0,t}};function ki(){return {uuid:"",module:""}}const Go={encode(e,t=new H){return e.uuid!==""&&t.uint32(10).string(e.uuid),e.module!==""&&t.uint32(18).string(e.module),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=ki();for(;n.pos>>3){case 1:{if(r!==10)break;o.uuid=n.string();continue}case 2:{if(r!==18)break;o.module=n.string();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {uuid:S(e.uuid)?globalThis.String(e.uuid):"",module:S(e.module)?globalThis.String(e.module):""}},toJSON(e){const t={};return e.uuid!==""&&(t.uuid=e.uuid),e.module!==""&&(t.module=e.module),t},create(e){return Go.fromPartial(e??{})},fromPartial(e){const t=ki();return t.uuid=e.uuid??"",t.module=e.module??"",t}};function xi(){return {secretKey:"",expires:0}}const Ko={encode(e,t=new H){return e.secretKey!==""&&t.uint32(10).string(e.secretKey),e.expires!==0&&t.uint32(16).int32(e.expires),t},decode(e,t){const n=e instanceof V?e:new V(e);let i=t===void 0?n.len:n.pos+t;const o=xi();for(;n.pos>>3){case 1:{if(r!==10)break;o.secretKey=n.string();continue}case 2:{if(r!==16)break;o.expires=n.int32();continue}}if((r&7)===4||r===0)break;n.skip(r&7);}return o},fromJSON(e){return {secretKey:S(e.secretKey)?globalThis.String(e.secretKey):"",expires:S(e.expires)?globalThis.Number(e.expires):0}},toJSON(e){const t={};return e.secretKey!==""&&(t.secretKey=e.secretKey),e.expires!==0&&(t.expires=Math.round(e.expires)),t},create(e){return Ko.fromPartial(e??{})},fromPartial(e){const t=xi();return t.secretKey=e.secretKey??"",t.expires=e.expires??0,t}};function Yo(e){if(globalThis.Buffer)return Uint8Array.from(globalThis.Buffer.from(e,"base64"));{const t=globalThis.atob(e),n=new Uint8Array(t.length);for(let i=0;i{t.push(globalThis.String.fromCharCode(n));}),globalThis.btoa(t.join(""))}}function S(e){return e!=null}const Fs=(function(){const t=typeof document<"u"&&document.createElement("link").relList;return t&&t.supports&&t.supports("modulepreload")?"modulepreload":"preload"})(),Hs=function(e){return "/"+e},Si={},$s=function(t,n,i){let o=Promise.resolve();if(n&&n.length>0){let l=function(c){return Promise.all(c.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");o=l(n.map(c=>{if(c=Hs(c),c in Si)return;Si[c]=true;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":Fs,d||(h.as="script"),h.crossOrigin="",h.href=c,a&&h.setAttribute("nonce",a),document.head.appendChild(h),d)return new Promise((m,v)=>{h.addEventListener("load",m),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${c}`)));})}));}function r(s){const a=new Event("vite:preloadError",{cancelable:true});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return o.then(s=>{for(const a of s||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})};var qt;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENCE=4]="SILENCE";})(qt||(qt={}));const Re=`[vot.js v${K.version}]`;function fe(e){return K.loggerLevel<=e}function Us(...e){fe(qt.DEBUG)&&console.log(Re,...e);}function Ws(...e){fe(qt.INFO)&&console.info(Re,...e);}function zs(...e){fe(qt.WARN)&&console.warn(Re,...e);}function qs(...e){fe(qt.ERROR)&&console.error(Re,...e);}const C={canLog:fe,log:Us,info:Ws,warn:zs,error:qs},{componentVersion:hn}=K;async function Gs(){return typeof window<"u"&&window.crypto?window.crypto:await $s(()=>module.import('./__vite-browser-external-BIHI7g3E-DUmwvnCo.js'),void 0)}const Ln=new TextEncoder;async function Xo(e,t,n){const i=await Gs(),o=await i.subtle.importKey("raw",Ln.encode(t),{name:"HMAC",hash:{name:e}},false,["sign","verify"]);return await i.subtle.sign("HMAC",o,n)}async function fn(e){const t=await Xo("SHA-256",K.hmac,e);return new Uint8Array(t).reduce((n,i)=>n+i.toString(16).padStart(2,"0"),"")}async function Dt(e,t,n,i){const{secretKey:o,uuid:r}=t,s=`${r}:${i}:${hn}`,a=Ln.encode(s),l=await fn(a);if(e==="Ya-Summary")return {[`X-${e}-Sk`]:o,[`X-${e}-Token`]:`${l}:${s}`};if(!n)throw new TypeError(`Body is required for sec type ${e}`);const c=await fn(n);return {[`${e}-Signature`]:c,[`Sec-${e}-Sk`]:o,[`Sec-${e}-Token`]:`${l}:${s}`}}function Ks(){const e="0123456789ABCDEF";let t="";for(let n=0;n<32;n++){const i=Math.floor(Math.random()*16);t+=e[i];}return t}async function Ys(e,t){try{const n=Ln.encode(t),i=await Xo("SHA-1",e,n);return btoa(String.fromCharCode(...new Uint8Array(i)))}catch(n){return C.error(n),false}}const jo={"sec-ch-ua":`"Chromium";v="142", "YaBrowser";v="${hn.slice(0,5)}", "Not?A_Brand";v="24", "Yowser";v="2.5"`,"sec-ch-ua-full-version-list":`"Chromium";v="142.0.7444.59", "YaBrowser";v="${hn}", "Not?A_Brand";v="24.0.0.0", "Yowser";v="2.5"`,"Sec-Fetch-Mode":"no-cors"},Js={afr:"af",aka:"ak",alb:"sq",amh:"am",ara:"ar",arm:"hy",asm:"as",aym:"ay",aze:"az",baq:"eu",bel:"be",ben:"bn",bos:"bs",bul:"bg",bur:"my",cat:"ca",chi:"zh",cos:"co",cze:"cs",dan:"da",div:"dv",dut:"nl",eng:"en",epo:"eo",est:"et",ewe:"ee",fin:"fi",fre:"fr",fry:"fy",geo:"ka",ger:"de",gla:"gd",gle:"ga",glg:"gl",gre:"el",grn:"gn",guj:"gu",hat:"ht",hau:"ha",hin:"hi",hrv:"hr",hun:"hu",ibo:"ig",ice:"is",ind:"id",ita:"it",jav:"jv",jpn:"ja",kan:"kn",kaz:"kk",khm:"km",kin:"rw",kir:"ky",kor:"ko",kur:"ku",lao:"lo",lat:"la",lav:"lv",lin:"ln",lit:"lt",ltz:"lb",lug:"lg",mac:"mk",mal:"ml",mao:"mi",mar:"mr",may:"ms",mlg:"mg",mlt:"mt",mon:"mn",nep:"ne",nor:"no",nya:"ny",ori:"or",orm:"om",pan:"pa",per:"fa",pol:"pl",por:"pt",pus:"ps",que:"qu",rum:"ro",rus:"ru",san:"sa",sin:"si",slo:"sk",slv:"sl",smo:"sm",sna:"sn",snd:"sd",som:"so",sot:"st",spa:"es",srp:"sr",sun:"su",swa:"sw",swe:"sv",tam:"ta",tat:"tt",tel:"te",tgk:"tg",tha:"th",tir:"ti",tso:"ts",tuk:"tk",tur:"tr",uig:"ug",ukr:"uk",urd:"ur",uzb:"uz",vie:"vi",wel:"cy",xho:"xh",yid:"yi",yor:"yo",zul:"zu"};async function Zo(e,t={headers:{"User-Agent":K.userAgent}}){const{timeout:n=3e3,signal:i,...o}=t;if(!i&&(!n||n<=0))return await fetch(e,o);const r=new AbortController,s=l=>{r.signal.aborted||r.abort(l);};i&&(i.aborted?s(i.reason):i.addEventListener("abort",()=>s(i.reason),{once:true}));let a;n&&n>0&&(a=setTimeout(()=>s(new Error("Fetch timeout")),n));try{return await fetch(e,{...o,signal:r.signal})}finally{a&&clearTimeout(a);}}function Xs(){return Math.floor(Date.now()/1e3)}function X(e){return e.length===3?Js[e]:e.toLowerCase().split(/[_;-]/)[0].trim()}function at(e,t="mp4"){const n=`https://${K.mediaProxy}/v1/proxy/video.${t}?format=base64&force=true`;return e instanceof URL?`${n}&url=${btoa(e.href)}&origin=${e.origin}&referer=${e.origin}`:`${n}&url=${btoa(e)}`}function te(e,t){const n="https:",i=t.hostname.replace(/^m\./,""),o=e.replace(/^\/+/,""),r=i.endsWith("vkvideo.ru")?"vkvideo.ru":i.endsWith("vk.com")||i.endsWith("vk.ru")?"vk.com":i,s=t.pathname.replace(/\/+$/,""),l=/^\/(?:video|clip)-?\d+_\d+$/.test(s)?`${n}//${r}${s}`:`${n}//${r}/${o}`,c=new URL(l);for(const d of ["list","access_key"]){const u=t.searchParams.get(d);u&&c.searchParams.set(d,u);}return c.toString()}function js(e,t,n,i,o,{forceSourceLang:r=false,wasStream:s=false,videoTitle:a="",bypassCache:l=false,useLivelyVoice:c=false,firstRequest:d=true}={}){return Bo.encode({url:e,firstRequest:d,duration:t,unknown0:1,language:n,forceSourceLang:r,unknown1:0,translationHelp:o??[],responseLanguage:i,wasStream:s,unknown2:1,unknown3:2,bypassCache:l,useLivelyVoice:c,videoTitle:a}).finish()}function Zs(e){return Ro.decode(new Uint8Array(e))}function Qs(e,t,n,i){return No.encode({url:e,duration:t,language:n,responseLanguage:i}).finish()}function ta(e){return Fo.decode(new Uint8Array(e))}function Qo(e){return "chunkId"in e}function ea(e,t,n,i){return i&&Qo(n)?un.encode({url:e,translationId:t,partialAudioInfo:{...i,audioBuffer:n}}).finish():un.encode({url:e,translationId:t,audioInfo:n}).finish()}function na(e){return Ho.decode(new Uint8Array(e))}function ia(e,t){return $o.encode({url:e,language:t}).finish()}function oa(e){return Uo.decode(new Uint8Array(e))}function ra(e){return qo.encode({pingId:e}).finish()}function sa(e,t,n){return Wo.encode({url:e,language:t,responseLanguage:n,unknown0:1,unknown1:0}).finish()}function aa(e){return zo.decode(new Uint8Array(e))}const nt={encodeTranslationRequest:js,decodeTranslationResponse:Zs,encodeTranslationCacheRequest:Qs,decodeTranslationCacheResponse:ta,isPartialAudioBuffer:Qo,encodeTranslationAudioRequest:ea,decodeTranslationAudioResponse:na,encodeSubtitlesRequest:ia,decodeSubtitlesResponse:oa,encodeStreamPingRequest:ra,encodeStreamRequest:sa,decodeStreamResponse:aa};function la(e,t){return Go.encode({uuid:e,module:t}).finish()}function ca(e){return Ko.decode(new Uint8Array(e))}const Ti={encodeSessionRequest:la,decodeSessionResponse:ca};var lt;(function(e){e[e.FAILED=0]="FAILED",e[e.FINISHED=1]="FINISHED",e[e.WAITING=2]="WAITING",e[e.LONG_WAITING=3]="LONG_WAITING",e[e.PART_CONTENT=5]="PART_CONTENT",e[e.AUDIO_REQUESTED=6]="AUDIO_REQUESTED",e[e.SESSION_REQUIRED=7]="SESSION_REQUIRED";})(lt||(lt={}));var Gt;(function(e){e.WEB_API_VIDEO_SRC_FROM_IFRAME="web_api_video_src_from_iframe",e.WEB_API_VIDEO_SRC="web_api_video_src",e.WEB_API_GET_ALL_GENERATING_URLS_DATA_FROM_IFRAME="web_api_get_all_generating_urls_data_from_iframe",e.WEB_API_GET_ALL_GENERATING_URLS_DATA_FROM_IFRAME_TMP_EXP="web_api_get_all_generating_urls_data_from_iframe_tmp_exp",e.WEB_API_REPLACED_FETCH_INSIDE_IFRAME="web_api_replaced_fetch_inside_iframe",e.ANDROID_API="android_api",e.WEB_API_SLOW="web_api_slow",e.WEB_API_STEAL_SIG_AND_N="web_api_steal_sig_and_n",e.WEB_API_COMBINED="web_api_get_all_generating_urls_data_from_iframe,web_api_steal_sig_and_n";})(Gt||(Gt={}));var g;(function(e){e.custom="custom",e.directlink="custom",e.youtube="youtube",e.piped="piped",e.invidious="invidious",e.niconico="niconico",e.vk="vk",e.nine_gag="nine_gag",e.gag="nine_gag",e.twitch="twitch",e.proxitok="proxitok",e.tiktok="tiktok",e.vimeo="vimeo",e.xvideos="xvideos",e.xhamster="xhamster",e.spankbang="spankbang",e.rule34video="rule34video",e.picarto="picarto",e.olympicsreplay="olympics_replay",e.pornhub="pornhub",e.twitter="twitter",e.x="twitter",e.rumble="rumble",e.facebook="facebook",e.rutube="rutube",e.coub="coub",e.bilibili="bilibili",e.mail_ru="mailru",e.mailru="mailru",e.bitchute="bitchute",e.eporner="eporner",e.peertube="peertube",e.dailymotion="dailymotion",e.trovo="trovo",e.yandexdisk="yandexdisk",e.ok_ru="okru",e.okru="okru",e.googledrive="googledrive",e.bannedvideo="bannedvideo",e.weverse="weverse",e.weibo="weibo",e.newgrounds="newgrounds",e.egghead="egghead",e.youku="youku",e.archive="archive",e.kodik="kodik",e.patreon="patreon",e.reddit="reddit",e.kick="kick",e.apple_developer="apple_developer",e.appledeveloper="apple_developer",e.epicgames="epicgames",e.odysee="odysee",e.coursehunterLike="coursehunterLike",e.sap="sap",e.watchpornto="watchpornto",e.linkedin="linkedin",e.incestflix="incestflix",e.porntn="porntn",e.dzen="dzen",e.cloudflarestream="cloudflarestream",e.loom="loom",e.rtnews="rtnews",e.bitview="bitview",e.thisvid="thisvid",e.ign="ign",e.zdf="zdf",e.bunkr="bunkr",e.imdb="imdb",e.telegram="telegram";})(g||(g={}));function Ai(e,t,n){return e===g.patreon?{service:"mux",videoId:new URL(n).pathname.slice(1)}:{service:e,videoId:t}}class F extends Error{data;constructor(t,n=void 0){super(t),this.data=n,this.name="VOTJSError";}}class da{host;schema;fetch;fetchOpts;sessions={};userAgent=K.userAgent;headers={"User-Agent":this.userAgent,Accept:"application/x-protobuf","Accept-Language":"en","Content-Type":"application/x-protobuf",Pragma:"no-cache","Cache-Control":"no-cache"};hostSchemaRe=/(http(s)?):\/\//;constructor({host:t=K.host,fetchFn:n=Zo,fetchOpts:i={},headers:o={}}={}){const r=this.hostSchemaRe.exec(t)?.[1];this.host=r?t.replace(`${r}://`,""):t,this.schema=r??"https",this.fetch=n,this.fetchOpts=i,this.headers={...this.headers,...o};}async request(t,n,i={},o="POST"){const r=this.getOpts(new Blob([n]),i,o);try{const s=await this.fetch(`${this.schema}://${this.host}${t}`,r),a=await s.arrayBuffer();return {success:s.status===200,data:a}}catch(s){return {success:false,data:s?.message}}}async requestJSON(t,n=null,i={},o="POST"){const r=this.getOpts(n,{"Content-Type":"application/json",...i},o);try{const s=await this.fetch(`${this.schema}://${this.host}${t}`,r),a=await s.json();return {success:s.status===200,data:a}}catch(s){return {success:false,data:s?.message}}}getOpts(t,n={},i="POST"){return {method:i,headers:{...this.headers,...n},body:t,...this.fetchOpts}}async getSession(t){const n=Xs(),i=this.sessions[t];if(i&&i.timestamp+i.expires>n)return i;const{secretKey:o,expires:r,uuid:s}=await this.createSession(t);return this.sessions[t]={secretKey:o,expires:r,timestamp:n,uuid:s},this.sessions[t]}async createSession(t){const n=Ks(),i=Ti.encodeSessionRequest(n,t),o=await this.request("/session/create",i,{"Vtrans-Signature":await fn(i)});if(!o.success)throw new F("Failed to request create session",o);return {...Ti.decodeSessionResponse(o.data),uuid:n}}}let tr=class extends da{hostVOT;schemaVOT;apiToken;requestLang;responseLang;paths={videoTranslation:"/video-translation/translate",videoTranslationFailAudio:"/video-translation/fail-audio-js",videoTranslationAudio:"/video-translation/audio",videoTranslationCache:"/video-translation/cache",videoSubtitles:"/video-subtitles/get-subtitles",streamPing:"/stream-translation/ping-stream",streamTranslation:"/stream-translation/translate-stream"};isCustomLink(t){return !!(/\.(m3u8|m4(a|v)|mpd)/.exec(t)??/^https:\/\/cdn\.qstv\.on\.epicgames\.com/.exec(t))}headersVOT={"User-Agent":`vot.js/${K.version}`,"Content-Type":"application/json",Pragma:"no-cache","Cache-Control":"no-cache"};constructor({host:t,hostVOT:n=K.hostVOT,fetchFn:i,fetchOpts:o,requestLang:r="en",responseLang:s="ru",apiToken:a,headers:l}={}){super({host:t,fetchFn:i,fetchOpts:o,headers:l});const c=this.hostSchemaRe.exec(n)?.[1];this.hostVOT=c?n.replace(`${c}://`,""):n,this.schemaVOT=c??"https",this.requestLang=r,this.responseLang=s,this.apiToken=a;}get apiTokenHeader(){return this.apiToken?{Authorization:`OAuth ${this.apiToken}`}:{}}async requestVOT(t,n,i={}){const o=this.getOpts(JSON.stringify(n),{...this.headersVOT,...i});try{const r=await this.fetch(`${this.schemaVOT}://${this.hostVOT}${t}`,o),s=await r.json();return {success:r.status===200,data:s}}catch(r){return {success:false,data:r?.message}}}async translateVideoYAImpl({videoData:t,requestLang:n=this.requestLang,responseLang:i=this.responseLang,translationHelp:o=null,headers:r={},extraOpts:s={},shouldSendFailedAudio:a=true}){const{url:l,duration:c=K.defaultDuration}=t,d=await this.getSession("video-translation"),u=nt.encodeTranslationRequest(l,c,n,i,o,s),h=this.paths.videoTranslation,m=await Dt("Vtrans",d,u,h),v=s.useLivelyVoice?this.apiTokenHeader:{},b=await this.request(h,u,{...m,...v,...r});if(!b.success)throw new F("Failed to request video translation",b);const y=nt.decodeTranslationResponse(b.data);C.log("translateVideo",y);const{status:k,translationId:x}=y;switch(k){case lt.FAILED:throw new F("Yandex couldn't translate video",y);case lt.FINISHED:case lt.PART_CONTENT:if(!y.url)throw new F("Audio link wasn't received from Yandex response",y);return {translationId:x,translated:true,url:y.url,status:k,remainingTime:y.remainingTime??-1};case lt.WAITING:case lt.LONG_WAITING:return {translationId:x,translated:false,status:k,remainingTime:y.remainingTime??-1};case lt.AUDIO_REQUESTED:return l.startsWith("https://youtu.be/")&&a?(await this.requestVtransFailAudio(l),await this.requestVtransAudio(l,y.translationId,{audioFile:new Uint8Array,fileId:Gt.WEB_API_GET_ALL_GENERATING_URLS_DATA_FROM_IFRAME}),await this.translateVideoYAImpl({videoData:t,requestLang:n,responseLang:i,translationHelp:o,headers:r,shouldSendFailedAudio:false})):{translationId:x,translated:false,status:k,remainingTime:y.remainingTime??-1};case lt.SESSION_REQUIRED:throw new F("Yandex auth required to translate video. See docs for more info",y);default:throw C.error("Unknown response",y),new F("Unknown response from Yandex",y)}}async translateVideoVOTImpl({url:t,videoId:n,service:i,requestLang:o=this.requestLang,responseLang:r=this.responseLang,headers:s={},provider:a="yandex"}){const l=Ai(i,n,t),c=await this.requestVOT(this.paths.videoTranslation,{provider:a,service:l.service,video_id:l.videoId,from_lang:o,to_lang:r,raw_video:t},{...s});if(!c.success)throw new F("Failed to request video translation",c);const d=c.data;switch(d.status){case "failed":throw new F("Yandex couldn't translate video",d);case "success":if(!d.translated_url)throw new F("Audio link wasn't received from VOT response",d);return {translationId:String(d.id),translated:true,url:d.translated_url,status:1,remainingTime:-1};case "waiting":return {translationId:"",translated:false,remainingTime:d.remaining_time,status:2,message:d.message}}}async requestVtransFailAudio(t){const n=await this.requestJSON(this.paths.videoTranslationFailAudio,JSON.stringify({video_url:t}),void 0,"PUT");if(!n.data||typeof n.data=="string"||n.data.status!==1)throw new F("Failed to request to fake video translation fail audio js",n);return n}async requestVtransAudio(t,n,i,o,r={}){const s=await this.getSession("video-translation");let a;if(nt.isPartialAudioBuffer(i)){if(!o)throw new F("Partial audio metadata is required for partial audio buffer",i);a=nt.encodeTranslationAudioRequest(t,n,i,o);}else a=nt.encodeTranslationAudioRequest(t,n,i,void 0);const l=this.paths.videoTranslationAudio,c=await Dt("Vtrans",s,a,l),d=await this.request(l,a,{...c,...r},"PUT");if(!d.success)throw new F("Failed to request video translation audio",d);return nt.decodeTranslationAudioResponse(d.data)}async translateVideoCache({videoData:t,requestLang:n=this.requestLang,responseLang:i=this.responseLang,headers:o={}}){const{url:r,duration:s=K.defaultDuration}=t,a=await this.getSession("video-translation"),l=nt.encodeTranslationCacheRequest(r,s,n,i),c=this.paths.videoTranslationCache,d=await Dt("Vtrans",a,l,c),u=await this.request(c,l,{...d,...o},"POST");if(!u.success)throw new F("Failed to request video translation cache",u);return nt.decodeTranslationCacheResponse(u.data)}async translateVideo({videoData:t,requestLang:n=this.requestLang,responseLang:i=this.responseLang,translationHelp:o=null,headers:r={},extraOpts:s={},shouldSendFailedAudio:a=true}){const{url:l,videoId:c,host:d}=t;return this.isCustomLink(l)?await this.translateVideoVOTImpl({url:l,videoId:c,service:d,requestLang:n,responseLang:i,headers:r,provider:s.useLivelyVoice?"yandex_lively":"yandex"}):await this.translateVideoYAImpl({videoData:t,requestLang:n,responseLang:i,translationHelp:o,headers:r,extraOpts:s,shouldSendFailedAudio:a})}async getSubtitlesYAImpl({videoData:t,requestLang:n=this.requestLang,headers:i={}}){const{url:o}=t,r=await this.getSession("video-translation"),s=nt.encodeSubtitlesRequest(o,n),a=this.paths.videoSubtitles,l=await Dt("Vsubs",r,s,a),c=await this.request(a,s,{...l,...i});if(!c.success)throw new F("Failed to request video subtitles",c);const d=nt.decodeSubtitlesResponse(c.data),u=d.subtitles.map(h=>{const{language:m,url:v,translatedLanguage:b,translatedUrl:y}=h;return {language:m,url:v,translatedLanguage:b,translatedUrl:y}});return {waiting:d.waiting,subtitles:u}}async getSubtitlesVOTImpl({url:t,videoId:n,service:i,headers:o={}}){const r=Ai(i,n,t),s=await this.requestVOT(this.paths.videoSubtitles,{provider:"yandex",service:r.service,video_id:r.videoId},o);if(!s.success)throw new F("Failed to request video subtitles",s);const a=s.data;return {waiting:false,subtitles:a.reduce((c,d)=>{if(!d.lang_from)return c;const u=a.find(h=>h.lang===d.lang_from);return u&&c.push({language:u.lang,url:u.subtitle_url,translatedLanguage:d.lang,translatedUrl:d.subtitle_url}),c},[])}}async getSubtitles({videoData:t,requestLang:n=this.requestLang,headers:i={}}){const{url:o,videoId:r,host:s}=t;return this.isCustomLink(o)?await this.getSubtitlesVOTImpl({url:o,videoId:r,service:s,headers:i}):await this.getSubtitlesYAImpl({videoData:t,requestLang:n,headers:i})}async pingStream({pingId:t,headers:n={}}){const i=await this.getSession("video-translation"),o=nt.encodeStreamPingRequest(t),r=this.paths.streamPing,s=await Dt("Vtrans",i,o,r),a=await this.request(r,o,{...s,...n});if(!a.success)throw new F("Failed to request stream ping",a);return true}async translateStream({videoData:t,requestLang:n=this.requestLang,responseLang:i=this.responseLang,headers:o={}}){const{url:r}=t;if(this.isCustomLink(r))throw new F("Unsupported video URL for getting stream translation");const s=await this.getSession("video-translation"),a=nt.encodeStreamRequest(r,n,i),l=this.paths.streamTranslation,c=await Dt("Vtrans",s,a,l),d=await this.request(l,a,{...c,...o});if(!d.success)throw new F("Failed to request stream translation",d);const u=nt.decodeStreamResponse(d.data),h=u.interval;switch(h){case Z.NO_CONNECTION:case Z.TRANSLATING:return {translated:false,interval:h,message:h===Z.NO_CONNECTION?"streamNoConnectionToServer":"translationTakeFewMinutes"};case Z.STREAMING:{if(u.pingId===void 0)throw new F("Stream ping id wasn't received from Yandex response",u);return {translated:true,interval:h,pingId:u.pingId,result:u.translatedInfo}}default:throw C.error("Unknown response",u),new F("Unknown response from Yandex",u)}}},ua=class extends tr{constructor(t={}){t.host=t.host??K.hostWorker,super(t);}async request(t,n,i={},o="POST"){const r=this.getOpts(JSON.stringify({headers:{...this.headers,...i},body:Array.from(n)}),{"Content-Type":"application/json"},o);try{const s=await this.fetch(`${this.schema}://${this.host}${t}`,r),a=await s.arrayBuffer();return {success:s.status===200,data:a}}catch(s){return {success:false,data:s?.message}}}async requestJSON(t,n=null,i={},o="POST"){const r=this.getOpts(JSON.stringify({headers:{...this.headers,"Content-Type":"application/json",Accept:"application/json",...i},body:n}),{Accept:"application/json","Content-Type":"application/json"},o);try{const s=await this.fetch(`${this.schema}://${this.host}${t}`,r),a=await s.json();return {success:s.status===200,data:a}}catch(s){return {success:false,data:s?.message}}}};class ha extends tr{constructor(t){super(t),this.headers={...jo,...this.headers};}}class fa extends ua{constructor(t){super(t),this.headers={...jo,...this.headers};}}class ee extends Error{constructor(t){super(t),this.name="VideoDataError";}}const pa=/(file:\/\/(\/)?|(http(s)?:\/\/)(127\.0\.0\.1|localhost|192\.168\.(\d){1,3}\.(\d){1,3}))/,ga=["yewtu.be","inv.nadeko.net","invidious.nerdvpn.de","invidious.protokolla.fi","invidious.materialio.us","iv.melmac.space"],ma=["piped.video","piped.kavin.rocks","piped.private.coffee"],va=["proxitok.pabloferreiro.es","proxitok.pussthecat.org","tok.habedieeh.re","proxitok.esmailelbob.xyz","proxitok.privacydev.net","tok.artemislena.eu","tok.adminforge.de","tt.vern.cc","cringe.whatever.social","proxitok.lunar.icu","proxitok.privacy.com.de"],ba=["peertube.tmp.rcp.tf","dalek.zone","video.sadmin.io","videos.viorsan.com","peertube.1312.media","tube.shanti.cafe","bee-tube.fr","video.blender.org","beetoons.tv","makertube.net","peertube.tv","framatube.org","tilvids.com","diode.zone","fedimovie.com","video.hardlimit.com","share.tube","peervideo.club"],ya=["coursehunter.net","coursetrain.net"];var U;(function(e){e.udemy="udemy",e.coursera="coursera",e.douyin="douyin",e.artstation="artstation",e.kickstarter="kickstarter",e.oraclelearn="oraclelearn",e.deeplearningai="deeplearningai",e.netacad="netacad";})(U||(U={}));({...g,...U});const O={bilibiliPlayer:".bpx-player-video-wrap, div.player-mobile-box.player-mobile-autoplay",flowplayer:".fp-player",idPlayer:"#player",jwPlayer:".jwplayer, .jw-media",player:".player",videoJsUniversal:"[id^='vjs_video_']:not([id*='_html5_api']):not(video), video-js:not([id*='_html5_api']), .video-js:not(video):not([id*='_html5_api']), .vjs-player:not([id*='_html5_api']), [data-vjs-player]:not([id*='_html5_api'])",vkVideoPlayer:".videoplayer_media, vk-video-player"},wa=[{additionalData:"mobile",host:g.youtube,url:"https://youtu.be/",match:/^m.youtube.com$/,selector:".player-container",needExtraData:true},{host:g.youtube,url:"https://youtu.be/",match:/^(www.)?youtube(-nocookie|kids)?.com$/,selector:".html5-video-container:not(#inline-player *)",needExtraData:true},{host:g.invidious,url:"https://youtu.be/",match:ga,selector:O.idPlayer,needBypassCSP:true},{host:g.piped,url:"https://youtu.be/",match:ma,selector:".shaka-video-container",needBypassCSP:true},{host:g.zdf,url:"https://www.zdf.de/play/",match:[/^zdf.de$/,/^(www.)?zdf.de$/],selector:"div.zdfplayer-app.zdfplayer-desktop, div.zdfplayer-app"},{host:g.niconico,url:"https://www.nicovideo.jp/watch/",match:[/^(www\.|sp\.)?nicovideo\.jp$/,/^nico\.ms$/],selector:'[class*="grid-area_[player]"] > div'},{additionalData:"mobile",host:g.vk,url:"https://vk.com/video?z=",match:[/^m.vk.(com|ru)$/,/^m.vkvideo.ru$/],selector:O.vkVideoPlayer,shadowRoot:true,needExtraData:true},{additionalData:"clips",host:g.vk,url:"https://vk.com/video?z=",match:/^(www.|m.)?vk.(com|ru)$/,selector:'div[data-testid="clipcontainer-video"]',needExtraData:true},{host:g.vk,url:"https://vk.com/video?z=",match:[/^(www\.|m\.)?vk\.(com|ru)$/,/^(.*\.)?vkvideo\.ru$/],selector:O.vkVideoPlayer,needExtraData:true},{host:g.nine_gag,url:"https://9gag.com/gag/",match:/^9gag.com$/,selector:".video-post",needExtraData:true},{host:g.twitch,url:"https://twitch.tv/",match:[/^m.twitch.tv$/,/^(www.)?twitch.tv$/,/^clips.twitch.tv$/,/^player.twitch.tv$/],needExtraData:true,selector:".video-ref, main > div > section > div > div > div"},{host:g.proxitok,url:"https://www.tiktok.com/",match:va,selector:".column.has-text-centered"},{host:g.tiktok,url:"https://www.tiktok.com/",match:/^(www.)?tiktok.com$/,selector:null},{host:U.douyin,url:"https://www.douyin.com/",match:/^(www.)?douyin.com/,selector:".xg-video-container",needExtraData:true,needBypassCSP:true},{host:g.vimeo,url:"https://vimeo.com/",match:/^(www\.|m\.)?vimeo.com$/,needExtraData:true,selector:O.player},{host:g.vimeo,url:"https://player.vimeo.com/",match:/^player.vimeo.com$/,additionalData:"embed",needExtraData:true,needBypassCSP:true,selector:O.player},{host:g.xvideos,url:"https://www.xvideos.com/",match:[/^(www.)?xvideos(-ar)?.com$/,/^(www.)?xvideos(\d\d\d).com$/,/^(www.)?xv-ru.com$/],selector:"#hlsplayer",needBypassCSP:true},{host:g.xhamster,url:"https://xhamster.com/",match:e=>/^(?:[^.]+\.)?(?:xhamster\.(?:com|desi)|xhamster\d+\.(?:com|desi)|xhvid\.com)$/.test(e.host)&&/\/(?:videos\/[^/]+-[\dA-Za-z]+)\/?$/.test(e.pathname),selector:"#player-container"},{host:g.spankbang,url:"https://spankbang.com/",match:e=>/^(?:[^.]+\.)?spankbang\.com$/.test(e.host)&&/\/(?:[\da-z]+\/(?:video|play|embed)(?:\/[^/]+)?|[\da-z]+-[\da-z]+\/playlist\/[^/?#&]+)\/?$/i.test(e.pathname),selector:"#main_video_player"},{host:g.rule34video,url:"https://rule34video.com/video/",match:e=>/^(www\.)?rule34video\.com$/.test(e.host)&&/\/videos?\/\d+/.test(e.pathname),selector:O.flowplayer},{host:g.picarto,url:"https://picarto.tv/",match:e=>/^(www\.)?picarto\.tv$/.test(e.host)&&/^(?:\/[^/]+\/(?:profile\/)?videos\/[^/?#&]+|\/videopopout\/[^/?#&]+|\/[^/#?]+\/?)$/.test(e.pathname),selector:'[class*="VideosTab__PlayerWrapper"]'},{host:g.olympicsreplay,url:"https://olympics.com/",match:e=>/^(www\.)?olympics\.com$/.test(e.host)&&/^\/[a-z]{2}\/(?:[a-z0-9-]+\/)?(?:replay|videos?|original-series\/episode)\/[\w-]+\/?$/i.test(e.pathname),selector:O.videoJsUniversal},{host:g.pornhub,url:"https://rt.pornhub.com/view_video.php?viewkey=",match:/^[a-z]+.pornhub.(com|org)$/,selector:".mainPlayerDiv > .video-element-wrapper-js > div",eventSelector:".mgp_eventCatcher"},{additionalData:"embed",host:g.pornhub,url:"https://rt.pornhub.com/view_video.php?viewkey=",match:e=>/^[a-z]+.pornhub.(com|org)$/.exec(e.host)&&e.pathname.startsWith("/embed/"),selector:O.idPlayer},{host:g.twitter,url:"https://twitter.com/i/status/",match:/^(twitter|x).com$/,selector:'div[data-testid="videoComponent"] > div:nth-child(1) > div',eventSelector:'div[data-testid="videoPlayer"]',needBypassCSP:true},{host:g.rumble,url:"https://rumble.com/",match:/^rumble.com$/,selector:"#videoPlayer > .videoPlayer-Rumble-cls > div"},{host:g.facebook,url:"https://facebook.com/",match:e=>e.host.includes("facebook.com")&&e.pathname.includes("/videos/"),selector:'div[role="main"] div[data-pagelet$="video" i]',needBypassCSP:true},{additionalData:"reels",host:g.facebook,url:"https://facebook.com/",match:e=>e.host.includes("facebook.com")&&e.pathname.includes("/reel/"),selector:'div[role="main"]',needBypassCSP:true},{host:g.rutube,url:"https://rutube.ru/video/",match:/^rutube.ru$/,selector:".video-player > div > div > div:nth-child(2)"},{additionalData:"embed",host:g.rutube,url:"https://rutube.ru/video/",match:/^rutube.ru$/,selector:"#app > div > div"},{host:g.bilibili,url:"https://www.bilibili.com/",match:/^(www|m|player).bilibili.com$/,selector:O.bilibiliPlayer},{host:g.bilibili,url:"https://www.bilibili.tv/",match:/^(?:www\.|m\.)?bilibili\.tv$/,selector:O.bilibiliPlayer},{additionalData:"old",host:g.bilibili,url:"https://www.bilibili.com/",match:/^(www|m).bilibili.com$/,selector:null},{host:g.mailru,url:"https://my.mail.ru/",match:/^my.mail.ru$/,selector:"#b-video-wrapper"},{host:g.bitchute,url:"https://www.bitchute.com/video/",match:/^(www.)?bitchute.com$/,selector:O.videoJsUniversal},{host:g.eporner,url:"https://www.eporner.com/",match:/^(www.)?eporner.com$/,selector:O.videoJsUniversal},{host:g.peertube,url:"stub",match:ba,selector:O.videoJsUniversal},{host:g.dailymotion,url:"https://www.dailymotion.com/video/",match:/^((www\.)?dailymotion\.com|geo(\d+)?\.dailymotion\.com|dai\.ly)$/,selector:O.player},{host:g.trovo,url:"https://trovo.live/s/",match:/^trovo.live$/,selector:".player-video"},{host:g.yandexdisk,url:"https://yadi.sk/",match:/^disk.yandex.(ru|kz|com(\.(am|ge|tr))?|by|az|co\.il|ee|lt|lv|md|net|tj|tm|uz)$/,selector:".video-player__player > div:nth-child(1)",eventSelector:".video-player__player",needBypassCSP:true,needExtraData:true},{host:g.okru,url:"https://ok.ru/video/",match:/^ok.ru$/,selector:O.vkVideoPlayer,shadowRoot:true},{host:g.googledrive,url:"https://drive.google.com/file/d/",match:/^youtube.googleapis.com$/,selector:".html5-video-container"},{host:g.bannedvideo,url:"https://madmaxworld.tv/watch?id=",match:/^(www.)?banned.video|madmaxworld.tv$/,selector:O.videoJsUniversal,needExtraData:true},{host:g.weverse,url:"https://weverse.io/",match:/^weverse.io$/,selector:".webplayer-internal-source-wrapper",needExtraData:true},{host:g.weibo,url:"https://weibo.com/",match:e=>/^(?:www\.)?weibo\.com$/.test(e.host)&&/^\/(?:\d+\/[A-Za-z0-9]+|0\/[A-Za-z0-9]+|tv\/show\/\d+:(?:[\da-f]{32}|\d{16,}))\/?$/.test(e.pathname)||/^video\.weibo\.com$/.test(e.host)&&/^\/show\/?$/.test(e.pathname)&&/^\d+:(?:[\da-f]{32}|\d{16,})$/i.test(e.searchParams.get("fid")??"")||/^(?:www\.)?weibo\.com$/.test(e.host)&&/^\/newlogin\/?$/.test(e.pathname)&&(e.searchParams.has("url")||/^[A-Za-z0-9]+$/.test(e.searchParams.get("layerid")??"")),selector:O.videoJsUniversal},{host:g.newgrounds,url:"https://www.newgrounds.com/",match:/^(www.)?newgrounds.com$/,selector:".ng-video-player"},{host:g.egghead,url:"https://egghead.io/",match:/^egghead.io$/,selector:".cueplayer-react-video-holder"},{host:g.youku,url:"https://v.youku.com/",match:/^v.youku.com$/,selector:"#ykPlayer"},{host:g.archive,url:"https://archive.org/details/",match:/^archive.org$/,selector:O.jwPlayer},{host:g.kodik,url:"stub",match:/^kodik.(info|biz|cc)$/,selector:O.flowplayer,needExtraData:true},{host:g.patreon,url:"stub",match:/^(www.)?patreon.com$/,selector:'div[data-tag="post-card"] div[elevation="subtle"] > div > div > div > div',needExtraData:true},{additionalData:"old",host:g.reddit,url:"stub",match:/^old.reddit.com$/,selector:".reddit-video-player-root",needExtraData:true,needBypassCSP:true},{host:g.reddit,url:"stub",match:/^(www.|new.)?reddit.com$/,selector:"div[slot=post-media-container]",shadowRoot:true,needExtraData:true,needBypassCSP:true},{host:g.kick,url:"https://kick.com/",match:/^kick.com$/,selector:"#injected-embedded-channel-player-video > div",needExtraData:true},{host:g.appledeveloper,url:"https://developer.apple.com/",match:/^developer.apple.com$/,selector:".developer-video-player",needExtraData:true,needBypassCSP:true},{host:g.epicgames,url:"https://dev.epicgames.com/community/learning/",match:/^dev.epicgames.com$/,selector:O.videoJsUniversal,needExtraData:true},{host:g.odysee,url:"stub",match:/^odysee.com$/,selector:O.videoJsUniversal,needExtraData:true},{host:g.coursehunterLike,url:"stub",match:ya,selector:"#oframeplayer > pjsdiv:has(video)",needExtraData:true},{host:g.sap,url:"https://learning.sap.com/courses/",match:/^learning.sap.com$/,selector:".playkit-container",eventSelector:".playkit-player",needExtraData:true,needBypassCSP:true},{host:U.udemy,url:"https://www.udemy.com/",match:/udemy.com$/,selector:'div[data-purpose="curriculum-item-viewer-content"] > section > div > div > div > div:nth-of-type(2)',needExtraData:true},{host:U.coursera,url:"https://www.coursera.org/",match:/coursera.org$/,selector:O.videoJsUniversal,needExtraData:true},{host:g.watchpornto,url:"https://watchporn.to/",match:/^watchporn.to$/,selector:O.flowplayer},{host:g.linkedin,url:"https://www.linkedin.com/learning/",match:/^(www.)?linkedin.com$/,selector:O.videoJsUniversal,needExtraData:true,needBypassCSP:true},{host:g.incestflix,url:"https://www.incestflix.net/watch/",match:/^(www.)?incestflix.(net|to|com)$/,selector:"#incflix-stream",needExtraData:true},{host:g.porntn,url:"https://porntn.com/videos/",match:/^porntn.com$/,selector:O.flowplayer,needExtraData:true},{host:g.dzen,url:"https://dzen.ru/video/watch/",match:/^dzen.ru$/,selector:".zen-ui-video-video-player"},{host:g.cloudflarestream,url:"stub",match:/^(watch|embed|iframe|customer-[^.]+).cloudflarestream.com$/,selector:null},{host:g.loom,url:"https://www.loom.com/share/",match:/^(www.)?loom.com$/,selector:".VideoLayersContainer",needExtraData:true,needBypassCSP:true},{host:U.artstation,url:"https://www.artstation.com/learning/",match:/^(www.)?artstation.com$/,selector:O.videoJsUniversal,needExtraData:true},{host:g.rtnews,url:"https://www.rt.com/",match:/^(www.)?rt.com$/,selector:O.jwPlayer,needExtraData:true},{host:g.bitview,url:"https://www.bitview.net/watch?v=",match:/^(www.)?bitview.net$/,selector:".vlScreen",needExtraData:true},{host:U.kickstarter,url:"https://www.kickstarter.com/",match:/^(www.)?kickstarter.com/,selector:".ksr-video-player",needExtraData:true},{host:g.thisvid,url:"https://thisvid.com/",match:/^(www.)?thisvid.com$/,selector:O.flowplayer},{additionalData:"regional",host:g.ign,url:"https://de.ign.com/",match:/^(\w{2}.)?ign.com$/,needExtraData:true,selector:".video-container"},{host:g.ign,url:"https://www.ign.com/",match:/^(www.)?ign.com$/,selector:O.player,needExtraData:true},{host:g.bunkr,url:"https://bunkr.site/",match:/^bunkr\.(site|black|cat|media|red|site|ws|org|s[kiu]|c[ir]|fi|p[hks]|ru|la|is|to|a[cx])$/,needExtraData:true,selector:".plyr__video-wrapper"},{host:g.imdb,url:"https://www.imdb.com/video/",match:/^(www\.)?imdb\.com$/,selector:O.jwPlayer},{host:g.telegram,url:"https://t.me/",match:e=>/^web\.telegram\.org$/.test(e.hostname)&&e.pathname.startsWith("/k"),selector:".ckin__player"},{host:U.oraclelearn,url:"https://mylearn.oracle.com/ou/course/",match:/^mylearn\.oracle\.com/,selector:O.videoJsUniversal,needExtraData:true,needBypassCSP:true},{host:U.deeplearningai,url:"https://learn.deeplearning.ai/courses/",match:/^learn(-dev|-staging)?\.deeplearning\.ai/,selector:".lesson-video-player",needExtraData:true},{host:U.netacad,url:"https://www.netacad.com/",match:/^(www\.)?netacad\.com/,selector:O.videoJsUniversal,needExtraData:true},{host:g.custom,url:"stub",match:e=>/([^.]+)\.(mp4|webm)/.test(e.pathname),rawResult:true}];class M extends Error{constructor(t){super(t),this.name="VideoHelperError";}}class T{API_ORIGIN=window.location.origin;fetch;extraInfo;referer;origin;service;video;language;constructor({fetchFn:t=Zo,extraInfo:n=true,referer:i=document.referrer??`${window.location.origin}/`,origin:o=window.location.origin,service:r,video:s,language:a="en"}={}){this.fetch=t,this.extraInfo=n,this.referer=i,this.origin=/^(http(s)?):\/\//.test(String(o))?o:window.location.origin,this.service=r,this.video=s,this.language=a;}getVideoData(t){return Promise.resolve(void 0)}getVideoId(t){return Promise.resolve(void 0)}returnBaseData(t){if(this.service)return {url:this.service.url+t,videoId:t,host:this.service.host,duration:void 0}}}class ka extends T{API_ORIGIN="https://developer.apple.com";async getVideoData(t){try{const n=document.querySelector("meta[property='og:video']")?.content;if(!n)throw new M("Failed to find content url");return {url:n}}catch(n){C.error(`Failed to get apple developer video data by video ID: ${t}`,n.message);return}}async getVideoId(t){return /videos\/play\/([^/]+)\/([\d]+)/.exec(t.pathname)?.[0]}}class xa extends T{async getVideoId(t){return /(details|embed)\/([^/]+)/.exec(t.pathname)?.[2]}}class Sa extends T{API_ORIGIN="https://www.artstation.com/api/v2/learning";getCSRFToken(){return document.querySelector('meta[name="public-csrf-token"]')?.content}async getCourseInfo(t){try{const n=this.getCSRFToken();return await(await this.fetch(`${this.API_ORIGIN}/courses/${t}/autoplay.json`,{method:"POST",headers:n?{"PUBLIC-CSRF-TOKEN":n}:{}})).json()}catch(n){return C.error(`Failed to get artstation course info by courseId: ${t}.`,n.message),false}}async getVideoUrl(t){try{return (await(await this.fetch(`${this.API_ORIGIN}/quicksilver/video_url.json?chapter_id=${t}`)).json()).url.replace("qsep://","https://")}catch(n){return C.error(`Failed to get artstation video url by chapterId: ${t}.`,n.message),false}}async getVideoData(t){const[,n,,,i]=t.split("/"),o=await this.getCourseInfo(n);if(!o)return;const r=o.chapters.find(u=>u.hash_id===i);if(!r)return;const s=await this.getVideoUrl(r.id);if(!s)return;const{title:a,duration:l,subtitles:c}=r,d=c.filter(u=>u.format==="vtt").map(u=>({language:X(u.locale),source:"artstation",format:"vtt",url:u.file_url}));return {url:s,title:a,duration:l,subtitles:d}}async getVideoId(t){return /courses\/(\w{3,5})\/([^/]+)\/chapters\/(\w{3,5})/.exec(t.pathname)?.[0]}}class Ta extends T{API_ORIGIN="https://api.banned.video";async getVideoInfo(t){try{return await(await this.fetch(`${this.API_ORIGIN}/graphql`,{method:"POST",body:JSON.stringify({operationName:"GetVideo",query:`query GetVideo($id: String!) { getVideo(id: $id) { title description: summary duration: videoDuration videoUrl: directUrl isStream: live } }`,variables:{id:t}}),headers:{"User-Agent":"bannedVideoFrontEnd","apollographql-client-name":"banned-web","apollographql-client-version":"1.3","content-type":"application/json"}})).json()}catch(n){return console.error(`Failed to get bannedvideo video info by videoId: ${t}.`,n.message),false}}async getVideoData(t){const n=await this.getVideoInfo(t);if(!n)return;const{videoUrl:i,duration:o,isStream:r,description:s,title:a}=n.data.getVideo;return {url:i,duration:o,isStream:r,title:a,description:s}}async getVideoId(t){return t.searchParams.get("id")??void 0}}class Aa extends T{async getVideoId(t){const n=/bangumi\/play\/([^/]+)/.exec(t.pathname)?.[0];if(n)return n;const i=t.searchParams.get("bvid");if(i)return `video/${i}`;const o=/^\/(?:[a-z]{2}\/)?((?:play\/\d+(?:\/\d+)?|video\/\d+))\/?$/i.exec(t.pathname)?.[1];if(o)return o;let r=/video\/([^/]+)/.exec(t.pathname)?.[0];return r&&t.searchParams.get("p")!==null&&(r+=`/?p=${t.searchParams.get("p")}`),r}}class La extends T{async getVideoId(t){return /(video|embed)\/([^/]+)/.exec(t.pathname)?.[2]}}class Ia extends T{async getVideoData(t){try{const n=document.querySelector(".vlScreen > video")?.src;if(!n)throw new M("Failed to find video URL");return {url:n}}catch(n){C.error(`Failed to get Bitview data by videoId: ${t}`,n.message);return}}async getVideoId(t){return t.searchParams.get("v")}}class Pa extends T{async getVideoData(t){const n=document.querySelector('#player > source[type="video/mp4"]')?.src;if(n)return {url:n}}async getVideoId(t){return /\/f\/([^/]+)/.exec(t.pathname)?.[1]}}class Ca extends T{async getVideoId(t){return t.pathname+t.search}}class Ea extends T{API_ORIGIN=this.origin??"https://coursehunter.net";async getCourseId(){const t=window.course_id;return t!==void 0?String(t):document.querySelector('input[name="course_id"]')?.value}async getLessonsData(t){const n=window.lessons;if(n?.length)return n;try{return await(await this.fetch(`${this.API_ORIGIN}/api/v1/course/${t}/lessons`)).json()}catch(i){C.error(`Failed to get CoursehunterLike lessons data by courseId: ${t}, because ${i.message}`);return}}getLessondId(t){let n=t.split("?lesson=")?.[1];return n||(n=document.querySelector(".lessons-item_active")?.dataset?.index,n)?+n:1}async getVideoData(t){const n=await this.getCourseId();if(!n)return;const i=await this.getLessonsData(n);if(!i)return;const o=this.getLessondId(t),r=i?.[o-1],{file:s,duration:a,title:l}=r;if(s)return {url:at(s),duration:a,title:l}}async getVideoId(t){const n=/course\/([^/]+)/.exec(t.pathname)?.[0];return n?n+t.search:void 0}}const _t=["auto","ru","en","zh","ko","lt","lv","ar","fr","it","es","de","ja"],In=["ru","en","kk"],Va=["srt","vtt","json"];class Vt extends T{SUBTITLE_SOURCE="videojs";SUBTITLE_FORMAT="vtt";static getPlayer(){const t=window.videojs,n=document.querySelector("video.vjs-tech[id], video[id$='_html5_api']"),i=n?.id?.endsWith("_html5_api")?n.id.slice(0,-10):void 0;if(t?.getPlayer){if(i){const r=t.getPlayer(i);if(r)return r}if(n){const r=t.getPlayer(n);if(r)return r}}const o=(typeof t?.getPlayers=="function"?t.getPlayers():t?.players)??{};for(const r of Object.values(o)){const s=r,l=(typeof s.el=="function"?s.el():null)?.querySelector?.("video.vjs-tech, video")??null;if(l&&n&&l===n||i&&typeof s.id=="function"&&s.id()===i)return r}}getVideoDataByPlayer(t){try{const n=Vt.getPlayer(),i=document.querySelector("video.vjs-tech, video[id$='_html5_api'], video[src]");if(!n&&!i)throw new Error(`Video player/video element not found, videoId ${t}`);const o=n?.duration?.()??i?.duration;let r;if(n){const l=typeof n.currentSources=="function"?n.currentSources():n.getCache?.()?.sources;r=(Array.isArray(l)?l.find(d=>d?.type==="video/mp4"||d?.type==="video/webm"||d?.src):void 0)?.src;}if(r??=i?.currentSrc||i?.src||i?.getAttribute?.("src")||void 0,!r)throw new Error(`Failed to find video url for videoID ${t}`);const a=(i?Array.from(i.querySelectorAll("track[src]")):[]).filter(l=>l.kind!=="metadata").flatMap(l=>{const c=l.getAttribute("src");if(!c)return [];const d=new URL(c,window.location.href).toString();return [{language:X(l.srclang||""),source:this.SUBTITLE_SOURCE,format:this.SUBTITLE_FORMAT,url:d}]});return {url:r,duration:o,subtitles:a}}catch(n){C.error("Failed to get videojs video data",n.message);return}}}class Pn extends Vt{API_ORIGIN="https://www.coursera.org/api";SUBTITLE_SOURCE="coursera";async getCourseData(t){try{return (await(await this.fetch(`${this.API_ORIGIN}/onDemandCourses.v1/${t}`)).json())?.elements?.[0]}catch(n){C.error(`Failed to get course data by courseId: ${t}`,n.message);return}}static getPlayer(){return Vt.getPlayer()}async getVideoData(t){const n=this.getVideoDataByPlayer(t);if(!n)return;const{options_:i}=Pn.getPlayer()??{};!n.subtitles?.length&&i&&(n.subtitles=i.tracks.map(h=>({url:h.src,language:X(h.srclang),source:this.SUBTITLE_SOURCE,format:this.SUBTITLE_FORMAT})));const o=i?.courseId;if(!o)return n;let r="en";const s=await this.getCourseData(o);if(s){const{primaryLanguageCodes:[h]}=s;r=h?X(h):"en";}_t.includes(r)||(r="en");const l=(n.subtitles.find(h=>h.language===r)??n.subtitles?.[0])?.url;l||C.warn("Failed to find any subtitle file");const{url:c,duration:d}=n,u=l?[{target:"subtitles_file_url",targetUrl:l},{target:"video_file_url",targetUrl:c}]:null;return {...l?{url:this.service?.url+t,translationHelp:u}:{url:c,translationHelp:u},detectedLanguage:r,duration:d}}async getVideoId(t){return (/learn\/([^/]+)\/lecture\/([^/]+)/.exec(t.pathname)??/lecture\/([^/]+)\/([^/]+)/.exec(t.pathname))?.[0]}}class Ma extends T{async getVideoId(t){return new Promise(n=>{const i="https://www.dailymotion.com",o=setTimeout(()=>n(void 0),3e3);window.addEventListener("message",r=>{r.origin===i&&(typeof r.data!="object"||r.data?.type!=="dailymotionVideoId"||(clearTimeout(o),n(r.data.videoId)));}),window.top?.postMessage({type:"getDailymotionVideoId"},i);})}}class _a extends T{async getVideoData(t){if(!this.video)return;const n=this.video.querySelector('source[type="application/x-mpegurl"]')?.src;if(n)return {url:n}}async getVideoId(t){return /courses\/(([^/]+)\/lesson\/([^/]+)\/([^/]+))/.exec(t.pathname)?.[1]}}class Pe extends T{static getPlayer(){if(!(typeof player>"u"))return player}async getVideoData(t){const n=Pe.getPlayer();if(!n)return;const{config:{url:i,duration:o,lang:r,isLive:s}}=n;if(!i)return;const a=i.find(l=>l.src.includes("www.douyin.com/aweme/v1/play/"));if(a)return {url:at(a.src),duration:o,isStream:s,..._t.includes(r)?{detectedLanguage:r}:{}}}async getVideoId(t){const n=/video\/([\d]+)/.exec(t.pathname)?.[0];return n||Pe.getPlayer()?.config.vid}}class Oa extends T{async getVideoId(t){return /video\/watch\/([^/]+)/.exec(t.pathname)?.[1]}}class Da extends T{async getVideoId(t){return t.pathname.slice(1)}}class Ba extends T{API_ORIGIN="https://dev.epicgames.com/community/api/learning";async getPostInfo(t){try{return await(await this.fetch(`${this.API_ORIGIN}/post.json?hash_id=${t}`)).json()}catch(n){return C.error(`Failed to get epicgames post info by videoId: ${t}.`,n.message),false}}getVideoBlock(){const t=/videoUrl\s?=\s"([^"]+)"?/,n=Array.from(document.body.querySelectorAll("script")).find(s=>t.exec(s.innerHTML));if(!n)return;const i=n.innerHTML.trim(),o=t.exec(i)?.[1]?.replace("qsep://","https://");if(!o)return;let r=/sources\s?=\s(\[([^\]]+)\])?/.exec(i)?.[1];if(!r)return {playlistUrl:o,subtitles:[]};try{r=`${r.replace(/src:(\s)+?(videoUrl)/g,'src:"removed"').substring(0,r.lastIndexOf("},"))}]`.split(` `).map(l=>l.replace(/([^\s]+):\s?(?!.*\1)/,'"$1":')).join(` `);const a=JSON.parse(r).filter(l=>l.type==="captions");return {playlistUrl:o,subtitles:a}}catch{return {playlistUrl:o,subtitles:[]}}}async getVideoData(t){const n=t.split(":")?.[1],i=await this.getPostInfo(n);if(!i)return;const o=this.getVideoBlock();if(!o)return;const{playlistUrl:r,subtitles:s}=o,{title:a,description:l}=i,c=s.map(d=>({language:X(d.srclang),source:"epicgames",format:"vtt",url:d.src}));return {url:r,title:a,description:l,subtitles:c}}async getVideoId(t){return new Promise(n=>{const i="https://dev.epicgames.com",o=btoa(window.location.href);window.addEventListener("message",r=>{if(r.origin!==i||!(typeof r.data=="string"&&r.data.startsWith("getVideoId:")))return;const s=r.data.replace("getVideoId:","");return n(s)}),window.top?.postMessage(`getVideoId:${o}`,i);})}}class Ra extends T{async getVideoId(t){return /video-([^/]+)\/([^/]+)/.exec(t.pathname)?.[0]}}class Na extends T{async getVideoId(t){return t.pathname.slice(1)}}class Fa extends T{getPlayerData(){return document.querySelector("#movie_player")?.getVideoData?.()??void 0}async getVideoId(t){return this.getPlayerData()?.video_id}}class Ha extends T{getVideoDataBySource(t){const n=document.querySelector('.icms.video > source[type="video/mp4"][data-quality="360"]')?.src;return n?{url:at(n)}:this.returnBaseData(t)}getVideoDataByNext(t){try{const n=document.getElementById("__NEXT_DATA__")?.textContent;if(!n)throw new ee("Not found __NEXT_DATA__ content");const i=JSON.parse(n),{props:{pageProps:{page:{description:o,title:r,video:{videoMetadata:{duration:s},assets:a}}}}}=i,l=a.find(c=>c.height===360&&c.url.includes(".mp4"))?.url;if(!l)throw new ee("Not found video URL in assets");return {url:at(l),duration:s,title:r,description:o}}catch(n){return C.warn(`Failed to get ign video data by video ID: ${t}, because ${n.message}. Using clear link instead...`),this.returnBaseData(t)}}async getVideoData(t){return document.getElementById("__NEXT_DATA__")?this.getVideoDataByNext(t):this.getVideoDataBySource(t)}async getVideoId(t){return /([^/]+)\/([\d]+)\/video\/([^/]+)/.exec(t.pathname)?.[0]??/\/videos\/([^/]+)/.exec(t.pathname)?.[0]}}class $a extends T{async getVideoId(t){return /video\/([^/]+)/.exec(t.pathname)?.[1]}}class Ua extends T{async getVideoData(t){try{const n=document.querySelector("#incflix-stream source:first-of-type");if(!n)throw new M("Failed to find source element");const i=n.getAttribute("src");if(!i)throw new M("Failed to find source link");const o=new URL(i.startsWith("//")?`https:${i}`:i);return o.searchParams.append("media-proxy","video.mp4"),{url:at(o)}}catch(n){C.error(`Failed to get Incestflix data by videoId: ${t}`,n.message);return}}async getVideoId(t){return /\/watch\/([^/]+)/.exec(t.pathname)?.[1]}}class Wa extends T{API_ORIGIN="https://kick.com/api";async getClipInfo(t){try{const i=await(await this.fetch(`${this.API_ORIGIN}/v2/clips/${t}`)).json(),{clip_url:o,duration:r,title:s}=i.clip;return {url:o,duration:r,title:s}}catch(n){C.error(`Failed to get kick clip info by clipId: ${t}.`,n.message);return}}async getVideoInfo(t){try{const i=await(await this.fetch(`${this.API_ORIGIN}/v1/video/${t}`)).json(),{source:o,livestream:r}=i,{session_title:s,duration:a}=r;return {url:o,duration:Math.round(a/1e3),title:s}}catch(n){C.error(`Failed to get kick video info by videoId: ${t}.`,n.message);return}}async getVideoData(t){return t.startsWith("videos")?await this.getVideoInfo(t.replace("videos/","")):await this.getClipInfo(t.replace("clips/",""))}async getVideoId(t){return /([^/]+)\/((videos|clips)\/([^/]+))/.exec(t.pathname)?.[2]}}class za extends T{async getVideoData(t){try{const n=document.querySelector(".ksr-video-player > video"),i=n?.querySelector("source[type^='video/mp4']")?.src;if(!i)throw new M("Failed to find video URL");const o=n?.querySelectorAll("track")??[];return {url:i,subtitles:Array.from(o).reduce((r,s)=>{const a=s.getAttribute("srclang"),l=s.getAttribute("src");return !a||!l||r.push({language:X(a),url:l,format:"vtt",source:"kickstarter"}),r},[])}}catch(n){C.error(`Failed to get Kickstarter data by videoId: ${t}`,n.message);return}}async getVideoId(t){return t.pathname.slice(1)}}class qa extends T{API_ORIGIN=window.location.origin;getSecureData(t){try{const[n,i,o]=t.split("/").filter(v=>v),r=Array.from(document.getElementsByTagName("script")),s=r.filter(v=>v.innerHTML.includes(`videoId = "${i}"`)||v.innerHTML.includes(`serialId = Number(${i})`));if(!s.length)throw new M("Failed to find secure script");const a=s[0]?.textContent?.trim();if(!a)throw new M("Secure script content is empty");const l=/'{[^']+}'/.exec(a)?.[0];if(!l)throw new M("Secure json wasn't found in secure script");const c=JSON.parse(l.replaceAll("'",""));if(n!=="serial")return {videoType:n,videoId:i,hash:o,...c};const d=r.find(v=>v.innerHTML.includes("var videoInfo = {}"))?.textContent?.trim();if(!d)throw new M("Failed to find videoInfo content");const u=/videoInfo\.type\s+?=\s+?'([^']+)'/.exec(d)?.[1],h=/videoInfo\.id\s+?=\s+?'([^']+)'/.exec(d)?.[1],m=/videoInfo\.hash\s+?=\s+?'([^']+)'/.exec(d)?.[1];if(!u||!h||!m)throw new M("Failed to parse videoInfo content");return {videoType:u,videoId:h,hash:m,...c}}catch(n){return C.error(`Failed to get kodik secure data by videoPath: ${t}.`,n.message),false}}async getFtor(t){const{videoType:n,videoId:i,hash:o,d:r,d_sign:s,pd:a,pd_sign:l,ref:c,ref_sign:d}=t;try{return await(await this.fetch(`${this.API_ORIGIN}/ftor`,{method:"POST",headers:{"User-Agent":K.userAgent,Origin:this.API_ORIGIN,Referer:`${this.API_ORIGIN}/${n}/${i}/${o}/360p`},body:new URLSearchParams({d:r,d_sign:s,pd:a,pd_sign:l,ref:decodeURIComponent(c),ref_sign:d,bad_user:"false",cdn_is_working:"true",info:"{}",type:n,hash:o,id:i})})).json()}catch(u){return C.error(`Failed to get kodik video data (type: ${n}, id: ${i}, hash: ${o})`,u.message),false}}decryptUrl(t){return `https:${atob(t.replace(/[a-zA-Z]/g,i=>{const o=i.charCodeAt(0)+18,r=i<="Z"?90:122;return String.fromCharCode(r>=o?o:o-26)}))}`}async getVideoData(t){const n=this.getSecureData(t);if(!n)return;const i=await this.getFtor(n);if(!i)return;const r=Object.entries(i.links[i.default.toString()]).find(([,s])=>s.type==="application/x-mpegURL")?.[1];if(r)return {url:r.src.startsWith("//")?`https:${r.src}`:this.decryptUrl(r.src)}}async getVideoId(t){return /\/(uv|video|seria|episode|season|serial)\/([^/]+)\/([^/]+)\/([\d]+)p/.exec(t.pathname)?.[0]}}class Ga extends Vt{SUBTITLE_SOURCE="linkedin";async getVideoData(t){const n=this.getVideoDataByPlayer(t);if(!n)return;const{url:i,duration:o,subtitles:r}=n;return {url:at(new URL(i)),duration:o,subtitles:r}}async getVideoId(t){return /\/learning\/(([^/]+)\/([^/]+))/.exec(t.pathname)?.[1]}}var Li;(function(e){e.Channel="Channel",e.Video="Video";})(Li||(Li={}));function Ii(e,t=","){const n=e/1e3,i=Math.floor(n/3600),o=Math.floor(n%3600/60),r=Math.floor(n%60),s=Math.floor(e%1e3);return `${i.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}${t}${s.toString().padStart(3,"0")}`}function Pi(e){const t=e.split(" ")?.[0]?.split(":");t.length<3&&t.unshift("00");const[n,i,o]=t,r=+o.replace(/[,.]/,""),s=+i*6e4;return +n*36e5+s+r}function Ci(e,t="srt"){const n=t==="vtt",i=n?".":",",o=e.subtitles.map((r,s)=>(n?"":`${s+1} `)+`${Ii(r.startMs,i)} --> ${Ii(r.startMs+r.durationMs,i)} ${r.text} `).join("").trim();return n?`WEBVTT ${o}`:o}function Ka(e,t="srt"){const n=e.split(/\r?\n\r?\n/g);t==="vtt"&&n.shift(),/^\d+\r?\n/.exec(n?.[0]??"")&&(t="srt");const i=+(t==="srt");return {containsTokens:false,subtitles:n.reduce((r,s)=>{const a=s.trim().split(` `),l=a[i],c=a.slice(i+1).join(` `);if((a.length!==2||!s.includes(" --> "))&&!l?.includes(" --> "))return r.length===0||(r[r.length-1].text+=` ${a.join(` `)}`),r;const[d,u]=l.split(" --> "),h=Pi(d),v=Pi(u)-h;return r.push({text:c,startMs:h,durationMs:v,speakerId:"0"}),r},[])}}function Ya(e){return typeof e!="string"?"json":/^(WEBVTT([^\n]+)?)(\r?\n)/.exec(e)?"vtt":"srt"}function er(e,t="srt"){const n=Ya(e);return n===t?e:n==="json"?Ci(e,t):(e=Ka(e,n),t==="json"?e:Ci(e,t))}class Ja extends T{getClientVersion(){if(!(typeof SENTRY_RELEASE>"u"))return SENTRY_RELEASE.id}async getVideoData(t){try{const n=this.getClientVersion();if(!n)throw new M("Failed to get client version");const i=await this.fetch("https://www.loom.com/graphql",{headers:{"User-Agent":K.userAgent,"content-type":"application/json","x-loom-request-source":`loom_web_${n}`,"apollographql-client-name":"web","apollographql-client-version":n,"Alt-Used":"www.loom.com"},body:`{"operationName":"FetchCaptions","variables":{"videoId":"${t}"},"query":"query FetchCaptions($videoId: ID!, $password: String) {\\n fetchVideoTranscript(videoId: $videoId, password: $password) {\\n ... on VideoTranscriptDetails {\\n id\\n captions_source_url\\n language\\n __typename\\n }\\n ... on GenericError {\\n message\\n __typename\\n }\\n __typename\\n }\\n}"}`,method:"POST"});if(i.status!==200)throw new M("Failed to get data from graphql");const r=(await i.json()).data.fetchVideoTranscript;if(r.__typename==="GenericError")throw new M(r.message);return {url:this.service?.url+t,subtitles:[{format:"vtt",language:X(r.language),source:"loom",url:r.captions_source_url}]}}catch(n){return C.error(`Failed to get Loom video data, because: ${n.message}`),this.returnBaseData(t)}}async getVideoId(t){return /(embed|share)\/([^/]+)?/.exec(t.pathname)?.[2]}}class Xa extends T{API_ORIGIN="https://my.mail.ru";async getVideoMeta(t){try{return await(await this.fetch(`${this.API_ORIGIN}/+/video/meta/${t}?xemail=&ajax_call=1&func_name=&mna=&mnb=&ext=1&_=${Date.now()}`)).json()}catch(n){C.error("Failed to get mail.ru video data",n.message);return}}async getVideoId(t){const n=t.pathname;if(/\/(v|mail|bk|inbox)\//.exec(n))return n.slice(1);const i=/video\/embed\/([^/]+)/.exec(n)?.[1];if(!i)return;const o=await this.getVideoMeta(i);if(o)return o.meta.url.replace("//my.mail.ru/","")}}class ja extends Vt{SUBTITLE_SOURCE="netacad";async getVideoData(t){const n=this.getVideoDataByPlayer(t);if(!n)return;const{url:i,duration:o,subtitles:r}=n;return {url:at(new URL(i)),duration:o,subtitles:r}}async getVideoId(t){return t.pathname+t.search}}class Za extends T{async getVideoId(t){return /([^/]+)\/(view)\/([^/]+)/.exec(t.pathname)?.[0]}}class Qa extends T{async getVideoId(t){return t.hostname==="nico.ms"?t.pathname.replace(/^\//,"").split("/")[0]||void 0:/\/watch\/([^/?#]+)/.exec(t.pathname)?.[1]}}class tl extends T{async getVideoData(t){const n=this.returnBaseData(t);if(!n)return n;try{if(!this.video)throw new Error("Video element not found");const i=this.video.querySelector('source[type^="video/mp4"], source[type^="video/webm"]')?.src;if(!i||!/^https?:\/\//.test(i))throw new Error("Video source not found");return {...n,translationHelp:[{target:"video_file_url",targetUrl:i}]}}catch{return n}}async getVideoId(t){return /gag\/([^/]+)/.exec(t.pathname)?.[1]}}class el extends T{API_ORIGIN="https://odysee.com";async getVideoData(t){try{const i=await(await this.fetch(`${this.API_ORIGIN}/${t}`)).text(),o=/"contentUrl":(\s)?"([^"]+)"/.exec(i)?.[2];if(!o)throw new M("Odysee url doesn't parsed");return {url:o}}catch(n){C.error(`Failed to get odysee video data by video ID: ${t}`,n.message);return}}async getVideoId(t){return t.pathname.slice(1)}}class nl extends T{async getVideoId(t){return /\/video\/(\d+)/.exec(t.pathname)?.[1]}}class il extends T{async getVideoId(t){return /\/([a-z]{2}\/(?:[a-z0-9-]+\/)?(?:replay|videos?|original-series\/episode)\/[\w-]+)\/?$/i.exec(t.pathname)?.[1]}}class ol extends Vt{SUBTITLE_SOURCE="oraclelearn";async getVideoData(t){const n=this.getVideoDataByPlayer(t);if(!n)return;const{url:i,duration:o,subtitles:r}=n,s=this.returnBaseData(t),a=at(new URL(i));return s?{url:s.url,duration:o,subtitles:r,translationHelp:[{target:"video_file_url",targetUrl:a}]}:{url:a,duration:o,subtitles:r}}async getVideoId(t){return /\/ou\/course\/(([^/]+)\/(\d+)\/(\d+))/.exec(t.pathname)?.[1]}}class rl extends T{API_ORIGIN="https://www.patreon.com/api";async getPosts(t){try{return await(await this.fetch(`${this.API_ORIGIN}/posts/${t}?json-api-use-default-includes=false`)).json()}catch(n){return C.error(`Failed to get patreon posts by postId: ${t}.`,n.message),false}}async getVideoData(t){const n=await this.getPosts(t);if(!n)return;const i=n.data.attributes.post_file.url;if(i)return {url:i}}async getVideoId(t){const n=/posts\/([^/]+)/.exec(t.pathname)?.[1];if(n)return n.replace(/[^\d.]/g,"")}}class sl extends T{async getVideoId(t){return /\/w\/([^/]+)/.exec(t.pathname)?.[0]}}class al extends T{async getVideoId(t){return /\/((?:videopopout|[^/]+(?:\/profile)?\/videos)\/[^/?#&/]+)\/?$/.exec(t.pathname)?.[1]??/^\/([^/#?]+)\/?$/.exec(t.pathname)?.[1]}}class ll extends T{async getVideoId(t){return t.searchParams.get("viewkey")??/embed\/([^/]+)/.exec(t.pathname)?.[1]}}class cl extends T{async getVideoData(t){try{if(typeof flashvars>"u")return;const{rnd:n,video_url:i,video_title:o}=flashvars;if(!i||!n)throw new M("Failed to find video source or rnd");const r=new URL(i);r.searchParams.append("rnd",n),C.log("PornTN get_file link",r.href);const s=await this.fetch(r.href,{method:"head"}),a=new URL(s.url);return C.log("PornTN cdn link",a.href),{url:at(a),title:o}}catch(n){C.error(`Failed to get PornTN data by videoId: ${t}`,n.message);return}}async getVideoId(t){return /\/videos\/(([^/]+)\/([^/]+))/.exec(t.pathname)?.[1]}}class dl extends T{API_ORIGIN="https://www.reddit.com";async getContentUrl(t){if(this.service?.additionalData!=="old"){const i=document.querySelector("shreddit-player-2, shreddit-player");return (i?.getAttribute("src")??i?.querySelector('source[type="application/vnd.apple.mpegURL"]')?.getAttribute("src"))?.replaceAll("&","&")}return document.querySelector("[data-hls-url]")?.dataset.hlsUrl?.replaceAll("&","&")}async getVideoData(t){try{const n=await this.getContentUrl(t);if(!n)throw new M("Failed to find content url");return {url:decodeURIComponent(n)}}catch(n){C.error(`Failed to get reddit video data by video ID: ${t}`,n.message);return}}async getVideoId(t){return /\/r\/(([^/]+)\/([^/]+)\/([^/]+)\/([^/]+))/.exec(t.pathname)?.[1]}}class ul extends T{async getVideoData(t){const n=document.querySelector(".jw-video, .media__video_noscript");if(!n)return;let i=n.getAttribute("src");if(i)return i.endsWith(".MP4")&&(i=at(i)),{videoId:t,url:i}}async getVideoId(t){return t.pathname.slice(1)}}class hl extends T{async getVideoId(t){const n=/\/videos?\/(\d+)(?:\/(.+))?\/?$/.exec(t.pathname);if(!n)return;const[,i,o]=n;return o?`${i}/${o.replace(/\/+$/,"")}/`:i}}class fl extends T{async getVideoId(t){return t.pathname.slice(1)}}class pl extends T{async getVideoId(t){return /(?:video|embed)\/([^/]+)/.exec(t.pathname)?.[1]}}class gl extends T{API_ORIGIN="https://learning.sap.com/";async requestKaltura(t,n,i){const o="html5:v3.17.22",r="3.3.0";try{return await(await this.fetch(`https://${t}/api_v3/service/multirequest`,{method:"POST",body:JSON.stringify({1:{service:"session",action:"startWidgetSession",widgetId:`_${n}`},2:{service:"baseEntry",action:"list",ks:"{1:result:ks}",filter:{redirectFromEntryId:i},responseProfile:{type:1,fields:"id,referenceId,name,description,dataUrl,duration,flavorParamsIds,type,dvrStatus,externalSourceType,createdAt,updatedAt,endDate,plays,views,downloadUrl,creatorId"}},3:{service:"baseEntry",action:"getPlaybackContext",entryId:"{2:result:objects:0:id}",ks:"{1:result:ks}",contextDataParams:{objectType:"KalturaContextDataParams",flavorTags:"all"}},apiVersion:r,format:1,ks:"",clientTag:o,partnerId:n}),headers:{"Content-Type":"application/json"}})).json()}catch(s){C.error("Failed to request kaltura data",s.message);return}}async getKalturaData(t){try{const n=document.querySelector('script[data-nscript="beforeInteractive"]');if(!n)throw new M("Failed to find script element");const i=/https:\/\/([^"]+)\/p\/([^"]+)\/embedPlaykitJs\/uiconf_id\/([^"]+)/.exec(n?.src);if(!i)throw new M(`Failed to get sap data for videoId: ${t}`);const[,o,r]=i;let s=document.querySelector("#shadow")?.firstChild?.getAttribute("id");if(!s){const a=document.querySelector("#__NEXT_DATA__");if(!a)throw new M("Failed to find next data element");s=/"sourceId":\s?"([^"]+)"/.exec(a.innerText)?.[1];}if(!o||Number.isNaN(+r)||!s)throw new M(`One of the necessary parameters for getting a link to a sap video in wasn't found for ${t}. Params: kalturaDomain = ${o}, partnerId = ${r}, entryId = ${s}`);return await this.requestKaltura(o,r,s)}catch(n){C.error("Failed to get kaltura data",n.message);return}}async getVideoData(t){const n=await this.getKalturaData(t);if(!n)return;const[,i,o]=n,{duration:r}=i.objects[0],s=o.sources.find(l=>l.format==="url"&&l.protocols==="http,https"&&l.url.includes(".mp4"))?.url;if(!s)return;const a=o.playbackCaptions.map(l=>({language:X(l.languageCode),source:"sap",format:"vtt",url:l.webVttUrl,isAutoGenerated:l.label.includes("auto-generated")}));return {url:s,subtitles:a,duration:r}}async getVideoId(t){return /((courses|learning-journeys)\/([^/]+)(\/[^/]+)?)/.exec(t.pathname)?.[1]}}class ml extends T{async getVideoId(t){return /\/([\da-z]+\/(?:video|play|embed)(?:\/[^/]+)?)\/?$/i.exec(t.pathname)?.[1]??/\/([\da-z]+-[\da-z]+\/playlist\/[^/]+)\/?$/i.exec(t.pathname)?.[1]}}class Cn extends T{static getMediaViewer(){if(!(typeof appMediaViewer>"u"))return appMediaViewer}async getVideoId(t){const n=Cn.getMediaViewer();if(!n||n.live)return;const i=n.target.message;if(i.peer_id._!=="peerChannel")return;const o=i.media;if(o._!=="messageMediaDocument"||o.document.type!=="video")return;const r=i.mid&4294967295;return `${await n.managers.appPeersManager.getPeerUsername(i.peerId)}/${r}`}}class vl extends T{async getVideoId(t){return /(videos|embed)\/[^/]+/.exec(t.pathname)?.[0]}}class Ei extends T{async getVideoId(t){return /([^/]+)\/video\/([^/]+)/.exec(t.pathname)?.[0]}}class bl extends T{async getVideoId(t){const n=t.searchParams.get("vid"),i=/([^/]+)\/([\d]+)/.exec(t.pathname)?.[0];if(!(!n||!i))return `${i}?vid=${n}`}}class yl extends T{API_ORIGIN="https://clips.twitch.tv";async getClipLink(t,n){const i=document.querySelector("script[type='application/ld+json']"),o=t.slice(1);if(i){const c=JSON.parse(i.innerText)["@graph"].find(u=>u["@type"]==="VideoObject")?.creator.url;if(!c)throw new M("Failed to find channel link");return `${c.replace("https://www.twitch.tv/","")}/clip/${o}`}const r=o==="embed",s=document.querySelector(r?".tw-link[data-test-selector='stream-info-card-component__stream-avatar-link']":".clips-player a:not([class])");return s?`${s.href.replace("https://www.twitch.tv/","")}/clip/${r?n:o}`:void 0}async getVideoData(t){const n=document.querySelector('[data-a-target="stream-title"], [data-test-selector="stream-info-card-component__subtitle"]')?.innerText,i=!!document.querySelector('[data-a-target="animated-channel-viewers-count"], .channel-status-info--live, .top-bar--pointer-enabled .tw-channel-status-text-indicator');return {url:this.service?.url+t,isStream:i,title:n}}async getVideoId(t){const n=t.pathname;if(/^m\.twitch\.tv$/.test(n))return /videos\/([^/]+)/.exec(t.href)?.[0]??n.slice(1);if(/^player\.twitch\.tv$/.test(t.hostname))return `videos/${t.searchParams.get("video")}`;const i=/([^/]+)\/(?:clip)\/([^/]+)/.exec(n);if(i)return i[0];if(/^clips\.twitch\.tv$/.test(t.hostname))return await this.getClipLink(n,t.searchParams.get("clip"));const r=/(?:videos)\/([^/]+)/.exec(n);if(r)return r[0];const s=document.querySelector(".home-offline-hero .tw-link");if(s?.href){const a=new URL(s.href);return /(?:videos)\/([^/]+)/.exec(a.pathname)?.[0]}return document.querySelector(".persistent-player")?n:void 0}}class wl extends T{async getVideoId(t){const n=/status\/([^/]+)/.exec(t.pathname)?.[1];if(n)return n;const o=this.video?.closest('[data-testid="tweet"]')?.querySelector('a[role="link"][aria-label]')?.href;return o?/status\/([^/]+)/.exec(o)?.[1]:void 0}}function pn(e){return typeof e=="object"&&e!==null}function Vi(e){return typeof e=="object"&&e!==null}function Ge(e){if(Array.isArray(e))return e.filter(Vi);if(typeof e!="object"||e===null)return [];const t=e;return (Array.isArray(t.Video)?t.Video:Array.isArray(t.video)?t.video:[]).filter(Vi)}function kl(e){if(!pn(e))return [];const t=[];for(const[n,i]of Object.entries(e))!pn(i)||typeof i.url!="string"||t.push({src:i.url,type:typeof i.type=="string"?i.type:void 0,label:typeof i.height=="number"||typeof i.height=="string"?i.height:n});return t}function xl(e){if(typeof e=="number"&&Number.isFinite(e))return e;const t=String(e??"").match(/(\d{3,4})/);return Number(t?.[1]??0)}function Sl(e){if(typeof e.file=="string")return e.file;if(typeof e.src=="string")return e.src}function Tl(e,t){return e.includes("mpegurl")||/\.m3u8(?:$|[?#])/i.test(t)}function Al(e,t){return e.includes("dash")||/\.mpd(?:$|[?#])/i.test(t)}class Ll extends T{API_ORIGIN=`${window.location.origin}/api-2.0`;getModuleData(){const n=(document.querySelector(".ud-app-loader[data-module-id='course-taking']")??document.querySelector("[data-module-id='course-taking']"))?.dataset?.moduleArgs;if(n)try{return JSON.parse(n)}catch{return}}getLectureId(t){const n=/(?:\/learn\/(?:v4\/t\/)?lecture\/|#\/?lecture\/|\/lecture\/view\/\?(?:[^#]*?&)*lecture(?:_|)id=)(\d+)/i;return n.exec(window.location.href)?.[1]??(t?n.exec(`/${t}`)?.[1]:void 0)}getCourseId(t){const n=t,i=this.normalizeId(n?.courseId??n?.course_id??n?.course?.id);if(i)return i;const o=this.normalizeId(document.querySelector("[data-course-id]")?.getAttribute("data-course-id"));if(o)return o;const r=document.documentElement?.innerHTML??"";return /data-course-id=["'](\d+)/i.exec(r)?.[1]??/"courseId"\s*:\s*(\d+)/i.exec(r)?.[1]??/"courseId"\s*:\s*(\d+)/i.exec(r)?.[1]}normalizeId(t){if(typeof t=="number"&&Number.isFinite(t))return String(t);if(typeof t=="string")return /^\d+$/.test(t)?t:void 0}parseJson(t){try{return JSON.parse(t)}catch{const n=t.replaceAll(""",'"').replaceAll(""",'"').replaceAll("'","'").replaceAll("'","'");try{return JSON.parse(n)}catch{return}}}getViewHtmlCandidates(t){if(typeof t!="string"||!t.trim())return [];const n=new DOMParser().parseFromString(t,"text/html"),i=[];for(const o of Array.from(n.querySelectorAll("source"))){const r=o.getAttribute("src");r&&i.push({src:r,type:o.getAttribute("type")??void 0,label:o.getAttribute("data-res")??void 0});}for(const o of Array.from(n.querySelectorAll("[videojs-setup-data]"))){const r=o.getAttribute("videojs-setup-data");if(!r)continue;const s=this.parseJson(r);s&&i.push(...Ge(s.sources));}return i}isErrorData(t){return Object.hasOwn(t,"error")||Object.hasOwn(t,"detail")&&!Object.hasOwn(t,"_class")}async getLectureData(t,n){try{const o=await(await this.fetch(`${this.API_ORIGIN}/users/me/subscribed-courses/${t}/lectures/${n}/?`+new URLSearchParams({"fields[lecture]":"title,description,view_html,asset,download_url,is_free,last_watched_second","fields[asset]":"asset_type,length,stream_url,media_sources,stream_urls,download_urls,external_url,captions,data,thumbnail_sprite,slides,slide_urls,course_is_drmed,media_license_token"}).toString())).json();if(this.isErrorData(o))throw new M(o.detail??"unknown error");return o}catch(i){C.error(`Failed to get lecture data by courseId: ${t} and lectureId: ${n}`,i.message);return}}async getCourseLang(t){try{const i=await(await this.fetch(`${this.API_ORIGIN}/users/me/subscribed-courses/${t}?`+new URLSearchParams({"fields[course]":"locale"}).toString())).json();if(!this.isErrorData(i))return i;const r=await(await this.fetch(`${this.API_ORIGIN}/courses/${t}/?`+new URLSearchParams({"fields[course]":"locale"}).toString())).json();if(this.isErrorData(r))throw new M(r.detail??"unknown error");return r}catch(n){C.error(`Failed to get course lang by courseId: ${t}`,n.message);return}}findVideoUrl(t,n,i,o,r,s,a){const l=[],c=Array.isArray(t)?t:[];for(const k of c)l.push({src:k.src,type:k.type,label:k.label});l.push(...Ge(n)),l.push(...Ge(i)),l.push(...kl(s)),typeof a=="string"&&l.push(...this.getViewHtmlCandidates(a)),typeof o=="string"&&l.push({src:o}),typeof r=="string"&&l.push({src:r});const d=this.video?.currentSrc||this.video?.src;typeof d=="string"&&d&&l.push({src:d});const u=new Map;for(const k of l){const x=Sl(k);if(!x||/^javascript:/i.test(x))continue;const A=xl(k.label??k.quality??k.height),D=String(k.type??"").toLowerCase(),Y=u.get(x);(!Y||A>Y.quality)&&u.set(x,{url:x,type:D,quality:A,isYouTubeWatch:/:\/\/(?:www\.)?youtube\.com\/watch\?/i.test(x)});}const h=Array.from(u.values());if(!h.length)return;const m=h.filter(k=>k.type.includes("mp4")||/\.mp4(?:$|[?#])/i.test(k.url));if(m.length)return m.sort((k,x)=>x.quality-k.quality),m[0]?.url;const v=h.find(k=>Tl(k.type,k.url))?.url;if(v)return v;const b=h.find(k=>Al(k.type,k.url))?.url;if(b)return b;const y=h.find(k=>!k.isYouTubeWatch)?.url;return y||h[0]?.url}getCaptionLocale(t){const n=typeof t.locale_id=="string"?t.locale_id:typeof t.locale?.locale=="string"?t.locale.locale:void 0;return n?X(n):void 0}findSubtitleUrl(t,n){if(!Array.isArray(t))return;const i=t.filter(r=>pn(r)&&(typeof r.url=="string"||typeof r.download_url=="string")),o=i.find(r=>this.getCaptionLocale(r)===n)??i.find(r=>this.getCaptionLocale(r)==="en")??i[0];return o?.url??o?.download_url}async getVideoData(t){const n=this.getModuleData(),i=this.getCourseId(n),o=this.getLectureId(t);if(C.log(`[Udemy] courseId: ${i}, lectureId: ${o}`),!o||!i)return;const r=await this.getLectureData(i,o);if(!r)return;const{title:s,description:a,asset:l,view_html:c}=r,{length:d,media_sources:u,captions:h}=l,m=l,v=m.stream_urls,b=m.download_urls,y=this.findVideoUrl(u,v,b,m.stream_url??m.streamUrl,m.external_url,m.data?.outputs,c);if(!y){C.log("Failed to find video file in asset sources",l);return}let k="en";const A=(await this.getCourseLang(i))?.locale?.locale;typeof A=="string"&&(k=X(A)),_t.includes(k)||(k="en");const D=this.findSubtitleUrl(h,k);return D||C.log("Failed to find subtitle file in captions",h),{...D?{url:this.service?.url+t,translationHelp:[{target:"subtitles_file_url",targetUrl:D},{target:"video_file_url",targetUrl:y}],detectedLanguage:k}:{url:y,translationHelp:null},duration:d,title:s,description:a}}async getVideoId(t){return t.pathname.slice(1)}}class Il extends T{API_KEY="";DEFAULT_SITE_ORIGIN="https://vimeo.com";SITE_ORIGIN=this.service?.url?.slice(0,-1)??this.DEFAULT_SITE_ORIGIN;isErrorData(t){return Object.hasOwn(t,"error")}isPrivatePlayer(){return this.referer&&!this.referer.includes("vimeo.com")&&this.origin.endsWith("player.vimeo.com")}async getViewerData(){try{const n=await(await this.fetch("https://vimeo.com/_next/viewer")).json(),{apiUrl:i,jwt:o}=n;return this.API_ORIGIN=`https://${i}`,this.API_KEY=`jwt ${o}`,n}catch(t){return C.error("Failed to get default viewer data.",t.message),false}}async getVideoInfo(t){try{const n=new URLSearchParams({fields:"name,link,description,duration"}).toString(),o=await(await this.fetch(`${this.API_ORIGIN}/videos/${t}?${n}`,{headers:{Authorization:this.API_KEY}})).json();if(this.isErrorData(o))throw new Error(o.developer_message??o.error);return o}catch(n){return C.error(`Failed to get video info by video ID: ${t}`,n.message),false}}async getPrivateVideoSource(t){try{const{default_cdn:n,cdns:i}=t.dash,o=i[n].url,r=await this.fetch(o);if(r.status!==200)throw new M(await r.text());const s=await r.json(),a=new URL(s.base_url,o),l=s.audio.find(m=>m.mime_type==="audio/mp4"&&m.format==="dash");if(!l)throw new M("Failed to find video data");const c=l.segments?.[0]?.url;if(!c)throw new M("Failed to find first segment url");const[d,u]=c.split("?",2),h=new URLSearchParams(u);return h.delete("range"),new URL(`${l.base_url}${d}?${h.toString()}`,a).href}catch(n){return C.error("Failed to get private video source",n.message),false}}async getPrivateVideoInfo(t){try{if(typeof playerConfig>"u")return;const n=await this.getPrivateVideoSource(playerConfig.request.files);if(!n)throw new M("Failed to get private video source");const{video:{title:i,duration:o},request:{text_tracks:r}}=playerConfig;return {url:`${this.SITE_ORIGIN}/${t}`,video_url:n,title:i,duration:o,subs:r}}catch(n){return C.error(`Failed to get private video info by video ID: ${t}`,n.message),false}}async getSubsInfo(t){try{const n=new URLSearchParams({per_page:"100",fields:"language,type,link"}).toString(),o=await(await this.fetch(`${this.API_ORIGIN}/videos/${t}/texttracks?${n}`,{headers:{Authorization:this.API_KEY}})).json();if(this.isErrorData(o))throw new Error(o.developer_message??o.error);return o.data}catch(n){return C.error(`Failed to get subtitles info by video ID: ${t}`,n.message),[]}}async getVideoData(t){if(this.isPrivatePlayer()){const u=await this.getPrivateVideoInfo(t);if(!u)return;const{url:h,subs:m,video_url:v,title:b,duration:y}=u,k=m.map(A=>({language:X(A.lang),source:"vimeo",format:"vtt",url:this.SITE_ORIGIN+A.url,isAutoGenerated:A.lang.includes("autogenerated")})),x=k.length?[{target:"video_file_url",targetUrl:v},{target:"subtitles_file_url",targetUrl:k[0].url}]:null;return {...x?{url:h,translationHelp:x}:{url:v},subtitles:k,title:b,duration:y}}if(!this.extraInfo)return this.returnBaseData(t);if(t.includes("/")&&(t=t.replace("/",":")),!await this.getViewerData())return this.returnBaseData(t);const o=await this.getVideoInfo(t);if(!o)return this.returnBaseData(t);const s=(await this.getSubsInfo(t)).map(u=>({language:X(u.language),source:"vimeo",format:"vtt",url:u.link,isAutoGenerated:u.language.includes("autogen")})),{link:a,duration:l,name:c,description:d}=o;return {url:a,title:c,description:d,subtitles:s,duration:l}}async getVideoId(t){const n=/video\/[^/]+$/.exec(t.pathname)?.[0];if(this.isPrivatePlayer())return n;if(n){const o=t.searchParams.get("h"),r=n.replace("video/","");return o?`${r}/${o}`:r}const i=/channels\/[^/]+\/([^/]+)/.exec(t.pathname)?.[1]??/groups\/[^/]+\/videos\/([^/]+)/.exec(t.pathname)?.[1]??/(showcase|album)\/[^/]+\/video\/([^/]+)/.exec(t.pathname)?.[2];return i||/([^/]+\/)?[^/]+$/.exec(t.pathname)?.[0]}}class En extends T{static getPlayer(){if(!(typeof Videoview>"u"))try{return Videoview?.getPlayerObject?.()}catch{return}}async getVideoData(t){const n=new URL(window.location.href),i=En.getPlayer();if(!i){const o=this.returnBaseData(t);return o&&{...o,url:te(t,n)}}try{const{description:o,duration:r,md_title:s}=i.vars,l=new DOMParser().parseFromString(o,"text/html"),c=Array.from(l.body.childNodes).filter(u=>u.nodeName!=="BR").map(u=>u.textContent).join(` `);let d;return Object.hasOwn(i.vars,"subs")&&(d=i.vars.subs.map(u=>({language:X(u.lang),source:"vk",format:"vtt",url:u.url,isAutoGenerated:!!u.is_auto}))),{url:te(t,n),title:s,description:c,duration:r,subtitles:d}}catch(o){C.error(`Failed to get VK video data, because: ${o.message}`);const r=this.returnBaseData(t);return r&&{...r,url:te(t,n)}}}async getVideoId(t){const n=/^\/((?:video|clip)-?\d+_\d+)(?:\/)?$/.exec(t.pathname);if(n)return n[1];const i=/\/playlist\/[^/]+\/(video-?\d+_\d+)/.exec(t.pathname);if(i)return i[1];const o=t.searchParams.get("z");if(o)return o.split("/")[0];const r=t.searchParams.get("oid"),s=t.searchParams.get("id");if(r&&s){const a=Math.abs(Number.parseInt(r,10));if(!Number.isNaN(a))return `video-${a}_${s}`}}}class Pl extends T{async getVideoId(t){return /(video|embed)\/(\d+)(\/[^/]+\/)?/.exec(t.pathname)?.[0]}}const Cl=/^\d+:(?:[\da-f]{32}|\d{16,})$/i,El=/^[A-Za-z0-9]+$/,Vl=/^(?:www\.)?weibo\.com$/,Ml=/^\/newlogin\/?$/;class _l extends T{async getVideoId(t){if(t.hostname==="video.weibo.com"){const i=t.searchParams.get("fid");return !i||!Cl.test(i)?void 0:`tv/show/${i}`}if(Vl.test(t.host)&&Ml.test(t.pathname)){const i=t.searchParams.get("url");if(i)try{const r=new URL(i,t.origin);if(r.href!==t.href){const s=await this.getVideoId(r);if(s)return s}}catch{}const o=t.searchParams.get("layerid");if(o&&El.test(o))return `0/${o}`}const n=t.pathname.replace(/\/+$/,"");if(/^\/\d+\/[A-Za-z0-9]+$/.test(n)||/^\/0\/[A-Za-z0-9]+$/.test(n)||/^\/tv\/show\/\d+:(?:[\da-f]{32}|\d{16,})$/i.test(n))return n.slice(1)}}class Ol extends T{API_ORIGIN="https://global.apis.naver.com/weverse/wevweb";API_APP_ID="be4d79eb8fc7bd008ee82c8ec4ff6fd4";API_HMAC_KEY="1b9cb6378d959b45714bec49971ade22e6e24e42";HEADERS={Accept:"application/json, text/plain, */*",Origin:"https://weverse.io",Referer:"https://weverse.io/"};getURLData(){return {appId:this.API_APP_ID,language:"en",os:"WEB",platform:"WEB",wpf:"pc"}}async createHash(t){const n=Date.now(),i=t.substring(0,Math.min(255,t.length))+n,o=await Ys(this.API_HMAC_KEY,i);if(!o)throw new M("Failed to get weverse HMAC signature");return {wmsgpad:n.toString(),wmd:o}}async getHashURLParams(t){const n=await this.createHash(t);return new URLSearchParams(n).toString()}async getPostPreview(t){const n=`/post/v1.0/post-${t}/preview?`+new URLSearchParams({fieldSet:"postForPreview",...this.getURLData()}).toString();try{const i=await this.getHashURLParams(n);return await(await this.fetch(`${this.API_ORIGIN+n}&${i}`,{headers:this.HEADERS})).json()}catch(i){return C.error(`Failed to get weverse post preview by postId: ${t}`,i.message),false}}async getVideoInKey(t){const n=`/video/v1.1/vod/${t}/inKey?`+new URLSearchParams({gcc:"RU",...this.getURLData()}).toString();try{const i=await this.getHashURLParams(n);return await(await this.fetch(`${this.API_ORIGIN+n}&${i}`,{method:"POST",headers:this.HEADERS})).json()}catch(i){return C.error(`Failed to get weverse InKey by videoId: ${t}`,i.message),false}}async getVideoInfo(t,n,i){const o=Date.now();try{const r=new URLSearchParams({key:n,sid:i,nonce:o.toString(),devt:"html5_pc",prv:"N",aup:"N",stpb:"N",cpl:"en",env:"prod",lc:"en",adi:JSON.stringify([{adSystem:null}]),adu:"/"}).toString();return await(await this.fetch(`https://global.apis.naver.com/rmcnmv/rmcnmv/vod/play/v2.0/${t}?`+r,{headers:this.HEADERS})).json()}catch(r){return C.error(`Failed to get weverse video info (infraVideoId: ${t}, inkey: ${n}, serviceId: ${i}`,r.message),false}}extractVideoInfo(t){return t.find(n=>n.useP2P===false&&n.source.includes(".mp4"))}async getVideoData(t){const n=await this.getPostPreview(t);if(!n)return;const{videoId:i,serviceId:o,infraVideoId:r}=n.extension.video;if(!(i&&o&&r))return;const s=await this.getVideoInKey(i);if(!s)return;const a=await this.getVideoInfo(r,s.inKey,o);if(!a)return;const l=this.extractVideoInfo(a.videos.list);if(l)return {url:l.source,duration:l.duration}}async getVideoId(t){return /([^/]+)\/(live|media)\/([^/]+)/.exec(t.pathname)?.[3]}}class Dl extends T{async getVideoId(t){return /\/(videos\/[^/]+-[\dA-Za-z]+)\/?$/.exec(t.pathname)?.[1]}}class Bl extends T{async getVideoId(t){return /[^/]+\/[^/]+$/.exec(t.pathname)?.[0]}}class Rl extends T{API_ORIGIN=window.location.origin;CLIENT_PREFIX="/client/disk";INLINE_PREFIX="/i/";DISK_PREFIX="/d/";isErrorData(t){return Object.hasOwn(t,"error")}async getClientVideoData(t){const i=new URL(window.location.href).searchParams.get("idDialog");if(!i)return;const o=document.querySelector("#preloaded-data");if(o)try{const r=JSON.parse(o.innerText),{idClient:s,sk:a}=r.config,c=await(await this.fetch(`${this.API_ORIGIN}/models-v2?m=mpfs/info`,{method:"POST",body:JSON.stringify({apiMethod:"mpfs/info",connection_id:s,requestParams:{path:i},sk:a}),headers:{"Content-Type":"application/json"}})).json();if(this.isErrorData(c))throw new M(c.error?.message??c.error?.code);if(c?.type!=="file")throw new M("Failed to get resource info");const{meta:{short_url:d,video_info:u},name:h}=c;if(!u)throw new M("There's no video open right now");if(!d)throw new M("Access to the video is limited");const m=this.clearTitle(h),v=Math.round(u.duration/1e3);return {url:d,title:m,duration:v}}catch(r){C.error(`Failed to get yandex disk video data by video ID: ${t}, because ${r.message}`);return}}clearTitle(t){return t.replace(/(\.[^.]+)$/,"")}getBodyHash(t,n){const i=JSON.stringify({hash:t,sk:n});return encodeURIComponent(i)}async fetchList(t,n){const i=this.getBodyHash(t,n),r=await(await this.fetch(`${this.API_ORIGIN}/public/api/fetch-list`,{method:"POST",body:i})).json();if(Object.hasOwn(r,"error"))throw new M("Failed to fetch folder list");return r.resources}async getDownloadUrl(t,n){const i=this.getBodyHash(t,n),r=await(await this.fetch(`${this.API_ORIGIN}/public/api/download-url`,{method:"POST",body:i})).json();if(r.error)throw new M("Failed to get download url");return r.data.url}async getDiskVideoData(t){try{const n=document.getElementById("store-prefetch");if(!n)throw new M("Failed to get prefetch data");const i=t.split("/").slice(3);if(!i.length)throw new M("Failed to find video file path");const o=JSON.parse(n.innerText),{resources:r,rootResourceId:s,environment:{sk:a}}=o,l=r[s],c=i.length-1,d=i.filter((Y,$)=>$!==c).join("/");let u=Object.values(r);d.includes("/")&&(u=await this.fetchList(`${l.hash}:/${d}`,a));const h=u.find(Y=>Y.name===i[c]);if(!h)throw new M("Failed to find resource");if(h&&h.type==="dir")throw new M("Path is dir, but expected file");const{meta:{short_url:m,mediatype:v,videoDuration:b},path:y,name:k}=h;if(v!=="video")throw new M("Resource isn't a video");const x=this.clearTitle(k),A=Math.round(b/1e3);if(m)return {url:m,duration:A,title:x};const D=await this.getDownloadUrl(y,a);return {url:at(new URL(D)),duration:A,title:x}}catch(n){C.error(`Failed to get yandex disk video data by disk video ID: ${t}`,n.message);return}}async getVideoData(t){return t.startsWith(this.INLINE_PREFIX)||/^\/d\/([^/]+)$/.exec(t)?{url:this.service?.url+t.slice(1)}:(t=decodeURIComponent(t),t.startsWith(this.CLIENT_PREFIX)?await this.getClientVideoData(t):await this.getDiskVideoData(t))}async getVideoId(t){if(t.pathname.startsWith(this.CLIENT_PREFIX))return t.pathname+t.search;const n=/\/i\/([^/]+)/.exec(t.pathname)?.[0];return n||(/\/d\/([^/]+)/.exec(t.pathname)?t.pathname:void 0)}}class Nl extends T{async getVideoId(t){return /v_show\/id_[\w=]+/.exec(t.pathname)?.[0]}}class _ extends T{static isMobile(){return /^m\.youtube\.com$/.test(window.location.hostname)}static getPlayer(){return window.location.pathname.startsWith("/shorts/")&&!_.isMobile()?document.querySelector("#shorts-player"):document.querySelector("#movie_player")}static getPlayerResponse(){return _.getPlayer()?.getPlayerResponse?.call(void 0)}static getPlayerData(){return _.getPlayer()?.getVideoData?.call(void 0)}static getVolume(){const t=_.getPlayer();return t?.getVolume?t.getVolume()/100:1}static setVolume(t){const n=_.getPlayer();return n?.setVolume?(n.setVolume(Math.round(t*100)),true):false}static isMuted(){const t=_.getPlayer();return t?.isMuted?t.isMuted():false}static videoSeek(t,n){C.log("videoSeek",n);const o=(_.getPlayer()?.getProgressState()?.seekableEnd??t.currentTime)-n;t.currentTime=o;}static getPoToken(){const t=_.getPlayer();if(!t)return;const n=t.getAudioTrack?.call(void 0);if(!n?.captionTracks?.length)return;const i=n.captionTracks.find(o=>o.url.includes("&pot="));if(i)return /&pot=([^&]+)/.exec(i.url)?.[1]}static getGlobalConfig(){return typeof yt<"u"?yt?.config_:typeof ytcfg<"u"?ytcfg?.data_:void 0}static getDeviceParams(){const t=_.getGlobalConfig();if(!t)return "c=WEB";const n=t.INNERTUBE_CONTEXT?.client,i=new URLSearchParams(t.DEVICE);return i.delete("ceng"),i.delete("cengver"),i.set("c",n?.clientName??t.INNERTUBE_CLIENT_NAME),i.set("cver",n?.clientVersion??t.INNERTUBE_CLIENT_VERSION),i.set("cplayer","UNIPLAYER"),i.toString()}static getSubtitles(t){const i=_.getPlayerResponse()?.captions?.playerCaptionsTracklistRenderer;if(!i)return [];const o=i.captionTracks??[],s=(i.translationLanguages??[]).find(d=>d.languageCode===t),l=o.find(d=>d?.kind==="asr")?.languageCode??"en",c=o.reduce((d,u)=>{if(!("languageCode"in u))return d;const h=u.languageCode?X(u.languageCode):void 0,m=u.baseUrl;if(!h||!m)return d;const v=`${m.startsWith("http")?m:`${window.location.origin}/${m}`}&fmt=json3`;return d.push({source:"youtube",format:"json",language:h,isAutoGenerated:u?.kind==="asr",url:v}),s&&u.isTranslatable&&u.languageCode===l&&t!==h&&d.push({source:"youtube",format:"json",language:t,isAutoGenerated:u?.kind==="asr",translatedFromLanguage:h,url:`${v}&tlang=${t}`}),d},[]);return C.log("youtube subtitles:",c),c}static getLanguage(){if(!_.isMobile()){const o=_.getPlayer()?.getAudioTrack?.call(void 0)?.getLanguageInfo();if(o&&o.id!=="und")return X(o.id.split(".")[0])}const n=_.getPlayerResponse()?.captions?.playerCaptionsTracklistRenderer.captionTracks.find(i=>i.kind==="asr"&&i.languageCode);return n?X(n.languageCode):void 0}async getVideoData(t){const{title:n}=_.getPlayerData()??{},{shortDescription:i,isLive:o,title:r}=_.getPlayerResponse()?.videoDetails??{},s=_.getSubtitles(this.language);let a=_.getLanguage();a&&!_t.includes(a)&&(a=void 0);const l=_.getPlayer()?.getDuration?.call(void 0)??void 0;return {url:this.service?.url+t,isStream:o,title:r,localizedTitle:n,detectedLanguage:a,description:i,subtitles:s,duration:l}}async getVideoId(t){if(t.hostname==="youtu.be"&&(t.search=`?v=${t.pathname.replace("/","")}`,t.pathname="/watch"),t.searchParams.has("enablejsapi")){const n=_.getPlayer()?.getVideoUrl();t=n?new URL(n):t;}return /(?:watch|embed|shorts|live)\/([^/]+)/.exec(t.pathname)?.[1]??t.searchParams.get("v")}}const Fl=/^\/play\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)\/?$/i;class Hl extends T{async getVideoId(t){const n=Fl.exec(t.pathname);if(!n)return;const[,i,o,r]=n;return `${i}/${o}/${r}`}}const nr={[g.mailru]:Xa,[g.weverse]:Ol,[g.weibo]:_l,[g.kodik]:qa,[g.patreon]:rl,[g.reddit]:dl,[g.bannedvideo]:Ta,[g.kick]:Wa,[g.appledeveloper]:ka,[g.epicgames]:Ba,[g.odysee]:el,[g.coursehunterLike]:Ea,[g.twitch]:yl,[g.sap]:gl,[g.linkedin]:Ga,[g.vimeo]:Il,[g.yandexdisk]:Rl,[g.vk]:En,[g.trovo]:bl,[g.incestflix]:Ua,[g.porntn]:cl,[g.googledrive]:Fa,[g.bilibili]:Aa,[g.xvideos]:Bl,[g.xhamster]:Dl,[g.spankbang]:ml,[g.rule34video]:hl,[g.picarto]:al,[g.olympicsreplay]:il,[g.watchpornto]:Pl,[g.archive]:xa,[g.dailymotion]:Ma,[g.youku]:Nl,[g.egghead]:Da,[g.newgrounds]:Za,[g.okru]:nl,[g.peertube]:sl,[g.eporner]:Ra,[g.bitchute]:La,[g.rutube]:pl,[g.facebook]:Na,[g.rumble]:fl,[g.twitter]:wl,[g.pornhub]:ll,[g.tiktok]:Ei,[g.proxitok]:Ei,[g.nine_gag]:tl,[g.youtube]:_,[g.invidious]:_,[g.piped]:_,[g.zdf]:Hl,[g.dzen]:Oa,[g.cloudflarestream]:Ca,[g.loom]:Ja,[g.rtnews]:ul,[g.bitview]:Ia,[g.thisvid]:vl,[g.ign]:Ha,[g.bunkr]:Pa,[g.imdb]:$a,[g.telegram]:Cn,[g.niconico]:Qa,[U.udemy]:Ll,[U.coursera]:Pn,[U.douyin]:Pe,[U.artstation]:Sa,[U.kickstarter]:za,[U.oraclelearn]:ol,[U.deeplearningai]:_a,[U.netacad]:ja};class ir{helpersData;constructor(t={}){this.helpersData=t;}getHelper(t){return new nr[t](this.helpersData)}}function or(e){return e in nr}function $l(){if(pa.exec(window.location.href))return [];const e=window.location.hostname,t=new URL(window.location.href),n=i=>i instanceof RegExp?i.test(e):typeof i=="string"?e.includes(i):typeof i=="function"?i(t):false;return wa.filter(i=>!!i.match&&(Array.isArray(i.match)?i.match.some(n):n(i.match))&&i.host&&i.url)}async function rr(e,t={}){const n=new URL(window.location.href),i=e.host;return or(i)?await new ir(t).getHelper(i).getVideoId(n):i===g.custom?n.href:void 0}async function Ul(e,t={}){const n=new URL(window.location.href),i=await rr(e,t);if(!i)throw new ee(`Entered unsupported link: "${e.host}"`);const o=n.origin;if([g.peertube,g.coursehunterLike,g.cloudflarestream].includes(e.host)&&(e.url=o),e.rawResult)return {url:i,videoId:i,host:e.host,duration:void 0};if(!e.needExtraData)return e.host===g.vk?{url:te(i,n),videoId:i,host:e.host,duration:void 0}:{url:e.url+i,videoId:i,host:e.host,duration:void 0};if(!or(e.host))throw new ee(`No helper is available for "${e.host}"`);const s=await new ir({...t,service:e,origin:o}).getHelper(e.host).getVideoData(i);if(!s)throw new ee(`Failed to get video raw url for ${e.host}`);return {...s,url:e.host===g.vk?te(i,n):s.url,videoId:i,host:e.host}}const ne={version:"1.0.6",debug:false,fetchFn:fetch.bind(window)},q={log:(...e)=>{if(ne.debug)return console.log(`%c✦ chaimu.js v${ne.version} ✦`,"background: #000; color: #fff; padding: 0 8px",...e)}},Mi=["playing","ratechange","play","waiting","pause","seeked"];function Vn(){const e=window.AudioContext||window.webkitAudioContext;return e?new e:void 0}class sr{static name="BasePlayer";chaimu;fetch;_src;fetchOpts;constructor(t,n){this.chaimu=t,this._src=n,this.fetch=this.chaimu.fetchFn,this.fetchOpts=this.chaimu.fetchOpts;}async init(){return this}async clear(){return this}lipSync(t=false){return this}handleVideoEvent=t=>(q.log(`handle video ${t.type}`),this.lipSync(t.type),this);removeVideoEvents(){for(const t of Mi)this.chaimu.video?.removeEventListener(t,this.handleVideoEvent);return this}addVideoEvents(){for(const t of Mi)this.chaimu.video?.addEventListener(t,this.handleVideoEvent);return this}async play(){return this}async pause(){return this}get name(){return this.constructor.name}set src(t){this._src=t;}get src(){return this._src}get currentSrc(){return this._src}set volume(t){}get volume(){return 0}get playbackRate(){return 0}set playbackRate(t){}get currentTime(){return 0}}class Wl extends sr{static name="AudioPlayer";audio;gainNode;audioSource;constructor(t,n){super(t,n),this.updateAudio();}initAudioBooster(){return this.chaimu.audioContext?(this.disconnectAudioNodes(),this.gainNode=this.chaimu.audioContext.createGain(),this.gainNode.connect(this.chaimu.audioContext.destination),this.audioSource=this.chaimu.audioContext.createMediaElementSource(this.audio),this.audioSource.connect(this.gainNode),this):this}disconnectAudioNodes(){this.audioSource&&(this.audioSource.disconnect(),this.audioSource=void 0),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=void 0);}updateAudio(){return this.audio=new Audio(this.src),this.audio.crossOrigin="anonymous",this}async init(){return this.updateAudio(),this.initAudioBooster(),this}audioErrorHandle=t=>{console.error("[AudioPlayer]",t);};lipSync(t=false){if(q.log("[AudioPlayer] lipsync video",this.chaimu.video),!this.chaimu.video)return this;if(this.audio.currentTime=this.chaimu.video.currentTime,this.audio.playbackRate=this.chaimu.video.playbackRate,!t)return q.log("[AudioPlayer] lipsync mode isn't set"),this;switch(q.log(`[AudioPlayer] lipsync mode is ${t}`),t){case "play":case "playing":case "seeked":return this.chaimu.video.paused||this.syncPlay(),this;case "pause":case "waiting":return this.pause(),this;default:return this}}async clear(){return this.audio.pause(),this.audio.src="",this.audio.removeAttribute("src"),this.disconnectAudioNodes(),this}syncPlay(){return q.log("[AudioPlayer] sync play called"),this.audio&&this.audio.play().catch(this.audioErrorHandle),this}async play(){return q.log("[AudioPlayer] play called"),this.audio&&await this.audio.play().catch(this.audioErrorHandle),this}async pause(){return q.log("[AudioPlayer] pause called"),this.audio&&this.audio.pause(),this}set src(t){if(this._src=t,!t){this.clear();return}this.audio.src=t;}get src(){return this._src}get currentSrc(){return this.audio.currentSrc}set volume(t){if(this.gainNode){this.gainNode.gain.value=t;return}this.audio.volume=t;}get volume(){return this.gainNode?this.gainNode.gain.value:this.audio.volume}get playbackRate(){return this.audio.playbackRate}set playbackRate(t){this.audio.playbackRate=t;}get currentTime(){return this.audio.currentTime}}class zl extends sr{static name="ChaimuPlayer";audioBuffer;audioElement;mediaElementSource;gainNode;blobUrl;isClearing=false;isInitializing=false;clearingPromise;async fetchAudio(){if(!this._src)throw new Error("No audio source provided");if(!this.chaimu.audioContext)throw new Error("No audio context available");q.log(`[ChaimuPlayer] Fetching audio from ${this._src}...`);let t;try{const n=await this.fetch(this._src,this.fetchOpts);q.log("[ChaimuPlayer] Decoding fetched audio...");const i=await n.arrayBuffer(),o=new Blob([i]);t=URL.createObjectURL(o),this.audioBuffer=await this.chaimu.audioContext.decodeAudioData(i),this.blobUrl&&URL.revokeObjectURL(this.blobUrl),this.blobUrl=t,t=void 0;}catch(n){throw t&&URL.revokeObjectURL(t),new Error(`Failed to fetch audio file, because ${n.message}`)}return this}initAudioBooster(){return this.chaimu.audioContext?(this.disconnectAudioNodes(),this.gainNode=this.chaimu.audioContext.createGain(),this):this}disconnectAudioNodes(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=void 0),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=void 0);}async init(){if(this.isInitializing)throw new Error("Initialization already in progress");this.isInitializing=true;try{return await this.fetchAudio(),this.initAudioBooster(),this.createAudioElement(),this}finally{this.isInitializing=false;}}createAudioElement(){if(!this.chaimu.audioContext)throw new Error("No audio context available");if(!this.blobUrl)throw new Error("No blob URL available.");const t=new Audio(this.blobUrl);t.crossOrigin="anonymous","preservesPitch"in t&&(t.preservesPitch=true,"mozPreservesPitch"in t&&(t.mozPreservesPitch=true),"webkitPreservesPitch"in t&&(t.webkitPreservesPitch=true)),this.audioElement=t,this.mediaElementSource=this.chaimu.audioContext.createMediaElementSource(t),this.mediaElementSource.connect(this.gainNode),this.gainNode.connect(this.chaimu.audioContext.destination);}lipSync(t=false){if(q.log("[ChaimuPlayer] lipsync video",this.chaimu.video,this),!this.chaimu.video)return this;if(!t)return q.log("[ChaimuPlayer] lipsync mode isn't set"),this;switch(q.log(`[ChaimuPlayer] lipsync mode is ${t}`),t){case "play":case "playing":case "ratechange":case "seeked":return this.chaimu.video.paused||this.start(),this;case "pause":case "waiting":return this.pause(),this;default:return this}}async reopenCtx(){if(!this.chaimu.audioContext)throw new Error("No audio context available");try{this.chaimu.audioContext.state!=="closed"&&await this.chaimu.audioContext.close();}catch(t){q.log("[ChaimuPlayer] Failed to close audio context:",t);}return this.chaimu.audioContext=Vn(),this}async clear(){if(this.isClearing&&this.clearingPromise)return this.clearingPromise;if(!this.chaimu.audioContext)throw new Error("No audio context available");return q.log("clear audio context"),this.isClearing=true,this.clearingPromise=(async()=>{try{await this.pause(),this.audioElement&&(this.audioElement.pause(),this.audioElement=void 0),this.blobUrl&&(URL.revokeObjectURL(this.blobUrl),this.blobUrl=void 0),this.disconnectAudioNodes();const t=this.gainNode?this.gainNode.gain.value:1;return await this.reopenCtx(),this.chaimu.audioContext&&(this.initAudioBooster(),this.volume=t),this}finally{this.isClearing=false,this.clearingPromise=void 0;}})(),this.clearingPromise}async start(){if(!this.chaimu.audioContext)throw new Error("No audio context available");if(!this.audioElement)throw new Error("Audio element is missing");return this.isClearing&&this.clearingPromise&&(q.log("The other cleaner is still running, waiting..."),await this.clearingPromise),q.log("starting audio via HTMLAudioElement"),await this.play(),this.chaimu.video&&(this.audioElement.currentTime=this.chaimu.video.currentTime,this.audioElement.playbackRate=this.chaimu.video.playbackRate),this.audioElement.play().catch(t=>q.log("[ChaimuPlayer] Play audioElement failed:",t)),this}async pause(){if(!this.chaimu.audioContext)throw new Error("No audio context available");return this.audioElement&&this.audioElement.pause(),this.chaimu.audioContext.state==="running"&&await this.chaimu.audioContext.suspend(),this}async play(){if(!this.chaimu.audioContext)throw new Error("No audio context available");return await this.chaimu.audioContext.resume(),this}set src(t){this._src=t;}get src(){return this._src}get currentSrc(){return this._src}set volume(t){this.gainNode&&(this.gainNode.gain.value=t);}get volume(){return this.gainNode?this.gainNode.gain.value:0}set playbackRate(t){this.audioElement&&(this.audioElement.playbackRate=t);}get playbackRate(){return this.audioElement?this.audioElement.playbackRate:this.chaimu.video?.playbackRate??1}get currentTime(){return this.chaimu.video?.currentTime??0}}class ql{_debug=false;audioContext;player;video;fetchFn;fetchOpts;constructor({url:t,video:n,debug:i=false,fetchFn:o=ne.fetchFn,fetchOpts:r={},preferAudio:s=false}){this._debug=ne.debug=i,this.fetchFn=o,this.fetchOpts=r,this.audioContext=Vn(),this.player=this.audioContext&&!s?new zl(this,t):new Wl(this,t),this.video=n;}async init(){await this.player.init(),this.video&&!this.video.paused&&this.player.lipSync("play"),this.player.addVideoEvents();}set debug(t){this._debug=ne.debug=t;}get debug(){return this._debug}}const Mn=()=>{},Gl=Mn,Kl=Mn,Yl=Mn,E={log:Gl,warn:Kl,error:Yl};function ar(e){if(!e)return "";if(typeof e=="string")return e;const t=e;return t?.data?.message||t?.error?.message||t?.message||(typeof t?.toString=="function"?t.toString():"")||String(t)}function Ne(e){const t=e;return typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"||t instanceof Error&&t.name==="AbortError"||t?.message==="AbortError"}function wt(e="Aborted"){try{return new DOMException(e,"AbortError")}catch{const t=new Error(e);return t.name="AbortError",t}}const _n="vot_iframe",On=()=>globalThis.self!==globalThis.top,lr=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`main-world-bridge-${crypto.randomUUID()}`:`main-world-bridge-${Date.now()}-${Math.random().toString(36).slice(2)}`,Jl=15e3,cr=e=>document.getElementById(e),dr=e=>{if(!e||typeof e!="object")return false;const t=e;return typeof t.messageType=="string"&&typeof t.messageDirection=="string"},_i=e=>{try{return new URL(e,globalThis.location.href).href}catch{return null}},Xl=(e,t)=>{const n=_i(t),i=_i(e.src);return !n||!i?e.getAttribute("src")===t:i===n},jl=(e,t)=>!e?.isConnected||!e.contentWindow?false:Xl(e,t);async function Zl(e,t,n){document.body||await new Promise(s=>{document.readyState==="loading"?globalThis.addEventListener("DOMContentLoaded",()=>s(),{once:true}):s();});const i=document.createElement("iframe");i.style.position="fixed",i.style.left="0",i.style.top="0",i.style.width="1px",i.style.height="1px",i.style.opacity="0",i.style.pointerEvents="none",i.style.border="0",i.style.zIndex="-1",i.setAttribute("allow","autoplay; encrypted-media"),i.id=t,i.src=`${e}#${_n}`,document.body.appendChild(i);const o=i.contentWindow,r=`say-${n}-iframe-is-ready`;try{await new Promise((s,a)=>{const l=u=>{u.source===o&&dr(u.data)&&(u.data.messageType!==r||u.data.messageDirection!=="response"||(d(),s()));},c=globalThis.setTimeout(()=>{d(),a(new Error("Service iframe did not have time to be ready"));},Jl),d=()=>{globalThis.clearTimeout(c),globalThis.removeEventListener("message",l);};globalThis.addEventListener("message",l);});}catch(s){throw i.remove(),s}return i}async function Ql(e,t,n,i){if(t.includes("#"))throw new Error("The src parameter should not contain a hash (#) character.");const o=`${t}#${_n}`,r=cr(n);return jl(r,o)?r:(r&&r.remove(),Zl(t,n,i))}function tc(e,t){globalThis.addEventListener("message",t),globalThis.parent.postMessage({messageType:`say-${e}-iframe-is-ready`,messageDirection:"response"},"*");}function ec(e,t,n){const i=lr(),o=n?.signal,r=new Promise((s,a)=>{let l=false,c=null,d=null;const u=()=>{c&&globalThis.removeEventListener("message",c),o&&d&&o.removeEventListener("abort",d);},h=m=>{l||(l=true,u(),m());};if(d=()=>{h(()=>a(wt()));},c=m=>{if(m.source!==globalThis.window||!dr(m.data))return;const v=m.data;v?.messageId===i&&v.messageType===e&&v.messageDirection==="response"&&h(()=>v.error?a(v.error):s(v.payload));},o?.aborted){d();return}globalThis.addEventListener("message",c),o?.addEventListener("abort",d,{once:true}),globalThis.postMessage({messageId:i,messageType:e,messageDirection:"request",...t!==void 0&&{payload:t}},"*");});return {messageId:i,promise:r}}const Oi="vot_iframe_player",ur="service",nc="www.youtube.com",hr=K.minChunkSize,fr=.9,Ke=[6e4,8e4,15e4,33e4,46e4],Di=15e3,ic=.9,pr=e=>typeof e=="string"?e:e.url;function gr(e){const t=new Uint8Array([120,0]);if(typeof e=="string")return {body:t,cache:"no-store",credentials:"include",method:"POST"};const{headers:n,cache:i,credentials:o,integrity:r,keepalive:s,method:a,mode:l,redirect:c,referrer:d,referrerPolicy:u}=e,h=[...n.entries()];return {body:t,cache:i,credentials:o,headersEntries:h,integrity:r,keepalive:s,method:a,mode:l,redirect:c,referrer:d,referrerPolicy:u}}function mr(e){const{headersEntries:t,body:n,...i}=e,o=new Headers(t),r={...i,headers:o};if(n&&n.byteLength>0){const s=new Uint8Array(n.byteLength);s.set(n),r.body=s.buffer;}return r}function oc(e){const{ok:t,redirected:n,status:i,statusText:o,type:r,url:s}=e;return {ok:t,redirected:n,status:i,statusText:o,type:r,url:s}}const rc=e=>new Promise(t=>setTimeout(t,e));function vr(e,t="Operation timed out"){return new Promise((n,i)=>setTimeout(()=>i(new Error(t)),e))}async function sc(e,t,n=false){const i=Date.now()+t;for(;!e();){if(Date.now()>=i){if(n)throw new Error(`Wait for condition reached timeout of ${t}`);return}await rc(100);}}let Ce="";const ac=()=>_.getPlayerResponse()?.streamingData?.adaptiveFormats;async function lc(e,t){if(!e.includes("googlevideo.com/videoplayback")||typeof t=="string")return false;try{const n=t.clone().body?.getReader();if(!n)return !1;let i=0;for(;;){const{done:o,value:r}=await n.read();if(o)break;if(i+=r.length,i>2)return !0}}catch{}return false}function cc(){const e=ac();if(!e?.length){const i=e?"Empty adaptive formats":"Cannot get adaptive formats";throw new Error(`Audio downloader. WEB API. ${i}`)}const t=e.filter(({audioQuality:i,mimeType:o})=>i||o?.includes("audio"));if(!t.length)throw new Error("Audio downloader. WEB API. No audio adaptive formats");return t.filter(({itag:i})=>i===251).sort(({contentLength:i},{contentLength:o})=>i&&o?Number.parseInt(i,10)-Number.parseInt(o,10):-1).at(-1)??t[0]}const dc=async()=>(await sc(()=>!!_.getPlayer(),1e4),_.getPlayer()),uc=async e=>{const t=await dc();if(e.messageId!==Ce)throw new Error("Audio downloader. Download started for another video while getting player");if(!t?.loadVideoById)throw new Error("Audio downloader. There is no player.loadVideoById in iframe");t.loadVideoById(e.payload.videoId),t.pauseVideo?.(),t.mute?.(),setTimeout(()=>{if(e.messageId!==Ce){console.error("Audio Downloader. Download started for another video while waiting to repause video");return}if(!t){console.error("[Critical] Audio Downloader. Player not found in iframe after timeout");return}t.pauseVideo?.();},1e3);};async function hc(e){try{Ce=e.messageId,E.log("getDownloadAudioData",e);const t=unsafeWindow.fetch;unsafeWindow.fetch=async(n,i)=>{n instanceof URL&&(n=n.toString());const o=pr(n);if(await lc(o,n))return globalThis.parent.postMessage({...e,messageDirection:"response",error:"Audio downloader. Detected encoded request."},"*"),unsafeWindow.fetch=t,t(n,i);const r=await t(n,i);return e.messageId!==Ce?(unsafeWindow.fetch=t,r):(o.includes("&itag=251&")&&(unsafeWindow.fetch=t,globalThis.parent.postMessage({...e,messageDirection:"response",payload:{requestInfo:o,requestInit:i||gr(n),adaptiveFormat:cc(),itag:251}},"*")),r)},await uc(e);}catch(t){globalThis.parent.postMessage({...e,messageDirection:"response",error:t},"*");}}const fc=async({data:e})=>{if(e?.messageDirection==="request")try{e.messageType==="get-download-audio-data-in-iframe"?await hc(e.payload):E.log(`NOT IMPLEMENTED: ${e.messageType}`,e.payload);}catch(t){console.error("[VOT] Main world bridge",{error:t});}};function pc(){return tc(ur,fc)}const gc="__VOT_MAIN_BOOT_STATE__";function mc(e){return e==="idle"||e==="booting"||e==="booted"||e==="failed"}function vc(e){return !e||typeof e!="object"?false:mc(e.status)}function bc(e=gc){const t=globalThis,n=t[e];if(vc(n))return n;const i={status:"idle",promise:null,error:null};return t[e]=i,i}const yc="api.browser.yandex.ru",wc="media-proxy.toil.cc/v1/proxy/m3u8",ie="vot-worker.toil.cc",kc="https://vot.toil.cc/v1",xc="https://translate.toil.cc/v2",Sc="https://rust-server-531j.onrender.com/detect",br="https://t2mc.toil.cc",Bi="https://avatars.mds.yandex.net/get-yapic",yr="ilyhalight/voice-over-translation",Ri=`https://raw.githubusercontent.com/${yr}`,Tc=`https://github.com/${yr}`,Fe=15,wr=900,Ac=5,He="yandexbrowser",Dn="rust-server",Lc=["Tampermonkey","Violentmonkey"],kr=["UA","LV","LT"],Bn=1e3,oe="2025-05-09",Ic=["autoTranslate","autoSubtitles","dontTranslateLanguages","enabledDontTranslateLanguages","enabledAutoVolume","enabledSmartDucking","autoVolume","buttonPos","showVideoSlider","syncVolume","downloadWithName","sendNotifyOnComplete","subtitlesMaxLength","subtitlesSmartLayout","highlightWords","subtitlesFontSize","subtitlesOpacity","subtitlesDownloadFormat","responseLanguage","defaultVolume","onlyBypassMediaCSP","newAudioPlayer","showPiPButton","translateAPIErrors","translationService","detectService","translationHotkey","subtitlesHotkey","m3u8ProxyHost","proxyWorkerHost","translateProxyEnabled","translateProxyEnabledDefault","audioBooster","useLivelyVoice","autoHideButtonDelay","useAudioDownload","compatVersion","localePhrases","localeLang","localeHash","localeUpdatedAt","localeLangOverride","account"];function Ni(e){const t=e.throwIfAborted;if(typeof t=="function")try{t.call(e);return}catch(n){throw e.aborted||Ne(n)?wt():n instanceof Error?n:new Error(String(n))}if(e.aborted)throw wt()}function Pc(e,t){const n=typeof AbortSignal<"u"&&"timeout"in AbortSignal,i=typeof AbortSignal<"u"&&"any"in AbortSignal;let o=false;if(!(Number.isFinite(e)&&e>0))return t?{signal:t,didTimeout:()=>false,cleanup:()=>{}}:{signal:new AbortController().signal,didTimeout:()=>false,cleanup:()=>{}};if(n&&i){const c=AbortSignal.timeout(e),d=AbortSignal.any(t?[t,c]:[c]),u=setTimeout(()=>{o=true;},e);return {signal:d,didTimeout:()=>o,cleanup:()=>clearTimeout(u)}}const s=new AbortController,a=()=>s.abort(t?.reason);t&&(t.aborted?s.abort(t.reason):t.addEventListener("abort",a,{once:true}));const l=setTimeout(()=>{o=true,s.abort(wt("Timeout"));},e);return {signal:s.signal,didTimeout:()=>o,cleanup:()=>{clearTimeout(l),t?.removeEventListener("abort",a);}}}function Cc(){return navigator.language?.substring(0,2).toLowerCase()||"en"}const Ec=new Set(["uk","be","bg","mk","sr","bs","hr","sl","pl","sk","cs"]);function Vc(e){return In.includes(e)?e:Ec.has(e)?"ru":"en"}const Rn=Cc(),Te=Vc(Rn);function Mc(e){const t=new WeakSet;return JSON.stringify(e,(n,i)=>{if(i&&typeof i=="object"){const o=i;if(t.has(o))return "[Circular]";if(t.add(o),Array.isArray(i))return i;const r={},s=Object.entries(i).sort(([a],[l])=>a.localeCompare(l));for(const[a,l]of s)r[a]=l;return r}return i})}function _c(e){let t=2166136261,n=0;for(;n65535?2:1;}return (t>>>0).toString(36)}const xr=()=>"pictureInPictureEnabled"in document&&!!document.pictureInPictureEnabled;function gn(e,t){const n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t,document.body.appendChild(i),i.click(),i.remove(),Dc(n);}const Oc=3e4;function Dc(e,t=Oc){globalThis.setTimeout(()=>URL.revokeObjectURL(e),t);}function Fi(e){const t=e.trim();return t?t.replace(/^https?:\/\//,"").replaceAll(/[\\/:*?"'<>|]/g,"-"):new Date().toISOString().slice(0,10)}const Ye=()=>Math.floor(Date.now()/1e3),Bc=e=>e?Object.fromEntries(new Headers(e).entries()):{},N=(e,t=0,n=100)=>Math.min(Math.max(e,t),n);function Hi(e){const t={},n=Object.entries(e);for(;n.length;){const i=n.pop();if(!i)continue;const[o,r]=i;if(r===void 0)continue;if(!(r!==null&&typeof r=="object"&&!Array.isArray(r))){t[o]=r;continue}for(const[a,l]of Object.entries(r))n.push([`${o}.${a}`,l]);}return t}async function Rc(){const e=document;if(!(!e.fullscreenElement&&!e.webkitFullscreenElement))return e.exitFullscreen?e.exitFullscreen():e.webkitExitFullscreen?.()}const Nc="api.browser.yandex.ru",$i=typeof GM_info<"u"?GM_info?.scriptHandler:void 0,Sr=!(typeof IS_EXTENSION<"u"&&IS_EXTENSION)&&!!$i&&!Lc.includes($i),Ui=typeof GM<"u",Tr=typeof unsafeWindow<"u",Ar=typeof GM_xmlhttpRequest<"u";function Fc(e){return e.includes(Nc)}async function Wi(e,t,n){const i=Bc(n.headers);return await new Promise((o,r)=>{const s=typeof GM_xmlhttpRequest<"u"?GM_xmlhttpRequest:globalThis.GM_xmlhttpRequest;if(typeof s!="function"){r(new TypeError("GM_xmlhttpRequest is not available"));return}let a=false,l;const c=()=>{l&&n.signal?.removeEventListener("abort",l);},d=h=>{a||(a=true,c(),r(h));},u=s({method:n.method||"GET",url:e,responseType:"blob",data:n.body,timeout:t,headers:i,onload:h=>{if(a)return;a=true,c();const m=String(h.responseHeaders||"").split(/\r?\n/).reduce((b,y)=>{const[,k,x]=y.match(/^([\w-]+):\s*(.+)$/)||[];return k&&(b[k]=x),b},{}),v=new Response(h.response,{status:h.status,headers:m});Object.defineProperty(v,"url",{value:h.finalUrl??""}),o(v);},ontimeout:()=>d(new Error("Timeout")),onerror:h=>d(new Error(String(h))),onabort:()=>d(wt())});if(l=()=>{try{u?.abort?.();}catch{}d(wt());},n.signal){if(n.signal.aborted){l();return}n.signal.addEventListener("abort",l,{once:true});}})}async function tt(e,t={}){const{timeout:n=15e3,...i}=t,o=typeof e=="string"?e:e instanceof URL?e.href:e.url;if(Fc(o))return await Wi(o,n,i);const{signal:r,cleanup:s}=Pc(n,i.signal);try{return await fetch(e,{signal:r,...i})}catch(a){if(Ne(a)||i.signal?.aborted)throw a;return E.log("GM_fetch preventing CORS by GM_xmlhttpRequest",a?.message??String(a)),await Wi(o,n,i)}finally{s();}}const Je={numToBool:[["autoTranslate"],["dontTranslateYourLang","enabledDontTranslateLanguages"],["autoSetVolumeYandexStyle","enabledAutoVolume"],["showVideoSlider"],["syncVolume"],["downloadWithName"],["sendNotifyOnComplete"],["highlightWords"],["onlyBypassMediaCSP"],["newAudioPlayer"],["showPiPButton"],["translateAPIErrors"],["audioBooster"],["useNewModel","useLivelyVoice"]],number:[["autoVolume"]],array:[["dontTranslateLanguage","dontTranslateLanguages"]],string:[["hotkeyButton","translationHotkey"],["locale-lang-override","localeLangOverride"],["locale-lang","localeLang"]]};function Hc(e,t,n){if(typeof t=="number")return n?.number.some(i=>i[0]===e)?"number":"numToBool";if(Array.isArray(t))return "array";if(typeof t=="string"||t===null)return "string"}function $c(e,t){return ["string","array","number"].includes(e)?t:!!t}async function Uc(e){if(e.compatVersion===oe)return e;const t=Object.values(Je).flat().reduce((l,c)=>(c[1]&&(l[c[0]]=void 0),l),{}),n=await I.getValues(t),i=Object.fromEntries(Object.entries(n).filter(([l,c])=>c!==void 0)),o={...e,...i},r=Object.keys(o).reduce((l,c)=>(l[c]=void 0,l),{}),s=await I.getValues(r),a=e;for(const[l,c]of Object.entries(o)){const d=Hc(l,c,Je);if(!d)continue;const u=Je[d].find(v=>v[0]===l);if(!u)continue;const h=u[1]??l;if(s[l]===void 0)continue;let m=$c(d,c);l==="autoVolume"&&c<1&&(m=Math.round(c*100)),a[h]=m,i[l]!==void 0&&await I.delete(l),await I.set(h,m);}return {...a,compatVersion:oe}}class zi{supportGM=false;supportGMPromises=false;supportGMGetValues=false;supportResolved=false;resolveSupport(){this.supportResolved||(this.supportResolved=true,this.supportGM=typeof GM_getValue=="function",this.supportGMPromises=Ui&&typeof GM?.getValue=="function",this.supportGMGetValues=Ui&&typeof GM?.getValues=="function",E.log(`[VOT Storage] GM Promises: ${this.supportGMPromises} | GM: ${this.supportGM}`));}get isSupportOnlyLS(){return this.resolveSupport(),!this.supportGM&&!this.supportGMPromises}syncGet(t,n){if(this.resolveSupport(),this.supportGM)return GM_getValue(t,n);const i=globalThis.localStorage.getItem(t);if(!i)return n;try{return JSON.parse(i)}catch{return n}}async get(t,n){return this.resolveSupport(),this.supportGMPromises?await GM.getValue(t,n):this.syncGet(t,n)}async getValues(t){return this.resolveSupport(),this.supportGMGetValues?await GM.getValues(t):Object.fromEntries(await Promise.all(Object.entries(t).map(async([n,i])=>{const o=await this.get(n,i);return [n,o]})))}syncSet(t,n){return this.resolveSupport(),this.supportGM?GM_setValue(t,n):globalThis.localStorage.setItem(t,JSON.stringify(n))}async set(t,n){return this.resolveSupport(),this.supportGMPromises?await GM.setValue(t,n):this.syncSet(t,n)}syncDelete(t){return this.resolveSupport(),this.supportGM?GM_deleteValue(t):globalThis.localStorage.removeItem(t)}async delete(t){return this.resolveSupport(),this.supportGMPromises?await GM.deleteValue(t):this.syncDelete(t)}syncList(){return this.resolveSupport(),this.supportGM?GM_listValues():Ic}async list(){return this.resolveSupport(),this.supportGMPromises?await GM.listValues():this.syncList()}}const qi="__VOT_STORAGE_SINGLETON__",I=(()=>{const e=globalThis,t=e[qi];if(t instanceof zi)return t;const n=new zi;return e[qi]=n,n})();async function Wc(){const{access_token:e,expires_in:t}=Object.fromEntries(new URLSearchParams(globalThis.location.hash.slice(1)));if(!e||!t)throw new Error("[VOT] Invalid token response");const n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError("[VOT] Invalid expires_in value");await I.set("account",{token:e,expires:Date.now()+n*1e3,username:void 0,avatarId:void 0});}async function zc(){const{avatar_id:e,username:t}=_userData;if(!e||!t)throw new Error("[VOT] Invalid user data");const n=await I.get("account");if(!n)throw new Error("[VOT] No account data found");await I.set("account",{...n,username:t,avatarId:e});}async function qc(){if(globalThis.location.pathname==="/auth/callback")return await Wc();if(globalThis.location.pathname==="/my/profile")return await zc()}const Gc="recommended",Kc="Translate video",Yc="Turn off",Jc="Translation settings",Xc="Subtitles settings",jc="Smart subtitle layout",Zc="Reset settings",Qc="The video is being translated",td="Video language",ed="Translation language",nd="The translation will take",id="The translation will take more than an hour",od="The translation will take about a minute",rd="The translation will take a few minutes",sd="The translation will take approximately {0} minutes",ad="The translation will take approximately {0} minutes",ld="Failed to request video translation",cd="Audio link not received",dd="Failed to download audio",ud="The audio format is not supported",hd="Translate on open",fd="Subtitles on open",pd="Don't translate from my language",gd="Video volume:",md="Translation volume:",vd="Reduce video volume to",bd="Video volume slider",yd="Link translation and video volume",wd="You have disabled the translation of the video in your language",kd="Video is too long",xd="No video ID found",Sd="Subtitles",Td="Disabled",Ad="Subtitles max length",Ld="Highlight words",Id="translated from",Pd="autogenerated",Cd="VOT Settings",Ed="Menu language",Vd="Authors",Md="Version",_d="Loader",Od="Browser",Dd="Show PiP button",Bd={auto:"Auto",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",hy:"Armenian",as:"Assamese",ay:"Aymara",az:"Azerbaijani",bn:"Bangla",eu:"Basque",be:"Belarusian",bho:"Bhojpuri",bs:"Bosnian",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ceb:"Cebuano",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",co:"Corsican",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Divehi",nl:"Dutch",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fil:"Filipino",fi:"Finnish",fr:"French",gl:"Galician",lg:"Ganda",ka:"Georgian",de:"German",el:"Greek",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",haw:"Hawaiian",iw:"Hebrew",hi:"Hindi",hmn:"Hmong",hu:"Hungarian",is:"Icelandic",ig:"Igbo",id:"Indonesian",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kk:"Kazakh",km:"Khmer",rw:"Kinyarwanda",ko:"Korean",kri:"Krio",ku:"Kurdish",ky:"Kyrgyz",lo:"Lao",la:"Latin",lv:"Latvian",ln:"Lingala",lt:"Lithuanian",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Māori",mr:"Marathi",mn:"Mongolian",ne:"Nepali",nso:"Northern Sotho",no:"Norwegian",ny:"Nyanja",or:"Odia",om:"Oromo",ps:"Pashto",fa:"Persian",pl:"Polish",pt:"Portuguese",pa:"Punjabi",qu:"Quechua",ro:"Romanian",ru:"Russian",sm:"Samoan",sa:"Sanskrit",gd:"Scottish Gaelic",sr:"Serbian",sn:"Shona",sd:"Sindhi",si:"Sinhala",sk:"Slovak",sl:"Slovenian",so:"Somali",st:"Southern Sotho",es:"Spanish",su:"Sundanese",sw:"Swahili",sv:"Swedish",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",ti:"Tigrinya",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",uk:"Ukrainian",ur:"Urdu",ug:"Uyghur",uz:"Uzbek",vi:"Vietnamese",cy:"Welsh",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",zu:"Zulu"},Rd="There is no connection to the server",Nd="Search...",Fd="Translate errors from the API",Hd="Language detection service",$d="Enter the proxy worker address",Ud="Enter the address of the m3u8 proxy worker",Wd="Proxy Settings",zd="The translation will take approximately {0} minutes",qd="Extended translation volume increase",Gd="Subtitles design",Kd="Font size of subtitles",Yd="Transparency of the subtitle background",Jd="The format for downloading subtitles",Xd="Download files with the video name",jd="Update localization files",Zd="Locale hash",Qd="Updated at",tu="To enable this, you must have a Web Audio API",eu="Media CSP is enabled on this site",nu="Use it only for bypassing Media CSP",iu="Use the new audio player",ou="Use an experimental variation of Yandex voices for some videos",ru="The translation is slightly delayed",su="The translation on the {0} has been completed!",au="Send a notification that the video has been translated",lu="Report a bug",cu="Disabled",du="Enabled",uu="Proxy everything",hu="Proxying mode",fu="Translated by {0}",pu="Translate stream isn't available",gu="Text translation service",mu="Doesn't affect the translation of text in voice over",vu="Don't translate from selected languages",bu="Display the video volume slider",yu="Hotkeys settings",wu="None",ku="Use lively voices. Speakers sound like native Russians.",xu="Misc settings",Su={yandexbrowser:"Yandex Browser",msedge:"Microsoft Edge","rust-server":"Rust Server"},Tu="About extension",Au="Appearance",Lu="Button position in the player",Iu={left:"Left",right:"Right",top:"Top",default:"Default"},Pu="secs",Cu="Delay before hiding the translate button",Eu="not found",Vu="The button position only changes in players larger than 600 pixels.",Mu="Completely disabling proxying in your country may break the extension",_u="Press the key combination...",Ou="Use audio download",Du="Disabling audio downloads may affect the functionality of the extension",Bu="You need to log in to use this feature",Ru="My account",Nu="Login",Fu="Logout",Hu="Refresh",$u="Enter the Yandex OAuth Token",Uu="You can manually set the account token in this field. Please note that we don't check its validity before sending a translate request",Wu="Login via token",zu="Adaptive volume",qu={recommended:Gc,translateVideo:Kc,disableTranslate:Yc,translationSettings:Jc,subtitlesSettings:Xc,subtitlesSmartLayout:jc,resetSettings:Zc,videoBeingTranslated:Qc,videoLanguage:td,translationLanguage:ed,translationTake:nd,translationTakeMoreThanHour:id,translationTakeAboutMinute:od,translationTakeFewMinutes:rd,translationTakeApproximatelyMinutes:sd,translationTakeApproximatelyMinute:ad,requestTranslationFailed:ld,audioNotReceived:cd,VOTFailedDownloadAudio:dd,audioFormatNotSupported:ud,VOTAutoTranslate:hd,VOTAutoSubtitles:fd,VOTDontTranslateYourLang:pd,VOTVolume:gd,VOTVolumeTranslation:md,VOTAutoSetVolume:vd,VOTShowVideoSlider:bd,VOTSyncVolume:yd,VOTDisableFromYourLang:wd,VOTVideoIsTooLong:kd,VOTNoVideoIDFound:xd,VOTSubtitles:Sd,VOTSubtitlesDisabled:Td,VOTSubtitlesMaxLength:Ad,VOTHighlightWords:Ld,VOTTranslatedFrom:Id,VOTAutogenerated:Pd,VOTSettings:Cd,VOTMenuLanguage:Ed,VOTAuthors:Vd,VOTVersion:Md,VOTLoader:_d,VOTBrowser:Od,VOTShowPiPButton:Dd,langs:Bd,streamNoConnectionToServer:Rd,searchField:Nd,VOTTranslateAPIErrors:Fd,VOTDetectService:Hd,VOTProxyWorkerHost:$d,VOTM3u8ProxyHost:Ud,proxySettings:Wd,translationTakeApproximatelyMinute2:zd,VOTAudioBooster:qd,VOTSubtitlesDesign:Gd,VOTSubtitlesFontSize:Kd,VOTSubtitlesOpacity:Yd,VOTSubtitlesDownloadFormat:Jd,VOTDownloadWithName:Xd,VOTUpdateLocaleFiles:jd,VOTLocaleHash:Zd,VOTUpdatedAt:Qd,VOTNeedWebAudioAPI:tu,VOTMediaCSPEnabledOnSite:eu,VOTOnlyBypassMediaCSP:nu,VOTNewAudioPlayer:iu,VOTUseNewModel:ou,TranslationDelayed:ru,VOTTranslationCompletedNotify:su,VOTSendNotifyOnComplete:au,VOTBugReport:lu,VOTTranslateProxyDisabled:cu,VOTTranslateProxyEnabled:du,VOTTranslateProxyEverything:uu,VOTTranslateProxyStatus:hu,VOTTranslatedBy:fu,VOTStreamNotAvailable:pu,VOTTranslationTextService:gu,VOTNotAffectToVoice:mu,DontTranslateSelectedLanguages:vu,showVideoVolumeSlider:bu,hotkeysSettings:yu,None:wu,VOTUseLivelyVoice:ku,miscSettings:xu,services:Su,aboutExtension:Tu,appearance:Au,buttonPosition:Lu,position:Iu,secs:Pu,autoHideButtonDelay:Cu,notFound:Eu,minButtonPositionContainer:Vu,VOTTranslateProxyStatusDefault:Mu,PressTheKeyCombination:_u,VOTUseAudioDownload:Ou,VOTUseAudioDownloadWarning:Du,VOTAccountRequired:Bu,VOTMyAccount:Ru,VOTLogin:Nu,VOTLogout:Fu,VOTRefresh:Hu,VOTYandexToken:$u,VOTYandexTokenInfo:Uu,VOTLoginViaToken:Wu,smartDucking:zu};var Xe=["auto","en","ru","af","am","ar","az","bg","bn","bs","ca","cs","cy","da","de","el","es","et","eu","fa","fi","fr","gl","hi","hr","hu","hy","id","it","ja","jv","kk","km","kn","ko","lo","mk","ml","mn","ms","mt","my","ne","nl","pa","pl","pt","ro","si","sk","sl","sq","sr","su","sv","sw","tr","uk","ur","uz","vi","zh","zu"];const Gi="master",je=typeof Xe<"u"&&Array.isArray(Xe)?Xe:["en"];class Gu{storageKeys=["localePhrases","localeLang","localeHash","localeUpdatedAt","localeLangOverride"];lang;locale;defaultLocale=Hi(qu);cacheTTL=7200;localesUrl=`${Ri}/${Gi}/src/localization/locales`;hashesUrl=`${Ri}/${Gi}/src/localization/hashes.json`;_langOverride="auto";constructor(){this.lang=this.getLang(),this.locale={};}async init(){this._langOverride=await I.get("localeLangOverride","auto"),this.lang=this.getLang();const t=await I.get("localePhrases","");return this.setLocaleFromJsonString(t),this}get langOverride(){return this._langOverride}getLang(){return this.langOverride!=="auto"?this.langOverride:Rn}getAvailableLangs(){return je.includes("auto")?je:["auto",...je]}async reset(){for(const t of this.storageKeys)await I.delete(t);return this}buildUrl(t,n,i=false){const o=i?`?timestamp=${Ye()}`:"";return `${t}${n}${o}`}async changeLang(t){return this.langOverride===t?false:(await I.set("localeLangOverride",t),this._langOverride=t,this.lang=this.getLang(),await this.update(true),true)}async checkUpdates(t=false){try{const n=await tt(this.buildUrl(this.hashesUrl,"",t));if(!n.ok)throw n.status;const i=await n.json();return await I.get("localeHash")!==i[this.lang]?i[this.lang]:!1}catch(n){return console.error("[VOT] [localizationProvider] Failed to get locales hash:",n),false}}async update(t=false){const n=await I.get("localeUpdatedAt",0);if(!t&&n+this.cacheTTL>Ye()&&await I.get("localeLang")===this.lang)return this;const i=await this.checkUpdates(t);if(await I.set("localeUpdatedAt",Ye()),!i)return this;try{const o=await tt(this.buildUrl(this.localesUrl,`/${this.lang}.json`,t));if(!o.ok)throw o.status;const r=await o.text();await I.set("localePhrases",r),await I.set("localeHash",i),await I.set("localeLang",this.lang),this.setLocaleFromJsonString(r);}catch(o){console.error("[VOT] [localizationProvider] Failed to get locale:",o),this.setLocaleFromJsonString(await I.get("localePhrases",""));}return this}setLocaleFromJsonString(t){try{const n=JSON.parse(t)||{};this.locale=Hi(n);}catch(n){console.error("[VOT] [localizationProvider]",n),this.locale={};}return this}getFromLocale(t,n){return t?.[n]??this.warnMissingKey(t,n)}warnMissingKey(t,n){console.warn("[VOT] [localizationProvider] locale",t,"doesn't contain key",n);}getDefault(t){return this.getFromLocale(this.defaultLocale,t)??t}get(t){return this.getFromLocale(this.locale,t)??this.getDefault(t)}getLangLabel(t){const n=`langs.${t}`;if(n in this.defaultLocale){const i=this.get(n);if(i)return i}return typeof t=="string"?t.toUpperCase():""}}const p=new Gu;let Ki=null;function Ku(){return Ki??=p.init(),Ki}function Yu(){const t=Object.entries({"https://www.dailymotion.com":{targetOrigin:"https://geo.dailymotion.com",dataFilter:n=>typeof n=="object"&&n!==null&&"type"in n&&n.type==="getDailymotionVideoId",extractVideoId:n=>/\/video\/(\w+)/.exec(n.pathname)?.[1]??null,responseFormatter:n=>({type:"dailymotionVideoId",videoId:n})},"https://dev.epicgames.com":{targetOrigin:"https://dev.epicgames.com",dataFilter:n=>typeof n=="string"&&n.startsWith("getVideoId:"),extractVideoId:n=>n.pathname.split("/").at(-2)??null,responseFormatter:(n,i)=>`${typeof i=="string"?i:""}:${n}`}}).find(([n])=>globalThis.location.origin===n&&(n!=="https://dev.epicgames.com"||globalThis.location.pathname.includes("/community/learning/")))?.[1];t&&globalThis.addEventListener("message",n=>{try{if(n.origin!==t.targetOrigin||!t.dataFilter(n.data))return;const i=t.extractVideoId(new URL(globalThis.location.href));if(!i)return;const o=t.responseFormatter(i,n.data);n.source&&"postMessage"in n.source&&n.source.postMessage(o,t.targetOrigin);}catch(i){console.error("Iframe communication error:",i);}});}let Ze=false,Xt=null,Yi=false;async function Ji(e,t){if(!Ze){if(Xt!==null){await Xt;return}Xt=(async()=>{if(t("Activating runtime",{reason:e}),globalThis.location.origin===br){await qc(),Ze=true;return}await Ku(),On()||await p.update(),E.log(`Selected menu language: ${p.lang}`),Yi||(Yi=true,Yu()),Ze=true;})();try{await Xt;}finally{Xt=null;}}}let Xi=false;function Ju(e){if(Xi)return;Xi=true;const{videoObserver:t,videosWrappers:n,ensureRuntimeActivated:i,getServicesCached:o,findContainer:r,createVideoHandler:s}=e,a=new WeakSet,l=new WeakMap,c=new WeakMap,d=new WeakMap,u=b=>{const y=c.get(b);return y&&l.get(y)===b&&l.delete(y),c.delete(b),y??void 0},h=b=>{b&&d.delete(b);},m=async b=>{if(!b)return;const y=d.get(b);y&&(d.delete(b),!(!y.isConnected||n.has(y)||a.has(y))&&await v(y));},v=async b=>{if(!(n.has(b)||a.has(b))){a.add(b);try{try{await i("video-detected");}catch(D){console.error("[VOT] Failed to activate runtime",D);return}let y=null;const k=o().find(D=>(y=r(D,b),!!y));if(!k||!y)return;const x=l.get(y);if(x&&x!==b){if(x.isConnected){d.set(y,b);return}try{await n.get(x)?.release();}catch(D){console.error("[VOT] Failed to release stale videoHandler",D);}n.delete(x),u(x);}["peertube","directlink"].includes(k.host)&&(k.url=globalThis.location.origin);const A=s(b,y,k);n.set(b,A),c.set(b,y),l.set(y,b);try{if(await A.init(),n.get(b)!==A)return;try{await A.setCanPlay();}catch(D){console.error("[VOT] Failed to get video data",D);}}catch(D){if(n.get(b)===A){n.delete(b);const Y=u(b);h(Y),await m(Y);}throw D}}catch(y){console.error("[VOT] Failed to initialize videoHandler",y);}finally{a.delete(b);}}};t.onVideoAdded.addListener(v),t.onVideoRemoved.addListener(async b=>{const y=u(b);n.has(b)&&(await n.get(b)?.release(),n.delete(b)),a.delete(b),y&&d.get(y)===b&&h(y),await m(y);});}function Xu(e){return !e.isIframe||e.hash.includes(e.iframeHash)?false:e.href==="about:blank"||e.href.startsWith("about:srcdoc")||e.origin==="null"}function ju(e){return e.isIframe&&e.hash.includes(e.iframeHash)?"iframe-helper":Xu(e)?"skip":e.isIframe?"iframe-lazy":"top-full"}const mn=7200*1e3;class Zu{cache=new Map;lastCleanupAt=0;clear(){this.cache.clear(),this.lastCleanupAt=0;}getTranslation(t){const n=this.cache.get(t);if(!n)return;const i=n.translationExpiresAt;if(i!==void 0&&i<=Date.now()){n.translation=void 0,n.translationExpiresAt=void 0,this.evictIfEmpty(t,n);return}return n.translation}setTranslation(t,n){this.maybeCleanup();const i=this.getOrCreateEntry(t);i.translation=n,i.translationExpiresAt=Date.now()+mn;}getSubtitles(t){const n=this.cache.get(t);if(!n)return;const i=n.subtitlesExpiresAt;if(i!==void 0&&i<=Date.now()){n.subtitles=void 0,n.subtitlesExpiresAt=void 0,this.evictIfEmpty(t,n);return}return n.subtitles}setSubtitles(t,n){this.maybeCleanup();const i=this.getOrCreateEntry(t);i.subtitles=n,i.subtitlesExpiresAt=Date.now()+mn;}deleteSubtitles(t){const n=this.cache.get(t);n&&(n.subtitles=void 0,n.subtitlesExpiresAt=void 0,this.evictIfEmpty(t,n));}evictIfEmpty(t,n){n.translation===void 0&&n.subtitles===void 0&&this.cache.delete(t);}maybeCleanup(){const t=Date.now();if(!(t-this.lastCleanupAt<6e4)){this.lastCleanupAt=t;for(const[n,i]of this.cache)i.translationExpiresAt!==void 0&&i.translationExpiresAt<=t&&(i.translation=void 0,i.translationExpiresAt=void 0),i.subtitlesExpiresAt!==void 0&&i.subtitlesExpiresAt<=t&&(i.subtitles=void 0,i.subtitlesExpiresAt=void 0),this.evictIfEmpty(n,i);}}getOrCreateEntry(t){const n=this.cache.get(t);if(n)return n;const i={};return this.cache.set(t,i),i}}function Lr(e){return e?typeof ShadowRoot<"u"&&e instanceof ShadowRoot?e.host:e.parentNode??null:null}function Nn(e,t){let n=t;for(;n;){if(n===e)return true;n=Lr(n);}return false}function Qu(e,t){if(!e||!t)return null;const n=e instanceof Document?null:e,i=o=>{if(!o)return null;if(o instanceof Document){if(n){const a=o.querySelectorAll(t);return Array.from(a).find(l=>Nn(l,n))??null}return o.querySelector(t)}const r=o.closest(t);if(r)return r;const s=o.getRootNode();if(s instanceof ShadowRoot)return i(s.host);if(s instanceof Document)return i(s);if(s!==o){const a=Lr(s);if(a&&a!==o&&a instanceof Element)return i(a)}return null};return i(e)}function th(e,{maxPointerEventsHops:t=30,maxPositionedHops:n=10,preferPositioned:i=true}={}){let o=e,r=0;for(;o?.parentElement&&r=hr||s.end===e)&&(i.push(o),o=[],r=0);return i}function Cr({contentLength:e}){if(typeof e!="string")throw new TypeError(`Audio downloader. WEB API. Content length (${e}) is not a string`);const t=Number.parseInt(e,10);if(!Number.isFinite(t))throw new TypeError(`Audio downloader. WEB API. Parsed content length is not finite (${t})`);return t}function ih(e){const t=Cr(e),n=nh(t);if(!n.length)throw new Error("Audio downloader. WEB API. No chunk parts generated");return n}function oh(e){if(e<1)throw new Error("Audio downloader. WEB API. contentLength cannot be less than 1");const t=Math.round(e*fr);return Pr(e,t)}function rh(e){const t=Cr(e),n=oh(t);if(!n.length)throw new Error("Audio downloader. WEB API. Empty chunk ranges");return n}function sh(e){const t=e.reduce((o,r)=>o+r.byteLength,0),n=new Uint8Array(t);let i=0;for(const o of e)n.set(new Uint8Array(o),i),i+=o.byteLength;return n}async function ah(e,t){const{videoId:n}=t.payload,i=`https://${nc}/embed/${n}?autoplay=0&mute=1`;try{const o=await Ql(eh,i,Oi,ur);if(!cr(Oi))throw new Error("Audio downloader. WEB API. Service iframe deleted");o.contentWindow?.postMessage({messageId:lr(),messageType:e,messageDirection:"request",payload:t,error:t.error},"*");}catch(o){t.error=o,t.messageDirection="response",globalThis.postMessage(t,"*");}}function lh(e,t,n){return JSON.stringify({downloadType:e,itag:t,minChunkSize:hr,fileSize:n})}const Qe="Audio downloader. WEB API. Can not get getGeneratingAudioUrlsDataFromIframe due to timeout",tn="Audio downloader. WEB API. Incorrect response on fetch media url",ji="Audio downloader. WEB API. Can not fetch media url",Zi="Audio downloader. WEB API. Can not get array buffer from media url",ch=new TextDecoder("ascii");let dh=1;function uh(e,{start:t,end:n}){const i=new URL(e);return i.searchParams.set("range",`${t}-${n}`),i.searchParams.set("rn",String(dh++)),i.searchParams.delete("ump"),i.toString()}function Qi(e,{start:t,end:n}){const i=n-t;return i>Di&&e.byteLengthic}const hh=e=>/https:\/\/.*$/.exec(ch.decode(e))?.[0],fh=Gt.WEB_API_GET_ALL_GENERATING_URLS_DATA_FROM_IFRAME;function ph(e){return !!e&&typeof e=="object"&&"headersEntries"in e}function gh(e,t){return e?ph(e)?mr(e):e:t}const mh=(e,t)=>ec("get-download-audio-data-in-main-world",e,{signal:t}).promise;async function vh(e,t){try{return await Promise.race([mh({videoId:e},t),vr(2e4,Qe)])}catch(n){const i=n instanceof Error&&n.message===Qe;throw new Error(i?Qe:"Audio downloader. WEB API. Failed to get audio data")}}async function Er({mediaUrl:e,chunkRange:t,requestInit:n,signal:i,isUrlChanged:o=false}){const r=uh(e,t);let s;try{if(s=await tt(r,{...n,signal:i}),!s.ok){const c=oc(s);throw console.error(tn,c),new Error(tn)}}catch(c){throw c instanceof Error&&c.message===tn?c:(console.error(ji,{mediaUrl:r,error:c}),new Error(ji))}let a;try{a=await s.arrayBuffer();}catch(c){throw console.error(Zi,{mediaUrl:r,error:c}),new Error(Zi)}if(E.log("isChunkLengthAcceptable",Qi(a,t),a.byteLength,t),Qi(a,t))return {media:a,url:o?e:null,isAcceptableLast:false};const l=hh(a);if(l)return Er({mediaUrl:l,chunkRange:t,requestInit:n,signal:i,isUrlChanged:true});if(!t.mustExist)return {media:a,url:null,isAcceptableLast:true};throw new Error(`Audio downloader. WEB API. Can not get redirected media url ${r}`)}async function to(e,t,n,i){let o=e;const r=[];let s=false;for(const a of n){const l=await Er({mediaUrl:o,chunkRange:a,requestInit:t,signal:i});if(l.url&&(o=l.url),r.push(l.media),s=l.isAcceptableLast,s)break}return {media:sh(r),url:o,isAcceptableLast:s}}async function bh({videoId:e,returnByParts:t=false,signal:n}){const{requestInit:i,requestInfo:o,adaptiveFormat:r,itag:s}=await vh(e,n);if(!o)throw new Error("Audio downloader. WEB API. Can not get requestInfo");let a=pr(o);const l=gr(o),c=mr(l),d=gh(i,c),u=t?ih(r):null;return {fileId:lh(fh,s,r.contentLength),mediaPartsLength:u?.length??1,async*getMediaBuffers(){if(t){if(!u?.length)throw new Error("Audio downloader. WEB API. Empty chunk parts");for(const h of u){const{media:m,url:v,isAcceptableLast:b}=await to(a,d,h,n);if(v&&(a=v),yield m,b)break}}else {const h=rh(r),{media:m}=await to(a,d,h,n);yield m;}}}}const yh={[Gt.WEB_API_GET_ALL_GENERATING_URLS_DATA_FROM_IFRAME]:bh};async function wh({audioDownloader:e,translationId:t,videoId:n,signal:i}){const o=await yh[e.strategy]({videoId:n,returnByParts:true,signal:i});if(!o)throw new Error("Audio downloader. Can not get audio data");E.log("Audio downloader. Url found",{audioDownloadType:e.strategy});const{getMediaBuffers:r,mediaPartsLength:s,fileId:a}=o;if(s<2){const{value:c}=await r().next();if(!c)throw new Error("Audio downloader. Empty audio");await e.onDownloadedAudio.dispatchAsync(t,{videoId:n,fileId:a,audioData:c});return}let l=0;for await(const c of r()){if(!c)throw new Error("Audio downloader. Empty audio");await e.onDownloadedPartialAudio.dispatchAsync(t,{videoId:n,fileId:a,audioData:c,version:1,index:l,amount:s}),l++;}}async function eo(e){const{data:t,source:n}=e;try{if(t?.messageType!=="get-download-audio-data-in-main-world")return;if(t.messageDirection==="response"){n!==globalThis.window&&globalThis.postMessage(t,"*");return}if(t.messageDirection!=="request")return;await ah("get-download-audio-data-in-iframe",t);}catch(i){console.error("[VOT] Main world bridge",{error:i});}}class kh{onDownloadedAudio=new B;onDownloadedPartialAudio=new B;onDownloadAudioError=new B;strategy;constructor(t=Gt.WEB_API_GET_ALL_GENERATING_URLS_DATA_FROM_IFRAME){this.strategy=t;}async runAudioDownload(t,n,i){globalThis.addEventListener("message",eo);try{await wh({audioDownloader:this,translationId:n,videoId:t,signal:i}),E.log("Audio downloader. Audio download finished",{videoId:t});}catch(o){console.error("Audio downloader. Failed to download audio",o),this.onDownloadAudioError.dispatch(t);}globalThis.removeEventListener("message",eo);}addEventListener(t,n){switch(t){case "downloadedAudio":this.onDownloadedAudio.addListener(n);break;case "downloadedPartialAudio":this.onDownloadedPartialAudio.addListener(n);break;case "downloadAudioError":this.onDownloadAudioError.addListener(n);break}return this}removeEventListener(t,n){switch(t){case "downloadedAudio":this.onDownloadedAudio.removeListener(n);break;case "downloadedPartialAudio":this.onDownloadedPartialAudio.removeListener(n);break;case "downloadAudioError":this.onDownloadAudioError.removeListener(n);break}return this}}const xh=.66;function Sh(e,t){let n=Math.floor(e/60);if(Math.floor(e%60)/60>=xh&&(n+=1),n>=60)return t("translationTakeMoreThanHour");if(n<=1)return t("translationTakeAboutMinute");const r=String(n);return n!==11&&n%10===1?t("translationTakeApproximatelyMinute2").replace("{0}",r):![12,13,14].includes(n)&&[2,3,4].includes(n%10)?t("translationTakeApproximatelyMinute").replace("{0}",r):t("translationTakeApproximatelyMinutes").replace("{0}",r)}class it extends Error{name="VOTLocalizedError";unlocalizedMessage;localizedMessage;constructor(t){super(p.getDefault(t)),this.unlocalizedMessage=t,this.localizedMessage=p.get(t);}}function Fn(e){return e??null}async function Vr(e,t){const n=await e.translateVideoImpl(t.videoData,t.requestLang,t.responseLang,Fn(t.translationHelp),!t.useAudioDownload,t.signal);return n?.url?{url:n.url,usedLivelyVoice:!!n.usedLivelyVoice}:null}function Th(e){return {videoId:e.videoId,from:e.requestLang,to:e.responseLang,url:e.downloadTranslationUrl??e.fallbackUrl,useLivelyVoice:e.usedLivelyVoice}}async function Mr(e){return e.isActionStale(e.actionContext)||(await e.updateTranslation(e.url,e.actionContext),e.isActionStale(e.actionContext))?false:(e.scheduleTranslationRefresh(),true)}async function Ah(e){const t=await Vr(e.requester,{videoData:e.request.videoData,requestLang:e.request.requestLang,responseLang:e.request.responseLang,translationHelp:e.request.translationHelp,useAudioDownload:e.request.useAudioDownload,signal:e.request.signal});return !t||!await Mr({url:t.url,actionContext:e.actionContext,isActionStale:e.isActionStale,updateTranslation:e.updateTranslation,scheduleTranslationRefresh:e.scheduleTranslationRefresh})||e.isActionStale(e.actionContext)?null:t}function Lh(e){e.setTranslation(e.cacheKey,Th({videoId:e.videoId,requestLang:e.requestLang,responseLang:e.responseLang,fallbackUrl:e.fallbackUrl,downloadTranslationUrl:e.downloadTranslationUrl,usedLivelyVoice:e.usedLivelyVoice}));}function _r(e){return e.aborted||!e.translateApiErrorsEnabled||!e.hadAsyncWait?e.hadAsyncWait:(e.notify({videoId:e.videoId,message:e.error}),false)}function Or(e){if(!e||typeof e!="object")return null;const t=e,n=t.data&&typeof t.data=="object"?t.data:void 0;return {name:t.name,message:t.message,data:n}}function Ih(e){const n=Or(e)?.data?.message;return typeof n=="string"&&n.length>0?n:void 0}function Ph(e){const t=Or(e);if(!t||t.name!=="VOTJSError")return e;const n=typeof t.message=="string"?t.message:"",i=typeof t.data?.message=="string"&&t.data.message.length>0;return n==="Yandex couldn't translate video"&&!i?new it("requestTranslationFailed"):n==="Failed to request video translation"?new it("requestTranslationFailed"):n==="Audio link wasn't received"||n==="Audio link wasn't received from VOT response"?new it("audioNotReceived"):e}class Ch{videoHandler;audioDownloader;downloading;downloadWaiters=new Set;requestedFailAudio=new Set;constructor(t){this.videoHandler=t,this.audioDownloader=new kh,this.downloading=false,this.audioDownloader.addEventListener("downloadedAudio",this.onDownloadedAudio).addEventListener("downloadedPartialAudio",this.onDownloadedPartialAudio).addEventListener("downloadAudioError",this.onDownloadAudioError);}onDownloadedAudio=async(t,n)=>{if(!this.downloading)return;const{videoId:i,fileId:o,audioData:r}=n,s=this.getCanonicalUrl(i);try{await this.videoHandler.votClient.requestVtransAudio(s,t,{audioFile:r,fileId:o});}catch{}this.finishDownloadSuccess();};onDownloadedPartialAudio=async(t,n)=>{if(!this.downloading)return;const{audioData:i,fileId:o,videoId:r,amount:s,version:a,index:l}=n,c=this.getCanonicalUrl(r);try{await this.videoHandler.votClient.requestVtransAudio(c,t,{audioFile:i,chunkId:l},{audioPartsLength:s,fileId:o,version:a});}catch{this.finishDownloadFailure(new Error("Audio downloader failed while uploading chunk"));return}l===s-1&&this.finishDownloadSuccess();};onDownloadAudioError=async t=>{if(!this.downloading)return;const n=this.getCanonicalUrl(t);if(!(this.videoHandler.site.host==="youtube"&&!!this.videoHandler.data?.useAudioDownload)){this.finishDownloadFailure(new it("VOTFailedDownloadAudio"));return}try{this.requestedFailAudio.has(n)?E.log("fail-audio-js request already sent for this video"):(E.log("Sending fail-audio-js request"),await this.videoHandler.votClient.requestVtransFailAudio(n),this.requestedFailAudio.add(n)),this.finishDownloadSuccess();}catch{this.finishDownloadFailure(new it("VOTFailedDownloadAudio"));}};finishDownloadSuccess(){this.downloading=false,this.resolveDownloadWaiters();}finishDownloadFailure(t){this.downloading=false,this.rejectDownloadWaiters(t);}getCanonicalUrl(t){return `https://youtu.be/${t}`}isLivelyVoiceUnavailableError(t){const n=ar(t);return !!n&&n.toLowerCase().includes("обычная озвучка")}scheduleRetry(t,n,i){return new Promise((o,r)=>{let s=null;const a=()=>{s!==null&&clearTimeout(s),i.removeEventListener("abort",l);},l=()=>{a(),r(wt());};if(i.addEventListener("abort",l,{once:true}),i.aborted){l();return}s=setTimeout(async()=>{if(i.aborted){l();return}a();try{const c=await t();o(c);}catch(c){r(c);}},n),s!==null&&(this.videoHandler.autoRetry=s);})}async translateVideoImpl(t,n,i,o=null,r=false,s=new AbortController().signal,a=false){clearTimeout(this.videoHandler.autoRetry),this.finishDownloadSuccess();const l=this.videoHandler.getRequestLangForTranslation(n,i);let c=a;try{Ni(s);const d=this.videoHandler.isLivelyVoiceAllowed(l,i);let u=!c&&d&&!!this.videoHandler.data?.useLivelyVoice,h;for(let v=0;v<2;v++){try{h=await this.videoHandler.votClient.translateVideo({videoData:t,requestLang:l,responseLang:i,translationHelp:o,extraOpts:{useLivelyVoice:u,videoTitle:this.videoHandler.videoData?.title},shouldSendFailedAudio:r});}catch(b){if(u&&this.isLivelyVoiceUnavailableError(b)){E.log("[translateVideoImpl] Lively voices are unavailable. Falling back to standard translation.",b),c=!0,u=!1;continue}throw b}if(u&&this.isLivelyVoiceUnavailableError(h)){E.log("[translateVideoImpl] Server responded that lively voices are unavailable. Falling back to standard translation.",h),c=!0,u=!1,h=void 0;continue}break}if(!h)throw new Error("Failed to get translation response");if(E.log("Translate video result",h),Ni(s),h.translated&&h.remainingTime<1)return E.log("Video translation finished with this data: ",h),{...h,usedLivelyVoice:u};const m=h.message??p.get("translationTakeFewMinutes");if(await this.videoHandler.updateTranslationErrorMsg(h.remainingTime>0?Sh(h.remainingTime,v=>p.get(v)):m,s),h.status===lt.AUDIO_REQUESTED&&this.videoHandler.isYouTubeHosts())return this.videoHandler.hadAsyncWait=!0,E.log("Start audio download"),this.downloading=!0,await this.audioDownloader.runAudioDownload(t.videoId,h.translationId,s),E.log("waiting downloading finish"),await this.waitForAudioDownloadCompletion(s,15e3),await this.translateVideoImpl(t,n,i,o,!0,s,c)}catch(d){if(Ne(d))return null;const u=Ph(d);return await this.videoHandler.updateTranslationErrorMsg(Ih(u)??u,s),this.videoHandler.hadAsyncWait=_r({aborted:!!this.videoHandler.actionsAbortController?.signal?.aborted,translateApiErrorsEnabled:!!this.videoHandler.data?.translateAPIErrors,hadAsyncWait:this.videoHandler.hadAsyncWait,videoId:t.videoId,error:d,notify:h=>this.videoHandler.notifier.translationFailed(h)}),console.error("[VOT]",d),null}return this.videoHandler.hadAsyncWait=true,this.scheduleRetry(()=>this.translateVideoImpl(t,n,i,o,r,s,c),2e4,s)}waitForAudioDownloadCompletion(t,n){return this.downloading?new Promise((i,o)=>{let r;const s=()=>{l(),o(wt());},a=setTimeout(()=>{l(),i();},n),l=()=>{clearTimeout(a),t.removeEventListener("abort",s),this.downloadWaiters.delete(r);};if(r={resolve:()=>{l(),i();},reject:c=>{l(),o(c);}},this.downloadWaiters.add(r),t.aborted){s();return}t.addEventListener("abort",s,{once:true});}):Promise.resolve()}resolveDownloadWaiters(){this.forEachDownloadWaiter(t=>t.resolve());}rejectDownloadWaiters(t){this.forEachDownloadWaiter(n=>n.reject(t));}forEachDownloadWaiter(t){if(!this.downloadWaiters.size)return;const n=Array.from(this.downloadWaiters);this.downloadWaiters.clear();for(const i of n)t(i);}}class Eh{state={status:"idle"};deps;constructor(t){this.deps=t;}get currentState(){return this.state}setState(t){this.state=t;}reset(){this.setState({status:"idle"});}async runAutoTranslationIfEligible(){if(this.state.status==="idle"&&this.deps.isFirstPlay()&&this.deps.isAutoTranslateEnabled()&&this.deps.getVideoId()){if(this.deps.isMobileYouTubeMuted?.()){this.setState({status:"deferred",reason:"muted"}),this.deps.setMuteWatcher?.(()=>{this.setState({status:"idle"}),this.runAutoTranslationIfEligible();});return}this.setState({status:"pending",reason:"auto"});try{this.deps.setFirstPlay(!1),await this.deps.scheduleAutoTranslate(),this.reset();}catch(t){throw this.setState({status:"error",message:t}),t}}}}function Vh(e,t={}){const{requireVideoData:n=false,clearVideoData:i=false}=t;n&&!e.videoData||(i&&(e.videoData=void 0),e.stopTranslation(),e.resetSubtitlesWidget());}function Ae(e,t={}){const{hideMenu:n=false}=t;e?.votButton?.container&&(e.votButton.container.hidden=true),n&&e?.votMenu&&(e.votMenu.hidden=true);}function Dr(e,t,n={}){const{requireVideoData:i,clearVideoData:o,hideMenu:r}=n;Vh(e,{requireVideoData:i,clearVideoData:o}),Ae(t,{hideMenu:r});}class Mh{host;lifecycleGeneration=0;lastSetCanPlaySourceKey="";activeSetCanPlaySourceKey="";setCanPlayRequested=false;setCanPlayLoopPromise;constructor(t){this.host=t;}isStale(t){return t!==this.lifecycleGeneration}resetActions(t){if(typeof this.host.resetActionsAbortController=="function"){this.host.resetActionsAbortController(t);return}this.host.actionsAbortController?.abort(t);}invalidateActiveSession(t){this.lifecycleGeneration!==0&&(this.lifecycleGeneration+=1,this.resetActions(`[VideoLifecycle] ${t}`),E.log(`[VideoLifecycle] cancelled active session (active: ${this.lifecycleGeneration})`,{reason:t}));}startSession(t){this.lifecycleGeneration+=1;const n=this.lifecycleGeneration;return this.resetActions(`[VideoLifecycle][session:${n}] ${t}`),n}shouldAbortHandleSrcChanged(t,n){return this.isStale(t)?(E.log(`[VideoLifecycle][session:${t}] handleSrcChanged aborted at ${n} (active: ${this.lifecycleGeneration})`),true):false}teardown(){this.setCanPlayRequested=false,this.invalidateActiveSession("teardown");}getCurrentSourceKey(){const t=this.host.video.srcObject?"1":"0";if(this.host.site.host==="youtube"){const i=globalThis.location.pathname;if(i.startsWith("/shorts/"))return `${globalThis.location.origin}${i}||${t}`}const n=this.host.video.currentSrc||this.host.video.src||"";return `${globalThis.location.href}||${n}||${t}`}resolveContainer(){const{site:t,video:n,container:i}=this.host;if(!t.selector)return n.parentElement??i;const o=Ir(n,t.selector);return o||(i.isConnected&&Nn(i,n)?i:n.parentElement??i)}async setCanPlay(){if(this.setCanPlayRequested=true,this.setCanPlayLoopPromise!==void 0){const n=this.getCurrentSourceKey();return this.activeSetCanPlaySourceKey&&n!==this.activeSetCanPlaySourceKey&&this.invalidateActiveSession("setCanPlay source changed while previous trigger is running"),await this.setCanPlayLoopPromise}const t=(async()=>{for(;this.setCanPlayRequested;)this.setCanPlayRequested=false,await this.runSetCanPlayOnce();})();this.setCanPlayLoopPromise=t;try{await t;}finally{this.setCanPlayLoopPromise===t&&(this.setCanPlayLoopPromise=void 0);}}async runSetCanPlayOnce(){const t=this.getCurrentSourceKey();if(this.host.videoData?.videoId&&t===this.lastSetCanPlaySourceKey)return;try{this.host.videoData=await this.host.getVideoData();}catch{this.host.videoData=void 0,Ae(this.host.uiManager.votOverlayView,{hideMenu:true});return}this.activeSetCanPlaySourceKey=t;const n=this.startSession(`setCanPlay (source: ${t})`);try{if(await this.handleSrcChanged(n,t),this.isStale(n)){E.log(`[VideoLifecycle][session:${n}] setCanPlay aborted after src change (active: ${this.lifecycleGeneration})`);return}const i=this.runAutoSubtitlesIfEnabled(n);if(await this.host.translationOrchestrator.runAutoTranslationIfEligible(),this.isStale(n)){E.log(`[VideoLifecycle][session:${n}] auto-translation result ignored (stale session)`);return}if(await i,this.isStale(n)){E.log(`[VideoLifecycle][session:${n}] auto-subtitles result ignored (stale session)`);return}E.log(`[VideoLifecycle][session:${n}] setCanPlay finished`);}finally{this.activeSetCanPlaySourceKey===t&&(this.activeSetCanPlaySourceKey="");}}async runAutoSubtitlesIfEnabled(t){if(!(!this.host.data.autoSubtitles||!this.host.videoData?.videoId))try{await this.host.enableSubtitlesForCurrentLangPair();}catch{}}async handleSrcChanged(t,n){const i=typeof t=="number"?t:this.startSession("manual handleSrcChanged"),o=typeof n=="string"&&n.length>0?n:this.getCurrentSourceKey();if(this.shouldAbortHandleSrcChanged(i,"before start"))return;this.host.firstPlay=true;const r=this.host.uiManager.votOverlayView;Dr(this.host,r,{requireVideoData:true}),!this.host.video.src&&!this.host.video.currentSrc&&!this.host.video.srcObject&&Ae(r,{hideMenu:true});const a=this.resolveContainer();if(a!==this.host.container&&(this.host.container=a),this.shouldAbortHandleSrcChanged(i,"before getVideoData")||(r.votButton.container.hidden=false,r.votButton.opacity=1,this.host.queueOverlayAutoHide?.(),this.shouldAbortHandleSrcChanged(i,"after getVideoData")))return;if(!this.host.videoData?.videoId){Ae(r,{hideMenu:true});return}const l=this.host.getSubtitlesCacheKey(this.host.videoData.videoId,this.host.videoData.detectedLanguage,this.host.videoData.responseLanguage);this.host.subtitles=this.host.cacheManager.getSubtitles(l)??[],await this.host.updateSubtitlesLangSelect(),!this.shouldAbortHandleSrcChanged(i,"after subtitles update")&&(this.host.translateToLang=this.host.data.responseLanguage??"ru",this.host.setSelectMenuValues(this.host.videoData.detectedLanguage,this.host.videoData.responseLanguage),r.votButton.container.hidden=false,r.votButton.opacity=1,this.host.queueOverlayAutoHide?.(),this.lastSetCanPlaySourceKey=o);}}const _h=/\b(?:https?:\/\/|www\.)\S+/gi,Oh=/#[^\s#]+/g,Dh=/auto-generated\s+by\s+youtube|provided\s+to\s+youtube\s+by|released\s+on/gi,Bh=/paypal?/gi,Rh=/0x[\da-f]{40}/gi,Nh=/[13][1-9a-z]{25,34}/gi,Fh=/4[\dab][1-9a-z]{93}/gi,Hh=/t[1-9a-z]{33}/gi,$h=[_h,Oh,Dh,Bh,Rh,Nh,Fh,Hh];function Uh(e,t){const n=`${e??""} ${t??""}`.trim();if(!n)return "";let i=n;for(const o of $h)i=i.replaceAll(o,"");return i.replaceAll(/[\p{P}\p{S}]+/gu," ").replaceAll(/\s+/g," ").trim().slice(0,450)}const Br=5e3;let me=null,no=0,ve=null,io=0;async function Wh(){const e=Date.now();if(me&&e-noo){const s=Et(e,"up",i);return Math.min(r,s)}return Et(e,"nearest",i)}const Fr=new Set(["youtube","googledrive"]),Qh=Fr,tf=new Set(["rutube","ok"]),ef=new Set(["youtube","invidious","piped"]);function be(e){return Fr.has(e)}function Hr(e){return Qh.has(e)}function nf(e){return tf.has(e)}function $r(e){return Hr(e.host)&&e.additionalData!=="mobile"}function of(e){return ef.has(e)}const rf={rutube:"ru","ok.ru":"ru",mail_ru:"ru",weverse:"ko",niconico:"ja",youku:"zh",bilibili:"zh",weibo:"zh",zdf:"de"},ro=".ytp-volume-panel [aria-valuenow]";function sf(...e){for(const t of e){if(typeof t!="string")continue;const n=t.trim();if(n)return n}}function Le(e){if(typeof e!="string")return;const t=e.toLowerCase().split(/[-_]/)[0];return _t.includes(t)?t:void 0}function af(e){return !!(e&&e!=="auto")}function lf(e,t,n){const i=sf(e,t,document.title);return Uh(i??"",typeof n=="string"?n:void 0)}function cf(e){const t=rf[e];if(t)return t;if(e==="vk"){const n=document.getElementsByTagName("track")?.[0]?.srclang;return Le(n)}}function so(e){const t=document.querySelector(e),n=t?.getAttribute("aria-valuenow"),i=t?.getAttribute("aria-valuemax"),o=n==null?Number.NaN:Number.parseFloat(n),r=i==null?Number.NaN:Number.parseFloat(i);return Number.isFinite(o)?Number.isFinite(r)&&r>0?dt(o/r*100):dt(o):null}class df{videoHandler;detectInFlightByVideoId=new Map;constructor(t){this.videoHandler=t;}async detectLanguageSingleFlight(t,n){const i=this.detectInFlightByVideoId.get(t);if(i!==void 0)return await i;const o=(async()=>{const r=Le(await Gh(n));return af(r)?r:void 0})();this.detectInFlightByVideoId.set(t,o);try{return await o}finally{this.detectInFlightByVideoId.get(t)===o&&this.detectInFlightByVideoId.delete(t);}}async getVideoData(){const{duration:t,url:n,videoId:i,host:o,title:r,translationHelp:s=null,localizedTitle:a,description:l,detectedLanguage:c,subtitles:d,isStream:u=false}=await Ul(this.videoHandler.site,{fetchFn:tt,video:this.videoHandler.video,language:p.lang}),h=Le(c);let m=h??"auto";if(!h){const y=lf(r,a,l);if(y)try{const k=await this.detectLanguageSingleFlight(i,y);k&&(m=k);}catch{}}const v=cf(this.videoHandler.site.host);v&&(m=v);const b={translationHelp:s,isStream:u,duration:t||this.videoHandler.video?.duration||K.defaultDuration,videoId:i,url:n,host:o,detectedLanguage:m,responseLanguage:this.videoHandler.translateToLang,subtitles:d,title:r,localizedTitle:a,description:l,downloadTitle:a??r??i};return console.log("[VOT] Detected language:",m),b}async videoValidator(){const t=this.videoHandler.videoData,n=this.videoHandler.data;if(!t||!n)throw new it("VOTNoVideoIDFound");if(E.log("VideoValidator videoData: ",this.videoHandler.videoData),this.videoHandler.data.enabledDontTranslateLanguages&&this.videoHandler.data.dontTranslateLanguages?.includes(this.videoHandler.videoData.detectedLanguage))throw new it("VOTDisableFromYourLang");if(this.videoHandler.videoData.isStream)throw new it("VOTStreamNotAvailable");if(this.videoHandler.videoData.duration>14400)throw new it("VOTVideoIsTooLong");return true}getVideoVolume(){const t=this.videoHandler.video;if(t){if(be(this.videoHandler.site.host)){const n=so(ro);if(n!=null)return Xh(n);const i=_.getVolume();if(typeof i=="number"&&Number.isFinite(i))return Et(i)}return Et(t.volume)}}setVideoVolume(t){const n=Et(t);if(!be(this.videoHandler.site.host))return this.videoHandler.video.volume=n,this;try{const i=_.setVolume(n);if(typeof i=="boolean"&&i||typeof i=="number"&&Number.isFinite(i))return this}catch{}return this.videoHandler.video.volume=n,this}isMuted(){return be(this.videoHandler.site.host)?_.isMuted():this.videoHandler.video?.muted}syncVideoVolumeSlider(){const t=this.videoHandler.uiManager.votOverlayView;if(!t?.isInitialized())return this;const n=be(this.videoHandler.site.host)?so(ro):null,i=this.isMuted()?0:n??Nr(this.getVideoVolume()??0);return t.videoVolumeSlider.value=i,this.videoHandler.onVideoVolumeSliderSynced?.(i),this}setSelectMenuValues(t,n){const i=this.videoHandler.videoData;if(!i)return this;const o=Le(t)??"auto";console.log(`[VOT] Set translation from ${o} to ${n}`),i.detectedLanguage=o,i.responseLanguage=n,this.videoHandler.translateFromLang=o,this.videoHandler.translateToLang=n;const r=this.videoHandler.uiManager.votOverlayView;if(!r?.isInitialized())return this;r.languagePairSelect.fromSelect.selectTitle=p.getLangLabel(o),r.languagePairSelect.toSelect.selectTitle=p.getLangLabel(n),r.languagePairSelect.fromSelect.setSelectedValue(o),r.languagePairSelect.toSelect.setSelectedValue(n);}}const Hn=globalThis,ao=e=>e,Ve=Hn.trustedTypes,lo=Ve?Ve.createPolicy("lit-html",{createHTML:e=>e}):void 0,Ur="$lit$",mt=`lit$${Math.random().toFixed(9).slice(2)}$`,Wr="?"+mt,uf=`<${Wr}>`,Mt=document,re=()=>Mt.createComment(""),se=e=>e===null||typeof e!="object"&&typeof e!="function",$n=Array.isArray,hf=e=>$n(e)||typeof e?.[Symbol.iterator]=="function",en=`[ \f\r]`,jt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,co=/-->/g,uo=/>/g,Tt=RegExp(`>|${en}(?:([^\\s"'>=/]+)(${en}*=${en}*(?:[^ \f\r"'\`<>=]|("|')|))|$)`,"g"),ho=/'/g,fo=/"/g,zr=/^(?:script|style|textarea|title)$/i,qr=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),Zt=qr(1),ot=qr(2),ae=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),po=new WeakMap,Ct=Mt.createTreeWalker(Mt,129);function Gr(e,t){if(!$n(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return lo!==void 0?lo.createHTML(t):t}const ff=(e,t)=>{const n=e.length-1,i=[];let o,r=t===2?"":t===3?"":"",s=jt;for(let a=0;a"?(s=o??jt,u=-1):d[1]===void 0?u=-2:(u=s.lastIndex-d[2].length,c=d[1],s=d[3]===void 0?Tt:d[3]==='"'?fo:ho):s===fo||s===ho?s=Tt:s===co||s===uo?s=jt:(s=Tt,o=void 0);const m=s===Tt&&e[a+1].startsWith("/>")?" ":"";r+=s===jt?l+uf:u>=0?(i.push(c),l.slice(0,u)+Ur+l.slice(u)+mt+m):l+mt+(u===-2?a:m);}return [Gr(e,r+(e[n]||"")+(t===2?"":t===3?"":"")),i]};class le{constructor({strings:t,_$litType$:n},i){let o;this.parts=[];let r=0,s=0;const a=t.length-1,l=this.parts,[c,d]=ff(t,n);if(this.el=le.createElement(c,i),Ct.currentNode=this.el.content,n===2||n===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes);}for(;(o=Ct.nextNode())!==null&&l.length0){o.textContent=Ve?Ve.emptyScript:"";for(let m=0;m2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=z;}_$AI(t,n=this,i,o){const r=this.strings;let s=false;if(r===void 0)t=Yt(this,t,n,0),s=!se(t)||t!==this._$AH&&t!==ae,s&&(this._$AH=t);else {const a=t;let l,c;for(t=r[0],l=0;l{const i=t;let o=i._$litPart$;return o===void 0&&(i._$litPart$=o=new pe(t.insertBefore(re(),null),null,void 0,{})),o._$AI(e),o},wf='.vot-button{--vot-helper-theme:var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243));--vot-helper-ontheme:var(--vot-ontheme-rgb,var(--vot-onprimary-rgb,255, 255, 255));box-sizing:border-box;vertical-align:middle;text-align:center;text-overflow:ellipsis;cursor:pointer;min-width:64px;height:36px;color:rgb(var(--vot-helper-ontheme));background-color:rgb(var(--vot-helper-theme));box-shadow:var(--vot-shadow-1);transition:box-shadow var(--vot-duration-medium) var(--vot-easing-standard);outline:none;font-size:14px;line-height:36px;display:inline-block;position:relative;border-radius:var(--vot-radius-s)!important;padding:0 var(--vot-space-4)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;border:none!important;font-weight:500!important}.vot-button:before,.vot-button:after{content:"";opacity:0;position:absolute;inset:0;border-radius:inherit!important}.vot-button:before{background-color:rgb(var(--vot-helper-ontheme));transition:opacity var(--vot-duration-medium) var(--vot-easing-standard)}.vot-button:after{transition:opacity var(--vot-duration-slow) var(--vot-easing-standard),background-size var(--vot-duration-slow) var(--vot-easing-standard);background:radial-gradient(circle,currentColor 1%,#0000 1%) 50%/10000% 10000% no-repeat}.vot-button:hover:before{opacity:.08}.vot-button:active:after{opacity:.32;background-size:100% 100%;transition:background-size}.vot-button:hover,.vot-button:active{box-shadow:var(--vot-shadow-2)}.vot-button[disabled=true]{background-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.12);color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);box-shadow:none;cursor:initial}.vot-button[disabled=true]:before,.vot-button[disabled=true]:after{opacity:0}.vot-outlined-button{--vot-helper-theme:var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243));box-sizing:border-box;vertical-align:middle;text-align:center;text-overflow:ellipsis;cursor:pointer;min-width:64px;height:36px;color:rgb(var(--vot-helper-theme));background-color:#0000;outline:none;font-size:14px;line-height:34px;display:inline-block;position:relative;border-radius:var(--vot-radius-s)!important;padding:0 var(--vot-space-4)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;border:solid 1px var(--vot-border-color)!important;margin:0!important;font-weight:500!important}.vot-outlined-button:before,.vot-outlined-button:after{content:"";opacity:0;position:absolute;inset:0;border-radius:inherit!important}.vot-outlined-button:before{background-color:rgb(var(--vot-helper-theme));transition:opacity var(--vot-duration-medium) var(--vot-easing-standard)}.vot-outlined-button:after{transition:opacity var(--vot-duration-slow) var(--vot-easing-standard),background-size var(--vot-duration-slow) var(--vot-easing-standard);background:radial-gradient(circle,currentColor 1%,#0000 1%) 50%/10000% 10000% no-repeat}.vot-outlined-button:hover:before{opacity:.04}.vot-outlined-button:active:after{opacity:.16;background-size:100% 100%;transition:background-size}.vot-outlined-button[disabled=true]{color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);cursor:initial;background-color:#0000}.vot-outlined-button[disabled=true]:before,.vot-outlined-button[disabled=true]:after{opacity:0}.vot-text-button{--vot-helper-theme:var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243));box-sizing:border-box;vertical-align:middle;text-align:center;text-overflow:ellipsis;cursor:pointer;min-width:64px;height:36px;color:rgb(var(--vot-helper-theme));background-color:#0000;outline:none;font-size:14px;line-height:36px;display:inline-block;position:relative;border-radius:var(--vot-radius-s)!important;padding:0 var(--vot-space-2)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;border:none!important;margin:0!important;font-weight:500!important}.vot-text-button:before,.vot-text-button:after{content:"";opacity:0;position:absolute;inset:0;border-radius:inherit!important}.vot-text-button:before{background-color:rgb(var(--vot-helper-theme));transition:opacity var(--vot-duration-medium) var(--vot-easing-standard)}.vot-text-button:after{transition:opacity var(--vot-duration-slow) var(--vot-easing-standard),background-size var(--vot-duration-slow) var(--vot-easing-standard);background:radial-gradient(circle,currentColor 1%,#0000 1%) 50%/10000% 10000% no-repeat}.vot-text-button:hover:before{opacity:.04}.vot-text-button:active:after{opacity:.16;background-size:100% 100%;transition:background-size}.vot-text-button[disabled=true]{color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);cursor:initial;background-color:#0000}.vot-text-button[disabled=true]:before,.vot-text-button[disabled=true]:after{opacity:0}.vot-icon-button{--vot-helper-onsurface:rgba(var(--vot-onsurface-rgb,0, 0, 0), .87);box-sizing:border-box;vertical-align:middle;text-align:center;text-overflow:ellipsis;cursor:pointer;width:36px;min-width:36px;height:36px;fill:var(--vot-helper-onsurface);color:var(--vot-helper-onsurface);background-color:#0000;outline:none;font-size:14px;line-height:36px;display:inline-block;position:relative;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;border:none!important;border-radius:50%!important;margin:0!important;padding:0!important;font-weight:500!important}.vot-icon-button:before,.vot-icon-button:after{content:"";opacity:0;position:absolute;inset:0;border-radius:inherit!important}.vot-icon-button:before{background-color:var(--vot-helper-onsurface);transition:opacity var(--vot-duration-medium) var(--vot-easing-standard)}.vot-icon-button:after{transition:opacity var(--vot-duration-slow) var(--vot-easing-standard),background-size var(--vot-duration-slow) var(--vot-easing-standard);background:radial-gradient(circle,currentColor 1%,#0000 1%) 50%/10000% 10000% no-repeat}.vot-icon-button:hover:before{opacity:.04}.vot-icon-button:active:after{opacity:.32;background-size:100% 100%;transition:background-size}.vot-icon-button[disabled=true]{color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);fill:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);cursor:initial;background-color:#0000}.vot-icon-button[disabled=true]:before,.vot-icon-button[disabled=true]:after{opacity:0}.vot-icon-button svg{fill:inherit;stroke:inherit;width:24px;height:36px}.vot-hotkey{justify-content:flex-start;align-items:center;gap:var(--vot-space-3,12px);flex-wrap:wrap;display:flex}.vot-hotkey-label{word-break:break-word;max-width:80%}.vot-hotkey-button{--vot-helper-theme:var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243));box-sizing:border-box;vertical-align:middle;text-align:center;text-overflow:ellipsis;cursor:pointer;background-color:#0000;outline:none;width:fit-content;min-width:32px;height:fit-content;font-size:15px;line-height:1.5;display:inline-block;position:relative;border-radius:var(--vot-radius-s)!important;padding:0 var(--vot-space-2)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;border:solid 1px var(--vot-border-color)!important;margin:0!important;font-weight:400!important}.vot-hotkey-button:before,.vot-hotkey-button:after{content:"";opacity:0;position:absolute;inset:0;border-radius:inherit!important}.vot-hotkey-button:before{background-color:rgb(var(--vot-helper-theme));transition:opacity var(--vot-duration-medium) var(--vot-easing-standard)}.vot-hotkey-button:after{transition:opacity var(--vot-duration-slow) var(--vot-easing-standard),background-size var(--vot-duration-slow) var(--vot-easing-standard);background:radial-gradient(circle,currentColor 1%,#0000 1%) 50%/10000% 10000% no-repeat}.vot-hotkey-button:hover:before{opacity:.04}.vot-hotkey-button:active:after{opacity:.16;background-size:100% 100%;transition:background-size}.vot-hotkey-button[data-status=active]{color:rgb(var(--vot-helper-theme))}.vot-hotkey-button[data-status=active]:before{opacity:.04}.vot-hotkey-button[disabled=true]{color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);cursor:initial;background-color:#0000}.vot-hotkey-button[disabled=true]:before,.vot-hotkey-button[disabled=true]:after{opacity:0}.vot-textfield{display:inline-block;--vot-helper-theme:rgb(var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243)))!important;--vot-helper-safari1:rgba(var(--vot-onsurface-rgb,0, 0, 0), .38)!important;--vot-helper-safari2:rgba(var(--vot-onsurface-rgb,0, 0, 0), .6)!important;--vot-helper-safari3:rgba(var(--vot-onsurface-rgb,0, 0, 0), .87)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;text-align:start!important;padding-top:6px!important;font-size:16px!important;line-height:1.5!important;position:relative!important}.vot-textfield>:is(input,textarea){box-sizing:border-box!important;border-style:solid!important;border-width:1px!important;border-color:transparent var(--vot-helper-safari2) var(--vot-helper-safari2)!important;width:100%!important;height:inherit!important;color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.87)!important;-webkit-text-fill-color:currentColor!important;font-family:inherit!important;font-size:inherit!important;line-height:inherit!important;caret-color:var(--vot-helper-theme)!important;background-color:#0000!important;border-radius:4px!important;margin:0!important;padding:15px 13px!important;transition:border .2s,box-shadow .2s!important;box-shadow:inset 1px 0 #0000,inset -1px 0 #0000,inset 0 -1px #0000!important}.vot-textfield>:is(input,textarea):not(:focus):not(:is(.vot-show-placeholder,.vot-show-placeholer))::placeholder{color:#0000!important}.vot-textfield>:is(input,textarea):not(:focus):placeholder-shown{border-top-color:var(--vot-helper-safari2)!important}.vot-textfield>:is(input,textarea)+span{font-family:inherit;width:100%!important;max-height:100%!important;color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.6)!important;cursor:text!important;pointer-events:none!important;font-size:75%!important;line-height:15px!important;transition:color .2s,font-size .2s,line-height .2s!important;display:flex!important;position:absolute!important;top:0!important;left:0!important}.vot-textfield>:is(input,textarea):not(:focus):placeholder-shown+span{font-size:inherit!important;line-height:68px!important}.vot-textfield>input+span:before,.vot-textfield>input+span:after,.vot-textfield>textarea+span:before,.vot-textfield>textarea+span:after{content:""!important;box-sizing:border-box!important;border-top:solid 1px var(--vot-helper-safari2)!important;pointer-events:none!important;min-width:10px!important;height:8px!important;margin-top:6px!important;transition:border .2s,box-shadow .2s!important;display:block!important;box-shadow:inset 0 1px #0000!important}.vot-textfield>input+span:before,.vot-textfield>textarea+span:before{border-left:1px solid #0000!important;border-radius:4px 0!important;margin-right:4px!important}.vot-textfield>input+span:after,.vot-textfield>textarea+span:after{border-right:1px solid #0000!important;border-radius:0 4px!important;flex-grow:1!important;margin-left:4px!important}.vot-textfield>input:is(.vot-show-placeholder,.vot-show-placeholer)+span:before,.vot-textfield>textarea:is(.vot-show-placeholder,.vot-show-placeholer)+span:before{margin-right:0!important}.vot-textfield>input:is(.vot-show-placeholder,.vot-show-placeholer)+span:after,.vot-textfield>textarea:is(.vot-show-placeholder,.vot-show-placeholer)+span:after{margin-left:0!important}.vot-textfield>input:not(:focus):placeholder-shown+span:before,.vot-textfield>input:not(:focus):placeholder-shown+span:after,.vot-textfield>textarea:not(:focus):placeholder-shown+span:before,.vot-textfield>textarea:not(:focus):placeholder-shown+span:after{border-top-color:#0000!important}.vot-textfield:hover>input:not(:disabled),.vot-textfield:hover>textarea:not(:disabled){border-color:transparent var(--vot-helper-safari3) var(--vot-helper-safari3)!important}.vot-textfield:hover>input:not(:disabled)+span:before,.vot-textfield:hover>input:not(:disabled)+span:after,.vot-textfield:hover>textarea:not(:disabled)+span:before,.vot-textfield:hover>textarea:not(:disabled)+span:after{border-top-color:var(--vot-helper-safari3)!important}.vot-textfield:hover>input:not(:disabled):not(:focus):placeholder-shown,.vot-textfield:hover>textarea:not(:disabled):not(:focus):placeholder-shown{border-color:var(--vot-helper-safari3)!important}.vot-textfield>input:focus,.vot-textfield>textarea:focus{border-color:transparent var(--vot-helper-theme) var(--vot-helper-theme)!important;box-shadow:inset 1px 0 var(--vot-helper-theme),inset -1px 0 var(--vot-helper-theme),inset 0 -1px var(--vot-helper-theme)!important;outline:none!important}.vot-textfield>input:focus+span,.vot-textfield>textarea:focus+span{color:var(--vot-helper-theme)!important}.vot-textfield>input:focus+span:before,.vot-textfield>input:focus+span:after,.vot-textfield>textarea:focus+span:before,.vot-textfield>textarea:focus+span:after{border-top-color:var(--vot-helper-theme)!important;box-shadow:inset 0 1px var(--vot-helper-theme)!important}.vot-textfield>input:disabled,.vot-textfield>input:disabled+span,.vot-textfield>textarea:disabled,.vot-textfield>textarea:disabled+span{border-color:transparent var(--vot-helper-safari1) var(--vot-helper-safari1)!important;color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38)!important;pointer-events:none!important}.vot-textfield>input:disabled+span:before,.vot-textfield>input:disabled+span:after,.vot-textfield>textarea:disabled+span:before,.vot-textfield>textarea:disabled+span:after,.vot-textfield>input:disabled:placeholder-shown,.vot-textfield>input:disabled:placeholder-shown+span,.vot-textfield>textarea:disabled:placeholder-shown,.vot-textfield>textarea:disabled:placeholder-shown+span{border-top-color:var(--vot-helper-safari1)!important}.vot-textfield>input:disabled:placeholder-shown+span:before,.vot-textfield>input:disabled:placeholder-shown+span:after,.vot-textfield>textarea:disabled:placeholder-shown+span:before,.vot-textfield>textarea:disabled:placeholder-shown+span:after{border-top-color:#0000!important}@media not all and (min-resolution:.001dpcm){@supports ((-webkit-appearance:none)){.vot-textfield>input,.vot-textfield>input+span,.vot-textfield>textarea,.vot-textfield>textarea+span,.vot-textfield>input+span:before,.vot-textfield>input+span:after,.vot-textfield>textarea+span:before,.vot-textfield>textarea+span:after{transition-duration:.1s!important}}}.vot-checkbox{--vot-checkbox-label-offset:30px;--vot-helper-theme:var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243));--vot-helper-ontheme:var(--vot-ontheme-rgb,var(--vot-onprimary-rgb,255, 255, 255));z-index:0;color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.87);text-align:start;font-size:16px;line-height:1.5;display:inline-block;position:relative;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;text-transform:none!important}.vot-checkbox-sub{padding-left:var(--vot-checkbox-label-offset)!important}.vot-checkbox>input{appearance:none;z-index:10000;box-sizing:border-box;opacity:1;cursor:pointer;background:0 0;outline:none;width:18px;height:18px;transition:border-color .2s,background-color .2s;display:block;position:absolute;border:2px solid!important;border-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.6)!important;border-radius:2px!important;margin:3px 1px!important;padding:0!important}.vot-checkbox>input+span{box-sizing:border-box;width:inherit;cursor:pointer;font-family:inherit;display:inline-block;position:relative;padding-left:var(--vot-checkbox-label-offset)!important;font-weight:400!important}.vot-checkbox>input+span:before{content:"";background-color:rgb(var(--vot-onsurface-rgb,0, 0, 0));opacity:0;pointer-events:none;width:40px;height:40px;transition:opacity .3s,transform .2s;display:block;position:absolute;top:-8px;left:-10px;transform:scale(1);border-radius:50%!important}.vot-checkbox>input+span:after{content:"";z-index:10000;pointer-events:none;width:10px;height:5px;transition:border-color .2s;display:block;position:absolute;top:3px;left:1px;transform:translate(3px,4px)rotate(-45deg);box-sizing:content-box!important;border:0 solid #0000!important;border-width:0 0 2px 2px!important}.vot-checkbox>input:checked,.vot-checkbox>input:indeterminate{background-color:rgb(var(--vot-helper-theme));border-color:rgb(var(--vot-helper-theme))!important}.vot-checkbox>input:checked+span:before,.vot-checkbox>input:indeterminate+span:before{background-color:rgb(var(--vot-helper-theme))}.vot-checkbox>input:checked+span:after,.vot-checkbox>input:indeterminate+span:after{border-color:rgb(var(--vot-helper-ontheme,255, 255, 255))!important}.vot-checkbox>input:hover{box-shadow:none!important}.vot-checkbox>input:indeterminate+span:after{transform:translate(4px,3px);border-left-width:0!important}.vot-checkbox:hover>input+span:before{opacity:.04}.vot-checkbox:active>input,.vot-checkbox:active:hover>input:not(:disabled){border-color:rgb(var(--vot-helper-theme))!important}.vot-checkbox:active>input:checked{background-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.6);border-color:#0000!important}.vot-checkbox:active>input+span:before{opacity:1;transition:transform,opacity;transform:scale(0)}.vot-checkbox>input:disabled{cursor:initial;border-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38)!important}.vot-checkbox>input:disabled:checked,.vot-checkbox>input:disabled:indeterminate{background-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);border-color:#0000!important}.vot-checkbox>input:disabled+span{color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38);cursor:initial}.vot-checkbox>input:disabled+span:before{opacity:0;transform:scale(0)}html.vot-keyboard-nav .vot-checkbox>input:focus-visible{box-shadow:var(--vot-focus-ring),var(--vot-focus-ring-offset)!important}@supports not selector(:focus-visible){html.vot-keyboard-nav .vot-checkbox>input:focus{box-shadow:var(--vot-focus-ring),var(--vot-focus-ring-offset)!important}}.vot-slider{flex-direction:column;gap:6px;display:flex;width:100%!important;color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.87)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", BlinkMacSystemFont, system-ui, -apple-system)!important;text-align:start!important;font-size:16px!important;line-height:1.5!important}.vot-slider>span{order:1;margin:0!important;display:block!important}.vot-slider .vot-slider-label{flex-wrap:wrap;align-items:baseline;gap:6px;width:100%;display:inline-flex}.vot-slider-label-value{font-variant-numeric:tabular-nums;margin-left:0!important;font-weight:500!important}.vot-slider .vot-slider-label-text{min-width:0}.vot-slider>input{order:2;appearance:none!important;cursor:pointer!important;background-color:#0000!important;border:none!important;width:100%!important;height:32px!important;margin:0!important;padding:0!important;display:block!important;position:relative!important;top:0!important}.vot-slider>input:hover{box-shadow:none!important}.vot-slider>input:before{content:""!important;width:calc(100% * var(--vot-progress,0))!important;background:rgb(var(--vot-primary-rgb,33, 150, 243))!important;height:2px!important;display:block!important;position:absolute!important;top:calc(50% - 1px)!important}.vot-slider>input:disabled{cursor:default!important;opacity:.38!important}.vot-slider>input:disabled+span{color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38)!important}.vot-slider>input:disabled::-webkit-slider-runnable-track{background-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38)!important}.vot-slider>input:disabled::-moz-range-track{background-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38)!important}.vot-slider>input:disabled::-webkit-slider-thumb{background-color:rgb(var(--vot-onsurface-rgb,0, 0, 0))!important;box-shadow:0 0 0 1px rgb(var(--vot-surface-rgb,255, 255, 255))!important;transform:scale(4)!important}.vot-slider>input:disabled::-moz-range-thumb{background-color:rgb(var(--vot-onsurface-rgb,0, 0, 0))!important;box-shadow:0 0 0 1px rgb(var(--vot-surface-rgb,255, 255, 255))!important;transform:scale(4)!important}.vot-slider>input:disabled::-moz-range-progress{background-color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.87)!important}.vot-slider>input:focus{outline:none!important}.vot-slider>input::-webkit-slider-runnable-track{background-color:rgba(var(--vot-primary-rgb,33, 150, 243),.24)!important;border-radius:1px!important;width:100%!important;height:2px!important;margin:15px 0!important}.vot-slider>input::-moz-range-track{background-color:rgba(var(--vot-primary-rgb,33, 150, 243),.24)!important;border-radius:1px!important;width:100%!important;height:2px!important;margin:15px 0!important}.vot-slider>input::-webkit-slider-thumb{appearance:none!important;background-color:rgb(var(--vot-primary-rgb,33, 150, 243))!important;width:2px!important;height:2px!important;box-shadow:none!important;border:none!important;border-radius:50%!important;transition:box-shadow .2s!important;transform:scale(6)!important}.vot-slider>input::-moz-range-thumb{appearance:none!important;background-color:rgb(var(--vot-primary-rgb,33, 150, 243))!important;width:2px!important;height:2px!important;box-shadow:none!important;border:none!important;border-radius:50%!important;transition:box-shadow .2s!important;transform:scale(6)!important}.vot-slider>input::-webkit-slider-thumb{-webkit-appearance:none!important;margin:0!important}.vot-slider>input::-moz-range-progress{background-color:rgb(var(--vot-primary-rgb,33, 150, 243))!important;border-radius:1px!important;height:2px!important}.vot-slider>input:focus:not(:focus-visible)::-webkit-slider-thumb{box-shadow:none!important}.vot-slider>input:focus:not(:focus-visible)::-moz-range-thumb{box-shadow:none!important}html.vot-keyboard-nav .vot-slider>input:focus-visible::-webkit-slider-thumb{box-shadow:0 0 0 2px rgba(var(--vot-primary-rgb,33, 150, 243),.24)!important}html.vot-keyboard-nav .vot-slider>input:focus-visible::-moz-range-thumb{box-shadow:0 0 0 2px rgba(var(--vot-primary-rgb,33, 150, 243),.24)!important}@supports not selector(:focus-visible){html.vot-keyboard-nav .vot-slider>input:focus::-webkit-slider-thumb{box-shadow:0 0 0 2px rgba(var(--vot-primary-rgb,33, 150, 243),.24)!important}html.vot-keyboard-nav .vot-slider>input:focus::-moz-range-thumb{box-shadow:0 0 0 2px rgba(var(--vot-primary-rgb,33, 150, 243),.24)!important}}.vot-select{--vot-helper-theme-rgb:var(--vot-onsurface-rgb,0, 0, 0);--vot-helper-theme:rgba(var(--vot-helper-theme-rgb), .87);--vot-helper-safari1:rgba(var(--vot-onsurface-rgb,0, 0, 0), .6);--vot-helper-safari2:rgba(var(--vot-onsurface-rgb,0, 0, 0), .87);font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif);text-align:start;color:var(--vot-helper-theme);fill:var(--vot-helper-theme);justify-content:space-between;align-items:center;font-size:14px;line-height:1.5;display:flex;font-weight:400!important}.vot-select-outer{cursor:pointer;justify-content:space-between;align-items:center;width:120px;max-width:120px;display:flex;border:1px solid var(--vot-helper-safari1)!important;border-radius:4px!important;padding:0 5px!important;transition:border .2s!important}.vot-select-outer:hover{border-color:var(--vot-helper-safari2)!important}.vot-select-outer[disabled=true]{opacity:.5;cursor:default}.vot-select-outer[disabled=true]:hover{border-color:var(--vot-helper-safari1)!important}.vot-select-title{text-overflow:ellipsis;white-space:nowrap;font-family:inherit;overflow:hidden}.vot-select-arrow-icon{justify-content:center;align-items:center;width:20px;height:32px;display:flex}.vot-select-arrow-icon svg{fill:inherit;stroke:inherit}.vot-select-content-list{flex-direction:column;display:flex}.vot-select-content-list .vot-select-content-item{cursor:pointer;border-radius:8px!important;padding:5px 10px!important}.vot-select-content-list .vot-select-content-item:not([inert]):hover{background-color:#2a2c31}.vot-select-content-list .vot-select-content-item[data-vot-selected=true]{color:rgb(var(--vot-primary-rgb,33, 150, 243));background-color:rgba(var(--vot-primary-rgb,33, 150, 243),.2)}.vot-select-content-list .vot-select-content-item[data-vot-selected=true]:hover{background-color:rgba(var(--vot-primary-rgb,33, 150, 243),.1)!important}.vot-select-content-list .vot-select-content-item[inert]{cursor:default;color:rgba(var(--vot-onsurface-rgb,0, 0, 0),.38)}.vot-header{color:rgba(var(--vot-helper-onsurface-rgb),.87);font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif);text-align:start;line-height:1.5;font-weight:700!important}.vot-header:not(:first-child){padding-top:8px}.vot-header-level-1{font-size:2em}.vot-header-level-2{font-size:1.5em}.vot-header-level-3{font-size:1.17em}.vot-header-level-4{font-size:1em}.vot-header-level-5{font-size:.83em}.vot-header-level-6{font-size:.67em}.vot-info{color:rgba(var(--vot-helper-onsurface-rgb),.87);font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif);text-align:start;-webkit-user-select:text;user-select:text;font-size:16px;line-height:1.5;display:flex}.vot-info>:not(:first-child){color:rgba(var(--vot-helper-onsurface-rgb),.5);flex:1;margin-left:8px!important}.vot-details{color:rgba(var(--vot-helper-onsurface-rgb),.87);font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif);text-align:start;cursor:pointer;transition:background var(--vot-duration-medium) var(--vot-easing-standard);justify-content:space-between;align-items:center;font-size:16px;line-height:1.5;display:flex;border-radius:.5em!important;margin:-.5em!important;padding:.5em!important}.vot-details-arrow-icon{width:20px;height:32px;fill:rgba(var(--vot-helper-onsurface-rgb),.87);justify-content:center;align-items:center;display:flex;transform:scale(1.25)rotate(-90deg)}.vot-details:hover{background:rgba(var(--vot-onsurface-rgb,0, 0, 0),.06)}.vot-settings-section{border:1px solid var(--vot-border-color);border-radius:var(--vot-radius-l);padding:var(--vot-space-2);background:rgba(var(--vot-helper-onsurface-rgb),.03);flex-direction:column;display:flex}.vot-settings-section>*{margin:0!important}.vot-settings-section>*+*{margin-top:var(--vot-space-2)!important}.vot-settings-section-header{border-radius:var(--vot-radius-m);margin:0!important;padding:.45em .5em!important}.vot-settings-section-header .vot-details-arrow-icon{transition:transform var(--vot-duration-medium) var(--vot-easing-standard)}.vot-settings-section-header[data-open=true] .vot-details-arrow-icon{transform:scale(1.25)rotate(0)}.vot-settings-section-content{--vot-settings-control-width:200px;--vot-settings-row-gap:var(--vot-space-2);padding:0 var(--vot-space-1) var(--vot-space-1);flex-direction:column;display:flex}.vot-settings-section-content>*{margin:0!important}.vot-settings-section-content>*+*{margin-top:var(--vot-settings-row-gap)!important}.vot-settings-section-content>.vot-checkbox,.vot-settings-section-content>.vot-hotkey,.vot-settings-section-content>.vot-textfield,.vot-settings-section-content>.vot-select,.vot-settings-section-content>.vot-slider{padding:var(--vot-space-1);box-sizing:border-box;width:100%!important}.vot-settings-section-content>.vot-textfield{gap:var(--vot-space-1);flex-direction:column;padding-top:0!important;display:flex!important}.vot-settings-section-content>.vot-textfield>span{order:0;width:auto!important;max-height:none!important;color:rgba(var(--vot-helper-onsurface-rgb),.72)!important;cursor:default!important;pointer-events:none!important;font-size:13px!important;line-height:1.2!important;display:block!important;position:static!important}.vot-settings-section-content>.vot-textfield>span:before,.vot-settings-section-content>.vot-textfield>span:after{content:none!important;display:none!important}.vot-settings-section-content>.vot-textfield>input,.vot-settings-section-content>.vot-textfield>textarea{transition:border-color var(--vot-duration-fast) var(--vot-easing-standard),background-color var(--vot-duration-fast) var(--vot-easing-standard);order:1;width:100%!important;height:36px!important;padding:0 var(--vot-space-3)!important;border:1px solid var(--vot-border-color)!important;border-radius:var(--vot-radius-s)!important;background:rgba(var(--vot-helper-onsurface-rgb),.04)!important;color:rgba(var(--vot-helper-onsurface-rgb),.9)!important;-webkit-text-fill-color:currentColor!important;box-shadow:none!important}.vot-settings-section-content>.vot-textfield>textarea{resize:vertical;height:auto!important;min-height:84px!important;padding:var(--vot-space-2) var(--vot-space-3)!important}.vot-settings-section-content>.vot-textfield>input::placeholder,.vot-settings-section-content>.vot-textfield>textarea::placeholder{color:rgba(var(--vot-helper-onsurface-rgb),.55)!important}.vot-settings-section-content>.vot-textfield:hover>input,.vot-settings-section-content>.vot-textfield:hover>textarea{border-color:var(--vot-border-color-hover)!important}.vot-settings-section-content>.vot-textfield>input:not(:focus):placeholder-shown,.vot-settings-section-content>.vot-textfield>textarea:not(:focus):placeholder-shown{border-color:var(--vot-border-color)!important}.vot-settings-section-content>.vot-textfield>input:focus,.vot-settings-section-content>.vot-textfield>textarea:focus{border-color:rgba(var(--vot-primary-rgb),.7)!important}.vot-lang-select{--vot-helper-theme-rgb:var(--vot-onsurface-rgb,0, 0, 0);--vot-helper-theme:rgba(var(--vot-helper-theme-rgb), .87);color:var(--vot-helper-theme);fill:var(--vot-helper-theme);justify-content:space-between;align-items:center;display:flex}.vot-lang-select-icon{justify-content:center;align-items:center;width:32px;height:32px;display:flex}.vot-lang-select-icon svg{fill:inherit;stroke:inherit}.vot-segmented-button{--vot-helper-theme-rgb:var(--vot-onsurface-rgb,0, 0, 0);--vot-helper-theme:rgba(var(--vot-helper-theme-rgb), .87);-webkit-user-select:none;user-select:none;background:rgb(var(--vot-surface-rgb,255, 255, 255));max-width:100vw;height:36px;color:var(--vot-helper-theme);fill:var(--vot-helper-theme);cursor:default;transition:opacity var(--vot-duration-slow) var(--vot-easing-standard);z-index:2147483647;align-items:center;font-size:16px;line-height:1.5;display:flex;position:absolute;top:5rem;left:50%;overflow:hidden;transform:translate(-50%);opacity:1!important;pointer-events:auto!important;touch-action:none!important;border:1px solid var(--vot-border-color)!important;border-radius:var(--vot-radius-s)!important;box-shadow:var(--vot-shadow-1)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important}.vot-segmented-button.vot-segmented-button--hidden{opacity:0!important;pointer-events:none!important}.vot-segmented-button *{box-sizing:border-box!important}.vot-segmented-button .vot-separator{background:rgba(var(--vot-helper-theme-rgb),.1);width:1px;height:50%}.vot-segmented-button .vot-segment,.vot-segmented-button .vot-segment-only-icon{height:100%;color:inherit;transition:background-color var(--vot-duration-fast) var(--vot-easing-standard);-webkit-tap-highlight-color:transparent;background-color:#0000;outline:none;justify-content:center;align-items:center;display:flex;position:relative;overflow:hidden;padding:0 var(--vot-space-2)!important;border:none!important}.vot-segmented-button .vot-segment:focus,.vot-segmented-button .vot-segment-only-icon:focus{box-shadow:inset 0 0 0 2px var(--vot-focus-ring-color);outline:none}.vot-segmented-button .vot-segment:focus:not(:focus-visible),.vot-segmented-button .vot-segment-only-icon:focus:not(:focus-visible){box-shadow:none}.vot-segmented-button .vot-segment:before,.vot-segmented-button .vot-segment-only-icon:before,.vot-segmented-button .vot-segment:after,.vot-segmented-button .vot-segment-only-icon:after{content:"";opacity:0;position:absolute;inset:0;border-radius:inherit!important}.vot-segmented-button .vot-segment:before,.vot-segmented-button .vot-segment-only-icon:before{background-color:rgb(var(--vot-helper-theme-rgb));transition:opacity var(--vot-duration-medium) var(--vot-easing-standard)}.vot-segmented-button .vot-segment:after,.vot-segmented-button .vot-segment-only-icon:after{transition:opacity var(--vot-duration-slow) var(--vot-easing-standard),background-size var(--vot-duration-slow) var(--vot-easing-standard);background:radial-gradient(circle,currentColor 1%,#0000 1%) 50%/10000% 10000% no-repeat}.vot-segmented-button .vot-segment:hover:before,.vot-segmented-button .vot-segment-only-icon:hover:before{opacity:.04}.vot-segmented-button .vot-segment:active:after,.vot-segmented-button .vot-segment-only-icon:active:after{opacity:.16;background-size:100% 100%;transition:background-size}.vot-segmented-button .vot-segment-only-icon{min-width:36px;padding:0!important}.vot-segmented-button .vot-segment-label{white-space:nowrap;color:inherit;margin-left:var(--vot-space-2)!important;font-weight:400!important}.vot-segmented-button[data-status=success] .vot-translate-button{color:rgb(var(--vot-primary-rgb,33, 150, 243));fill:rgb(var(--vot-primary-rgb,33, 150, 243))}.vot-segmented-button[data-status=error] .vot-translate-button{color:#f28b82;fill:#f28b82}.vot-segmented-button[data-loading=true] #vot-loading-icon{display:block!important}.vot-segmented-button[data-loading=true] #vot-translate-icon{display:none!important}.vot-segmented-button[data-direction=column]{flex-direction:column;height:fit-content}.vot-segmented-button[data-direction=column] .vot-segment-label{display:none}.vot-segmented-button[data-direction=column]>.vot-segment-only-icon,.vot-segmented-button[data-direction=column]>.vot-segment{padding:8px!important}.vot-segmented-button[data-direction=column] .vot-separator{width:50%;height:1px}.vot-segmented-button[data-position=left]{top:12.5vh;left:50px}.vot-segmented-button[data-position=right]{top:12.5vh;left:auto;right:0}.vot-segmented-button svg{width:24px;fill:inherit;stroke:inherit}.vot-tooltip{--vot-helper-theme-rgb:var(--vot-onsurface-rgb,0, 0, 0);--vot-helper-theme:rgba(var(--vot-helper-theme-rgb), .87);--vot-helper-ondialog:rgb(var(--vot-ondialog-rgb,37, 38, 40));--vot-helper-border:rgb(var(--vot-tooltip-border,69, 69, 69));-webkit-user-select:none;user-select:none;background:rgb(var(--vot-surface-rgb,255, 255, 255));color:var(--vot-helper-theme);fill:var(--vot-helper-theme);cursor:default;z-index:2147483647;opacity:0;align-items:center;width:max-content;max-width:calc(100vw - 10px);height:max-content;font-size:14px;line-height:1.5;transition:opacity .5s;display:flex;position:absolute;inset:0;overflow:hidden;box-shadow:0 1px 3px #0000001f;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;border-radius:4px!important;padding:4px 8px!important}.vot-tooltip[data-trigger=click]{-webkit-user-select:text;user-select:text}.vot-tooltip.vot-tooltip-bordered{border:1px solid var(--vot-helper-border)}.vot-tooltip *{box-sizing:border-box!important;font-family:inherit!important}.vot-menu{--vot-helper-surface-rgb:var(--vot-surface-rgb,255, 255, 255);--vot-helper-surface:rgb(var(--vot-helper-surface-rgb));--vot-helper-onsurface-rgb:var(--vot-onsurface-rgb,0, 0, 0);--vot-helper-onsurface:rgba(var(--vot-helper-onsurface-rgb), .87);--vot-settings-control-width:clamp(120px, 45%, 200px);-webkit-user-select:none;user-select:none;background-color:var(--vot-helper-surface);color:var(--vot-helper-onsurface);cursor:default;z-index:2147483646;visibility:visible;opacity:1;transform-origin:top;width:fit-content;min-width:320px;max-width:min(90vw,560px);transition:opacity var(--vot-duration-medium) var(--vot-easing-standard),transform var(--vot-duration-medium) var(--vot-easing-standard);font-size:16px;line-height:1.5;position:absolute;top:calc(5rem + 48px);left:50%;overflow:hidden;transform:translate(-50%)scale(1);border:1px solid var(--vot-border-color)!important;border-radius:var(--vot-radius-m)!important;box-shadow:var(--vot-shadow-2)!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important}.vot-menu *{box-sizing:border-box!important}.vot-menu[hidden]{pointer-events:none;visibility:hidden;opacity:0;transform:translate(-50%,-4px)scale(.98);display:block!important}.vot-menu-content-wrapper{min-width:320px;min-height:100px;max-height:calc(var(--vot-container-height,75vh) - (5rem + 32px + 16px) * 2);flex-direction:column;display:flex;overflow:auto}.vot-menu-header-container{flex-shrink:0;align-items:center;min-height:31px;display:flex;padding-inline-end:var(--vot-space-2)!important}.vot-menu-header-container:empty{padding:0 0 16px!important}.vot-menu-header-container>.vot-icon-button{margin-inline-end:var(--vot-space-1)!important;margin-top:var(--vot-space-1)!important}.vot-menu-title-container{font-size:inherit;text-align:start;outline:0;flex:1;display:flex;font-weight:inherit!important;margin:0!important}.vot-menu-title{flex:1;font-size:16px;line-height:1;padding:var(--vot-space-4)!important;font-weight:500!important}.vot-menu-body-container{box-sizing:border-box;gap:var(--vot-space-2);overscroll-behavior:contain;flex-direction:column;min-height:1.375rem;display:flex;overflow:auto;padding:0 var(--vot-space-4)!important;scrollbar-color:rgba(var(--vot-helper-onsurface-rgb),.1) var(--vot-helper-surface)!important}.vot-menu-body-container::-webkit-scrollbar{background:var(--vot-helper-surface)!important;width:12px!important;height:12px!important}.vot-menu-body-container::-webkit-scrollbar-track{background:var(--vot-helper-surface)!important;width:12px!important;height:12px!important}.vot-menu-body-container::-webkit-scrollbar-thumb{border-radius:1ex;background:rgba(var(--vot-helper-onsurface-rgb),.1)!important;border:5px solid var(--vot-helper-surface)!important}.vot-menu-body-container::-webkit-scrollbar-thumb:hover{border-width:3px!important}.vot-menu-body-container::-webkit-scrollbar-corner{background:var(--vot-helper-surface)!important}.vot-menu-footer-container{flex-shrink:0;justify-content:flex-end;display:flex;padding:var(--vot-space-4)!important}.vot-menu-footer-container:empty{padding:var(--vot-space-4) 0 0 0!important}.vot-menu .vot-select--labeled>.vot-select-outer{margin-left:auto}.vot-menu[data-position=left]{transform-origin:0;top:12.5vh;left:240px}.vot-menu[data-position=right]{transform-origin:100%;top:12.5vh;left:auto;right:-80px}.vot-dialog{--vot-helper-surface-rgb:var(--vot-surface-rgb,255, 255, 255);--vot-helper-surface:rgb(var(--vot-helper-surface-rgb));--vot-helper-onsurface-rgb:var(--vot-onsurface-rgb,0, 0, 0);--vot-helper-onsurface:rgba(var(--vot-helper-onsurface-rgb), .87);--vot-dialog-viewport-margin:16px;--vot-dialog-max-height:75vh;max-width:initial;max-height:initial;width:min(var(--vot-dialog-width,512px),100%);border:1px solid var(--vot-border-color);border-radius:var(--vot-radius-l);background-color:var(--vot-helper-surface);height:fit-content;color:var(--vot-helper-onsurface);box-shadow:var(--vot-shadow-2);-webkit-user-select:none;user-select:none;visibility:visible;opacity:1;transform-origin:50%;transition:opacity var(--vot-duration-medium) var(--vot-easing-standard),transform var(--vot-duration-medium) var(--vot-easing-standard);font-size:16px;line-height:1.5;display:block;position:fixed;inset-block:0;inset-inline:0;overflow:auto hidden;transform:scale(1);font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;margin:auto!important;padding:0!important}[hidden]>.vot-dialog{pointer-events:none;opacity:0;transition:opacity var(--vot-duration-fast) var(--vot-easing-standard),transform var(--vot-duration-medium) var(--vot-easing-standard);transform:translateY(-4px)scale(.98)}.vot-dialog[data-vertical-align=top]{inset-block-start:var(--vot-dialog-viewport-margin);inset-block-end:auto;margin:0 auto!important}.vot-dialog-container{visibility:visible;z-index:2147483647;position:absolute}.vot-dialog-container[hidden]{pointer-events:none;visibility:hidden;display:block!important}.vot-dialog-container *{box-sizing:border-box!important}.vot-dialog-backdrop{opacity:1;background-color:#0009;transition:opacity .3s;position:fixed;inset:0}[hidden]>.vot-dialog-backdrop{pointer-events:none;opacity:0}.vot-dialog-content-wrapper{max-height:var(--vot-dialog-max-height,75vh);flex-direction:column;display:flex;overflow:auto}.vot-dialog-header-container{flex-shrink:0;align-items:flex-start;min-height:31px;display:flex}.vot-dialog-header-container:empty{padding:0 0 20px}.vot-dialog-header-container>.vot-icon-button{margin-inline-end:var(--vot-space-1)!important;margin-top:var(--vot-space-1)!important}.vot-dialog-title-container{font-size:inherit;outline:0;flex:1;display:flex;font-weight:inherit!important;margin:0!important}.vot-dialog-title{flex:1;font-size:115.385%;line-height:1;padding:var(--vot-space-5) var(--vot-space-5) var(--vot-space-4)!important;font-weight:700!important}.vot-dialog-body-container{box-sizing:border-box;gap:var(--vot-space-4);overscroll-behavior:contain;flex-direction:column;min-height:1.375rem;display:flex;overflow:auto;padding:0 var(--vot-space-5)!important;scrollbar-color:rgba(var(--vot-helper-onsurface-rgb),.1) var(--vot-helper-surface)!important}.vot-dialog-body-container::-webkit-scrollbar{background:var(--vot-helper-surface)!important;width:12px!important;height:12px!important}.vot-dialog-body-container::-webkit-scrollbar-track{background:var(--vot-helper-surface)!important;width:12px!important;height:12px!important}.vot-dialog-body-container::-webkit-scrollbar-thumb{border-radius:1ex;background:rgba(var(--vot-helper-onsurface-rgb),.1)!important;border:5px solid var(--vot-helper-surface)!important}.vot-dialog-body-container::-webkit-scrollbar-thumb:hover{border-width:3px!important}.vot-dialog-body-container::-webkit-scrollbar-corner{background:var(--vot-helper-surface)!important}.vot-dialog-footer-container{justify-content:flex-end;gap:var(--vot-space-2);flex-wrap:wrap;flex-shrink:0;display:flex;padding:var(--vot-space-4)!important}.vot-dialog-footer-container:empty{padding:var(--vot-space-5) 0 0 0!important}@media(max-width:480px){.vot-dialog-footer-container{flex-direction:column;align-items:stretch}.vot-dialog-footer-container>:is(.vot-button,.vot-outlined-button,.vot-text-button){white-space:normal;text-overflow:clip;text-align:center;justify-content:center;align-items:center;width:100%;height:auto;min-height:36px;padding:8px 16px;line-height:1.2;display:flex;overflow:visible}}.vot-inline-loader{aspect-ratio:5;--vot-loader-bg:no-repeat radial-gradient(farthest-side, rgba(var(--vot-onsurface-rgb,0, 0, 0), .38) 94%, transparent);background:var(--vot-loader-bg),var(--vot-loader-bg),var(--vot-loader-bg),var(--vot-loader-bg);background-size:20% 100%;height:8px;animation:.75s infinite alternate dotsSlide,1.5s infinite alternate dotsFlip}.vot-loader-progress{--vot-helper-theme:var(--vot-theme-rgb,var(--vot-primary-rgb,33, 150, 243));fill:none;stroke:rgb(var(--vot-helper-theme));stroke-width:2px;stroke-linecap:round;transform-origin:50%;transform:rotate(-90deg)}@keyframes dotsSlide{0%,10%{background-position:0 0,0 0,0 0,0 0}33%{background-position:0 0,33.3333% 0,33.3333% 0,33.3333% 0}66%{background-position:0 0,33.3333% 0,66.6667% 0,66.6667% 0}90%,to{background-position:0 0,33.3333% 0,66.6667% 0,100% 0}}@keyframes dotsFlip{0%,49.99%{transform:scale(1)}50%,to{transform:scale(-1)}}.vot-label{font-family:inherit;font-size:16px;line-height:1.5;display:block}.vot-label-text{display:inline}.vot-label-icon{vertical-align:text-bottom;cursor:help;justify-content:center;align-items:center;width:20px;height:20px;margin-left:4px;display:inline-flex}.vot-label-icon>svg{width:20px;height:20px;display:block}.vot-account{justify-content:space-between;align-items:center;gap:1rem;display:flex}.vot-account-container,.vot-account-wrapper,.vot-account-buttons{align-items:center;gap:1rem;display:flex}.vot-account-avatar{min-width:36px;max-width:36px;min-height:36px;max-height:36px;overflow:hidden}.vot-account-avatar-img{object-fit:cover;border-radius:50%;width:36px;height:36px}.vot-subtitles{--vot-subtitles-background:rgba(var(--vot-surface-rgb,46, 47, 52), var(--vot-subtitles-opacity,.8));max-width:var(--vot-subtitles-max-width,70vw);background:var(--vot-subtitles-background,#2e2f34cc);width:max-content;color:var(--vot-subtitles-color,#e3e3e3);pointer-events:all;touch-action:none;font-size:calc(var(--vot-subtitles-font-size,clamp(18px, 2.2vw, 36px)) * var(--vot-subtitles-scale-compensation,1));text-shadow:var(--vot-subtitles-text-shadow,0 1px 2px #0009, 0 2px 8px #00000059);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-synthesis:none;position:relative;--vot-subtitles-font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;font-family:var(--vot-subtitles-font-family)!important;font-style:normal!important;font-weight:var(--vot-subtitles-font-weight,500)!important;text-transform:none!important;letter-spacing:normal!important;border-radius:.5em!important;padding:.5em .75em!important;line-height:1.25!important}.vot-subtitles,.vot-subtitles *{font-family:var(--vot-subtitles-font-family)!important}.vot-subtitles{box-sizing:border-box;-webkit-user-select:none;user-select:none;contain:layout paint;isolation:isolate;text-align:center;margin:0 auto;display:block}.vot-subtitles.vot-subtitles--multiline{text-align:center}.vot-subtitles{text-wrap:wrap;white-space:normal;overflow-wrap:break-word}.vot-subtitles-widget{box-sizing:border-box;z-index:2147483647;--vot-subtitles-fallback-bottom-inset: calc(env(safe-area-inset-bottom,0px) + clamp(56px, 10vh, 220px) + 10px) ;left:50%;top:calc(100% - var(--vot-subtitles-fallback-bottom-inset));width:max-content;max-width:var(--vot-subtitles-max-width,70vw);pointer-events:none;will-change:left,top,transform;max-height:100%;display:block;position:absolute;transform:translate(-50%,-100%)}.vot-subtitles-info{flex-direction:column;gap:2px;display:flex;padding:6px!important}.vot-subtitles-info-service{color:var(--vot-subtitles-context-color,#86919b);margin-bottom:8px!important;font-size:10px!important;line-height:1!important}.vot-subtitles-info-header{color:var(--vot-subtitles-header-color,#fff);margin-bottom:6px!important;font-size:20px!important;font-weight:500!important;line-height:1!important}.vot-subtitles-info-context{color:var(--vot-subtitles-context-color,#86919b);font-size:12px!important;line-height:1.2!important}.vot-subtitles span{cursor:pointer;white-space:normal;overflow-wrap:inherit;word-break:normal;position:relative;font-size:inherit!important;font-family:inherit!important;font-style:inherit!important;font-weight:inherit!important;line-height:inherit!important;text-transform:inherit!important;text-decoration:none!important}.vot-subtitles span.passed{color:var(--vot-subtitles-passed-color,#2196f3)}.vot-subtitles span:before{content:"";z-index:-1;width:100%;height:100%;position:absolute;inset:2px -2px;border-radius:4px!important;padding:0 2px!important}.vot-subtitles span:hover:before{background:var(--vot-subtitles-hover-color,#ffffff8c)}.vot-subtitles span.selected:before{background:var(--vot-subtitles-passed-color,#2196f3)}@media(max-width:900px)and (pointer:coarse){.vot-subtitles-widget{--vot-subtitles-fallback-bottom-inset:env(safe-area-inset-bottom,0px)}}:-webkit-any(:-webkit-full-screen .vot-subtitles,:-webkit-full-screen .vot-subtitles){max-width:var(--vot-subtitles-max-width,80vw);font-size:calc(var(--vot-subtitles-font-size,clamp(18px, 2vw, 34px)) * var(--vot-subtitles-fullscreen-scale,1) * .95 * var(--vot-subtitles-scale-compensation,1))}:is(:fullscreen .vot-subtitles){max-width:var(--vot-subtitles-max-width,80vw);font-size:calc(var(--vot-subtitles-font-size,clamp(18px, 2vw, 34px)) * var(--vot-subtitles-fullscreen-scale,1) * .95 * var(--vot-subtitles-scale-compensation,1))}#vot-subtitles-info.vot-subtitles-info *{-webkit-user-select:text!important;user-select:text!important}:root{--vot-font-family:"Roboto", "Segoe UI", system-ui, sans-serif;--vot-primary-rgb:139, 180, 245;--vot-onprimary-rgb:32, 33, 36;--vot-surface-rgb:32, 33, 36;--vot-onsurface-rgb:227, 227, 227;--vot-subtitles-color:rgb(var(--vot-onsurface-rgb,227, 227, 227));--vot-subtitles-passed-color:rgb(var(--vot-primary-rgb,33, 150, 243));--vot-space-1:4px;--vot-space-2:8px;--vot-space-3:12px;--vot-space-4:16px;--vot-space-5:20px;--vot-space-6:24px;--vot-radius-xs:6px;--vot-radius-s:10px;--vot-radius-m:14px;--vot-radius-l:18px;--vot-border-color:rgba(var(--vot-onsurface-rgb,227, 227, 227), .14);--vot-border-color-hover:rgba(var(--vot-onsurface-rgb,227, 227, 227), .22);--vot-shadow-1:0 1px 2px #0000002e, 0 8px 24px #00000024;--vot-shadow-2:0 2px 4px #00000038, 0 12px 32px #00000038;--vot-duration-fast:.12s;--vot-duration-medium:.2s;--vot-duration-slow:.32s;--vot-easing-standard:cubic-bezier(.4, 0, .2, 1);--vot-focus-ring-color:rgba(var(--vot-primary-rgb,139, 180, 245), .9);--vot-focus-ring:0 0 0 2px var(--vot-focus-ring-color);--vot-focus-ring-offset:0 0 0 4px rgba(var(--vot-surface-rgb,32, 33, 36), .9)}vot-block,vot-block *{box-sizing:border-box;-webkit-tap-highlight-color:transparent}vot-block[hidden]:not(.vot-menu):not(.vot-dialog-container),vot-block [hidden]:not(.vot-menu):not(.vot-dialog-container){display:none!important}vot-block{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizelegibility;-moz-text-size-adjust:100%;text-size-adjust:100%;display:block;--vot-font-family:"Roboto", "Segoe UI", system-ui, sans-serif!important;font-family:var(--vot-font-family,"Roboto", "Segoe UI", system-ui, sans-serif)!important;visibility:visible!important;font-weight:400!important}vot-block *{font-weight:inherit!important}.vot-portal-local,.vot-subtitles-widget{isolation:isolate}vot-block:focus,vot-block :focus{box-shadow:none!important;outline:none!important}html.vot-keyboard-nav vot-block:focus-visible,html.vot-keyboard-nav vot-block :focus-visible{box-shadow:var(--vot-focus-ring),var(--vot-focus-ring-offset)!important}@supports not selector(:focus-visible){html.vot-keyboard-nav vot-block:focus,html.vot-keyboard-nav vot-block :focus{box-shadow:var(--vot-focus-ring),var(--vot-focus-ring-offset)!important}}@media(prefers-reduced-motion:reduce){.vot-portal-local *,.vot-portal *,.vot-subtitles-widget *{scroll-behavior:auto!important;transition-duration:.001ms!important;animation-duration:.001ms!important;animation-iteration-count:1!important}}.vot-portal{display:inline}.vot-portal-local{z-index:2147483647;position:fixed;top:0;left:0}';As(wf);function kf(){if(globalThis.__votKeyboardNavInitialized)return;globalThis.__votKeyboardNavInitialized=true;const e=document.documentElement,t="vot-keyboard-nav",n=()=>e.classList.add(t),i=()=>e.classList.remove(t);globalThis.addEventListener("keydown",o=>{o.key==="Tab"&&n();},true);for(const o of ["pointerdown","mousedown","touchstart"])globalThis.addEventListener(o,i,{capture:true,passive:true});}kf();const w={makeButtonLike(e,{ariaLabel:t}={}){e.setAttribute("role","button"),e.hasAttribute("tabindex")||(e.tabIndex=0);const n=e.tabIndex,i=()=>{e.getAttribute("disabled")==="true"?(e.setAttribute("aria-disabled","true"),e.tabIndex=-1):(e.removeAttribute("aria-disabled"),e.tabIndex=n);};return i(),new MutationObserver(()=>i()).observe(e,{attributes:true,attributeFilter:["disabled"]}),t&&e.setAttribute("aria-label",t),e.addEventListener("keydown",o=>{e.getAttribute("disabled")==="true"||e.getAttribute("aria-disabled")==="true"||(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),e.click());}),e},createEl(e,t=[],n=null){const i=document.createElement(e);return t.length&&i.classList.add(...t),n!==null&&i.append(n),i},createHeader(e,t=4){return w.createEl("vot-block",["vot-header",`vot-header-level-${t}`],e)},createInformation(e,t){const n=w.createEl("vot-block",["vot-info"]),i=w.createEl("vot-block");Q(e,i);const o=w.createEl("vot-block");return Q(t,o),n.append(i,o),{container:n,header:i,value:o}},createButton(e){const t=w.createEl("vot-block",["vot-button"],e);return w.makeButtonLike(t)},createTextButton(e){const t=w.createEl("vot-block",["vot-text-button"],e);return w.makeButtonLike(t)},createOutlinedButton(e){const t=w.createEl("vot-block",["vot-outlined-button"],e);return w.makeButtonLike(t)},createIconButton(e,t={}){const n=w.createEl("vot-block",["vot-icon-button"]);return Q(e,n),w.makeButtonLike(n,t)},createInlineLoader(){return w.createEl("vot-block",["vot-inline-loader"])},createPortal(e=false){return w.createEl("vot-block",[`vot-portal${e?"-local":""}`])},createSubtitleInfo(e,t,n){const i=w.createEl("vot-block",["vot-subtitles-info"]);i.id="vot-subtitles-info";const o=w.createEl("vot-block",["vot-subtitles-info-service"],p.get("VOTTranslatedBy").replace("{0}",n)),r=w.createEl("vot-block",["vot-subtitles-info-header"],e),s=w.createEl("vot-block",["vot-subtitles-info-context"],t);return i.append(o,r,s),{container:i,translatedWith:o,header:r,context:s}}},xf=["left","top","right","bottom"],Sf=["hover","click"];function kt(e,t,n){e[t].addListener(n);}function xt(e,t,n){e[t].removeListener(n);}function et(e,t){e.hidden=t;}function rt(e){return e.hidden}class G{showed=false;target;anchor;content;position;preferredPosition;trigger;parentElement;layoutRoot;offsetX;offsetY;_hidden;autoLayout;pageWidth;pageHeight;globalOffsetX;globalOffsetY;maxWidth;backgroundColor;borderRadius;_bordered;container;onResizeObserver;intersectionObserver;scrollListening=false;positionRafId=null;destroyFallbackTimerId;static DESTROY_FALLBACK_MS=700;tooltipId=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`vot-tooltip-${Math.random().toString(36).slice(2)}`;prevAriaDescribedBy=null;constructor({target:t,anchor:n=void 0,content:i="",position:o="top",trigger:r="hover",offset:s=4,maxWidth:a=void 0,hidden:l=false,autoLayout:c=true,backgroundColor:d=void 0,borderRadius:u=void 0,bordered:h=true,parentElement:m=document.body,layoutRoot:v=document.documentElement}){if(!(t instanceof HTMLElement))throw new TypeError("target must be a valid HTMLElement");this.target=t,this.anchor=n instanceof HTMLElement?n:t,this.content=i,typeof s=="number"?this.offsetY=this.offsetX=s:(this.offsetX=s.x,this.offsetY=s.y),this._hidden=l,this.autoLayout=c,this.trigger=G.validateTrigger(r)?r:"hover",this.position=G.validatePos(o)?o:"top",this.preferredPosition=this.position,this.parentElement=m,this.layoutRoot=v,this.borderRadius=u,this._bordered=h,this.maxWidth=a,this.backgroundColor=d,this.updatePageSize(),this.init();}static validatePos(t){return xf.includes(t)}static validateTrigger(t){return Sf.includes(t)}setPosition(t){return this.preferredPosition=G.validatePos(t)?t:"top",this.position=this.preferredPosition,this.schedulePositionUpdate(),this}setContent(t){return this.content=t,this.container?(this.container.replaceChildren(),typeof t=="string"?this.container.textContent=t:this.container.append(t),this.schedulePositionUpdate(),this):this}updateMount({parentElement:t,layoutRoot:n}){return t&&this.parentElement!==t&&(this.parentElement=t,this.container?.isConnected&&t.appendChild(this.container)),n&&this.layoutRoot!==n&&(this.layoutRoot=n),this.schedulePositionUpdate(),this}onResize=()=>{this.schedulePositionUpdate();};onClick=()=>{this.showed?this.destroy():this.create();};onScroll=()=>{this.schedulePositionUpdate();};onHoverPointerDown=t=>{t.pointerType!=="mouse"&&this.create();};onHoverPointerUp=t=>{t.pointerType!=="mouse"&&this.destroy();};onMouseEnter=()=>{this.create();};onMouseLeave=()=>{this.destroy();};updatePageSize(){if(this.layoutRoot===document.documentElement)this.globalOffsetX=0,this.globalOffsetY=0;else {const{left:t,top:n}=this.parentElement.getBoundingClientRect();this.globalOffsetX=t,this.globalOffsetY=n;}return this.pageWidth=(this.layoutRoot.clientWidth||document.documentElement.clientWidth)+(globalThis.scrollX??globalThis.pageXOffset??0),this.pageHeight=(this.layoutRoot.clientHeight||document.documentElement.clientHeight)+(globalThis.scrollY??globalThis.pageYOffset??0),this}onIntersect=([t])=>{if(!t.isIntersecting)return this.destroy(true)};init(){return this.onResizeObserver=new ResizeObserver(this.onResize),this.intersectionObserver=new IntersectionObserver(this.onIntersect),this.trigger==="click"?(this.target.addEventListener("pointerdown",this.onClick),this):(this.target.addEventListener("mouseenter",this.onMouseEnter),this.target.addEventListener("mouseleave",this.onMouseLeave),this.target.addEventListener("focusin",this.onMouseEnter),this.target.addEventListener("focusout",this.onMouseLeave),this.target.addEventListener("pointerdown",this.onHoverPointerDown),this.target.addEventListener("pointerup",this.onHoverPointerUp),this)}release(){return this.destroy(),this.detachScrollListener(),this.trigger==="click"?(this.target.removeEventListener("pointerdown",this.onClick),this):(this.target.removeEventListener("mouseenter",this.onMouseEnter),this.target.removeEventListener("mouseleave",this.onMouseLeave),this.target.removeEventListener("focusin",this.onMouseEnter),this.target.removeEventListener("focusout",this.onMouseLeave),this.target.removeEventListener("pointerdown",this.onHoverPointerDown),this.target.removeEventListener("pointerup",this.onHoverPointerUp),this)}schedulePositionUpdate(){this.positionRafId===null&&(this.positionRafId=requestAnimationFrame(()=>{this.positionRafId=null,this.updatePageSize(),this.updatePos();}));}cancelPositionUpdate(){this.positionRafId!==null&&(cancelAnimationFrame(this.positionRafId),this.positionRafId=null);}clearDestroyFallbackTimer(){this.destroyFallbackTimerId!==void 0&&(globalThis.clearTimeout(this.destroyFallbackTimerId),this.destroyFallbackTimerId=void 0);}create(){return this.destroy(true),this.showed=true,this.clearDestroyFallbackTimer(),this.container=w.createEl("vot-block",["vot-tooltip"],this.content),this.bordered&&this.container.classList.add("vot-tooltip-bordered"),this.container.setAttribute("role","tooltip"),this.container.id=this.tooltipId,this.container.dataset.trigger=this.trigger,this.container.dataset.position=this.position,this.parentElement.appendChild(this.container),this.schedulePositionUpdate(),this.backgroundColor!==void 0&&(this.container.style.backgroundColor=this.backgroundColor),this.borderRadius!==void 0&&(this.container.style.borderRadius=`${this.borderRadius}px`),this.hidden?this.container.hidden=true:this.syncAriaDescribedBy(true),this.container.style.opacity="1",this.attachScrollListener(),this.onResizeObserver?.observe(this.layoutRoot),this.onResizeObserver?.observe(this.anchor),this.intersectionObserver?.observe(this.target),this}updatePos(){if(!this.container)return this;const{top:t,left:n}=this.calcPos(this.autoLayout,this.preferredPosition),i=this.pageWidth-this.offsetX*2,o=this.maxWidth??Math.min(i,this.pageWidth-Math.min(n,this.pageWidth-i));return this.container.style.transform=`translate(${n}px, ${t}px)`,this.container.dataset.position=this.position,this.container.style.maxWidth=`${o}px`,this}calcPos(t=true,n=this.preferredPosition){if(!this.container)return {top:0,left:0};const{left:i,right:o,top:r,bottom:s,width:a,height:l}=this.anchor.getBoundingClientRect(),{width:c,height:d}=this.container.getBoundingClientRect(),u=N(c,0,this.pageWidth),h=N(d,0,this.pageHeight),m=i-this.globalOffsetX,v=o-this.globalOffsetX,b=r-this.globalOffsetY,y=s-this.globalOffsetY;let k;switch(n){case "top":{const x=N(b-h-this.offsetY,0,this.pageHeight);if(t&&x+this.offsetYthis.pageWidth-this.offsetX)return this.calcPos(false,"left");k={top:N(b+(l-h)/2,this.offsetY,this.pageHeight-h-this.offsetY),left:x};break}case "bottom":{const x=N(y+this.offsetY,0,this.pageHeight-h);if(t&&x+h>this.pageHeight-this.offsetY)return this.calcPos(false,"top");k={top:x,left:N(m-u/2+a/2,this.offsetX,this.pageWidth-u-this.offsetX)};break}case "left":{const x=Math.max(0,m-u-this.offsetX);if(t&&x+u>m-this.offsetX)return this.calcPos(false,"right");k={top:N(b+(l-h)/2,this.offsetY,this.pageHeight-h-this.offsetY),left:x};break}default:k={top:0,left:0};break}return this.position=n,k}destroy(t=false){if(!this.container)return this;if(this.cancelPositionUpdate(),this.clearDestroyFallbackTimer(),this.showed=false,this.syncAriaDescribedBy(false),this.onResizeObserver?.disconnect(),this.intersectionObserver?.disconnect(),this.detachScrollListener(),t)return this.container.remove(),this.container=void 0,this;const n=this.container;n.style.pointerEvents="none",n.style.opacity="0";const i=()=>{this.clearDestroyFallbackTimer(),n?.remove(),this.container===n&&(this.container=void 0);};return n.addEventListener("transitionend",i,{once:true}),n.addEventListener("transitioncancel",i,{once:true}),this.destroyFallbackTimerId=globalThis.setTimeout(i,G.DESTROY_FALLBACK_MS),this}syncAriaDescribedBy(t){const n=this.target.getAttribute("aria-describedby");if(this.prevAriaDescribedBy??=n,!t){this.prevAriaDescribedBy===null?this.target.removeAttribute("aria-describedby"):this.target.setAttribute("aria-describedby",this.prevAriaDescribedBy),this.prevAriaDescribedBy=null;return}const i=new Set((n??"").split(/\s+/).filter(Boolean));i.add(this.tooltipId),this.target.setAttribute("aria-describedby",Array.from(i).join(" "));}set bordered(t){this._bordered=t,this.container?.classList.toggle("vot-tooltip-bordered",t);}get bordered(){return this._bordered}set hidden(t){this._hidden=t,this.container&&et(this.container,t),this.showed&&this.syncAriaDescribedBy(!t);}get hidden(){return this._hidden}attachScrollListener(){this.scrollListening||(this.scrollListening=true,document.addEventListener("scroll",this.onScroll,{passive:true,capture:true}));}detachScrollListener(){this.scrollListening&&(this.scrollListening=false,document.removeEventListener("scroll",this.onScroll,{capture:true}));}}function Tf(e,t){return e>=t.startMs&&e>1,r=t[o];if(e=r.startMs+r.durationMs)n=o+1;else return o}return -1}function Lf(e,t,n=0){return `${e}:${t}:${n}`}function Lt(e,t,n){return Math.max(t,Math.min(e,n))}function If(e,t,n,i,o){const r=n-e,s=i-t;return r*r+s*s>=o*o}function Pf({anchorX:e,anchorY:t,elementWidth:n,elementHeight:i,boxWidth:o,boxHeight:r,bottomInset:s}){let a=e,l=t;const c=Math.max(0,r-s),d=i||0;if(n){let u=a-n/2;const h=o-n;h>=0?u=Lt(u,0,h):u=h/2,a=u+n/2;}return l=Lt(l,d,c),{anchorX:a,anchorY:l}}const Kr=.55;function wn(e,t,n){return Number.isNaN(e)?t:Math.min(n,Math.max(t,e))}function Yr(e){return e<1?28:e<1.4?32:42}function Jr(e){return !Number.isFinite(e)||e<=0?.9:e>=1.4?.68:e>=1.2?.9:.92}function Cf(e){const t=Math.max(1,e.w),n=Math.max(1,e.h),i=t/n,o=Jr(i),r=t*o,s=Yr(i),l=36/1080,d=i<1?l*.89:l,u=18,h=50,m=1080,v=m*d,y=n<=m?n*d:v*(n/m)**.35,k=r/(s*Kr),x=Math.round(Math.min(y,k));return wn(x,u,h)}function Ef(e){const t=Math.max(1,e.w),n=Math.max(1,e.h),i=t/n,o=Cf(e),r=Jr(i),s=t*r,a=Yr(i),l=o*Kr,c=a*l,d=t*(i<1?.8:.55),u=wn(c,d,s),h=u/l,m=wn(Math.round(h*2),50,180);return {fontSizePx:o,maxWidthPx:u,maxLength:m}}const Xr=e=>!!(e?.isWordLike&&e.text?.trim()),ce=(e,t,n)=>Math.min(n,Math.max(t,e)),go=e=>{const t=new Array(e.length+1).fill(0);for(let n=0;nnt(s.textToNextWord)),i=e.map(s=>s.textToNextWord.length),o=e.map(s=>t(s.trailingGapAfterBreakText)),r=e.map(s=>s.trailingGapAfterBreakText.length);return {widths:n,chars:i,trailingGapWidths:o,trailingGapChars:r,prefixWidths:go(n),prefixChars:go(i)}}function bt(e,t,n){if(n{const a=[e,t],l=(e+t)/2;let c=0;for(const y of a){const k=n-y;if(k>=0)c+=k*k;else {const x=-k;c+=x*x*1e4;}}let d=0;for(const y of a){const k=y-l;d+=k*k;}const h=r>=4&&(i<=1||o<=1)?1e9:0,v=r>=6&&(i<=2||o<=2)?2e7:0;let b=c+d+h+v;return e>t&&(b+=(e-t)/Math.max(1,n)*.15),b};function Qr(e,t,n,i){if(i<=0||n<=t)return null;let o=null,r=Number.POSITIVE_INFINITY;const s=n-t+1;for(let a=t;ai||c>i)continue;const d=a-t+1,u=n-a,h=Bf(l,c,i,d,u,s);h=0;i-=1)if(Zr(e,0,i,t))return i;return null}function Nf(e,t){if(t<=0)return {breakAfterWordIndices:[],truncateAfterWordIndex:null};const n=e.widths.length;if(n<=1)return {breakAfterWordIndices:[],truncateAfterWordIndex:null};if(bt(e,0,n-1)<=t)return {breakAfterWordIndices:[],truncateAfterWordIndex:null};const o=ts(e,t);if(o.length)return {breakAfterWordIndices:o,truncateAfterWordIndex:null};const s=Rf(e,t)??0;if(s>=n-1)return {breakAfterWordIndices:[],truncateAfterWordIndex:null};const a=Qr(e,0,s,t);return {breakAfterWordIndices:a===null?[]:[a],truncateAfterWordIndex:s}}const Un=e=>e.endWord-e.startWord+1,Ff=(e,t)=>{const n=[];let i=0;for(;i{if(t<=0)return false;const i=e[t],o=e[t-1];if(!i||!o||Un(o)<3)return false;const r=o.endWord,s={startWord:o.startWord,endWord:r-1},a={startWord:r,endWord:i.endWord};return !n(s.startWord,s.endWord)||!n(a.startWord,a.endWord)?false:(o.endWord=s.endWord,i.startWord=a.startWord,true)},$f=(e,t,n)=>{if(t>=e.length-1)return false;const i=e[t],o=e[t+1];if(!i||!o||Un(o)<3)return false;const r=o.startWord,s={startWord:i.startWord,endWord:r},a={startWord:r+1,endWord:o.endWord};return !n(s.startWord,s.endWord)||!n(a.startWord,a.endWord)?false:(i.endWord=s.endWord,o.startWord=a.startWord,true)},Uf=(e,t)=>{for(let n=e.length-1;n>=0;n-=1)Un(e[n])===1&&(Hf(e,n,t)||$f(e,n,t));},Wf=(e,t,n)=>{const i=t[n];if(!i)return "";let o="";for(let r=i.tokenIndex;r<=i.breakAfterTokenIndex;r+=1)o+=e[r]?.text??"";return o.trimEnd()},zf=(e,t,n,i)=>{for(let o=0;o=l;v-=1)if(Vf.test(Wf(t,n,v))){a=v;break}if(a{const i=[];for(const o of e){const r=t[o.startWord],s=t[o.endWord];if(!r||!s)continue;const a=r.tokenIndex,l=s.breakAfterTokenIndex+1,c=n[a]?.startMs??0,d=n[s.tokenIndex]?.startMs??c,u=n[s.tokenIndex]?.durationMs??0,h=t[o.endWord+1],v=(h?n[h.tokenIndex]?.startMs:void 0)??d+u;i.push({startToken:a,endToken:l,startMs:c,endMs:v});}return i};function Gf(e,t,n,i,o){const r=t.length;if(r===0)return [];const s=Number.isFinite(o)&&o>0?o:null,a=(c,d)=>ds?false:Zr(n,c,d,i),l=Ff(r,a);return Uf(l,a),zf(l,e,t,a),qf(l,t,e)}function Kf(e,t,n){return !e||typeof t!="number"?false:t>=0&&tthis.onPointerDown(s),this.onPointerUpBound=s=>this.onPointerUp(s),this.onPointerMoveBound=s=>this.onPointerMove(s),this.onTimeUpdateBound=()=>this.requestUpdate(),this.onPlaybackStateChangeBound=()=>this.handlePlaybackStateChange(),this.onVisualViewportChangeBound=()=>this.scheduleReposition(),this.checkerUnsubscribe=this.intervalIdleChecker.subscribe(()=>{this.onCheckerTick();}),this.bindEvents();}setPortal(t){this.portal=t;}resetTranslationContext(t=false){this.strTranslatedTokens="",t&&this.releaseTooltip();}resetSegmentationMemo(){this.tokenProcessingMemo=null,this.tokenPrecomputeMemo=null,this.lineMeasureMemo=null,this.lastSegmentIndex=0;}resetWrapMemo(){this.setBreakAfterTokenIndices([]),this.smartTruncateAfterTokenIndex=null,this.lastWrapKey=null;}resetRenderMemo(){this.lastRenderKey=null,this.lastMultilineMeasureSignature=null,this.lastLayoutAffectingKey=null;}computeAnchorBoxLayout(t){const n={left:0,top:0,w:t.w,h:t.h},i=this.video;if(!i)return n;const o=i.getBoundingClientRect();if(!(o.width>0&&o.height>0))return n;const r=t.rect;if(!(o.right>r.left&&o.leftr.top&&o.top0&&l>0))return n;const c=(o.left-r.left)/t.scaleX,d=(o.top-r.top)/t.scaleY,u=t.w-a,h=t.h-l,m=u>=0?Lt(c,0,u):(t.w-a)/2,v=h>=0?Lt(d,0,h):(t.h-l)/2;return {left:m,top:v,w:a,h:l}}ensureSmartLayout(t){if(!this.smartLayoutEnabled)return this.maxLength=this.manualMaxLength,null;const n=Ef(t),i=`${Math.round(n.fontSizePx)}|${Math.round(n.maxWidthPx)}|${n.maxLength}`,o=n.fontSizePx!==this.smartFontSizePx,r=Math.abs(n.maxWidthPx-this.smartMaxWidthPx)>.5,s=n.maxLength!==this.smartMaxLength;return i!==this.lastSmartLayoutKey&&(this.lastSmartLayoutKey=i,this.smartFontSizePx=n.fontSizePx,this.smartMaxWidthPx=n.maxWidthPx,this.smartMaxLength=n.maxLength),s&&(this.maxLength=n.maxLength,this.resetRenderMemo(),this.resetSegmentationMemo()),o&&this.subtitlesBlock&&this.subtitlesBlock.style.setProperty("--vot-subtitles-font-size",`${n.fontSizePx}px`),(o||r)&&this.lastWrapTokens&&(this.lastWrapKey=null,this.scheduleWrapRecompute(),this.resetSegmentationMemo()),n}scheduleReposition(){this.abortController.signal.aborted||this.subtitles&&(this.repositionPending=true,this.intervalIdleChecker.markActivity("subtitles-reposition"),this.intervalIdleChecker.requestImmediateTick());}createSubtitlesContainer(){if(this.subtitlesContainer)return this.subtitlesContainer;getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative");const t=document.createElement("vot-block");return t.classList.add("vot-subtitles-widget"),this.container.appendChild(t),this.subtitlesContainer=t,t.addEventListener("pointerdown",this.onPointerDownBound,{signal:this.abortController.signal,passive:true}),t.style.transform="translate(-50%, -100%)",this.updateContainerRect(),t}bindEvents(){const{signal:t}=this.abortController,n={signal:t};this.video?.addEventListener("play",this.onPlaybackStateChangeBound,n),this.video?.addEventListener("pause",this.onPlaybackStateChangeBound,n),this.video?.addEventListener("seeking",this.onPlaybackStateChangeBound,n),this.video?.addEventListener("seeked",this.onPlaybackStateChangeBound,n),this.video?.addEventListener("ended",this.onPlaybackStateChangeBound,n),this.resizeObserver=new ResizeObserver(()=>this.onResize()),this.resizeObserver.observe(this.container),this.video&&this.resizeObserver.observe(this.video),globalThis.visualViewport?.addEventListener("resize",this.onVisualViewportChangeBound,n),globalThis.visualViewport?.addEventListener("scroll",this.onVisualViewportChangeBound,n);}getUpdateMinIntervalMs(){return this.highlightWords?this.updateMinIntervalHighlightMs:this.updateMinIntervalMs}requestUpdate(t=performance.now()){if(this.abortController.signal.aborted||!this.subtitles)return;const n=this.getUpdateMinIntervalMs();t-this.lastUpdateRequestTs{if(this.videoFrameRequestId=null,this.abortController.signal.aborted)return;const i=this.video;!i||i.paused||i.ended||this.subtitles&&(this.requestUpdate(t),this.startVideoFrameLoop());};onCheckerTick(){this.abortController.signal.aborted||(this.repositionPending&&(this.repositionPending=false,this.updateContainerRect(),this.updatePending=true),this.wrapPending&&(this.wrapPending=false,this.recomputeWrapNow()),this.positionRefreshPending&&(this.positionRefreshPending=false,this.applySubtitlePosition()),this.updatePending&&(this.updatePending=false,this.update()));}attachDragDocumentListeners(){this.dragDocListenersAttached||(this.dragDocListenersAttached=true,document.addEventListener("pointermove",this.onPointerMoveBound,{passive:false}),document.addEventListener("pointerup",this.onPointerUpBound),document.addEventListener("pointercancel",this.onPointerUpBound));}detachDragDocumentListeners(){this.dragDocListenersAttached&&(this.dragDocListenersAttached=false,document.removeEventListener("pointermove",this.onPointerMoveBound),document.removeEventListener("pointerup",this.onPointerUpBound),document.removeEventListener("pointercancel",this.onPointerUpBound));}onResize(){this.scheduleReposition();}updateContainerRect(){const t=this.getLayoutSize();if(!t.w||!t.h)return;const n=this.computeAnchorBoxLayout(t);!n.w||!n.h||(this.refreshBottomInsetNow(t,n),this.applySubtitlePositionWithLayout(t,n));}getLayoutSize(){const t=this.container.getBoundingClientRect(),n=this.container.clientWidth||t.width,i=this.container.clientHeight||t.height,o=t.width&&n?t.width/n:1,r=t.height&&i?t.height/i:1;return {w:n,h:i,rect:t,scaleX:o,scaleY:r}}ensureSafeAreaProbe(){if(this.safeAreaProbeEl)return;const t=document.createElement("div");t.style.position="fixed",t.style.left="0",t.style.right="0",t.style.bottom="0",t.style.height="env(safe-area-inset-bottom, 0px)",t.style.pointerEvents="none",t.style.opacity="0",t.style.zIndex="-1",document.documentElement.appendChild(t),this.safeAreaProbeEl=t;}getSafeAreaBottomInsetPx(){return this.ensureSafeAreaProbe(),this.safeAreaProbeEl&&this.safeAreaProbeEl.offsetHeight||0}isMobileViewport(){return typeof globalThis.matchMedia!="function"?false:globalThis.matchMedia("(max-width: 900px) and (pointer: coarse)").matches}getBottomInsetPreset(){const t=document,n=t.fullscreenElement??t.webkitFullscreenElement;if(!(n instanceof Element))return this.bottomInsetByMode.normal;const{container:i,video:o}=this;return n===i||n.contains(i)||i.contains(n)?this.bottomInsetByMode.fullscreen:o&&(n===o||n.contains(o)||o.contains(n))?this.bottomInsetByMode.fullscreen:this.bottomInsetByMode.normal}computeReservedBottomInsetPx(t,n=this.getBottomInsetPreset()){const i=t*n.ratio;return Lt(i,n.minPx,n.maxPx)}refreshBottomInsetNow(t,n){const i=n?.h??this.computeAnchorBoxLayout(t??this.getLayoutSize()).h;if(!i){this.bottomInsetCachedPx=0;return}const o=this.getBottomInsetPreset();this.bottomInsetCachedPx=this.computeReservedBottomInsetPx(i,o);}getBottomInsetPx(t,n){const i=this.getBottomInsetPreset(),o=this.getSafeAreaBottomInsetPx(),r=Number.parseFloat(getComputedStyle(this.container).paddingBottom||"0")||0;if(this.isMobileViewport())return Math.max(r,o);const s=n?.h??this.computeAnchorBoxLayout(t??this.getLayoutSize()).h,a=s?this.computeReservedBottomInsetPx(s,i):i.minPx,l=Math.max(this.bottomInsetCachedPx,a);return Math.max(r,o,l)+i.gapPx}onPointerDown(t){const n=this.subtitlesContainer;if(!n)return;const i=t.target;if(!(i instanceof Node)||!n.contains(i)||!t.isPrimary||t.pointerType==="mouse"&&t.button!==0)return;const o=this.getLayoutSize(),{rect:r,w:s,h:a,scaleX:l,scaleY:c}=o;if(!s||!a)return;const d=this.computeAnchorBoxLayout(o);if(!d.w||!d.h)return;this.lastPositionRefreshTs=performance.now();const u=n.getBoundingClientRect(),h=(t.clientX-r.left)/l-d.left,m=(t.clientY-r.top)/c-d.top,v=(u.left-r.left+u.width/2)/l-d.left,b=(u.top-r.top+u.height)/c-d.top;this.dragging.pointerId=t.pointerId,this.dragging.candidate=true,this.dragging.active=false,this.dragging.moved=false,this.dragging.startClientX=t.clientX,this.dragging.startClientY=t.clientY,this.dragging.offset.x=v-h,this.dragging.offset.y=b-m,this.attachDragDocumentListeners();const y=this.subtitlesBlock??(i instanceof Element?i:null);try{y?.setPointerCapture(t.pointerId);}catch{}}onPointerUp(t){this.dragging.pointerId!==null&&t.pointerId===this.dragging.pointerId&&(this.dragging.moved&&(this.suppressTokenClicksUntil=performance.now()+450),this.dragging.pointerId=null,this.dragging.candidate=false,this.dragging.active=false,this.dragging.moved=false,this.detachDragDocumentListeners());}onPointerMove(t){if(!this.dragging.candidate||this.dragging.pointerId===null||t.pointerId!==this.dragging.pointerId)return;if(this.dragging.active)this.dragging.moved=true;else {if(!If(this.dragging.startClientX,this.dragging.startClientY,t.clientX,t.clientY,this.dragStartThresholdPx))return;this.dragging.active=true,this.dragging.moved=true,this.suppressTokenClicksUntil=performance.now()+450,this.releaseTooltip();}t.preventDefault(),t.stopPropagation();const n=this.getLayoutSize(),{rect:i,w:o,h:r,scaleX:s,scaleY:a}=n;if(!o||!r)return;const l=this.computeAnchorBoxLayout(n);if(!l.w||!l.h)return;const c=(t.clientX-i.left)/s-l.left,d=(t.clientY-i.top)/a-l.top;let u=c+this.dragging.offset.x,h=d+this.dragging.offset.y;const m=this.subtitlesContainer?.offsetWidth??0,v=this.subtitlesContainer?.offsetHeight??0,b=this.getBottomInsetPx(n,l);(({anchorX:u,anchorY:h}=Pf({anchorX:u,anchorY:h,elementWidth:m,elementHeight:v,boxWidth:l.w,boxHeight:l.h,bottomInset:b}))),this.position.left=u/l.w*100,this.position.top=h/l.h*100,this.applySubtitlePositionWithLayout(n,l);}applySubtitlePosition(){if(!this.subtitlesContainer)return;const n=this.getLayoutSize();if(!n.w||!n.h)return;const i=this.computeAnchorBoxLayout(n);!i.w||!i.h||this.applySubtitlePositionWithLayout(n,i);}applySubtitlePositionWithLayout(t,n){const i=this.subtitlesContainer;if(!i)return;const o=Math.min(t.scaleX||1,t.scaleY||1),r=o>0&&o<.999?Math.min(1/o,3):1;Math.abs(r-1)<.001?i.style.removeProperty("--vot-subtitles-scale-compensation"):i.style.setProperty("--vot-subtitles-scale-compensation",r.toFixed(3));let s=0;if(this.smartLayoutEnabled){const D=this.ensureSmartLayout(n);s=D?Math.max(0,D.maxWidthPx):Math.max(0,n.w*.7);}else s=Math.max(0,n.w*.7);Math.abs(s-this.subtitleMaxWidthPx)>.5&&(this.subtitleMaxWidthPx=s,i.style.setProperty("--vot-subtitles-max-width",`${Math.round(s)}px`),this.resetSegmentationMemo(),this.scheduleWrapRecompute());const a=i.offsetWidth,l=i.offsetHeight,c=this.getBottomInsetPx(t,n);let d=this.position.left/100*n.w,u=this.position.top/100*n.h,h=d-a/2,m=u-l;const v=n.w-a,b=n.h-c-l;v>=0?h=Lt(h,0,v):h=v/2,b>=0?m=Lt(m,0,b):m=0,d=h+a/2,u=m+l;const y=n.left+d,k=n.top+u,x=y/t.w*100,A=k/t.h*100;i.style.left=`${x}%`,i.style.top=`${A}%`,i.style.transform="translate(-50%, -100%)",this.tokenTooltip?.updatePos();}applyPositionAfterContentRender(){const t=this.getLayoutSize();if(t.w&&t.h){const n=this.computeAnchorBoxLayout(t);if(n.w&&n.h){this.refreshBottomInsetNow(t,n),this.applySubtitlePositionWithLayout(t,n);return}this.refreshBottomInsetNow(t),this.applySubtitlePosition();return}this.refreshBottomInsetNow(),this.applySubtitlePosition();}trimEdgeWhitespaceTokens(t){if(!t.length)return t;let n=0,i=t.length;for(;nn&&!t[i-1]?.text.trim();)i-=1;return n===0&&i===t.length?t:n>=i?[]:t.slice(n,i)}splitRangesByMaxLength(t){const n=[];let i=0,o=0;for(const[r,s]of t.entries())o+=s.text.length,o>this.maxLength&&r>i&&(n.push([i,r]),i=r,o=s.text.length);return i({tokenIndex:a.tokenIndex,breakAfterTokenIndex:a.breakAfterTokenIndex})),wordSlices:i,normalizedWordsKey:o};return this.tokenPrecomputeMemo={tokens:t,value:s},s}getTokenLayoutInputs(t){const n=this.subtitlesBlock;if(n){const c=getComputedStyle(n),d=`${c.fontStyle} ${c.fontVariant} ${c.fontWeight} ${c.fontSize} ${c.fontFamily}`;t.font=d;const u=Number.parseFloat(c.maxWidth),h=Number.parseFloat(c.paddingLeft)||0,m=Number.parseFloat(c.paddingRight)||0,v=Number.isFinite(u)?u:this.subtitleMaxWidthPx||globalThis.innerWidth*.8;return {fontKey:d,maxWidthPx:Math.max(0,v-h-m)}}const i=Number.parseFloat(getComputedStyle(document.documentElement).fontSize)||16,s=Math.min(i*52,this.subtitleMaxWidthPx||globalThis.innerWidth*.8),a=this.fontSizeOverridden?this.fontSize:Math.min(24,Math.max(14,globalThis.innerWidth*.016)),l=`normal normal 500 ${a}px Roboto, "Segoe UI", system-ui, sans-serif`;return t.font=l,{fontKey:l,maxWidthPx:Math.max(0,s-a)}}getActiveLineKey(t){return this.lastActiveLineIndex!==null?`${this.lastActiveLineIndex}`:`${t[0]?.startMs??0}:${t[0]?.durationMs??0}:${t.length}`}getLineMeasureMemo(t,n){const{words:i,wordSlices:o,normalizedWordsKey:r}=this.buildTokenPrecomputeInput(t);if(!i.length)return null;const s=this.getMeasureContext();if(!s)return null;const{fontKey:a,maxWidthPx:l}=this.getTokenLayoutInputs(s);if(!Number.isFinite(l)||l<24)return null;const c=`${n}|${a}|${Math.round(l)}|${r}`;if(this.lineMeasureMemo?.key===c)return this.lineMeasureMemo;const d=Of(o,h=>s.measureText(h).width),u={key:c,words:i,metrics:d,maxWidthPx:l};return this.lineMeasureMemo=u,u}buildTokenProcessingMemo(t,n){const i=this.getLineMeasureMemo(t,n);if(!i)return null;const o=`${i.key}|${this.maxLength}`;if(this.tokenProcessingMemo?.key===o)return this.tokenProcessingMemo;const r=mo(i.maxWidthPx),s=this.computeTwoLineSegments(t,i.words,i.metrics,r,this.maxLength),a={key:o,segmentRanges:s};return this.tokenProcessingMemo=a,this.lastSegmentIndex=0,a}selectSegmentIndexFromRanges(t,n){if(!t.length)return -1;let i=this.lastSegmentIndex;for(i>=t.length&&(i=0);i=t[i].endMs;)i+=1;for(;i>0&&n=t[i].startMs&&nn>=r.startMs&&n=0?i=o:i=n{if(performance.now()r||n>o.startMs-100&&r-n<275;i.push(s);}return i}renderTokens(t){const n=this.breakAfterTokenIndexSet,i=typeof this.smartTruncateAfterTokenIndex=="number"?Math.max(0,Math.min(this.smartTruncateAfterTokenIndex,t.length-1)):null,o=Kf(this.smartLayoutEnabled,i,t.length),r=o?i??t.length-1:t.length-1,s=[];for(let a=0;a<=r;){const l=t[a];if(!l.text){a+=1;continue}if(l.isWordLike){let c=l.text,d=a,h=!!n?.has(a)?a:null;for(;h===null&&d+1<=r;){const m=t[d+1];if(!m||m.isWordLike)break;if(c+=m.text,d+=1,n?.has(d)){h=d;break}}if(s.push(Zt`${c}`),h!==null){for(s.push(Zt`
`),a=h+1;a<=r&&!t[a]?.isWordLike&&!t[a]?.text.trim();)a+=1;continue}a=d+1;}else s.push(l.text),n?.has(a)&&s.push(Zt`
`),a+=1;}if(o){const a=s.at(-1);if(typeof a=="string"){const l=a.replace(/\s+$/u,"");l?s[s.length-1]=l:s.pop();}s.push("…");}return s}updatePassedClasses(t){const n=this.renderedTokenEls,i=Math.min(n.length,t.length);for(let o=0;oo[b].breakAfterTokenIndex);else if(this.smartLayoutEnabled){const b=Nf(r,a);c=b.breakAfterWordIndices.map(y=>o[y].breakAfterTokenIndex),b.truncateAfterWordIndex!==null&&(d=o[b.truncateAfterWordIndex]?.breakAfterTokenIndex??null);}}const h=!this.arraysEqual(c,this.breakAfterTokenIndices),m=d!==this.smartTruncateAfterTokenIndex;(h||m)&&(this.setBreakAfterTokenIndices(c),this.smartTruncateAfterTokenIndex=d,this.resetRenderMemo(),this.update());}setContent(t,n=void 0){if(this.releaseTooltip(),this.subtitleLang=n,!t||!this.video){this.clearRenderedContent(),this.subtitles=null,this.clearPendingSchedulerState(),this.video?.removeEventListener("timeupdate",this.onTimeUpdateBound),this.stopVideoFrameLoop(),this.detachDragDocumentListeners();return}this.createSubtitlesContainer(),this.subtitles=t,this.lastActiveLineIndex=null,this.useVideoFrameCallbacks||this.video.addEventListener("timeupdate",this.onTimeUpdateBound,{signal:this.abortController.signal}),this.syncVideoFrameLoop(),this.updateContainerRect(),this.update(),this.intervalIdleChecker.requestImmediateTick();}setMaxLength(t){typeof t=="number"&&t>0&&(this.manualMaxLength=t,this.smartLayoutEnabled||(this.maxLength=t,this.resetSegmentationMemo(),this.update(),this.scheduleReposition()));}setHighlightWords(t){const n=this.highlightWords;this.highlightWords=!!t,n&&!this.highlightWords&&this.clearPassedClasses(),this.update();}applyManualFontSizeStyle(){if(this.subtitlesBlock){if(this.fontSizeOverridden){this.subtitlesBlock.style.setProperty("--vot-subtitles-font-size",`${this.fontSize}px`);return}this.subtitlesBlock.style.removeProperty("--vot-subtitles-font-size");}}setSmartLayout(t){const n=t!==false;n!==this.smartLayoutEnabled&&(this.smartLayoutEnabled=n,this.lastSmartLayoutKey=null,this.resetWrapMemo(),this.resetRenderMemo(),this.resetSegmentationMemo(),this.smartLayoutEnabled||(this.maxLength=this.manualMaxLength,this.applyManualFontSizeStyle()),this.update(),this.scheduleWrapRecompute(),this.scheduleReposition());}setFontSize(t){this.fontSize=t,this.fontSizeOverridden=true,this.smartLayoutEnabled||(this.applyManualFontSizeStyle(),this.lastWrapKey=null,this.resetSegmentationMemo(),this.scheduleWrapRecompute(),this.scheduleReposition());}setOpacity(t){this.opacity=((100-Number(t))/100).toFixed(2),this.subtitlesBlock&&this.subtitlesBlock.style.setProperty("--vot-subtitles-opacity",this.opacity);}stringifyTokens(t){return t.map(n=>n.text).join("")}updateMultilineAlignmentIfNeeded(t){const n=this.subtitlesBlock;if(!n||t===this.lastLayoutAffectingKey)return;const i=getComputedStyle(n),o=`${t}|${i.fontSize}|${Math.round(n.clientWidth)}`;this.updateMultilineAlignmentClass(o),this.lastLayoutAffectingKey=t;}updateMultilineAlignmentClass(t){const n=this.subtitlesBlock;if(!n||t===this.lastMultilineMeasureSignature)return;this.lastMultilineMeasureSignature=t;const i=getComputedStyle(n),o=Number.parseFloat(i.lineHeight);if(!Number.isFinite(o)||o<=0){n.classList.remove("vot-subtitles--multiline");return}const r=Number.parseFloat(i.paddingTop)||0,s=Number.parseFloat(i.paddingBottom)||0,a=Math.max(0,n.clientHeight-r-s);Math.max(1,Math.round(a/o))>1?n.classList.add("vot-subtitles--multiline"):n.classList.remove("vot-subtitles--multiline");}update(){if(!this.video||!this.subtitles)return;const t=this.video.currentTime*1e3,n=this.subtitles.subtitles;let i,o=-1;const r=this.lastActiveLineIndex;if(typeof r=="number"&&r>=0&&r500){this.lastSmartLayoutCheckTs=y;const k=this.getLayoutSize();if(k.w&&k.h){const x=this.computeAnchorBoxLayout(k);x.w&&x.h&&this.ensureSmartLayout(x);}}}else this.maxLength=this.manualMaxLength;const s=this.processTokens(i.tokens,t);this.lastWrapTokens=s;const a=this.stringifyTokens(s),l=a!==this.strTokens;l&&(this.releaseTooltip(),this.strTokens=a,this.resetTranslationContext(),this.resetWrapMemo());const c=this.highlightWords?this.buildPassedState(s,t):null,d=`${this.breakAfterTokenIndices.join(",")}|${this.smartTruncateAfterTokenIndex??""}`;let u=0;this.smartLayoutEnabled?u=Math.round(this.smartFontSizePx):this.fontSizeOverridden&&(u=this.fontSize);const h=Lf(a,d,u),m=`${o}:${a}:${d}`;if(m===this.lastRenderKey){this.highlightWords&&!l&&c&&this.updatePassedClasses(c),this.updateMultilineAlignmentIfNeeded(h),this.maybeRefreshPosition();return}this.lastRenderKey=m,this.subtitlesContainer=this.subtitlesContainer??this.createSubtitlesContainer();const v=[`--vot-subtitles-opacity: ${this.opacity}`];this.smartLayoutEnabled?this.smartFontSizePx>0&&v.push(`--vot-subtitles-font-size: ${this.smartFontSizePx}px`):this.fontSizeOverridden&&v.push(`--vot-subtitles-font-size: ${this.fontSize}px`),Q(Zt` ${this.renderTokens(s)} `,this.subtitlesContainer);const b=this.subtitlesContainer.firstElementChild;this.subtitlesBlock=b instanceof HTMLElement&&b.classList.contains("vot-subtitles")?b:null,this.renderedTokenEls=this.subtitlesBlock?Array.from(this.subtitlesBlock.querySelectorAll('span[data-vot-token="1"]')):[],this.highlightWords&&c&&this.updatePassedClasses(c),this.updateMultilineAlignmentIfNeeded(h),l?(this.applyPositionAfterContentRender(),this.scheduleWrapRecomputeBeforePaint(s),this.scheduleReposition()):this.maybeRefreshPosition();}release(){this.detachDragDocumentListeners(),this.stopVideoFrameLoop(),this.abortController.abort(),this.resizeObserver?.disconnect(),this.clearPendingSchedulerState(),this.checkerUnsubscribe?.(),this.checkerUnsubscribe=null,this.releaseTooltip(),this.subtitlesContainer&&(this.subtitlesContainer.remove(),this.subtitlesContainer=null),this.safeAreaProbeEl&&(this.safeAreaProbeEl.remove(),this.safeAreaProbeEl=null),this.measureCtx=null,this.measureCanvas=null;}}function Zf(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function Qf(e){return new Uint8Array([e>>>21&127,e>>>14&127,e>>>7&127,e&127])}function tp(e,t){const n=new TextEncoder().encode(t),i=new Uint8Array(n.length+1);i[0]=3,i.set(n,1);const o=new Uint8Array(10+i.length);o.set([84,73,84,50],0),o.set(Zf(i.length),4),o.set(i,10);const r=new Uint8Array(10);r.set([73,68,51,3,0,0],0),r.set(Qf(o.length),6);const s=new Uint8Array(e),a=new Uint8Array(r.length+o.length+s.length);return a.set(r,0),a.set(o,r.length),a.set(s,r.length+o.length),new Blob([a],{type:"audio/mpeg"})}async function ep(e,t){const n=Number(e.headers.get("Content-Length")??0);if(!e.body)return e.arrayBuffer();const i=e.body.getReader();let o=0,r=n>0?new Uint8Array(n):null;const s=[];for(;;){const{done:c,value:d}=await i.read();if(c)break;if(!(!d||d.byteLength===0)){if(r){const u=o+d.byteLength;if(u>r.length){const h=new Uint8Array(Math.max(u,r.length*2));h.set(r.subarray(0,o)),r=h;}r.set(d,o),o=u;}else s.push(d),o+=d.byteLength;n>0&&t(N(Math.round(o/n*100)));}}if(r)return r.buffer.slice(0,o);const a=new Uint8Array(o);let l=0;for(const c of s)a.set(c,l),l+=c.byteLength;return a.buffer}async function np(e,t,n=()=>{}){const i=await es(e,t,n);return gn(i,`${t}.mp3`),true}async function es(e,t,n=()=>{}){const i=await ep(e,n);return n(100),tp(i,t)}const ip=ot` `,op=ot` `,rp=ot` `,sp=ot` `,ap=ot` `,lp=ot` `,ns=ot` `,cp=ot` `,dp=ot` `,vo=ot` `,bo=ot` `,up=ot` `,hp=ot` `;class Ie{container;translateButton;separator;pipButton;separator2;menuButton;label;_opacity=1;_position;_direction;_status;_labelText;constructor({position:t="default",direction:n="default",status:i="none",labelHtml:o=""}){this._position=t,this._direction=n,this._status=i,this._labelText=o;const r=this.createElements();this.container=r.container,this.translateButton=r.translateButton,this.separator=r.separator,this.pipButton=r.pipButton,this.separator2=r.separator2,this.menuButton=r.menuButton,this.label=r.label;}static calcPosition(t,n){return n?t<=44?"left":t>=66?"right":"default":"default"}static calcDirection(t){return ["default","top"].includes(t)?"row":"column"}createElements(){const t=w.createEl("vot-block",["vot-segmented-button"]);t.dataset.position=this._position,t.dataset.direction=this._direction,t.dataset.status=this._status;const n=w.createEl("vot-block",["vot-segment","vot-translate-button"]);n.setAttribute("role","button"),n.tabIndex=0,n.setAttribute("aria-label",this._labelText||"Translate"),Q(ip,n);const i=w.createEl("span",["vot-segment-label"]);i.textContent=this._labelText,n.appendChild(i);const o=w.createEl("vot-block",["vot-separator"]),r=w.createEl("vot-block",["vot-segment-only-icon"]);r.setAttribute("role","button"),r.tabIndex=0,r.setAttribute("aria-label","Picture in picture"),Q(op,r);const s=w.createEl("vot-block",["vot-separator"]),a=w.createEl("vot-block",["vot-segment-only-icon"]);return a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("aria-label","Menu"),a.setAttribute("aria-haspopup","dialog"),a.setAttribute("aria-expanded","false"),Q(rp,a),t.append(n,o,r,s,a),{container:t,translateButton:n,separator:o,pipButton:r,separator2:s,menuButton:a,label:i}}showPiPButton(t){return this.separator2.hidden=this.pipButton.hidden=!t,this}setText(t){return this._labelText=t,this.label.textContent=t,this.translateButton.setAttribute("aria-label",t||"Translate"),this}remove(){return this.container.remove(),this}get tooltipPos(){switch(this.position){case "left":return "right";case "right":return "left";default:return "bottom"}}set status(t){this._status=this.container.dataset.status=t;}get status(){return this._status}set loading(t){this.container.dataset.loading=t.toString();}get loading(){return this.container.dataset.loading==="true"}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}get position(){return this._position}set position(t){this._position=this.container.dataset.position=t;}get direction(){return this._direction}set direction(t){this._direction=this.container.dataset.direction=t;}set opacity(t){const n=Number.isFinite(t)?t:1;this._opacity=n;const i=n<=.01;this.container.classList.toggle("vot-segmented-button--hidden",i);}get opacity(){return this._opacity}}class fp{button;loaderMain;loaderCircle;onClick=new B;events={click:this.onClick};_progress=0;constructor(){const t=this.createElements();this.button=t.button,this.loaderMain=t.loaderMain,this.loaderCircle=t.loaderCircle,this.progress=0;}createElements(){const t=w.createIconButton(sp,{ariaLabel:"Download translation"}),n=t.querySelector(".vot-loader-main");if(!n)throw new Error("[VOT] DownloadButton loader main element not found");const i=t.querySelector(".vot-loader-progress");if(!i)throw new Error("[VOT] DownloadButton loader circle element not found");return t.addEventListener("click",()=>{this.onClick.dispatch();}),{button:t,loaderMain:n,loaderCircle:i}}addEventListener(t,n){return kt(this.events,"click",n),this}removeEventListener(t,n){return xt(this.events,"click",n),this}get progress(){return this._progress}set progress(t){const n=pp(t);this._progress=n;const i=this.getCircleCircumference();this.loaderCircle.style.strokeDasharray=`${i}`;const o=i*(1-n/100);this.loaderCircle.style.strokeDashoffset=`${o}`,this.loaderMain.style.opacity=n===0?"1":"0",this.loaderCircle.style.opacity=n===0?"0":"1";}getCircleCircumference(){const t=this.loaderCircle.r?.baseVal?.value??0;return 2*Math.PI*t}set hidden(t){et(this.button,t);}get hidden(){return rt(this.button)}}function pp(e){if(!Number.isFinite(e))return 0;const t=e<1?e*100:e;return Math.max(0,Math.min(100,Math.round(t)))}class ft{container;icon;text;_labelText;_icon;constructor({labelText:t,icon:n}){this._labelText=t,this._icon=n;const i=this.createElements();this.container=i.container,this.icon=i.icon,this.text=i.text;}createElements(){const t=w.createEl("vot-block",["vot-label"]),n=w.createEl("span",["vot-label-text"]);n.textContent=this._labelText;const i=w.createEl("span",["vot-label-icon"]);return this._icon?Q(this._icon,i):i.hidden=true,t.append(n,i),{container:t,icon:i,text:n}}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}}class kn{container;backdrop;box;contentWrapper;headerContainer;titleContainer;title;closeButton;bodyContainer;footerContainer;onClose=new B;events={close:this.onClose};previouslyFocused=null;keydownListener;adaptiveAlignObserver;adaptiveAlignRaf=null;handleViewportChange=()=>{this.scheduleAdaptiveVerticalAlign();};titleId=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`vot-dialog-title-${Math.random().toString(36).slice(2)}`;_titleHtml;_isTemp;constructor({titleHtml:t,isTemp:n=false}){this._titleHtml=t,this._isTemp=n;const i=this.createElements();this.container=i.container,this.backdrop=i.backdrop,this.box=i.box,this.contentWrapper=i.contentWrapper,this.headerContainer=i.headerContainer,this.titleContainer=i.titleContainer,this.title=i.title,this.closeButton=i.closeButton,this.bodyContainer=i.bodyContainer,this.footerContainer=i.footerContainer;}createElements(){const t=w.createEl("vot-block",["vot-dialog-container"]);this._isTemp&&t.classList.add("vot-dialog-temp"),t.hidden=!this._isTemp,t.setAttribute("aria-hidden",t.hidden?"true":"false"),t.toggleAttribute("inert",t.hidden);const n=w.createEl("vot-block",["vot-dialog-backdrop"]),i=w.createEl("vot-block",["vot-dialog"]);i.dataset.verticalAlign="center",i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.tabIndex=-1;const o=w.createEl("vot-block",["vot-dialog-content-wrapper"]),r=w.createEl("vot-block",["vot-dialog-header-container"]),s=w.createEl("vot-block",["vot-dialog-title-container"]),a=w.createEl("vot-block",["vot-dialog-title"]);a.id=this.titleId,a.append(this._titleHtml),s.appendChild(a),i.setAttribute("aria-labelledby",this.titleId);const l=w.createIconButton(dp,{ariaLabel:"Close"});l.classList.add("vot-dialog-close-button"),n.addEventListener("click",()=>{this.close();}),l.addEventListener("click",()=>{this.close();}),r.append(s,l);const c=w.createEl("vot-block",["vot-dialog-body-container"]),d=w.createEl("vot-block",["vot-dialog-footer-container"]);return o.append(r,c,d),i.appendChild(o),t.append(n,i),i.addEventListener("click",u=>{u.stopPropagation();}),{container:t,backdrop:n,box:i,contentWrapper:o,headerContainer:r,titleContainer:s,title:a,closeButton:l,bodyContainer:c,footerContainer:d}}addEventListener(t,n){return kt(this.events,"close",n),this}removeEventListener(t,n){return xt(this.events,"close",n),this}open(){return this.previouslyFocused??=document.activeElement,this.hidden=false,this.attachKeydownTrap(),this.attachAdaptiveVerticalAlign(),queueMicrotask(()=>this.focusFirst()),this}remove(){return this.detachAdaptiveVerticalAlign(),this.detachKeydownTrap(),this.container.remove(),this.restoreFocus(),this.onClose.dispatch(),this}close(){return this._isTemp?this.remove():(this.detachAdaptiveVerticalAlign(),this.detachKeydownTrap(),this.hidden=true,this.restoreFocus(),this.onClose.dispatch(),this)}attachAdaptiveVerticalAlign(){if(this.adaptiveAlignObserver){this.scheduleAdaptiveVerticalAlign();return}typeof ResizeObserver<"u"&&(this.adaptiveAlignObserver=new ResizeObserver(()=>{this.scheduleAdaptiveVerticalAlign();}),this.adaptiveAlignObserver.observe(this.contentWrapper)),globalThis.addEventListener("resize",this.handleViewportChange,{passive:true}),globalThis.visualViewport&&(globalThis.visualViewport.addEventListener("resize",this.handleViewportChange,{passive:true}),globalThis.visualViewport.addEventListener("scroll",this.handleViewportChange,{passive:true})),this.scheduleAdaptiveVerticalAlign();}detachAdaptiveVerticalAlign(){this.adaptiveAlignObserver&&(this.adaptiveAlignObserver.disconnect(),this.adaptiveAlignObserver=void 0),globalThis.removeEventListener("resize",this.handleViewportChange),globalThis.visualViewport?.removeEventListener("resize",this.handleViewportChange),globalThis.visualViewport?.removeEventListener("scroll",this.handleViewportChange),this.adaptiveAlignRaf!==null&&(cancelAnimationFrame(this.adaptiveAlignRaf),this.adaptiveAlignRaf=null);}scheduleAdaptiveVerticalAlign(){this.adaptiveAlignRaf!==null&&cancelAnimationFrame(this.adaptiveAlignRaf),this.adaptiveAlignRaf=requestAnimationFrame(()=>{this.adaptiveAlignRaf=null,this.updateAdaptiveVerticalAlign();});}updateAdaptiveVerticalAlign(){const t=globalThis.visualViewport?.height??globalThis.innerHeight;if(!t||t<=0)return;const n=16,i=Math.max(160,Math.round(t*.75)),o=Math.max(160,Math.round(t-n*2)),r=this.contentWrapper.scrollHeight,s=this.box.dataset.verticalAlign==="top",a=i-8,l=Math.round(t*.6);(s?r>l:r>=a)?(this.box.dataset.verticalAlign="top",this.box.style.setProperty("--vot-dialog-max-height",`${o}px`)):(this.box.dataset.verticalAlign="center",this.box.style.setProperty("--vot-dialog-max-height",`${i}px`));}restoreFocus(){const t=this.previouslyFocused;this.previouslyFocused=null,t&&t instanceof HTMLElement&&document.contains(t)&&t.focus();}getFocusableElements(){const t=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])","[role='button']:not([aria-disabled='true'])"];return Array.from(this.container.querySelectorAll(t.join(","))).filter(n=>!n.hidden&&n.getClientRects().length>0)}focusFirst(){(this.getFocusableElements()[0]??this.closeButton??this.box).focus?.();}attachKeydownTrap(){this.keydownListener||(this.keydownListener=t=>{if(t.key==="Escape"){t.preventDefault(),this.close();return}if(t.key!=="Tab")return;const n=this.getFocusableElements();if(!n.length){t.preventDefault(),this.box.focus();return}const i=n[0],o=n.at(-1)??i,r=document.activeElement;t.shiftKey?(r===i||r===this.box)&&(t.preventDefault(),o.focus()):r===o&&(t.preventDefault(),i.focus());},this.container.addEventListener("keydown",this.keydownListener));}detachKeydownTrap(){this.keydownListener&&(this.container.removeEventListener("keydown",this.keydownListener),this.keydownListener=void 0);}set hidden(t){et(this.container,t),this.container.setAttribute("aria-hidden",t?"true":"false"),this.container.toggleAttribute("inert",t);}get hidden(){return rt(this.container)}get isDialogOpen(){return !this.container.hidden}}class xn{container;input;label;onInput=new B;onChange=new B;events={input:this.onInput,change:this.onChange};_labelHtml;_multiline;_placeholder;_value;constructor({labelHtml:t="",placeholder:n="",value:i="",multiline:o=false}){this._labelHtml=t,this._multiline=o,this._placeholder=n,this._value=i;const r=this.createElements();this.container=r.container,this.input=r.input,this.label=r.label;}createElements(){const t=w.createEl("vot-block",["vot-textfield"]),n=document.createElement(this._multiline?"textarea":"input");this._labelHtml||n.classList.add("vot-show-placeholer","vot-show-placeholder"),n.placeholder=this._placeholder,n.value=this._value;const i=w.createEl("span");return i.append(this._labelHtml),t.append(n,i),n.addEventListener("input",()=>{this._value=this.input.value,this.onInput.dispatch(this._value);}),n.addEventListener("change",()=>{this._value=this.input.value,this.onChange.dispatch(this._value);}),{container:t,label:i,input:n}}addEventListener(t,n){return kt(this.events,t,n),this}removeEventListener(t,n){return xt(this.events,t,n),this}get value(){return this._value}set value(t){this._value!==t&&(this.input.value=this._value=t,this.onChange.dispatch(this._value));}get placeholder(){return this._placeholder}set placeholder(t){this.input.placeholder=this._placeholder=t;}get disabled(){return this.input.disabled}set disabled(t){this.input.disabled=t;}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}}class j{container;outer;arrowIcon;title;dialogParent;labelElement;_selectTitle;_dialogTitle;multiSelect;_items;isLoading=false;isDialogOpen=false;onSelectItem=new B;onBeforeOpen=new B;events={selectItem:this.onSelectItem,beforeOpen:this.onBeforeOpen};contentList;selectedItems=[];selectedValues;constructor({selectTitle:t,dialogTitle:n,items:i,labelElement:o,dialogParent:r=document.documentElement,multiSelect:s}){this._selectTitle=t,this._dialogTitle=n,this._items=i,this.multiSelect=s??false,this.labelElement=o,this.dialogParent=r,this.selectedValues=this.calcSelectedValues();const a=this.createElements();this.container=a.container,this.outer=a.outer,this.arrowIcon=a.arrowIcon,this.title=a.title;}static genLanguageItems(t,n){return t.map(i=>{const o=`langs.${i}`,r=p.get(o);return {label:r===o?i.toUpperCase():r,value:i,selected:n===i}})}multiSelectItemHandle=(t,n)=>{const i=n.value;this.selectedValues.has(i)&&this.selectedValues.size>1?(this.selectedValues.delete(i),n.selected=false):(this.selectedValues.add(i),n.selected=true),t.dataset.votSelected=this.selectedValues.has(i).toString(),this.updateSelectedState(),this.onSelectItem.dispatch(Array.from(this.selectedValues));};singleSelectItemHandle=t=>{const n=t.value;this.selectedValues=new Set([n]);for(const i of this.selectedItems)i.dataset.votSelected=(i.dataset.votValue===n).toString();for(const i of this._items)i.selected=i.value===n;this.updateTitle(),this.onSelectItem.dispatch(n);};createDialogContentList(){const t=w.createEl("vot-block",["vot-select-content-list"]);for(const n of this._items){const i=w.createEl("vot-block",["vot-select-content-item"]);i.textContent=n.label,i.dataset.votSelected=n.selected===true?"true":"false",i.dataset.votValue=n.value,n.disabled&&(i.inert=true),i.addEventListener("click",o=>{if(!o.target.inert)return this.multiSelect?this.multiSelectItemHandle(i,n):this.singleSelectItemHandle(n)}),t.appendChild(i);}return this.selectedItems=Array.from(t.children),t}createElements(){const t=w.createEl("vot-block",["vot-select"]);this.labelElement?(t.classList.add("vot-select--labeled"),t.append(this.labelElement)):t.classList.add("vot-select--control-only");const n=w.createEl("vot-block",["vot-select-outer"]);w.makeButtonLike(n),n.setAttribute("aria-haspopup","dialog"),n.setAttribute("aria-expanded","false");const i=w.createEl("vot-block",["vot-select-title"]);i.textContent=this.visibleText;const o=w.createEl("vot-block",["vot-select-arrow-icon"]);return Q(ns,o),n.append(i,o),n.addEventListener("click",()=>{if(!(n.getAttribute("disabled")==="true"||n.getAttribute("aria-disabled")==="true")&&!(this.isLoading||this.isDialogOpen))try{this.isLoading=!0;const s=new kn({titleHtml:this._dialogTitle,isTemp:!0});this.onBeforeOpen.dispatch(s),this.dialogParent.appendChild(s.container),this.isDialogOpen=!0,n.setAttribute("aria-expanded","true");const a=new xn({labelHtml:p.get("searchField")});a.addEventListener("input",l=>{const c=l.toLowerCase();for(const d of this.selectedItems)d.hidden=!d.textContent?.toLowerCase().includes(c);}),this.contentList=this.createDialogContentList(),s.bodyContainer.append(a.container,this.contentList),s.addEventListener("close",()=>{this.isDialogOpen=!1,this.selectedItems=[],this.contentList=void 0,n.setAttribute("aria-expanded","false");}),s.open();}finally{this.isLoading=false;}}),t.appendChild(n),{container:t,outer:n,arrowIcon:o,title:i}}calcSelectedValues(){return new Set(this._items.filter(t=>t.selected).map(t=>t.value))}addEventListener(t,n){return kt(this.events,t,n),this}removeEventListener(t,n){return xt(this.events,t,n),this}updateTitle(){return this.title.textContent=this.visibleText,this}updateSelectedState(){if(this.selectedItems.length>0)for(const t of this.selectedItems){const n=t.dataset.votValue;n&&(t.dataset.votSelected=this.selectedValues.has(n).toString());}return this.updateTitle(),this}setSelectedValue(t){this.multiSelect?this.selectedValues=new Set(Array.isArray(t)?t.map(String):[String(t)]):this.selectedValues=new Set([String(t)]);for(const n of this._items)n.selected=this.selectedValues.has(String(n.value));return this.updateSelectedState(),this}updateItems(t){this._items=t,this.selectedValues=this.calcSelectedValues(),this.updateSelectedState();const n=this.contentList?.parentElement;if(!this.contentList||!n)return this;const i=this.contentList;return this.contentList=this.createDialogContentList(),n.replaceChild(this.contentList,i),this}get visibleText(){return this.multiSelect?this._items.filter(t=>this.selectedValues.has(t.value)).map(t=>t.label).join(", ")||this._selectTitle:this._items.find(t=>t.selected)?.label??this._selectTitle}set selectTitle(t){this._selectTitle=t,this.updateTitle();}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}get disabled(){return this.outer.getAttribute("disabled")==="true"}set disabled(t){this.outer.toggleAttribute("disabled",t);}}class gp{container;fromSelect;directionIcon;toSelect;dialogParent;_fromSelectTitle;_fromDialogTitle;_fromItems;_toSelectTitle;_toDialogTitle;_toItems;constructor({from:{selectTitle:t=p.get("videoLanguage"),dialogTitle:n=p.get("videoLanguage"),items:i},to:{selectTitle:o=p.get("translationLanguage"),dialogTitle:r=p.get("translationLanguage"),items:s},dialogParent:a=document.documentElement}){this._fromSelectTitle=t,this._fromDialogTitle=n,this._fromItems=i,this._toSelectTitle=o,this._toDialogTitle=r,this._toItems=s,this.dialogParent=a;const l=this.createElements();this.container=l.container,this.fromSelect=l.fromSelect,this.directionIcon=l.directionIcon,this.toSelect=l.toSelect;}createElements(){const t=w.createEl("vot-block",["vot-lang-select"]),n=new j({selectTitle:this._fromSelectTitle,dialogTitle:this._fromDialogTitle,items:this._fromItems,dialogParent:this.dialogParent}),i=w.createEl("vot-block",["vot-lang-select-icon"]);Q(cp,i);const o=new j({selectTitle:this._toSelectTitle,dialogTitle:this._toDialogTitle,items:this._toItems,dialogParent:this.dialogParent});return t.append(n.container,i,o.container),{container:t,fromSelect:n,directionIcon:i,toSelect:o}}setSelectedValues(t,n){return this.fromSelect.setSelectedValue(t),this.toSelect.setSelectedValue(n),this}updateItems(t,n){return this._fromItems=t,this._toItems=n,this.fromSelect=this.fromSelect.updateItems(t),this.toSelect=this.toSelect.updateItems(n),this}}class It{container;input;label;onInput=new B;_labelHtml;_value;_min;_max;_step;constructor({labelHtml:t,value:n=50,min:i=0,max:o=100,step:r=1}){this._labelHtml=t,this._value=n,this._min=i,this._max=o,this._step=r;const s=this.createElements();this.container=s.container,this.input=s.input,this.label=s.label,this.update();}updateProgress(){const t=this._max-this._min,n=t<=0?0:(this._value-this._min)/t,i=Math.max(0,Math.min(1,n));return this.container.style.setProperty("--vot-progress",i.toString()),this}update(){return this._value=this.input.valueAsNumber,this._min=+this.input.min,this._max=+this.input.max,this.updateProgress(),this}createElements(){const t=w.createEl("vot-block",["vot-slider"]),n=document.createElement("input");n.type="range",n.min=this._min.toString(),n.max=this._max.toString(),n.step=this._step.toString(),n.value=this._value.toString();const i=w.createEl("span");return Q(this._labelHtml,i),t.append(n,i),n.addEventListener("input",()=>{this.update(),this.onInput.dispatch(this._value,false);}),{container:t,label:i,input:n}}addEventListener(t,n){return this.onInput.addListener(n),this}removeEventListener(t,n){return this.onInput.removeListener(n),this}get value(){return this._value}set value(t){this._value=nn(t,this._min,this._max),this.input.value=this._value.toString(),this.updateProgress(),this.onInput.dispatch(this._value,true);}get min(){return this._min}set min(t){this._min=t,this.input.min=this._min.toString(),this._value=nn(this._value,this._min,this._max),this.input.value=this._value.toString(),this.updateProgress();}get max(){return this._max}set max(t){this._max=t,this.input.max=this._max.toString(),this._value=nn(this._value,this._min,this._max),this.input.value=this._value.toString(),this.updateProgress();}get step(){return this._step}set step(t){this._step=t,this.input.step=this._step.toString();}get disabled(){return this.input.disabled}set disabled(t){this.input.disabled=t;}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}}function nn(e,t,n){return !Number.isFinite(e)||n{this.defaultVolumePersistTimer=void 0,this.flushDefaultVolumePersist();},this.defaultVolumePersistDelayMs);}flushDefaultVolumePersist(){this.defaultVolumePersistTimer!==void 0&&(globalThis.clearTimeout(this.defaultVolumePersistTimer),this.defaultVolumePersistTimer=void 0),typeof this.data.defaultVolume=="number"&&I.set("defaultVolume",this.data.defaultVolume);}initUI(t="default"){if(this.isInitialized())throw new Error("[VOT] OverlayView is already initialized");this.initialized=true;const{position:n,direction:i}=this.calcButtonLayout(t);this.votOverlayPortal=w.createPortal(true),this.portalContainer.appendChild(this.votOverlayPortal),this.votButton=new Ie({position:n,direction:i,status:"none",labelHtml:p.get("translateVideo")}),this.votButton.opacity=0,this.pipButtonVisible||this.votButton.showPiPButton(false),this.root.appendChild(this.votButton.container),this.votButtonTooltip=new G({target:this.votButton.translateButton,content:p.get("translateVideo"),position:this.votButton.tooltipPos,autoLayout:false,hidden:i==="row",bordered:false,parentElement:this.votOverlayPortal,layoutRoot:this.tooltipLayoutRoot}),this.votMenu=new mp({titleHtml:p.get("VOTSettings"),position:n}),this.root.appendChild(this.votMenu.container),this.votButton.menuButton.setAttribute("aria-controls",this.votMenu.container.id),this.downloadTranslationButton=new fp,this.downloadTranslationButton.hidden=true,this.downloadSubtitlesButton=w.createIconButton(ap,{ariaLabel:"Download subtitles"}),this.downloadSubtitlesButton.hidden=true,this.openSettingsButton=w.createIconButton(lp,{ariaLabel:p.get("VOTSettings")}),this.votMenu.headerContainer.append(this.downloadTranslationButton.button,this.downloadSubtitlesButton,this.openSettingsButton);const o=this.videoHandler?.videoData?.detectedLanguage??"en",r=this.data.responseLanguage??"ru";this.languagePairSelect=new gp({from:{selectTitle:p.get(`langs.${o}`),items:j.genLanguageItems(_t,o)},to:{selectTitle:p.get(`langs.${r}`),items:j.genLanguageItems(In,r)}}),this.subtitlesSelectLabel=new ft({labelText:p.get("VOTSubtitles")}),this.subtitlesSelect=new j({selectTitle:p.get("VOTSubtitlesDisabled"),dialogTitle:p.get("VOTSubtitles"),labelElement:this.subtitlesSelectLabel.container,dialogParent:this.globalPortal,items:[{label:p.get("VOTSubtitlesDisabled"),value:"disabled",selected:true}]});const s=this.videoHandler?this.videoHandler.getVideoVolume()*100:100;this.videoVolumeSliderLabel=new Pt({labelText:p.get("VOTVolume"),value:s}),this.videoVolumeSlider=new It({labelHtml:this.videoVolumeSliderLabel.container,value:s}),this.videoVolumeSlider.hidden=!this.data.showVideoSlider||this.votButton.status!=="success";const a=this.data.defaultVolume??100;return this.translationVolumeSliderLabel=new Pt({labelText:p.get("VOTVolumeTranslation"),value:a}),this.translationVolumeSlider=new It({labelHtml:this.translationVolumeSliderLabel.container,value:a,max:this.data.audioBooster?wr:100}),this.translationVolumeSlider.hidden=this.votButton.status!=="success",this.votMenu.bodyContainer.append(this.languagePairSelect.container,this.subtitlesSelect.container,this.videoVolumeSlider.container,this.translationVolumeSlider.container),this}initUIEvents(){if(!this.isInitialized())throw new Error("[VOT] OverlayView isn't initialized");this.abortController=new AbortController;const t=this.abortController.signal;this.checkerUnsubscribe?.(),this.checkerUnsubscribe=this.intervalIdleChecker.subscribe(()=>{this.onCheckerTick();}),this.votButton.container.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation();},{signal:t});const n=a=>l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),a());},i=(a,{returnFocusToToggle:l=false}={})=>{this.isInitialized()&&(this.votMenu.hidden=!a,this.votButton.menuButton.setAttribute("aria-expanded",a.toString()),this.votButtonTooltip&&(this.votButtonTooltip.hidden=a||this.votButton.direction==="row"),a?queueMicrotask(()=>this.openSettingsButton?.focus?.()):l?queueMicrotask(()=>this.votButton.menuButton.focus?.()):this.votButton.menuButton.blur());},o=()=>i(this.votMenu.hidden),r=(a=false)=>i(false,{returnFocusToToggle:a});this.votButton.translateButton.addEventListener("pointerdown",()=>{r(),this.events["click:translate"].dispatch();},{signal:t}),this.votButton.translateButton.addEventListener("keydown",n(()=>{r(),this.events["click:translate"].dispatch();}),{signal:t}),this.votButton.pipButton.addEventListener("pointerdown",()=>{r(),this.events["click:pip"].dispatch();},{signal:t}),this.votButton.pipButton.addEventListener("keydown",n(()=>{r(),this.events["click:pip"].dispatch();}),{signal:t}),this.votButton.menuButton.addEventListener("pointerdown",a=>{a.preventDefault(),o();},{signal:t}),this.votButton.menuButton.addEventListener("keydown",n(o),{signal:t});const s="none";this.votButton.container.style.touchAction=s,this.votButton.translateButton.style.touchAction=s,this.votButton.pipButton.style.touchAction=s,this.votButton.menuButton.style.touchAction=s,this.votButton.container.addEventListener("pointerdown",this.onDragStart,{signal:t}),this.votButton.container.addEventListener("touchstart",this.onTouchDragStart,{signal:t,passive:false}),this.votMenu.container.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation();},{signal:t});for(const a of ["pointerdown","mousedown"])this.votMenu.container.addEventListener(a,l=>{l.stopImmediatePropagation();},{signal:t});return document.addEventListener("pointerdown",a=>{if(this.votMenu.hidden)return;const l=a.target,c=typeof a.composedPath=="function"?a.composedPath():[],d=l&&this.votMenu.container.contains(l)||c.includes(this.votMenu.container),u=l&&this.votButton.menuButton.contains(l)||c.includes(this.votButton.menuButton),h=l&&this.votButton.container.contains(l)||c.includes(this.votButton.container),m=l instanceof HTMLElement&&!!l.closest(".vot-dialog-container");d||u||h||m||r(false);},{signal:t,capture:true,passive:true}),this.votMenu.container.addEventListener("keydown",a=>{if(a.key!=="Escape")return;const l=document.documentElement.classList.contains("vot-keyboard-nav");a.preventDefault(),a.stopPropagation(),r(l),this.votButton.container.matches(":hover")||this.votMenu.container.matches(":hover")||this.videoHandler?.overlayVisibility?.queueAutoHide?.();},{signal:t}),this.downloadTranslationButton.addEventListener("click",()=>{this.events["click:downloadTranslation"].dispatch();}),this.downloadSubtitlesButton.addEventListener("click",()=>{this.events["click:downloadSubtitles"].dispatch();},{signal:t}),this.openSettingsButton.addEventListener("click",()=>{r(),this.events["click:settings"].dispatch();},{signal:t}),this.languagePairSelect.fromSelect.addEventListener("selectItem",a=>{this.videoHandler?.videoData&&(this.videoHandler.videoData.detectedLanguage=a),this.events["select:fromLanguage"].dispatch(a);}),this.languagePairSelect.toSelect.addEventListener("selectItem",async a=>{this.videoHandler?.videoData&&(this.videoHandler.translateToLang=this.videoHandler.videoData.responseLanguage=a);const l=this.data.responseLanguage;this.data.responseLanguage=a,await I.set("responseLanguage",this.data.responseLanguage),this.data.enabledDontTranslateLanguages&&Array.isArray(this.data.dontTranslateLanguages)&&this.data.dontTranslateLanguages.length===1&&typeof l=="string"&&this.data.dontTranslateLanguages[0]===l&&(this.data.dontTranslateLanguages=[a],await I.set("dontTranslateLanguages",this.data.dontTranslateLanguages)),this.events["select:toLanguage"].dispatch(a);}),this.subtitlesSelect.addEventListener("beforeOpen",async a=>{if(!this.videoHandler?.videoData)return;const l=this.videoHandler.getSubtitlesCacheKey(this.videoHandler.videoData.videoId,this.videoHandler.videoData.detectedLanguage,this.videoHandler.videoData.responseLanguage);if(this.videoHandler.cacheManager.getSubtitles(l))return;this.votButton&&(this.votButton.loading=true);const c=w.createInlineLoader();c.style.margin="0 auto",a.footerContainer.appendChild(c),await this.videoHandler.loadSubtitles(),c.remove(),this.votButton&&(this.votButton.loading=false);}),this.subtitlesSelect.addEventListener("selectItem",a=>{this.events["select:subtitles"].dispatch(a);}),this.videoVolumeSlider.addEventListener("input",(a,l)=>{this.videoVolumeSliderLabel&&(this.videoVolumeSliderLabel.value=a),!l&&this.events["input:videoVolume"].dispatch(a);}),this.translationVolumeSlider.addEventListener("input",(a,l)=>{this.translationVolumeSliderLabel&&(this.translationVolumeSliderLabel.value=a),this.data.defaultVolume=a,this.scheduleDefaultVolumePersist(),!l&&this.events["input:translationVolume"].dispatch(a);}),this}updateButtonLayout(t,n){return this.isInitialized()?(this.votMenu.position=t,this.votButton.position=t,this.votButton.direction=n,this.votButtonTooltip.hidden=n==="row",this.votButtonTooltip.setPosition(this.votButton.tooltipPos),this):this}moveButton(t){if(!this.isInitialized())return this;const n=this.dragIsBigContainer??this.isBigContainer,i=Ie.calcPosition(t,n);if(i===this.votButton.position)return this;const o=Ie.calcDirection(i);return this.data.buttonPos=i,this.updateButtonLayout(i,o),this}onDragStart=t=>{!t.isPrimary||t.button!==0||t.pointerType!=="touch"&&(t.preventDefault(),this.dragCandidate=true,this.dragging=false,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.currentClientX=t.clientX,this.containerRect=this.root.getBoundingClientRect(),this.dragIsBigContainer=this.isBigContainer,this.dragDirty=false,this.intervalIdleChecker.markActivity("overlay-pointer-down"),this.intervalIdleChecker.requestImmediateTick(),document.addEventListener("pointermove",this.onGlobalPointerMove),document.addEventListener("pointerup",this.onDragEnd),document.addEventListener("pointercancel",this.onDragEnd));};onTouchDragStart=t=>{if(!t.touches||t.touches.length===0)return;this.dragCandidate=true,this.dragging=false;const n=t.touches[0];this.dragStartX=n.clientX,this.dragStartY=n.clientY,this.currentClientX=n.clientX,this.containerRect=this.root.getBoundingClientRect(),this.dragIsBigContainer=this.isBigContainer,this.dragDirty=false,this.intervalIdleChecker.markActivity("overlay-touch-start"),this.intervalIdleChecker.requestImmediateTick(),document.addEventListener("touchmove",this.onGlobalTouchMove,{passive:false}),document.addEventListener("touchend",this.onDragEnd),document.addEventListener("touchcancel",this.onDragEnd);};onGlobalTouchMove=t=>{if(!t.touches||t.touches.length===0)return;const n=t.touches[0];this.currentClientX=n.clientX;const i=n.clientY;if(this.dragCandidate){if(!this.dragging){const o=Math.abs(this.currentClientX-this.dragStartX),r=Math.abs(i-this.dragStartY);o+r>=this.dragThresholdPx&&(this.dragging=true);}this.dragging&&t.preventDefault(),this.dragging&&(this.dragDirty=true,this.intervalIdleChecker.markActivity("overlay-touch-move"),this.intervalIdleChecker.requestImmediateTick());}};onGlobalPointerMove=t=>{this.currentClientX=t.clientX;const n=t.clientY;if(this.dragCandidate){if(!this.dragging){const i=Math.abs(this.currentClientX-this.dragStartX),o=Math.abs(n-this.dragStartY);i+o>=this.dragThresholdPx&&(this.dragging=true);}this.dragging&&(this.dragDirty=true,this.intervalIdleChecker.markActivity("overlay-pointer-move"),this.intervalIdleChecker.requestImmediateTick());}};applyDragFromState=()=>{if(!this.dragging||!this.dragDirty||!this.containerRect)return;this.dragDirty=false;const t=this.currentClientX-this.containerRect.left,i=Math.max(0,Math.min(t,this.containerRect.width))/this.containerRect.width*100;this.moveButton(i);};onCheckerTick=()=>{this.applyDragFromState();};onDragEnd=()=>{document.removeEventListener("pointermove",this.onGlobalPointerMove),document.removeEventListener("pointerup",this.onDragEnd),document.removeEventListener("pointercancel",this.onDragEnd),document.removeEventListener("touchmove",this.onGlobalTouchMove),document.removeEventListener("touchend",this.onDragEnd),document.removeEventListener("touchcancel",this.onDragEnd),this.applyDragFromState();const t=this.dragIsBigContainer??this.isBigContainer;this.dragging&&t&&this.data.buttonPos&&I.set("buttonPos",this.data.buttonPos),this.dragging=false,this.dragCandidate=false,this.dragDirty=false,this.containerRect=null,this.dragIsBigContainer=null;};updateButtonOpacity(t){return !this.isInitialized()||!this.votMenu.hidden?this:(Math.abs(this.votButton.opacity-t)>.01&&(this.votButton.opacity=t),this)}doReleaseUI(){this.votButton?.remove(),this.votMenu?.remove(),this.votButtonTooltip?.release(),this.votOverlayPortal?.remove();}doReleaseUIEvents(){this.abortController?.abort(),this.abortController=null,this.checkerUnsubscribe?.(),this.checkerUnsubscribe=null,this.onDragEnd(),this.flushDefaultVolumePersist();for(const t of Object.values(this.events))t.clear();}releaseUI(t=false){if(!this.isInitialized())throw new Error("[VOT] OverlayView isn't initialized");return this.doReleaseUI(),this.initialized=t,this}releaseUIEvents(t=false){if(!this.isInitialized())throw new Error("[VOT] OverlayView isn't initialized");return this.doReleaseUIEvents(),this.initialized=t,this}release(){return this.isInitialized()?(this.doReleaseUIEvents(),this.doReleaseUI(),this.initialized=false,this):this}get isBigContainer(){const t=this.videoHandler?.video?.getBoundingClientRect?.().width;if(typeof t=="number"&&Number.isFinite(t))return t>550;const n=this.videoHandler?.container?.getBoundingClientRect?.().width;return typeof n=="number"&&Number.isFinite(n)?n>550:this.root.clientWidth>550}get pipButtonVisible(){return xr()&&!!this.data.showPiPButton}}const bp=["default","top","left","right"],yp={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},is={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},L={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},J={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},pt={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class f{static getFirstMatch(t,n){const i=n.match(t);return i&&i.length>0&&i[1]||""}static getSecondMatch(t,n){const i=n.match(t);return i&&i.length>1&&i[2]||""}static matchAndReturnConst(t,n,i){if(t.test(n))return i}static getWindowsVersionName(t){switch(t){case "NT":return "NT";case "XP":return "XP";case "NT 5.0":return "2000";case "NT 5.1":return "XP";case "NT 5.2":return "2003";case "NT 6.0":return "Vista";case "NT 6.1":return "7";case "NT 6.2":return "8";case "NT 6.3":return "8.1";case "NT 10.0":return "10";default:return}}static getMacOSVersionName(t){const n=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);n.push(0);const i=n[0],o=n[1];if(i===10)switch(o){case 5:return "Leopard";case 6:return "Snow Leopard";case 7:return "Lion";case 8:return "Mountain Lion";case 9:return "Mavericks";case 10:return "Yosemite";case 11:return "El Capitan";case 12:return "Sierra";case 13:return "High Sierra";case 14:return "Mojave";case 15:return "Catalina";default:return}switch(i){case 11:return "Big Sur";case 12:return "Monterey";case 13:return "Ventura";case 14:return "Sonoma";case 15:return "Sequoia";default:return}}static getAndroidVersionName(t){const n=t.split(".").splice(0,2).map(i=>parseInt(i,10)||0);if(n.push(0),!(n[0]===1&&n[1]<5)){if(n[0]===1&&n[1]<6)return "Cupcake";if(n[0]===1&&n[1]>=6)return "Donut";if(n[0]===2&&n[1]<2)return "Eclair";if(n[0]===2&&n[1]===2)return "Froyo";if(n[0]===2&&n[1]>2)return "Gingerbread";if(n[0]===3)return "Honeycomb";if(n[0]===4&&n[1]<1)return "Ice Cream Sandwich";if(n[0]===4&&n[1]<4)return "Jelly Bean";if(n[0]===4&&n[1]>=4)return "KitKat";if(n[0]===5)return "Lollipop";if(n[0]===6)return "Marshmallow";if(n[0]===7)return "Nougat";if(n[0]===8)return "Oreo";if(n[0]===9)return "Pie"}}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,n,i=false){const o=f.getVersionPrecision(t),r=f.getVersionPrecision(n);let s=Math.max(o,r),a=0;const l=f.map([t,n],c=>{const d=s-f.getVersionPrecision(c),u=c+new Array(d+1).join(".0");return f.map(u.split("."),h=>new Array(20-h.length).join("0")+h).reverse()});for(i&&(a=s-Math.min(o,r)),s-=1;s>=a;){if(l[0][s]>l[1][s])return 1;if(l[0][s]===l[1][s]){if(s===a)return 0;s-=1;}else if(l[0][s]{i[l]=s[l];});}return t}static getBrowserAlias(t){return yp[t]}static getBrowserTypeByAlias(t){return is[t]||""}}const P=/version\/(\d+(\.?_?\d+)+)/i,wp=[{test:[/gptbot/i],describe(e){const t={name:"GPTBot"},n=f.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/chatgpt-user/i],describe(e){const t={name:"ChatGPT-User"},n=f.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/oai-searchbot/i],describe(e){const t={name:"OAI-SearchBot"},n=f.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(e){const t={name:"ClaudeBot"},n=f.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/omgilibot/i,/webzio-extended/i],describe(e){const t={name:"Omgilibot"},n=f.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/diffbot/i],describe(e){const t={name:"Diffbot"},n=f.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/perplexitybot/i],describe(e){const t={name:"PerplexityBot"},n=f.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/perplexity-user/i],describe(e){const t={name:"Perplexity-User"},n=f.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/youbot/i],describe(e){const t={name:"YouBot"},n=f.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/meta-webindexer/i],describe(e){const t={name:"Meta-WebIndexer"},n=f.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/meta-externalads/i],describe(e){const t={name:"Meta-ExternalAds"},n=f.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/meta-externalagent/i],describe(e){const t={name:"Meta-ExternalAgent"},n=f.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/meta-externalfetcher/i],describe(e){const t={name:"Meta-ExternalFetcher"},n=f.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/googlebot/i],describe(e){const t={name:"Googlebot"},n=f.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/linespider/i],describe(e){const t={name:"Linespider"},n=f.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/amazonbot/i],describe(e){const t={name:"AmazonBot"},n=f.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/bingbot/i],describe(e){const t={name:"BingCrawler"},n=f.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/baiduspider/i],describe(e){const t={name:"BaiduSpider"},n=f.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/duckduckbot/i],describe(e){const t={name:"DuckDuckBot"},n=f.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/ia_archiver/i],describe(e){const t={name:"InternetArchiveCrawler"},n=f.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return {name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(e){const t={name:"SlackBot"},n=f.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/yahoo!?[\s/]*slurp/i],describe(){return {name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return {name:"YandexBot"}}},{test:[/pingdom/i],describe(){return {name:"PingdomBot"}}},{test:[/opera/i],describe(e){const t={name:"Opera"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opr\/|opios/i],describe(e){const t={name:"Opera"},n=f.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:"Samsung Internet for Android"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Whale/i],describe(e){const t={name:"NAVER Whale Browser"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/PaleMoon/i],describe(e){const t={name:"Pale Moon"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MZBrowser/i],describe(e){const t={name:"MZ Browser"},n=f.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/focus/i],describe(e){const t={name:"Focus"},n=f.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/swing/i],describe(e){const t={name:"Swing"},n=f.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/coast/i],describe(e){const t={name:"Opera Coast"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(e){const t={name:"Opera Touch"},n=f.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/yabrowser/i],describe(e){const t={name:"Yandex Browser"},n=f.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/ucbrowser/i],describe(e){const t={name:"UC Browser"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:"Maxthon"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/epiphany/i],describe(e){const t={name:"Epiphany"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/puffin/i],describe(e){const t={name:"Puffin"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sleipnir/i],describe(e){const t={name:"Sleipnir"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/k-meleon/i],describe(e){const t={name:"K-Meleon"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/micromessenger/i],describe(e){const t={name:"WeChat"},n=f.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},n=f.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/msie|trident/i],describe(e){const t={name:"Internet Explorer"},n=f.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/\sedg\//i],describe(e){const t={name:"Microsoft Edge"},n=f.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:"Microsoft Edge"},n=f.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/vivaldi/i],describe(e){const t={name:"Vivaldi"},n=f.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/seamonkey/i],describe(e){const t={name:"SeaMonkey"},n=f.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sailfish/i],describe(e){const t={name:"Sailfish"},n=f.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return n&&(t.version=n),t}},{test:[/silk/i],describe(e){const t={name:"Amazon Silk"},n=f.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/phantom/i],describe(e){const t={name:"PhantomJS"},n=f.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/slimerjs/i],describe(e){const t={name:"SlimerJS"},n=f.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t={name:"BlackBerry"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:"WebOS Browser"},n=f.getFirstMatch(P,e)||f.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/bada/i],describe(e){const t={name:"Bada"},n=f.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/tizen/i],describe(e){const t={name:"Tizen"},n=f.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/qupzilla/i],describe(e){const t={name:"QupZilla"},n=f.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/librewolf/i],describe(e){const t={name:"LibreWolf"},n=f.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:"Firefox"},n=f.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/electron/i],describe(e){const t={name:"Electron"},n=f.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(e){const t={name:"Sogou Browser"},n=f.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,e),i=f.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),o=f.getFirstMatch(/se ([\d.]+)x/i,e),r=n||i||o;return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:"Miui"},n=f.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test(e){return e.hasBrand("DuckDuckGo")?true:e.test(/\sDdg\/[\d.]+$/i)},describe(e,t){const n={name:"DuckDuckGo"};if(t){const o=t.getBrandVersion("DuckDuckGo");if(o)return n.version=o,n}const i=f.getFirstMatch(/\sDdg\/([\d.]+)$/i,e);return i&&(n.version=i),n}},{test(e){return e.hasBrand("Brave")},describe(e,t){const n={name:"Brave"};if(t){const i=t.getBrandVersion("Brave");if(i)return n.version=i,n}return n}},{test:[/chromium/i],describe(e){const t={name:"Chromium"},n=f.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:"Chrome"},n=f.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/GSA/i],describe(e){const t={name:"Google Search"},n=f.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test(e){const t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe(e){const t={name:"Android Browser"},n=f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/playstation 4/i],describe(e){const t={name:"PlayStation 4"},n=f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:"Safari"},n=f.getFirstMatch(P,e);return n&&(t.version=n),t}},{test:[/.*/i],describe(e){const t=/^(.*)\/(.*) /,n=/^(.*)\/(.*)[ \t]\((.*)/,o=e.search("\\(")!==-1?n:t;return {name:f.getFirstMatch(o,e),version:f.getSecondMatch(o,e)}}}],kp=[{test:[/Roku\/DVP/],describe(e){const t=f.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return {name:J.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=f.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return {name:J.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=f.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),n=f.getWindowsVersionName(t);return {name:J.Windows,version:t,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(e){const t={name:J.iOS},n=f.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return n&&(t.version=n),t}},{test:[/macintosh/i],describe(e){const t=f.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),n=f.getMacOSVersionName(t),i={name:J.MacOS,version:t};return n&&(i.versionName=n),i}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=f.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return {name:J.iOS,version:t}}},{test:[/OpenHarmony/i],describe(e){const t=f.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,e);return {name:J.HarmonyOS,version:t}}},{test(e){const t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe(e){const t=f.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),n=f.getAndroidVersionName(t),i={name:J.Android,version:t};return n&&(i.versionName=n),i}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=f.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),n={name:J.WebOS};return t&&t.length&&(n.version=t),n}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t=f.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||f.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||f.getFirstMatch(/\bbb(\d+)/i,e);return {name:J.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=f.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return {name:J.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=f.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return {name:J.Tizen,version:t}}},{test:[/linux/i],describe(){return {name:J.Linux}}},{test:[/CrOS/],describe(){return {name:J.ChromeOS}}},{test:[/PlayStation 4/],describe(e){const t=f.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return {name:J.PlayStation4,version:t}}}],xp=[{test:[/googlebot/i],describe(){return {type:L.bot,vendor:"Google"}}},{test:[/linespider/i],describe(){return {type:L.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe(){return {type:L.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe(){return {type:L.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe(){return {type:L.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe(){return {type:L.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe(){return {type:L.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe(){return {type:L.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe(){return {type:L.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(){return {type:L.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe(){return {type:L.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe(){return {type:L.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe(){return {type:L.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe(){return {type:L.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe(){return {type:L.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe(){return {type:L.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe(){return {type:L.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe(){return {type:L.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe(){return {type:L.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe(){return {type:L.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return {type:L.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(){return {type:L.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe(){return {type:L.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return {type:L.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe(){return {type:L.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe(e){const t=f.getFirstMatch(/(can-l01)/i,e)&&"Nova",n={type:L.mobile,vendor:"Huawei"};return t&&(n.model=t),n}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return {type:L.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return {type:L.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return {type:L.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return {type:L.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return {type:L.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return {type:L.tablet}}},{test(e){const t=e.test(/ipod|iphone/i),n=e.test(/like (ipod|iphone)/i);return t&&!n},describe(e){const t=f.getFirstMatch(/(ipod|iphone)/i,e);return {type:L.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return {type:L.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe(e){const t=f.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,e),n={type:L.mobile,vendor:"Nokia"};return t&&(n.model=t),n}},{test:[/[^-]mobi/i],describe(){return {type:L.mobile}}},{test(e){return e.getBrowserName(true)==="blackberry"},describe(){return {type:L.mobile,vendor:"BlackBerry"}}},{test(e){return e.getBrowserName(true)==="bada"},describe(){return {type:L.mobile}}},{test(e){return e.getBrowserName()==="windows phone"},describe(){return {type:L.mobile,vendor:"Microsoft"}}},{test(e){const t=Number(String(e.getOSVersion()).split(".")[0]);return e.getOSName(true)==="android"&&t>=3},describe(){return {type:L.tablet}}},{test(e){return e.getOSName(true)==="android"},describe(){return {type:L.mobile}}},{test:[/smart-?tv|smarttv/i],describe(){return {type:L.tv}}},{test:[/netcast/i],describe(){return {type:L.tv}}},{test(e){return e.getOSName(true)==="macos"},describe(){return {type:L.desktop,vendor:"Apple"}}},{test(e){return e.getOSName(true)==="windows"},describe(){return {type:L.desktop}}},{test(e){return e.getOSName(true)==="linux"},describe(){return {type:L.desktop}}},{test(e){return e.getOSName(true)==="playstation 4"},describe(){return {type:L.tv}}},{test(e){return e.getOSName(true)==="roku"},describe(){return {type:L.tv}}}],Sp=[{test(e){return e.getBrowserName(true)==="microsoft edge"},describe(e){if(/\sedg\//i.test(e))return {name:pt.Blink};const n=f.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return {name:pt.EdgeHTML,version:n}}},{test:[/trident/i],describe(e){const t={name:pt.Trident},n=f.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test(e){return e.test(/presto/i)},describe(e){const t={name:pt.Presto},n=f.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test(e){const t=e.test(/gecko/i),n=e.test(/like gecko/i);return t&&!n},describe(e){const t={name:pt.Gecko},n=f.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return {name:pt.Blink}}},{test:[/(apple)?webkit/i],describe(e){const t={name:pt.WebKit},n=f.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}}];class yo{constructor(t,n=false,i=null){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t;let o=false;typeof n=="boolean"?(o=n,this._hints=i):n!=null&&typeof n=="object"?this._hints=n:this._hints=null,this.parsedResult={},o!==true&&this.parse();}getHints(){return this._hints}hasBrand(t){if(!this._hints||!Array.isArray(this._hints.brands))return false;const n=t.toLowerCase();return this._hints.brands.some(i=>i.brand&&i.brand.toLowerCase()===n)}getBrandVersion(t){if(!this._hints||!Array.isArray(this._hints.brands))return;const n=t.toLowerCase(),i=this._hints.brands.find(o=>o.brand&&o.brand.toLowerCase()===n);return i?i.version:void 0}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=f.find(wp,n=>{if(typeof n.test=="function")return n.test(this);if(Array.isArray(n.test))return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const t=f.find(kp,n=>{if(typeof n.test=="function")return n.test(this);if(Array.isArray(n.test))return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:n}=this.getOS();return t?String(n).toLowerCase()||"":n||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=false){const{type:n}=this.getPlatform();return t?String(n).toLowerCase()||"":n||""}parsePlatform(){this.parsedResult.platform={};const t=f.find(xp,n=>{if(typeof n.test=="function")return n.test(this);if(Array.isArray(n.test))return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=f.find(Sp,n=>{if(typeof n.test=="function")return n.test(this);if(Array.isArray(n.test))return n.test.some(i=>this.test(i));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return f.assign({},this.parsedResult)}satisfies(t){const n={};let i=0;const o={};let r=0;if(Object.keys(t).forEach(a=>{const l=t[a];typeof l=="string"?(o[a]=l,r+=1):typeof l=="object"&&(n[a]=l,i+=1);}),i>0){const a=Object.keys(n),l=f.find(a,d=>this.isOS(d));if(l){const d=this.satisfies(n[l]);if(d!==void 0)return d}const c=f.find(a,d=>this.isPlatform(d));if(c){const d=this.satisfies(n[c]);if(d!==void 0)return d}}if(r>0){const a=Object.keys(o),l=f.find(a,c=>this.isBrowser(c,true));if(l!==void 0)return this.compareVersion(o[l])}}isBrowser(t,n=false){const i=this.getBrowserName().toLowerCase();let o=t.toLowerCase();const r=f.getBrowserTypeByAlias(o);return n&&r&&(o=r.toLowerCase()),o===i}compareVersion(t){let n=[0],i=t,o=false;const r=this.getBrowserVersion();if(typeof r=="string")return t[0]===">"||t[0]==="<"?(i=t.substr(1),t[1]==="="?(o=true,i=t.substr(2)):n=[],t[0]===">"?n.push(1):n.push(-1)):t[0]==="="?i=t.substr(1):t[0]==="~"&&(o=true,i=t.substr(1)),n.indexOf(f.compareVersions(r,i,o))>-1}isOS(t){return this.getOSName(true)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(true)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(true)===String(t).toLowerCase()}is(t,n=false){return this.isBrowser(t,n)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(n=>this.is(n))}}class Tp{static getParser(t,n=false,i=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new yo(t,n,i)}static parse(t,n=null){return new yo(t,n).getResult()}static get BROWSER_MAP(){return is}static get ENGINE_MAP(){return pt}static get OS_MAP(){return J}static get PLATFORMS_MAP(){return L}}const ye=Tp.getParser(globalThis.navigator.userAgent).getResult(),Qt="unknown",wo=(...e)=>e.filter(Boolean).join(" ").trim()||Qt;function os(){const e=wo(ye.os?.name,ye.os?.version),t=wo(ye.browser?.name,ye.browser?.version),n=(()=>{const s=GM_info?.scriptHandler,a=GM_info?.version;return s&&a?`${s} v${a}`:s||a||Qt})(),i=GM_info?.script?.version??Qt,o=GM_info?.script?.name??Qt,r=globalThis?.location?.href??Qt;return {os:e,browser:t,loader:n,scriptVersion:i,scriptName:o,url:r}}class Ap{container;accountWrapper;buttons;usernameEl;avatarEl;avatarImg;actionButton;refreshButton;tokenButton;onClick=new B;onRefresh=new B;onClickSecret=new B;events={click:this.onClick,"click:secret":this.onClickSecret,refresh:this.onRefresh};_loggedIn;_username;_avatarId;constructor({loggedIn:t=false,username:n="unnamed",avatarId:i="0/0-0"}={}){this._loggedIn=t,this._username=n,this._avatarId=i;const o=this.createElements();this.container=o.container,this.accountWrapper=o.accountWrapper,this.buttons=o.buttons,this.usernameEl=o.usernameEl,this.avatarEl=o.avatarEl,this.avatarImg=o.avatarImg,this.actionButton=o.actionButton,this.refreshButton=o.refreshButton,this.tokenButton=o.tokenButton;}createElements(){const t=w.createEl("vot-block",["vot-account"]),n=w.createEl("vot-block",["vot-account-wrapper"]);n.hidden=!this._loggedIn;const i=w.createEl("img",["vot-account-avatar-img"]);i.src=`${Bi}/${this._avatarId}/islands-retina-middle`,i.loading="lazy",i.alt="user avatar";const o=w.createEl("vot-block",["vot-account-avatar"],i),r=w.createEl("vot-block",["vot-account-username"]);r.textContent=this._username,n.append(o,r);const s=w.createEl("vot-block",["vot-account-buttons"]),a=w.createOutlinedButton(this.buttonText);a.addEventListener("click",()=>{this.onClick.dispatch();});const l=w.createIconButton(hp,{ariaLabel:p.get("VOTLoginViaToken")});l.hidden=this._loggedIn,l.addEventListener("click",()=>{this.onClickSecret.dispatch();});const c=w.createIconButton(up,{ariaLabel:p.get("VOTRefresh")});return c.addEventListener("click",()=>{this.onRefresh.dispatch();}),s.append(a,l,c),t.append(n,s),{container:t,accountWrapper:n,buttons:s,usernameEl:r,avatarImg:i,avatarEl:o,actionButton:a,refreshButton:c,tokenButton:l}}addEventListener(t,n){return kt(this.events,t,n),this}removeEventListener(t,n){return xt(this.events,t,n),this}get buttonText(){return this._loggedIn?p.get("VOTLogout"):p.get("VOTLogin")}get loggedIn(){return this._loggedIn}set loggedIn(t){this._loggedIn=t,this.accountWrapper.hidden=!this._loggedIn,this.actionButton.textContent=this.buttonText,this.tokenButton.hidden=this._loggedIn;}get avatarId(){return this._avatarId}set avatarId(t){this._avatarId=t??"0/0-0",this.avatarImg.src=`${Bi}/${this._avatarId}/islands-retina-middle`;}get username(){return this._username}set username(t){this._username=t??"unnamed",this.usernameEl.textContent=this._username;}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}}class W{container;input;label;onChange=new B;events={change:this.onChange};_labelHtml;_checked;_isSubCheckbox;constructor({labelHtml:t,checked:n=false,isSubCheckbox:i=false}){this._labelHtml=t,this._checked=n,this._isSubCheckbox=i;const o=this.createElements();this.container=o.container,this.input=o.input,this.label=o.label;}createElements(){const t=w.createEl("label",["vot-checkbox"]);this._isSubCheckbox&&t.classList.add("vot-checkbox-sub");const n=document.createElement("input");n.type="checkbox",n.checked=this._checked,n.addEventListener("change",()=>{this._checked=n.checked,this.onChange.dispatch(this._checked);});const i=w.createEl("span");return Q(this._labelHtml,i),t.append(n,i),{container:t,input:n,label:i}}addEventListener(t,n){return kt(this.events,"change",n),this}removeEventListener(t,n){return xt(this.events,"change",n),this}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}get disabled(){return this.input.disabled}set disabled(t){this.input.disabled=t;}get checked(){return this._checked}set checked(t){this._checked!==t&&(this._checked=this.input.checked=t,this.onChange.dispatch(this._checked));}}class Lp{container;header;arrowIcon;onClick=new B;events={click:this.onClick};_titleHtml;constructor({titleHtml:t}){this._titleHtml=t;const n=this.createElements();this.container=n.container,this.header=n.header,this.arrowIcon=n.arrowIcon;}createElements(){const t=w.createEl("vot-block",["vot-details"]);w.makeButtonLike(t);const n=w.createEl("vot-block");n.append(this._titleHtml);const i=w.createEl("vot-block",["vot-details-arrow-icon"]);return Q(ns,i),t.append(n,i),t.addEventListener("click",()=>{this.onClick.dispatch();}),{container:t,header:n,arrowIcon:i}}addEventListener(t,n){return kt(this.events,"click",n),this}removeEventListener(t,n){return xt(this.events,"click",n),this}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}}class ko{container;button;onChange=new B;events={change:this.onChange};_labelHtml;_key;pressedKeys;comboKeys;recording=false;constructor({labelHtml:t,key:n=null}){this._labelHtml=t,this._key=n,this.pressedKeys=new Set,this.comboKeys=new Set;const i=this.createElements();this.container=i.container,this.button=i.button;}stopRecordingKeys(){this.recording=false,document.removeEventListener("keydown",this.keydownHandle),document.removeEventListener("keyup",this.keyupOrBlurHandle),globalThis.removeEventListener("blur",this.blurHandle),delete this.button.dataset.status,this.pressedKeys.clear(),this.comboKeys.clear();}keydownHandle=t=>{if(!(!this.recording||t.repeat)){if(t.preventDefault(),t.code==="Escape"){this.key=null,this.button.textContent=this.keyText,this.stopRecordingKeys();return}this.pressedKeys.add(t.code),this.comboKeys.add(t.code),this.button.textContent=we(this.pressedKeys);}};keyupOrBlurHandle=t=>{this.recording&&(t&&(this.pressedKeys.delete(t.code),this.button.textContent=this.pressedKeys.size?we(this.pressedKeys):we(this.comboKeys),this.pressedKeys.size)||(this.key=this.comboKeys.size?rs(this.comboKeys):null,this.stopRecordingKeys()));};blurHandle=()=>{this.keyupOrBlurHandle();};createElements(){const t=w.createEl("vot-block",["vot-hotkey"]),n=w.createEl("vot-block",["vot-hotkey-label"]);n.textContent=this._labelHtml;const i=w.createEl("vot-block",["vot-hotkey-button"]);return w.makeButtonLike(i),i.textContent=this.keyText,i.addEventListener("click",()=>{if(this.recording){this.stopRecordingKeys(),this.button.textContent=this.keyText;return}i.dataset.status="active",this.recording=true,this.pressedKeys.clear(),this.comboKeys.clear(),this.button.textContent=p.get("PressTheKeyCombination"),document.addEventListener("keydown",this.keydownHandle),document.addEventListener("keyup",this.keyupOrBlurHandle),globalThis.addEventListener("blur",this.blurHandle);}),t.append(n,i),{container:t,button:i,label:n}}addEventListener(t,n){return kt(this.events,"change",n),this}removeEventListener(t,n){return xt(this.events,"change",n),this}set hidden(t){et(this.container,t);}get hidden(){return rt(this.container)}get key(){return this._key}get keyText(){return this._key?we(this._key):p.get("None")}set key(t){this._key!==t&&(this._key=t,this.button.textContent=this.keyText,this.onChange.dispatch(this._key));}}function rs(e){return (Array.isArray(e)?e:Array.from(e)).map(n=>n.replace("Key","").replace("Digit","")).join("+")}function we(e){let t;typeof e=="string"?t=e.split("+").filter(Boolean):Array.isArray(e)?t=e:t=Array.from(e);const n=o=>{switch(o){case "ControlLeft":case "ControlRight":case "Control":return "Ctrl";case "ShiftLeft":case "ShiftRight":case "Shift":return "Shift";case "AltLeft":case "AltRight":case "Alt":return "Alt";case "MetaLeft":case "MetaRight":case "Meta":return "Meta";case "Space":return "Space";case "ArrowUp":return "↑";case "ArrowDown":return "↓";case "ArrowLeft":return "←";case "ArrowRight":return "→";default:return o.replace("Key","").replace("Digit","")}},i=o=>{const r=n(o);return r==="Ctrl"?0:r==="Alt"?1:r==="Shift"?2:r==="Meta"?3:10};return t.slice().sort((o,r)=>i(o)-i(r)).map(n).join("+")}const Ip=["click:bugReport","click:resetSettings","update:account","change:autoTranslate","change:autoSubtitles","change:showVideoVolume","change:audioBooster","change:syncVolume","change:useLivelyVoice","change:subtitlesHighlightWords","change:subtitlesSmartLayout","change:proxyWorkerHost","change:useNewAudioPlayer","change:onlyBypassMediaCSP","change:showPiPButton","input:subtitlesMaxLength","input:subtitlesFontSize","input:subtitlesBackgroundOpacity","input:autoHideButtonDelay","select:proxyTranslationStatus","select:translationTextService","select:buttonPosition","select:menuLanguage"];function Pp(){const e={};for(const t of Ip)e[t]=new B;return e}class Wn{static PERSIST_DELAY_MS=250;globalPortal;initialized=false;data;videoHandler;suppressSubtitlesSmartLayoutCheckboxChange=false;events=Pp();persistTimerIds={};dialog;accountButton;accountButtonRefreshTooltip;accountButtonTokenTooltip;autoTranslateCheckbox;autoSubtitlesCheckbox;dontTranslateLanguagesCheckbox;dontTranslateLanguagesSelect;autoSetVolumeSliderLabel;autoSetVolumeCheckbox;smartDuckingCheckbox;autoSetVolumeSlider;showVideoVolumeSliderCheckbox;audioBoosterCheckbox;audioBoosterTooltip;syncVolumeCheckbox;downloadWithNameCheckbox;sendNotifyOnCompleteCheckbox;useLivelyVoiceCheckbox;useLivelyVoiceTooltip;useAudioDownloadCheckbox;useAudioDownloadCheckboxLabel;useAudioDownloadCheckboxTooltip;subtitlesDownloadFormatSelectLabel;subtitlesDownloadFormatSelect;subtitlesHighlightWordsCheckbox;subtitlesSmartLayoutCheckbox;subtitlesMaxLengthSliderLabel;subtitlesMaxLengthSlider;subtitlesFontSizeSliderLabel;subtitlesFontSizeSlider;subtitlesBackgroundOpacitySliderLabel;subtitlesBackgroundOpacitySlider;translateHotkeyButton;subtitlesHotkeyButton;proxyWorkerHostTextfield;proxyTranslationStatusSelectLabel;proxyTranslationStatusSelectTooltip;proxyTranslationStatusSelect;translateAPIErrorsCheckbox;useNewAudioPlayerCheckbox;useNewAudioPlayerTooltip;onlyBypassMediaCSPCheckbox;onlyBypassMediaCSPTooltip;translationTextServiceLabel;translationTextServiceSelect;translationTextServiceTooltip;detectServiceLabel;detectServiceSelect;showPiPButtonCheckbox;autoHideButtonDelaySliderLabel;autoHideButtonDelaySlider;buttonPositionSelectLabel;buttonPositionSelect;buttonPositionTooltip;menuLanguageSelectLabel;menuLanguageSelect;bugReportButton;resetSettingsButton;constructor({globalPortal:t,data:n={},videoHandler:i}){this.globalPortal=t,this.data=n,this.videoHandler=i;}isInitialized(){return this.initialized}createAccordionSection(t,n={}){const i=w.createEl("vot-block",["vot-settings-section"]),o=new Lp({titleHtml:t});o.container.classList.add("vot-settings-section-header");const r=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,s=`vot-settings-section-header-${r}`,a=`vot-settings-section-content-${r}`;o.container.id=s;const l=w.createEl("vot-block",["vot-settings-section-content"]);l.id=a,l.setAttribute("role","region"),l.setAttribute("aria-labelledby",s),o.container.setAttribute("aria-controls",a);const c=u=>{o.container.dataset.open=u?"true":"false",o.container.setAttribute("aria-expanded",u?"true":"false"),l.hidden=!u;},d=()=>o.container.dataset.open==="true";return c(!!n.open),o.addEventListener("click",()=>{const u=o.container.dataset.open==="true";c(!u);}),i.append(o.container,l),{title:t,container:i,header:o.container,content:l,setOpen:c,getOpen:d}}setSubtitlesSmartLayout(t){this.data.subtitlesSmartLayout=t,I.set("subtitlesSmartLayout",t),this.subtitlesSmartLayoutCheckbox?.checked!==t&&(this.suppressSubtitlesSmartLayoutCheckboxChange=true,this.subtitlesSmartLayoutCheckbox.checked=t,this.suppressSubtitlesSmartLayoutCheckboxChange=false),this.events["change:subtitlesSmartLayout"].dispatch(t);}scheduleStoragePersist(t,n){const i=this.persistTimerIds[t];i!==void 0&&globalThis.clearTimeout(i),this.persistTimerIds[t]=globalThis.setTimeout(()=>{this.persistTimerIds[t]=void 0,I.set(t,n);},Wn.PERSIST_DELAY_MS);}flushStoragePersists(){for(const t of Object.keys(this.persistTimerIds)){const n=this.persistTimerIds[t];if(n===void 0)continue;globalThis.clearTimeout(n),this.persistTimerIds[t]=void 0;const i=this.data[t];typeof i=="number"&&I.set(t,i);}}bindPersistedSetting({control:t,event:n,apply:i,storageKey:o,readPersistedValue:r,logLabel:s,dispatch:a,afterPersist:l}){t.addEventListener(n,async c=>{i(c),await I.set(o,r()),l&&await l(c),a?.(c);});}initUI(){if(this.isInitialized())throw new Error("[VOT] SettingsView is already initialized");this.dialog=new kn({titleHtml:p.get("VOTSettings")}),this.globalPortal.appendChild(this.dialog.container);const t=this.createAccordionSection(p.get("VOTMyAccount"),{open:true}),n=this.createAccordionSection(p.get("translationSettings"),{open:true}),i=this.createAccordionSection(p.get("subtitlesSettings")),o=this.createAccordionSection(p.get("hotkeysSettings")),r=this.createAccordionSection(p.get("proxySettings")),s=this.createAccordionSection(p.get("miscSettings")),a=this.createAccordionSection(p.get("appearance")),l=this.createAccordionSection(p.get("aboutExtension")),c=[t,n,i,o,r,s,a,l];this.dialog.bodyContainer.append(...c.map(R=>R.container)),this.accountButton=new Ap({avatarId:this.data.account?.avatarId,username:this.data.account?.username,loggedIn:!!this.data.account?.token}),I.isSupportOnlyLS?(this.accountButton.refreshButton.setAttribute("disabled","true"),this.accountButton.actionButton.setAttribute("disabled","true")):this.accountButtonRefreshTooltip=new G({target:this.accountButton.refreshButton,content:p.get("VOTRefresh"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal}),this.accountButtonTokenTooltip=new G({target:this.accountButton.tokenButton,content:p.get("VOTLoginViaToken"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal}),this.autoTranslateCheckbox=new W({labelHtml:p.get("VOTAutoTranslate"),checked:this.data.autoTranslate}),this.autoSubtitlesCheckbox=new W({labelHtml:p.get("VOTAutoSubtitles"),checked:this.data.autoSubtitles});const d=this.data.dontTranslateLanguages??[];this.dontTranslateLanguagesCheckbox=new W({labelHtml:p.get("DontTranslateSelectedLanguages"),checked:this.data.enabledDontTranslateLanguages}),this.dontTranslateLanguagesSelect=new j({dialogParent:this.globalPortal,dialogTitle:p.get("DontTranslateSelectedLanguages"),selectTitle:d.map(R=>p.get(`langs.${R}`)).join(", ")||p.get("DontTranslateSelectedLanguages"),items:j.genLanguageItems(_t).map(R=>({...R,selected:d.includes(R.value)})),multiSelect:true,labelElement:this.dontTranslateLanguagesCheckbox.container}),this.dontTranslateLanguagesSelect.disabled=!this.dontTranslateLanguagesCheckbox.checked;const u=this.data.autoVolume??Fe;this.autoSetVolumeSliderLabel=new Pt({labelText:p.get("VOTAutoSetVolume"),value:u}),this.autoSetVolumeCheckbox=new W({labelHtml:this.autoSetVolumeSliderLabel.container,checked:this.data.enabledAutoVolume??true}),this.autoSetVolumeSlider=new It({labelHtml:this.autoSetVolumeCheckbox.container,value:u,min:0});const h=!!this.data.syncVolume;this.autoSetVolumeSlider.disabled=!this.autoSetVolumeCheckbox.checked,this.smartDuckingCheckbox=new W({labelHtml:p.get("smartDucking"),checked:this.data.enabledSmartDucking??true}),this.smartDuckingCheckbox.disabled=h||!this.autoSetVolumeCheckbox.checked,this.showVideoVolumeSliderCheckbox=new W({labelHtml:p.get("showVideoVolumeSlider"),checked:this.data.showVideoSlider}),this.audioBoosterCheckbox=new W({labelHtml:p.get("VOTAudioBooster"),checked:this.data.audioBooster}),this.videoHandler?.isAudioContextSupported||(this.audioBoosterCheckbox.disabled=true,this.audioBoosterTooltip=new G({target:this.audioBoosterCheckbox.container,content:p.get("VOTNeedWebAudioAPI"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal})),this.syncVolumeCheckbox=new W({labelHtml:p.get("VOTSyncVolume"),checked:this.data.syncVolume}),this.downloadWithNameCheckbox=new W({labelHtml:p.get("VOTDownloadWithName"),checked:this.data.downloadWithName}),this.downloadWithNameCheckbox.disabled=!Ar,this.sendNotifyOnCompleteCheckbox=new W({labelHtml:p.get("VOTSendNotifyOnComplete"),checked:this.data.sendNotifyOnComplete}),this.useLivelyVoiceCheckbox=new W({labelHtml:p.get("VOTUseLivelyVoice"),checked:this.data.useLivelyVoice}),this.useLivelyVoiceTooltip=new G({target:this.useLivelyVoiceCheckbox.container,content:p.get("VOTAccountRequired"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal,hidden:!!this.data.account?.token}),this.data.account?.token||(this.useLivelyVoiceCheckbox.disabled=true),this.useAudioDownloadCheckboxLabel=new ft({labelText:p.get("VOTUseAudioDownload"),icon:vo}),this.useAudioDownloadCheckbox=new W({labelHtml:this.useAudioDownloadCheckboxLabel.container,checked:this.data.useAudioDownload}),!Tr&&!(typeof IS_EXTENSION<"u"&&IS_EXTENSION)&&(this.useAudioDownloadCheckbox.disabled=true),this.useAudioDownloadCheckboxTooltip=new G({target:this.useAudioDownloadCheckboxLabel.container,content:p.get("VOTUseAudioDownloadWarning"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal}),t.content.append(this.accountButton.container),n.content.append(this.autoTranslateCheckbox.container,this.autoSubtitlesCheckbox.container,this.dontTranslateLanguagesSelect.container,this.autoSetVolumeSlider.container,this.smartDuckingCheckbox.container,this.showVideoVolumeSliderCheckbox.container,this.audioBoosterCheckbox.container,this.syncVolumeCheckbox.container,this.downloadWithNameCheckbox.container,this.sendNotifyOnCompleteCheckbox.container,this.useLivelyVoiceCheckbox.container,this.useAudioDownloadCheckbox.container),this.subtitlesDownloadFormatSelectLabel=new ft({labelText:p.get("VOTSubtitlesDownloadFormat")}),this.subtitlesDownloadFormatSelect=new j({selectTitle:this.data.subtitlesDownloadFormat??p.get("VOTSubtitlesDownloadFormat"),dialogTitle:p.get("VOTSubtitlesDownloadFormat"),dialogParent:this.globalPortal,labelElement:this.subtitlesDownloadFormatSelectLabel.container,items:Va.map(R=>({label:R.toUpperCase(),value:R,selected:R===this.data.subtitlesDownloadFormat}))}),this.subtitlesHighlightWordsCheckbox=new W({labelHtml:p.get("VOTHighlightWords"),checked:this.data.highlightWords});const m=this.data.subtitlesSmartLayout??true;this.subtitlesSmartLayoutCheckbox=new W({labelHtml:p.get("subtitlesSmartLayout"),checked:m});const v=this.data.subtitlesMaxLength??300;this.subtitlesMaxLengthSliderLabel=new Pt({labelText:p.get("VOTSubtitlesMaxLength"),labelEOL:":",value:v,symbol:""}),this.subtitlesMaxLengthSlider=new It({labelHtml:this.subtitlesMaxLengthSliderLabel.container,value:v,min:50,max:300});const b=this.data.subtitlesFontSize??20;this.subtitlesFontSizeSliderLabel=new Pt({labelText:p.get("VOTSubtitlesFontSize"),labelEOL:":",value:b,symbol:"px"}),this.subtitlesFontSizeSlider=new It({labelHtml:this.subtitlesFontSizeSliderLabel.container,value:b,min:8,max:50});const y=this.data.subtitlesOpacity??20;this.subtitlesBackgroundOpacitySliderLabel=new Pt({labelText:p.get("VOTSubtitlesOpacity"),labelEOL:":",value:y,symbol:"%"}),this.subtitlesBackgroundOpacitySlider=new It({labelHtml:this.subtitlesBackgroundOpacitySliderLabel.container,value:y,min:0,max:100}),i.content.append(this.subtitlesDownloadFormatSelect.container,this.subtitlesHighlightWordsCheckbox.container,this.subtitlesSmartLayoutCheckbox.container,this.subtitlesMaxLengthSlider.container,this.subtitlesFontSizeSlider.container,this.subtitlesBackgroundOpacitySlider.container),this.translateHotkeyButton=new ko({labelHtml:p.get("translateVideo"),key:this.data.translationHotkey}),this.subtitlesHotkeyButton=new ko({labelHtml:p.get("VOTSubtitles"),key:this.data.subtitlesHotkey}),o.content.append(this.translateHotkeyButton.container,this.subtitlesHotkeyButton.container),this.proxyWorkerHostTextfield=new xn({labelHtml:p.get("VOTProxyWorkerHost"),value:this.data.proxyWorkerHost,placeholder:ie});const k=[p.get("VOTTranslateProxyDisabled"),p.get("VOTTranslateProxyEnabled"),p.get("VOTTranslateProxyEverything")],x=this.data.translateProxyEnabled??0,A=Jt&&kr.includes(Jt);this.proxyTranslationStatusSelectLabel=new ft({icon:A?vo:void 0,labelText:p.get("VOTTranslateProxyStatus")}),A&&(this.proxyTranslationStatusSelectTooltip=new G({target:this.proxyTranslationStatusSelectLabel.icon,content:p.get("VOTTranslateProxyStatusDefault"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal})),this.proxyTranslationStatusSelect=new j({selectTitle:k[x],dialogTitle:p.get("VOTTranslateProxyStatus"),dialogParent:this.globalPortal,labelElement:this.proxyTranslationStatusSelectLabel.container,items:k.map((R,Ue)=>({label:R,value:Ue.toString(),selected:Ue===x,disabled:Ue===0&&Sr}))}),r.content.append(this.proxyWorkerHostTextfield.container,this.proxyTranslationStatusSelect.container),this.translateAPIErrorsCheckbox=new W({labelHtml:p.get("VOTTranslateAPIErrors"),checked:this.data.translateAPIErrors??true}),this.translateAPIErrorsCheckbox.hidden=p.lang==="ru",this.useNewAudioPlayerCheckbox=new W({labelHtml:p.get("VOTNewAudioPlayer"),checked:this.data.newAudioPlayer}),this.videoHandler?.isAudioContextSupported||(this.useNewAudioPlayerCheckbox.disabled=true,this.useNewAudioPlayerTooltip=new G({target:this.useNewAudioPlayerCheckbox.container,content:p.get("VOTNeedWebAudioAPI"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal}));const D=this.videoHandler?.site.needBypassCSP?`${p.get("VOTOnlyBypassMediaCSP")} (${p.get("VOTMediaCSPEnabledOnSite")})`:p.get("VOTOnlyBypassMediaCSP");this.onlyBypassMediaCSPCheckbox=new W({labelHtml:D,checked:this.data.onlyBypassMediaCSP,isSubCheckbox:true}),this.videoHandler?.isAudioContextSupported||(this.onlyBypassMediaCSPTooltip=new G({target:this.onlyBypassMediaCSPCheckbox.container,content:p.get("VOTNeedWebAudioAPI"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal})),this.onlyBypassMediaCSPCheckbox.disabled=!this.data.newAudioPlayer&&!!this.videoHandler?.isAudioContextSupported,this.data.newAudioPlayer||(this.onlyBypassMediaCSPCheckbox.hidden=true),this.translationTextServiceLabel=new ft({labelText:p.get("VOTTranslationTextService"),icon:bo});const Y=this.data.translationService??He;this.translationTextServiceSelect=new j({selectTitle:p.get(`services.${Y}`),dialogTitle:p.get("VOTTranslationTextService"),dialogParent:this.globalPortal,labelElement:this.translationTextServiceLabel.container,items:Rr.map(R=>({label:p.get(`services.${R}`),value:R,selected:R===Y}))}),this.translationTextServiceTooltip=new G({target:this.translationTextServiceLabel.icon,content:p.get("VOTNotAffectToVoice"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal}),this.detectServiceLabel=new ft({labelText:p.get("VOTDetectService")});const $=this.data.detectService??Dn;this.detectServiceSelect=new j({selectTitle:p.get(`services.${$}`),dialogTitle:p.get("VOTDetectService"),dialogParent:this.globalPortal,labelElement:this.detectServiceLabel.container,items:Kh.map(R=>({label:p.get(`services.${R}`),value:R,selected:R===$}))}),this.showPiPButtonCheckbox=new W({labelHtml:p.get("VOTShowPiPButton"),checked:this.data.showPiPButton}),this.showPiPButtonCheckbox.hidden=!xr();const St=Math.round((this.data.autoHideButtonDelay??Bn)/1e3*10)/10;this.autoHideButtonDelaySliderLabel=new Pt({labelText:p.get("autoHideButtonDelay"),labelEOL:":",value:St,symbol:` ${p.get("secs")}`}),this.autoHideButtonDelaySlider=new It({labelHtml:this.autoHideButtonDelaySliderLabel.container,value:St,min:.1,max:3,step:.1}),this.buttonPositionSelectLabel=new ft({labelText:p.get("buttonPosition"),icon:bo});const Ot=this.data.buttonPos??"default";this.buttonPositionSelect=new j({selectTitle:p.get(`position.${Ot}`),dialogTitle:p.get("buttonPosition"),labelElement:this.buttonPositionSelectLabel.container,dialogParent:this.globalPortal,items:bp.map(R=>({label:p.get(`position.${R}`),value:R,selected:R===Ot}))}),this.buttonPositionTooltip=new G({target:this.buttonPositionSelectLabel.icon,content:p.get("minButtonPositionContainer"),position:"bottom",backgroundColor:"var(--vot-helper-ondialog)",parentElement:this.globalPortal}),this.menuLanguageSelectLabel=new ft({labelText:p.get("VOTMenuLanguage")}),this.menuLanguageSelect=new j({selectTitle:p.get(`langs.${p.langOverride}`),dialogTitle:p.get("VOTMenuLanguage"),labelElement:this.menuLanguageSelectLabel.container,dialogParent:this.globalPortal,items:j.genLanguageItems(p.getAvailableLangs(),p.langOverride)}),this.bugReportButton=w.createOutlinedButton(p.get("VOTBugReport")),this.resetSettingsButton=w.createButton(p.get("resetSettings")),s.content.append(this.translateAPIErrorsCheckbox.container,this.useNewAudioPlayerCheckbox.container,this.onlyBypassMediaCSPCheckbox.container),n.content.append(this.translationTextServiceSelect.container,this.detectServiceSelect.container),a.content.append(this.showPiPButtonCheckbox.container,this.autoHideButtonDelaySlider.container,this.buttonPositionSelect.container,this.menuLanguageSelect.container);const ge=os(),vs=w.createInformation(`${p.get("VOTVersion")}:`,ge.scriptVersion||GM_info.script.version||p.get("notFound")),bs=w.createInformation(`${p.get("VOTAuthors")}:`,GM_info.script.author||"Toil, SashaXser, MrSoczekXD, mynovelhost, sodapng"),ys=w.createInformation(`${p.get("VOTLoader")}:`,ge.loader),ws=w.createInformation(`${p.get("VOTBrowser")}:`,`${ge.browser} (${ge.os})`),ks=new Date((this.data.localeUpdatedAt??0)*1e3).toLocaleString(),xs=this.data.localeHash??p.get("notFound"),Ss=Zt`${xs}
(${p.get("VOTUpdatedAt")} ${ks})`,Ts=w.createInformation(`${p.get("VOTLocaleHash")}:`,Ss),Jn=w.createOutlinedButton(p.get("VOTUpdateLocaleFiles"));return Jn.addEventListener("click",async()=>{await I.set("localeHash",""),await p.update(true),globalThis.location.reload();}),l.content.append(vs.container,bs.container,ys.container,ws.container,Ts.container,Jn),this.dialog.footerContainer.append(this.bugReportButton,this.resetSettingsButton),this.initialized=true,this}initUIEvents(){if(!this.isInitialized())throw new Error("[VOT] SettingsView isn't initialized");return this.accountButton.addEventListener("click",async()=>{if(!I.isSupportOnlyLS){if(this.accountButton.loggedIn)return await I.delete("account"),this.data.account={},this.updateAccountInfo();globalThis.open(br,"_blank")?.focus();}}),this.accountButton.addEventListener("click:secret",async()=>{const t=new kn({titleHtml:p.get("VOTLoginViaToken"),isTemp:true});this.globalPortal.appendChild(t.container);const n=w.createEl("vot-block",void 0,p.get("VOTYandexTokenInfo")),i=new xn({labelHtml:p.get("VOTYandexToken"),value:this.data.account?.token});i.addEventListener("change",async o=>{this.data.account=o?{expires:Date.now()+3153418e4,token:o}:{},await I.set("account",this.data.account),this.updateAccountInfo();}),t.bodyContainer.append(n,i.container),t.open();}),this.accountButton.addEventListener("refresh",async()=>{I.isSupportOnlyLS||(this.data.account=await I.get("account",{}),this.updateAccountInfo());}),this.bindPersistedSetting({control:this.autoTranslateCheckbox,event:"change",apply:t=>{this.data.autoTranslate=t;},storageKey:"autoTranslate",readPersistedValue:()=>this.data.autoTranslate,logLabel:"autoTranslate",dispatch:t=>this.events["change:autoTranslate"].dispatch(t)}),this.bindPersistedSetting({control:this.autoSubtitlesCheckbox,event:"change",apply:t=>{this.data.autoSubtitles=t;},storageKey:"autoSubtitles",readPersistedValue:()=>this.data.autoSubtitles,logLabel:"autoSubtitles",dispatch:t=>this.events["change:autoSubtitles"].dispatch(t)}),this.dontTranslateLanguagesCheckbox.addEventListener("change",async t=>{this.data.enabledDontTranslateLanguages=t,this.dontTranslateLanguagesSelect.disabled=!t,await I.set("enabledDontTranslateLanguages",this.data.enabledDontTranslateLanguages);}),this.dontTranslateLanguagesSelect.addEventListener("selectItem",async t=>{this.data.dontTranslateLanguages=t,await I.set("dontTranslateLanguages",this.data.dontTranslateLanguages);}),this.bindPersistedSetting({control:this.autoSetVolumeCheckbox,event:"change",apply:t=>{this.data.enabledAutoVolume=t,this.autoSetVolumeSlider.disabled=!t,this.smartDuckingCheckbox.disabled=!t||!!this.syncVolumeCheckbox?.checked;},storageKey:"enabledAutoVolume",readPersistedValue:()=>this.data.enabledAutoVolume,logLabel:"enabledAutoVolume",afterPersist:async()=>this.videoHandler?.setupAudioSettings?.()}),this.bindPersistedSetting({control:this.smartDuckingCheckbox,event:"change",apply:t=>{this.data.enabledSmartDucking=t;},storageKey:"enabledSmartDucking",readPersistedValue:()=>this.data.enabledSmartDucking,logLabel:"enabledSmartDucking",afterPersist:async()=>this.videoHandler?.setupAudioSettings?.()}),this.bindPersistedSetting({control:this.autoSetVolumeSlider,event:"input",apply:t=>{this.data.autoVolume=this.autoSetVolumeSliderLabel.value=t;},storageKey:"autoVolume",readPersistedValue:()=>this.data.autoVolume,logLabel:"autoVolume"}),this.bindPersistedSetting({control:this.showVideoVolumeSliderCheckbox,event:"change",apply:t=>{this.data.showVideoSlider=t;},storageKey:"showVideoSlider",readPersistedValue:()=>this.data.showVideoSlider,logLabel:"showVideoVolumeSlider",dispatch:t=>this.events["change:showVideoVolume"].dispatch(t)}),this.bindPersistedSetting({control:this.audioBoosterCheckbox,event:"change",apply:t=>{this.data.audioBooster=t;},storageKey:"audioBooster",readPersistedValue:()=>this.data.audioBooster,logLabel:"audioBooster",dispatch:t=>this.events["change:audioBooster"].dispatch(t)}),this.bindPersistedSetting({control:this.syncVolumeCheckbox,event:"change",apply:t=>{this.data.syncVolume=t,this.autoSetVolumeSlider.disabled=!this.autoSetVolumeCheckbox?.checked,this.smartDuckingCheckbox.disabled=t||!this.autoSetVolumeCheckbox?.checked,t&&this.smartDuckingCheckbox?.checked&&(this.smartDuckingCheckbox.checked=false);},storageKey:"syncVolume",readPersistedValue:()=>this.data.syncVolume,logLabel:"syncVolume",dispatch:t=>this.events["change:syncVolume"].dispatch(t)}),this.bindPersistedSetting({control:this.downloadWithNameCheckbox,event:"change",apply:t=>{this.data.downloadWithName=t;},storageKey:"downloadWithName",readPersistedValue:()=>this.data.downloadWithName,logLabel:"downloadWithName"}),this.bindPersistedSetting({control:this.sendNotifyOnCompleteCheckbox,event:"change",apply:t=>{this.data.sendNotifyOnComplete=t;},storageKey:"sendNotifyOnComplete",readPersistedValue:()=>this.data.sendNotifyOnComplete,logLabel:"sendNotifyOnComplete"}),this.bindPersistedSetting({control:this.useLivelyVoiceCheckbox,event:"change",apply:t=>{this.data.useLivelyVoice=t;},storageKey:"useLivelyVoice",readPersistedValue:()=>this.data.useLivelyVoice,logLabel:"useLivelyVoice",dispatch:t=>this.events["change:useLivelyVoice"].dispatch(t)}),this.bindPersistedSetting({control:this.useAudioDownloadCheckbox,event:"change",apply:t=>{this.data.useAudioDownload=t;},storageKey:"useAudioDownload",readPersistedValue:()=>this.data.useAudioDownload,logLabel:"useAudioDownload"}),this.bindPersistedSetting({control:this.subtitlesDownloadFormatSelect,event:"selectItem",apply:t=>{this.data.subtitlesDownloadFormat=t;},storageKey:"subtitlesDownloadFormat",readPersistedValue:()=>this.data.subtitlesDownloadFormat,logLabel:"subtitlesDownloadFormat"}),this.bindPersistedSetting({control:this.subtitlesHighlightWordsCheckbox,event:"change",apply:t=>{this.data.highlightWords=t;},storageKey:"highlightWords",readPersistedValue:()=>this.data.highlightWords,logLabel:"highlightWords",dispatch:t=>this.events["change:subtitlesHighlightWords"].dispatch(t)}),this.subtitlesSmartLayoutCheckbox?.addEventListener("change",t=>{this.suppressSubtitlesSmartLayoutCheckboxChange||this.setSubtitlesSmartLayout(t);}),this.subtitlesMaxLengthSlider.addEventListener("input",t=>{this.subtitlesMaxLengthSliderLabel.value=t,(this.data.subtitlesSmartLayout??true)===true&&this.setSubtitlesSmartLayout(false),this.data.subtitlesMaxLength=t,this.scheduleStoragePersist("subtitlesMaxLength",this.data.subtitlesMaxLength),this.events["input:subtitlesMaxLength"].dispatch(t);}),this.subtitlesFontSizeSlider.addEventListener("input",t=>{this.subtitlesFontSizeSliderLabel.value=t,(this.data.subtitlesSmartLayout??true)===true&&this.setSubtitlesSmartLayout(false),this.data.subtitlesFontSize=t,this.scheduleStoragePersist("subtitlesFontSize",this.data.subtitlesFontSize),this.events["input:subtitlesFontSize"].dispatch(t);}),this.subtitlesBackgroundOpacitySlider.addEventListener("input",t=>{this.subtitlesBackgroundOpacitySliderLabel.value=t,this.data.subtitlesOpacity=t,this.scheduleStoragePersist("subtitlesOpacity",this.data.subtitlesOpacity),this.events["input:subtitlesBackgroundOpacity"].dispatch(t);}),this.bindPersistedSetting({control:this.translateHotkeyButton,event:"change",apply:t=>{this.data.translationHotkey=t;},storageKey:"translationHotkey",readPersistedValue:()=>this.data.translationHotkey,logLabel:"translationHotkey"}),this.bindPersistedSetting({control:this.subtitlesHotkeyButton,event:"change",apply:t=>{this.data.subtitlesHotkey=t;},storageKey:"subtitlesHotkey",readPersistedValue:()=>this.data.subtitlesHotkey,logLabel:"subtitlesHotkey"}),this.proxyWorkerHostTextfield.addEventListener("change",async t=>{this.data.proxyWorkerHost=t||ie,await I.set("proxyWorkerHost",this.data.proxyWorkerHost),E.log("proxyWorkerHost value changed. New value:",this.data.proxyWorkerHost),this.events["change:proxyWorkerHost"].dispatch(t);}),this.proxyTranslationStatusSelect.addEventListener("selectItem",async t=>{this.data.translateProxyEnabled=Number.parseInt(t,10),await I.set("translateProxyEnabled",this.data.translateProxyEnabled),await I.set("translateProxyEnabledDefault",false),E.log("translateProxyEnabled value changed. New value:",this.data.translateProxyEnabled),this.events["select:proxyTranslationStatus"].dispatch(t);}),this.bindPersistedSetting({control:this.translateAPIErrorsCheckbox,event:"change",apply:t=>{this.data.translateAPIErrors=t;},storageKey:"translateAPIErrors",readPersistedValue:()=>this.data.translateAPIErrors,logLabel:"translateAPIErrors"}),this.bindPersistedSetting({control:this.useNewAudioPlayerCheckbox,event:"change",apply:t=>{this.data.newAudioPlayer=t,this.onlyBypassMediaCSPCheckbox.disabled=this.onlyBypassMediaCSPCheckbox.hidden=!t;},storageKey:"newAudioPlayer",readPersistedValue:()=>this.data.newAudioPlayer,logLabel:"newAudioPlayer",dispatch:t=>this.events["change:useNewAudioPlayer"].dispatch(t)}),this.bindPersistedSetting({control:this.onlyBypassMediaCSPCheckbox,event:"change",apply:t=>{this.data.onlyBypassMediaCSP=t;},storageKey:"onlyBypassMediaCSP",readPersistedValue:()=>this.data.onlyBypassMediaCSP,logLabel:"onlyBypassMediaCSP",dispatch:t=>this.events["change:onlyBypassMediaCSP"].dispatch(t)}),this.bindPersistedSetting({control:this.translationTextServiceSelect,event:"selectItem",apply:t=>{this.data.translationService=t;},storageKey:"translationService",readPersistedValue:()=>this.data.translationService,logLabel:"translationService",dispatch:t=>this.events["select:translationTextService"].dispatch(t)}),this.bindPersistedSetting({control:this.detectServiceSelect,event:"selectItem",apply:t=>{this.data.detectService=t;},storageKey:"detectService",readPersistedValue:()=>this.data.detectService,logLabel:"detectService"}),this.bindPersistedSetting({control:this.showPiPButtonCheckbox,event:"change",apply:t=>{this.data.showPiPButton=t;},storageKey:"showPiPButton",readPersistedValue:()=>this.data.showPiPButton,logLabel:"showPiPButton",dispatch:t=>this.events["change:showPiPButton"].dispatch(t)}),this.autoHideButtonDelaySlider.addEventListener("input",t=>{this.autoHideButtonDelaySliderLabel.value=t;const n=Math.round(t*1e3);this.data.autoHideButtonDelay=n,this.scheduleStoragePersist("autoHideButtonDelay",this.data.autoHideButtonDelay),this.events["input:autoHideButtonDelay"].dispatch(t);}),this.bindPersistedSetting({control:this.buttonPositionSelect,event:"selectItem",apply:t=>{this.data.buttonPos=t;},storageKey:"buttonPos",readPersistedValue:()=>this.data.buttonPos,logLabel:"buttonPos",dispatch:t=>this.events["select:buttonPosition"].dispatch(t)}),this.menuLanguageSelect.addEventListener("selectItem",async t=>{await p.changeLang(t)&&(this.data.localeUpdatedAt=await I.get("localeUpdatedAt",0),this.events["select:menuLanguage"].dispatch(t));}),this.bugReportButton.addEventListener("click",()=>this.events["click:bugReport"].dispatch()),this.resetSettingsButton.addEventListener("click",()=>this.events["click:resetSettings"].dispatch()),this}addEventListener(t,n){return this.events[t].addListener(n),this}removeEventListener(t,n){return this.events[t].removeListener(n),this}doReleaseUI(){this.dialog?.remove();for(const t of [this.accountButtonRefreshTooltip,this.accountButtonTokenTooltip,this.audioBoosterTooltip,this.useLivelyVoiceTooltip,this.useAudioDownloadCheckboxTooltip,this.useNewAudioPlayerTooltip,this.onlyBypassMediaCSPTooltip,this.translationTextServiceTooltip,this.proxyTranslationStatusSelectTooltip,this.buttonPositionTooltip])t?.release();}doReleaseUIEvents(){this.flushStoragePersists();for(const t of Object.values(this.events))t.clear();}releaseUI(t=false){if(!this.isInitialized())throw new Error("[VOT] SettingsView isn't initialized");return this.doReleaseUI(),this.initialized=t,this}releaseUIEvents(t=false){if(!this.isInitialized())throw new Error("[VOT] SettingsView isn't initialized");return this.doReleaseUIEvents(),this.initialized=t,this}release(){return this.isInitialized()?(this.doReleaseUIEvents(),this.doReleaseUI(),this.initialized=false,this):this}updateAccountInfo(){if(!this.isInitialized())throw new Error("[VOT] SettingsView isn't initialized");const t=!!this.data.account?.token;return this.accountButton.avatarId=this.data.account?.avatarId,this.useLivelyVoiceTooltip.hidden=this.accountButton.loggedIn=t,this.accountButton.username=this.data.account?.username,this.useLivelyVoiceCheckbox.disabled=!t,this.events["update:account"].dispatch(this.data.account),this}open(){if(!this.isInitialized())throw new Error("[VOT] SettingsView isn't initialized");return this.dialog.open()}close(){if(!this.isInitialized())throw new Error("[VOT] SettingsView isn't initialized");return this.dialog.close()}}const Cp=e=>{const t=e.subtitles.map(n=>({text:n.text,startMs:n.startMs,durationMs:n.durationMs,speakerId:n.speakerId,tokens:n.tokens.map(i=>({text:i.text,startMs:i.startMs,durationMs:i.durationMs}))}));return {containsTokens:t.some(n=>n.tokens.length>0),subtitles:t}};class Ep{mount;initialized=false;videoHandler;intervalIdleChecker;data;votGlobalPortal;votOverlayView;votSettingsView;constructor({mount:t,data:n={},videoHandler:i,intervalIdleChecker:o}){this.mount=t,this.videoHandler=i,this.data=n,this.intervalIdleChecker=o;}get root(){return this.mount.root}get portalContainer(){return this.mount.portalContainer}get tooltipLayoutRoot(){return this.mount.tooltipLayoutRoot}isInitialized(){return this.initialized}initUI(){if(this.isInitialized())throw new Error("[VOT] UIManager is already initialized");return this.initialized=true,this.votGlobalPortal=w.createPortal(),document.documentElement.appendChild(this.votGlobalPortal),this.votOverlayView=new vp({mount:this.mount,globalPortal:this.votGlobalPortal,data:this.data,videoHandler:this.videoHandler,intervalIdleChecker:this.intervalIdleChecker}),this.votOverlayView.initUI(this.data.buttonPos??"default"),this.votSettingsView=new Wn({globalPortal:this.votGlobalPortal,data:this.data,videoHandler:this.videoHandler}),this.votSettingsView.initUI(),this}updateMount(t){return this.mount=t,this.votOverlayView?.updateMount?.(t),this}initUIEvents(){if(!this.isInitialized())throw new Error("[VOT] UIManager isn't initialized");this.votOverlayView.initUIEvents(),this.votOverlayView.addEventListener("click:translate",async()=>{await this.handleTranslationBtnClick();}).addEventListener("click:pip",async()=>{if(!this.videoHandler)return;await(this.videoHandler.video===document.pictureInPictureElement?document.exitPictureInPicture():this.videoHandler.video.requestPictureInPicture());}).addEventListener("click:settings",async()=>{this.videoHandler?.subtitlesWidget?.releaseTooltip(),this.videoHandler?.overlayVisibility?.cancel(),this.videoHandler?.overlayVisibility?.show(),this.votSettingsView.open(),await Rc();}).addEventListener("click:downloadTranslation",async()=>{if(!this.votOverlayView.isInitialized()||!this.videoHandler?.downloadTranslationUrl||!this.videoHandler.videoData)return;const t=this.votOverlayView.downloadTranslationButton,n=this.videoHandler.downloadTranslationUrl,i=this.data.downloadWithName?Fi(this.videoHandler.videoData.downloadTitle):`translation_${this.videoHandler.videoData.videoId}`,o=this.videoHandler.site.additionalData==="mobile";t&&(t.progress=0);try{if(o){const s=await tt(n,{timeout:0});if(!s.ok)throw new Error(`HTTP ${s.status}`);const a=await es(s,i,l=>{t&&(t.progress=l);});await this.saveBlobWithMobileShare(a,`${i}.mp3`,!0);return}const r=await tt(n,{timeout:0});if(!r.ok)throw new Error(`HTTP ${r.status}`);await np(r,i,s=>{t&&(t.progress=s);});}catch(r){console.error("[VOT] Download translation failed:",r),this.triggerUrlDownload(n,`${i}.mp3`)||globalThis.open(n,"_blank")?.focus();}finally{t&&(t.progress=0);}}).addEventListener("click:downloadSubtitles",async()=>{const t=this.videoHandler;if(!t?.yandexSubtitles||!t.videoData)return;const n=this.data.subtitlesDownloadFormat??"json",i=er(Cp(t.yandexSubtitles),n),o=new Blob([n==="json"?JSON.stringify(i):i],{type:"text/plain"}),r=this.data.downloadWithName?Fi(t.videoData.downloadTitle):`subtitles_${t.videoData.videoId}`;gn(o,`${r}.${n}`);}).addEventListener("input:videoVolume",t=>{if(this.videoHandler){if(this.videoHandler.setVideoVolume(t/100),!this.data.syncVolume){this.videoHandler.onVideoVolumeSliderSynced(t);return}this.videoHandler.syncVolumeWrapper("video",t);}}).addEventListener("input:translationVolume",t=>{if(!this.videoHandler)return;const n=t??this.data.defaultVolume??100;if(this.videoHandler.audioPlayer.player.volume=n/100,!this.data.syncVolume){this.videoHandler.onTranslationVolumeSliderSynced(n);return}this.videoHandler.syncVolumeWrapper("translation",n);}).addEventListener("select:subtitles",async t=>{await this.videoHandler?.changeSubtitlesLang(t);}),this.votSettingsView.initUIEvents(),this.votSettingsView.addEventListener("update:account",async t=>{this.videoHandler&&(this.videoHandler.votClient.apiToken=t?.token);}).addEventListener("change:autoTranslate",async t=>{t&&this.videoHandler&&!this.videoHandler?.hasActiveSource()&&await this.handleTranslationBtnClick();}).addEventListener("change:autoSubtitles",async t=>{!t||!this.videoHandler?.videoData?.videoId||await this.videoHandler.enableSubtitlesForCurrentLangPair();}).addEventListener("change:showVideoVolume",()=>{this.withInitializedOverlayView(t=>{!t.videoVolumeSlider||!t.votButton||(t.videoVolumeSlider.container.hidden=!this.data.showVideoSlider||t.votButton.status!=="success");});}).addEventListener("change:audioBooster",async()=>{this.withInitializedOverlayView(t=>{if(!t.translationVolumeSlider)return;const n=t.translationVolumeSlider.value,i=this.data.audioBooster?wr:100;t.translationVolumeSlider.max=i;const o=N(n,0,i);t.translationVolumeSlider.value=o,this.videoHandler?.onTranslationVolumeSliderSynced(o);});}).addEventListener("change:syncVolume",t=>{this.videoHandler&&(this.videoHandler.setupAudioSettings(),t&&this.withInitializedOverlayView(n=>{const i=n.videoVolumeSlider,o=n.translationVolumeSlider;!i||!o||this.videoHandler.resetVolumeLinkState(Number(i.value),Number(o.value));}));}).addEventListener("change:useLivelyVoice",()=>{this.videoHandler?.stopTranslate();}).addEventListener("change:subtitlesHighlightWords",t=>{this.withSubtitlesWidget(n=>{n.setHighlightWords(this.data.highlightWords??t);});}).addEventListener("change:subtitlesSmartLayout",t=>{this.withSubtitlesWidget(n=>{n.setSmartLayout(this.data.subtitlesSmartLayout??t);});}).addEventListener("input:subtitlesMaxLength",t=>{this.withSubtitlesWidget(n=>{n.setMaxLength(this.data.subtitlesMaxLength??t);});}).addEventListener("input:subtitlesFontSize",t=>{this.withSubtitlesWidget(n=>{n.setFontSize(this.data.subtitlesFontSize??t);});}).addEventListener("input:subtitlesBackgroundOpacity",t=>{this.withSubtitlesWidget(n=>{n.setOpacity(this.data.subtitlesOpacity??t);});}).addEventListener("change:proxyWorkerHost",t=>{this.videoHandler&&this.videoHandler.handleProxySettingsChanged("proxyWorkerHost");}).addEventListener("select:proxyTranslationStatus",()=>{this.videoHandler?.handleProxySettingsChanged("proxyTranslationStatus");}).addEventListener("change:useNewAudioPlayer",()=>{this.restartAudioPlayer();}).addEventListener("change:onlyBypassMediaCSP",()=>{this.restartAudioPlayer();}).addEventListener("select:translationTextService",()=>{this.withSubtitlesWidget(t=>{t.resetTranslationContext(true);});}).addEventListener("change:showPiPButton",()=>{this.withInitializedOverlayView(t=>{t.votButton&&(t.votButton.pipButton.hidden=t.votButton.separator2.hidden=!t.pipButtonVisible);});}).addEventListener("select:buttonPosition",t=>{this.withInitializedOverlayView(n=>{const i=this.data.buttonPos??t;n.updateButtonLayout(i,Ie.calcDirection(i));});}).addEventListener("select:menuLanguage",async()=>{await this.reloadMenu();}).addEventListener("click:bugReport",()=>{if(!this.videoHandler)return;const t=new URLSearchParams(this.videoHandler.collectReportInfo()).toString();globalThis.open(`${Tc}/issues/new?${t}`,"_blank")?.focus();}).addEventListener("click:resetSettings",async()=>{const t=await I.list();await Promise.all(t.map(async n=>await I.delete(n))),await I.set("compatVersion",oe),globalThis.location.reload();});}async reloadMenu(){if(!this.votOverlayView?.isInitialized())throw new Error("[VOT] OverlayView isn't initialized");const t=this.votOverlayView.votButton.opacity,n=this.votOverlayView.votButton.container.hidden,i=this.votOverlayView.votMenu.hidden,o=this.data.buttonPos??"default",r=this.votSettingsView?.dialog?.container?.hidden===false;if(await this.videoHandler?.stopTranslation(),this.release(),this.initUI(),this.initUIEvents(),!this.videoHandler)return this;try{const{position:a,direction:l}=this.votOverlayView.calcButtonLayout(o);this.votOverlayView.updateButtonLayout(a,l),this.votOverlayView.votMenu.hidden=i,this.votOverlayView.votButton.container.hidden=n,this.votOverlayView.votButton.opacity=t;}catch{}try{this.videoHandler.rebindOverlayVisibilityTargets();}catch{}if(r)try{this.votSettingsView?.open();}catch{}await this.videoHandler.updateSubtitlesLangSelect();const s=this.videoHandler.subtitlesWidget;return s&&(s.setPortal(this.votOverlayView.votOverlayPortal),s.resetTranslationContext(true)),this}async handleTranslationBtnClick(){if(!this.votOverlayView?.isInitialized())throw new Error("[VOT] OverlayView isn't initialized");if(!this.videoHandler)return this;if(this.videoHandler.hasActiveSource())return await this.videoHandler.stopTranslation(),this;if(this.votOverlayView.votButton.status==="error"&&!this.votOverlayView.votButton.loading&&this.transformBtn("none",p.get("translateVideo")),this.votOverlayView.votButton.status!=="none"||this.votOverlayView.votButton.loading)return this.videoHandler.actionsAbortController.abort(),await this.videoHandler.stopTranslation(),this;try{if(E.log("[handleTranslationBtnClick] trying execute translation"),!this.videoHandler.videoData?.videoId)throw new it("VOTNoVideoIDFound");(this.videoHandler.site.host==="vk"&&this.videoHandler.site.additionalData==="clips"||this.videoHandler.site.host==="douyin")&&(this.videoHandler.videoData=await this.videoHandler.getVideoData()),E.log("[handleTranslationBtnClick] Run translateFunc",this.videoHandler.videoData.videoId),await this.videoHandler.translateFunc(this.videoHandler.videoData.videoId,this.videoHandler.videoData.isStream,this.videoHandler.videoData.detectedLanguage,this.videoHandler.videoData.responseLanguage,this.videoHandler.videoData.translationHelp);}catch(t){if(t instanceof Error&&t.name==="AbortError")return this.transformBtn("none",p.get("translateVideo")),this;if(console.error("[VOT]",t),!(t instanceof Error))return this.transformBtn("error",String(t)),this;const n=t.name==="VOTLocalizedError"?t.localizedMessage:t.message;this.transformBtn("error",n);}return this}isLoadingText(t){const n=p.get("TranslationDelayed");return typeof t=="string"&&(t.includes(p.get("translationTake"))||(n?t.includes(n):false))}transformBtn(t,n){if(!this.votOverlayView?.isInitialized())throw new Error("[VOT] OverlayView isn't initialized");return this.votOverlayView.votButton.status=t,this.votOverlayView.votButton.loading=t==="error"&&this.isLoadingText(n),this.votOverlayView.votButton.setText(n),this.votOverlayView.votButtonTooltip.setContent(n),this}releaseUI(t=false){if(!this.isInitialized())throw new Error("[VOT] UIManager isn't initialized");return this.votOverlayView.releaseUI(true),this.votSettingsView.releaseUI(true),this.votGlobalPortal.remove(),this.initialized=t,this}releaseUIEvents(t=false){if(!this.isInitialized())throw new Error("[VOT] UIManager isn't initialized");return this.votOverlayView.releaseUIEvents(false),this.votSettingsView.releaseUIEvents(false),this.initialized=t,this}release(){return this.isInitialized()?(this.votOverlayView.release(),this.votSettingsView.release(),this.votGlobalPortal.remove(),this.initialized=false,this):this}withInitializedOverlayView(t){this.votOverlayView?.isInitialized()&&t(this.votOverlayView);}withSubtitlesWidget(t){const n=this.videoHandler?.subtitlesWidget;n&&t(n);}triggerUrlDownload(t,n){try{const i=document.createElement("a");return i.href=t,i.download=n,i.target="_blank",i.rel="noopener noreferrer",i.style.display="none",document.body.appendChild(i),i.click(),i.remove(),!0}catch{return false}}async tryShareBlob(t,n){const i=typeof navigator>"u"?void 0:navigator;if(!i?.share||typeof File>"u")return false;let o;try{o=new File([t],n,{type:t.type||"application/octet-stream"});}catch{return false}if(typeof i.canShare=="function"&&!i.canShare({files:[o]}))return false;try{return await i.share({files:[o],title:n}),!0}catch(r){return r instanceof DOMException&&r.name==="AbortError"}}async saveBlobWithMobileShare(t,n,i){i&&await this.tryShareBlob(t,n)||gn(t,n);}restartAudioPlayer(){this.videoHandler&&(async()=>(await this.videoHandler?.stopTranslate(),this.videoHandler?.createPlayer()))();}}class Vp{deps;hideDeadlineMs=0;hideArmed=false;unsubscribeChecker;constructor(t){this.deps=t,this.unsubscribeChecker=this.deps.checker.subscribe(()=>{this.onCheckerTick();});}show(){const t=this.getView();return t?(t.updateButtonOpacity(1),t):null}cancel(){this.hideDeadlineMs=0,this.hideArmed=false;}release(){this.cancel(),this.unsubscribeChecker();}queueAutoHide(){if(!this.show())return;const t=this.deps.getAutoHideDelay();this.hideDeadlineMs=this.nowMs()+Math.max(0,t),this.hideArmed=true,this.deps.checker.markActivity("overlay-queue-hide"),this.deps.checker.requestImmediateTick();}handleOverlayInteraction(t){const n=t?.type;if(n){if(n==="focusin"){this.handleFocusIn();return}if(n.startsWith("pointer")){this.cancel(),this.show(),this.deps.checker.markActivity("overlay-interaction"),t.stopPropagation?.();return}this.handleHostInteraction(t);}}handleHostInteraction(t){const n=t?.type;if(n){if(n==="focusin"){this.handleFocusIn();return}if(n.startsWith("pointer")){const i=t.target;this.deps.isInteractiveNode(i)&&t.stopPropagation?.(),this.deps.checker.markActivity("overlay-host-pointer");}this.queueAutoHide();}}scheduleHide(t){if(!this.getView())return;const n=t?.currentTarget;let i=t?.relatedTarget??null;!i&&typeof t?.composedPath=="function"&&(i=t.composedPath()[1]??null);const o=i instanceof Node?i:null,r=n instanceof Node?n:null;o&&(r?.contains(o)||this.deps.isInteractiveNode(o))||this.queueAutoHide();}onCheckerTick(){if(!this.hideArmed||this.hideDeadlineMs<=0||this.nowMs()+2typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),queueMicrotask:e=>{if(typeof queueMicrotask=="function"){queueMicrotask(e);return}(async()=>(await Promise.resolve(),e()))();},isDocumentHidden:()=>typeof document<"u"&&typeof document.hidden=="boolean"?document.hidden:false}}class Op{profile;runtime;subscribers=new Set;timerId=null;running=false;destroyed=false;immediateQueued=false;currentMode="active";lastActivityAt;constructor(t={}){this.profile={...Mp,...t.profile},this.runtime={..._p(),...t.runtime},this.lastActivityAt=this.runtime.nowMs();}start(){this.destroyed||this.running||(this.running=true,this.lastActivityAt=this.runtime.nowMs(),this.runTick("start"));}stop(){this.running&&(this.running=false,this.clearTimer(),this.immediateQueued=false);}destroy(){this.destroyed||(this.stop(),this.subscribers.clear(),this.destroyed=true);}subscribe(t){return this.destroyed?()=>{}:(this.subscribers.add(t),()=>{this.subscribers.delete(t);})}markActivity(t){if(this.destroyed||(this.lastActivityAt=this.runtime.nowMs(),!this.running))return;const n=this.resolveMode(this.lastActivityAt);n!==this.currentMode&&(this.currentMode=n,this.restartTimer(n));}requestImmediateTick(){this.destroyed||!this.running||this.immediateQueued||(this.immediateQueued=true,this.runtime.queueMicrotask(()=>{this.immediateQueued=false,!(this.destroyed||!this.running)&&this.runTick("immediate");}));}resolveMode(t){return this.runtime.isDocumentHidden()?"hidden":t-this.lastActivityAt>=this.profile.idleAfterMs?"idle":"active"}intervalForMode(t){return t==="hidden"?this.profile.hiddenIntervalMs:t==="idle"?this.profile.idleIntervalMs:this.profile.activeIntervalMs}clearTimer(){this.timerId!==null&&(this.runtime.clearInterval(this.timerId),this.timerId=null);}restartTimer(t){this.clearTimer();const n=Math.max(1,this.intervalForMode(t));this.timerId=this.runtime.setInterval(()=>{this.runTick("interval");},n);}runTick(t){const n=this.runtime.nowMs(),i=this.resolveMode(n);(i!==this.currentMode||this.timerId===null)&&(this.currentMode=i,this.restartTimer(i));const o={nowMs:n,mode:i,source:t};for(const r of this.subscribers)try{r(o);}catch{}}}function zn(e){return new Op({profile:e})}const ss=()=>Date.now();function on(){return GM_info?.script?.name||"VOT"}function Dp(e,t){try{return p?.get?.(e)||t}catch{return t}}function Bp(e,t,n){if(!n)return true;const i=e.get(t)??0;return ss()-i>=n}function Rp(e,t){e.set(t,ss());}function Np(e){try{if(typeof GM_notification=="function")return GM_notification(e),!0;const t=globalThis.GM;if(t!==void 0&&typeof t.notification=="function"){const n={text:e.text,title:e.title,image:e.image,onclick:e.onclick,ondone:e.ondone};return t.notification(n),!0}}catch{}return false}class Fp{lastSentAt=new Map;send(t,n={}){try{const i=n.key||t.tag||`${t.title??""}|${t.text??""}`,o=n.cooldownMs??0;if(!Bp(this.lastSentAt,i,o))return;const r={...t,title:t.title??on()};Np(r)?Rp(this.lastSentAt,i):E.log("[notify] unavailable",r);}catch{}}translationCompleted(t){const n=Dp("VOTTranslationCompletedNotify","The translation on the {0} has been completed!").replace("{0}",t);this.send({text:n,title:on(),timeout:5e3,silent:true,tag:"VOTTranslationCompleted",onclick:()=>{try{globalThis.focus();}catch{}}},{key:`translation_completed_${t}`,cooldownMs:1e4});}translationFailed(t){const{videoId:n,message:i}=t;if(Ne(i))return;const o=ar(i)||"Translation failed",r=on();this.send({text:o,title:r,timeout:8e3,silent:true,tag:`VOTtranslationFailed_${n||"unknown"}`,onclick:()=>{try{globalThis.focus();}catch{}}},{key:`translation_failed_${n||"unknown"}`,cooldownMs:3e4});}}const Hp=["class","id","title"],Me="__votAttachShadowHook";function $p(){const e=globalThis,t=e[Me];if(t?.original&&t.subscribers)return t;const n=Element.prototype.attachShadow;if(typeof n!="function")return null;const i={original:n,subscribers:new Set},o=function(r){const s=n.call(this,r);for(const a of i.subscribers)try{a(s);}catch{}return s};try{Object.defineProperty(Element.prototype,"attachShadow",{configurable:!0,enumerable:!0,writable:!0,value:o});}catch{return null}return e[Me]=i,i}function Up(e){const t=globalThis,n=t[Me];if(n&&(n.subscribers.delete(e),!(n.subscribers.size>0))){try{Object.defineProperty(Element.prototype,"attachShadow",{configurable:!0,enumerable:!0,writable:!0,value:n.original});}catch{Element.prototype.attachShadow=n.original;}delete t[Me];}}class Ut{static adKeywords=new Set(["advertise","advertisement","promo","sponsor","banner","commercial","preroll","midroll","postroll","ad-container","sponsored"]);seenVideos=new WeakSet;activeVideos=new WeakSet;observedRoots=new WeakSet;pendingAdded=new Set;pendingRemoved=new Set;flushPending=false;static MAX_FLUSH_BUDGET_MS=6;static MAX_NODES_PER_SLICE=120;onVideoAdded=new B;onVideoRemoved=new B;observer=new MutationObserver(t=>this.onMutations(t));intervalIdleChecker;checkerUnsubscribe=null;enabled=false;attachShadowSubscriber=null;onDocumentReady=null;onPageShow=()=>{const t=document.documentElement;t&&(this.pendingAdded.add(t),this.scheduleFlush());};constructor(t=zn()){this.intervalIdleChecker=t;}static containsAdKeyword(t){for(const n of Ut.adKeywords)if(t===n||t.includes(n))return true;return false}isAdRelated(t){for(const n of Hp){const i=t.getAttribute(n);if(!i)continue;const o=i.toLowerCase(),r=n==="class"?o.split(/\s+/):[o];for(const s of r)if(s&&Ut.containsAdKeyword(s))return true}return false}isInsideAd(t){for(let n=t.parentElement;n;n=n.parentElement)if(this.isAdRelated(n))return true;return false}getCapturedAudioTrackCount(t){const n=t,i=n.captureStream??n.mozCaptureStream;if(typeof i!="function")return null;try{return i.call(t).getAudioTracks().length}catch{return null}}isLikelySilentDecorativeVideo(t){if(!(t.muted||t.defaultMuted)||!t.autoplay||!t.loop||t.controls)return false;const n=t;if(typeof n.mozHasAudio=="boolean")return !n.mozHasAudio;if("audioTracks"in n&&typeof n.audioTracks?.length=="number"){if(n.audioTracks.length>0)return false;const o=this.getCapturedAudioTrackCount(t);return o!==null?o===0:true}const i=this.getCapturedAudioTrackCount(t);return i!==null?i===0:false}hasAudio(t){const n=t;return t.srcObject instanceof MediaStream?t.srcObject.getAudioTracks().length>0:typeof n.mozHasAudio=="boolean"?n.mozHasAudio:typeof n.webkitAudioDecodedByteCount=="number"&&n.webkitAudioDecodedByteCount>0||"audioTracks"in n&&typeof n.audioTracks?.length=="number"&&n.audioTracks.length>0?true:!this.isLikelySilentDecorativeVideo(t)}isValidVideo(t){return !(this.isAdRelated(t)||this.isInsideAd(t)||!this.hasAudio(t))}observeRoot(t){this.observedRoots.has(t)||(this.observedRoots.add(t),this.observer.observe(t,{childList:true,subtree:true}));}scan(t){if(t instanceof HTMLVideoElement){this.trackVideo(t);return}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&t.nodeType!==Node.DOCUMENT_NODE)return;const n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const o=i;return o.tagName==="VIDEO"||o.shadowRoot?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();){const i=n.currentNode;if(i instanceof HTMLVideoElement){this.trackVideo(i);continue}const o=i.shadowRoot;o&&(this.observeRoot(o),this.scan(o));}}trackVideo(t){if(this.seenVideos.has(t))return;this.seenVideos.add(t);const n=()=>{this.isValidVideo(t)&&(this.activeVideos.has(t)||(this.activeVideos.add(t),this.onVideoAdded.dispatch(t)));};if(t.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA)n();else {t.addEventListener("loadeddata",n,{once:true});const i=()=>{t.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&n();};t.addEventListener("play",i,{once:true,passive:true});}t.addEventListener("emptied",()=>{t.isConnected||this.untrackVideo(t);},{passive:true});}untrackVideo(t){this.activeVideos.has(t)&&(this.onVideoRemoved.dispatch(t),this.activeVideos.delete(t)),this.seenVideos.delete(t);}collectVideos(t){const n=new Set,i=r=>{for(const s of r)n.add(s);};if(t instanceof HTMLVideoElement&&n.add(t),t instanceof ShadowRoot&&i(t.querySelectorAll("video")),t instanceof Element){i(t.querySelectorAll("video"));const r=t.shadowRoot;r&&i(r.querySelectorAll("video"));}const o=t;return o?.querySelectorAll&&i(o.querySelectorAll("video")),Array.from(n)}getNowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}isSliceBudgetReached(t,n){return n>=Ut.MAX_NODES_PER_SLICE?true:this.getNowMs()-t>=Ut.MAX_FLUSH_BUDGET_MS}processPendingAdded(t){let n=0;for(;this.pendingAdded.size>0;){const i=this.pendingAdded.values().next();if(i.done||(this.pendingAdded.delete(i.value),this.scan(i.value),n+=1,this.isSliceBudgetReached(t,n)))break}return n}processPendingRemoved(t,n){let i=n;for(;this.pendingRemoved.size>0&&!this.isSliceBudgetReached(t,i);){const o=this.pendingRemoved.values().next();if(o.done)break;this.pendingRemoved.delete(o.value);for(const r of this.collectVideos(o.value))r.isConnected||this.untrackVideo(r);i+=1;}return i}flushSlice=()=>{if(!this.enabled){this.pendingAdded.clear(),this.pendingRemoved.clear(),this.flushPending=false;return}const t=this.getNowMs(),n=this.processPendingAdded(t);this.processPendingRemoved(t,n),this.flushPending=this.pendingAdded.size>0||this.pendingRemoved.size>0,this.flushPending&&this.intervalIdleChecker.requestImmediateTick();};onCheckerTick=()=>{this.flushPending&&this.flushSlice();};scheduleFlush=()=>{this.enabled&&(this.flushPending=true,this.intervalIdleChecker.requestImmediateTick());};installAttachShadowHook(){if(this.attachShadowSubscriber)return;const t=$p();if(!t)return;const n=i=>{this.enabled&&(this.observeRoot(i),this.pendingAdded.add(i),this.scheduleFlush());};t.subscribers.add(n),this.attachShadowSubscriber=n;}uninstallAttachShadowHook(){this.attachShadowSubscriber&&(Up(this.attachShadowSubscriber),this.attachShadowSubscriber=null);}enqueueAddedNode(t){if(t.nodeType===Node.ELEMENT_NODE){const n=t.shadowRoot;n&&this.observeRoot(n);}this.pendingAdded.add(t);}enqueueMutation(t){for(const n of t.addedNodes)this.enqueueAddedNode(n);for(const n of t.removedNodes)this.pendingRemoved.add(n);}onMutations(t){for(const n of t)n.type==="childList"&&this.enqueueMutation(n);(this.pendingAdded.size>0||this.pendingRemoved.size>0)&&this.scheduleFlush();}enable(){if(this.enabled)return;this.enabled=true,this.checkerUnsubscribe?.(),this.checkerUnsubscribe=this.intervalIdleChecker.subscribe(()=>{this.onCheckerTick();}),this.intervalIdleChecker.start(),this.intervalIdleChecker.markActivity("video-observer-enable"),this.installAttachShadowHook(),globalThis.addEventListener("pageshow",this.onPageShow,{passive:true});const t=document.documentElement;if(t){this.observeRoot(t),this.scan(t);return}const n=()=>{const i=document.documentElement;i&&(document.removeEventListener("readystatechange",n),this.onDocumentReady=null,this.enabled&&(this.observeRoot(i),this.scan(i)));};this.onDocumentReady=n,document.addEventListener("readystatechange",n),typeof queueMicrotask=="function"?queueMicrotask(n):(async()=>(await Promise.resolve(),n()))();}disable(){this.enabled&&(this.enabled=false,globalThis.removeEventListener("pageshow",this.onPageShow),this.onDocumentReady&&(document.removeEventListener("readystatechange",this.onDocumentReady),this.onDocumentReady=null),this.uninstallAttachShadowHook(),this.observer.disconnect(),this.flushPending=false,this.checkerUnsubscribe?.(),this.checkerUnsubscribe=null,this.intervalIdleChecker.stop(),this.pendingAdded.clear(),this.pendingRemoved.clear(),this.seenVideos=new WeakSet,this.activeVideos=new WeakSet,this.observedRoots=new WeakSet);}}function rn(e,t){const n=dt(t);e.lastVideoPercent=n;}function sn(e,t){const n=Number(t);if(!Number.isFinite(n))return;const i=Math.max(0,Math.round(n));e.lastTranslationPercent=i;}function Wp({state:e,fromType:t,newVolume:n,currentVideo:i,currentTranslation:o,translationMin:r,translationMax:s}){if(e.initialized||(e.lastVideoPercent=Number(i),e.lastTranslationPercent=Number(o),e.initialized=true),t==="video"){const d=dt(n),u=d-dt(e.lastVideoPercent);e.lastVideoPercent=d;const h=yn(e.lastTranslationPercent+u,r,s);return e.lastTranslationPercent=h,{nextTranslation:h}}const a=yn(Number.isFinite(n)?n:o,r,s),l=a-e.lastTranslationPercent;e.lastTranslationPercent=a;const c=dt(e.lastVideoPercent+l);return e.lastVideoPercent=c,{nextVideo:c}}const xo={allowTouchMoveHandler:true,disableContainerDrag:false},zp={xvideos:{allowTouchMoveHandler:false},youtube:{disableContainerDrag:true}};function qp(e){if(!e)return xo;const t=zp[e]??{};return {...xo,...t}}function as(e){const t=(i,o,r,s)=>{i.addEventListener(o,r,{signal:e,...s});};return {add:t,addMany:(i,o,r,s)=>{for(const a of o)t(i,a,r,s);}}}function So(e,t,n){e(t,["pointerenter","focusin"],i=>n.handleOverlayInteraction(i)),e(t,["pointermove"],i=>n.handleOverlayInteraction(i),{passive:true}),e(t,["pointerleave","focusout"],i=>n.scheduleHide(i));}function Sn(e,t=0){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?dt(n):t}function ls(e,t,n={}){n.skipYouTubeLikeHosts&&Hr(e.site.host)||typeof e.smartVolumeDuckingInterval!="number"&&(!e.data?.syncVolume||!e.audioPlayer?.player?.src||e.isLikelyInternalVideoVolumeChange(t)||e.syncVolumeWrapper("video",t));}function an(e,t,n){const i=t.votMenu?.container;if(i){const s=n??e.video.getBoundingClientRect().height;i.style.setProperty("--vot-container-height",`${s}px`);}const{position:o,direction:r}=t.calcButtonLayout(e.data?.buttonPos??"default");t.updateButtonLayout(o,r);}function To(e,t){if(!t)return false;const n=rs(e).split("+").filter(Boolean),i=t.split("+").filter(Boolean);if(n.length!==i.length)return false;const o=new Set(n);return i.every(r=>o.has(r))}function Gp(e){const{self:t,overlayView:n,addMany:i}=e;t.resizeObserver=new ResizeObserver(o=>{for(const r of o)an(t,n,r.contentRect.height);}),t.resizeObserver.observe(t.video),an(t,n),i(document,["fullscreenchange","webkitfullscreenchange"],()=>an(t,n));}function Kp(e){const{self:t}=e;if(!$r(t.site))return;t.syncVolumeObserver=new MutationObserver(i=>{if(!t.audioPlayer?.player?.src)return;let o=false,r=null;for(const a of i){if(a.type!=="attributes"||a.attributeName!=="aria-valuenow")continue;o=true;const l=a.target instanceof Element?a.target.getAttribute("aria-valuenow"):null,c=l!=null?Number.parseFloat(l):Number.NaN;Number.isFinite(c)&&(r=c);}if(!o)return;let s;if(r!=null)s=Sn(r);else {const a=t.isMuted()?0:t.getVideoVolume();s=Sn(a*100);}t.syncVideoVolumeSlider(),ls(t,s);});const n=document.querySelector(".ytp-volume-panel");n&&t.syncVolumeObserver.observe(n,{attributes:true,subtree:true,attributeFilter:["aria-valuenow"]});}function Yp(e){const{self:t}=e;if(t.site.host!=="youtube"||t.site.additionalData==="mobile")return;const n=async()=>{if(!t.videoData)return;const r=_.getPlayer(),s=r?.getAvailableAudioTracks?.()??null;if(!Array.isArray(s)||s.length<=1)return;const l=r?.getAudioTrack?.()?.getLanguageInfo?.()?.id??void 0,c=l&&l!=="und"?l.toLowerCase().split(/[-_.]/)[0]:_.getLanguage();if(c&&c!==t.videoData.detectedLanguage&&(t.setSelectMenuValues(c,t.videoData.responseLanguage),t.data?.autoTranslate&&c!==t.videoData.responseLanguage))try{await t.uiManager.handleTranslationBtnClick();}catch{}},i=_.getPlayer(),o=["onApiChange","onStateChange"];if(i?.addEventListener)for(const r of o)try{i.addEventListener(r,n);}catch{}n(),t.abortController.signal.addEventListener("abort",()=>{if(i?.removeEventListener)for(const r of o)try{i.removeEventListener(r,n);}catch{}},{once:true});}function Jp(e){const{self:t,overlayView:n,add:i,addMany:o,platformConfig:r}=e;i(document,"click",c=>{const d=c.target,u=n.votButton?.container,h=n.votMenu?.container,m=t.uiManager.votSettingsView?.dialog?.container,v=document.querySelector(".vot-dialog-temp"),b=d&&u?u.contains(d):false,y=d&&h?h.contains(d):false,k=d?t.container.contains(d):false,x=d&&m?m.contains(d):false,A=d?v?.contains(d)??false:false;b||y||x||A||(k||n.updateButtonOpacity(0),h&&!h.hidden&&(h.hidden=true,t.overlayVisibility?.queueAutoHide()));});const s=new Set,a=()=>s.clear();i(document,"keydown",async c=>{const d=c;if(d.repeat)return;s.add(d.code);const u=document.activeElement,h=u?.tagName?.toLowerCase?.()??"";if(!(["input","textarea"].includes(h)||u?.isContentEditable)){if(To(s,t.data?.translationHotkey)){a(),await t.uiManager.handleTranslationBtnClick();return}To(s,t.data?.subtitlesHotkey)&&(a(),await t.toggleSubtitlesForCurrentLangPair());}}),i(document,"keyup",c=>s.delete(c.code)),i(document,"blur",a),i(document,"visibilitychange",()=>{document.hidden&&a();}),i(globalThis,"blur",a);const l=t.getEventContainer();l&&(o(l,["pointerenter","pointerdown"],c=>t.overlayVisibility.handleHostInteraction(c)),i(l,"pointermove",c=>t.overlayVisibility.handleHostInteraction(c),{passive:true}),i(l,"pointerleave",c=>t.overlayVisibility.scheduleHide(c))),t.rebindOverlayVisibilityTargets(),r.allowTouchMoveHandler&&i(document,"touchmove",c=>t.overlayVisibility.handleHostInteraction(c),{passive:true}),r.disableContainerDrag&&(t.container.draggable=false);}function Xp(e){const{self:t,overlayView:n,add:i}=e,o=async()=>{try{await t.setCanPlay();}catch{}};let r=false;const s=()=>{r||(r=true,queueMicrotask(async()=>{r=false,await o();}));};i(t.video,"canplay",()=>{t.site.host==="rutube"&&t.video.src||s();}),i(t.video,"emptied",async()=>{let a;try{a=await rr(t.site,{fetchFn:tt,video:t.video});}catch{}t.video.src&&t.videoData&&a&&a===t.videoData.videoId||Dr(t,n,{clearVideoData:true,hideMenu:true});}),nf(t.site.host)||i(t.video,"volumechange",()=>{t.syncVideoVolumeSlider();const a=t.uiManager.votOverlayView;if(!a?.isInitialized())return;const l=Sn(a.videoVolumeSlider.value);ls(t,l,{skipYouTubeLikeHosts:true});}),t.site.host==="youtube"&&!t.site.additionalData&&i(document,"yt-page-data-updated",()=>{globalThis.location.pathname.startsWith("/shorts/")&&s();});}function jp(){const e=this.uiManager.votOverlayView;if(!e?.subtitlesSelect)return;const{add:t,addMany:n}=as(this.abortController.signal),i={self:this,overlayView:e,platformConfig:qp(this.site.host),add:t,addMany:n};Gp(i),Kp(i),Yp(i),Jp(i),Xp(i);}function Zp(){this.overlayVisibilityTargetsAbortController?.abort(),this.overlayVisibilityTargetsAbortController=new AbortController;const{signal:e}=this.overlayVisibilityTargetsAbortController,t=this.uiManager?.votOverlayView?.votButton?.container,n=this.uiManager?.votOverlayView?.votMenu?.container;if(!t||!n||!this.overlayVisibility)return;const i=this.overlayVisibility,{addMany:o}=as(e);So(o,t,i),So(o,n,i);}function Qp(e){if(!(e instanceof Node))return false;const t=this.uiManager?.votOverlayView,n=t?.votButton?.container,i=t?.votMenu?.container;return n instanceof Node&&n.contains(e)||i instanceof Node&&i.contains(e)}function tg(){const e=this.data?.autoHideButtonDelay;return typeof e=="number"&&Number.isFinite(e)?e:Bn}function eg(){this.resizeObserver?.disconnect(),this.overlayVisibilityTargetsAbortController?.abort(),this.overlayVisibilityTargetsAbortController=void 0,$r(this.site)&&this.syncVolumeObserver?.disconnect();}let Jt;function ng(e){Jt=e;}let ln=null;async function ig(){Jt||(ln??=(async()=>{try{const n=(await(await tt("https://cloudflare-dns.com/cdn-cgi/trace",{timeout:7e3})).text()).split(` `).find(i=>i.startsWith("loc="));ng(n?.slice(4,6).toUpperCase());}catch(e){console.error("[VOT] Error getting country:",e);}})().finally(()=>{ln=null;}),await ln);}async function og(){if(this.initialized)return;const e=this.isAudioContextSupported;this.data=await I.getValues({autoTranslate:false,autoSubtitles:false,dontTranslateLanguages:[Te],enabledDontTranslateLanguages:true,enabledAutoVolume:true,enabledSmartDucking:true,autoVolume:Fe,buttonPos:"default",showVideoSlider:true,syncVolume:false,downloadWithName:Ar,sendNotifyOnComplete:false,subtitlesMaxLength:300,subtitlesSmartLayout:true,highlightWords:false,subtitlesFontSize:20,subtitlesOpacity:20,subtitlesDownloadFormat:"srt",responseLanguage:Te,defaultVolume:100,onlyBypassMediaCSP:e,newAudioPlayer:e,showPiPButton:false,translateAPIErrors:true,translationService:He,detectService:Dn,translationHotkey:null,subtitlesHotkey:null,m3u8ProxyHost:wc,proxyWorkerHost:ie,translateProxyEnabled:0,translateProxyEnabledDefault:true,audioBooster:false,useLivelyVoice:false,autoHideButtonDelay:Bn,useAudioDownload:Tr||typeof IS_EXTENSION<"u"&&IS_EXTENSION,compatVersion:"",account:{},localeHash:"",localeUpdatedAt:0}),this.data.compatVersion!==oe&&(this.data=await Uc(this.data),await I.set("compatVersion",oe));try{if(Te==="en"&&this.data?.enabledDontTranslateLanguages&&Array.isArray(this.data?.dontTranslateLanguages)&&this.data.dontTranslateLanguages.length===1&&this.data.dontTranslateLanguages[0]==="en"&&typeof this.data.responseLanguage=="string"&&this.data.responseLanguage!=="en"){const t=this.data.responseLanguage;this.data.dontTranslateLanguages=[t],await I.set("dontTranslateLanguages",this.data.dontTranslateLanguages);}}catch{}this.uiManager.data=this.data,console.log("[VOT] data from db:",this.data),!this.data.translateProxyEnabled&&Sr&&(this.data.translateProxyEnabled=1),await ig(),Jt&&kr.includes(Jt)&&this.data.translateProxyEnabledDefault&&(this.data.translateProxyEnabled=2),E.log("translateProxyEnabled",this.data.translateProxyEnabled,this.data.translateProxyEnabledDefault),this.initVOTClient(),this.uiManager.initUI(),this.uiManager.initUIEvents(),this.uiManager.votOverlayView?.votButton?.container&&(this.uiManager.votOverlayView.votButton.container.hidden=true),this.createPlayer(),this.translateToLang=this.data.responseLanguage??"ru",this.initExtraEvents(),this.initialized=true;}const Wt="und",Ao=new Map,rg=()=>typeof Intl<"u"&&typeof Intl.Segmenter=="function",Lo=/[\p{L}\p{N}]+|[^\p{L}\p{N}]+/gu,sg=/[\p{L}\p{N}]/u,ag=e=>{if(typeof Intl>"u"||!e)return Wt;try{return Intl.getCanonicalLocales(e)[0]||Wt}catch{return Wt}},lg=e=>{const t=ag(e);return t===Wt?void 0:Intl.Segmenter.supportedLocalesOf([t])[0]},cg=e=>{if(!rg())return null;const t=lg(e),n=t??Wt,i=Ao.get(n);if(i)return i;const o=new Intl.Segmenter(t,{granularity:"word"});return Ao.set(n,o),o},dg=e=>{const t=[];Lo.lastIndex=0;for(const n of e.matchAll(Lo)){const i=n[0];i&&t.push({text:i,index:n.index??0,isWordLike:sg.test(i)});}return t},cs=(e,t)=>{if(!e)return [];const n=cg(t);if(!n)return dg(e);const i=n.segment(e),o=[];for(const r of i)o.push({text:r.segment,index:r.index,isWordLike:!!r.isWordLike});return o},ug=e=>!!(e&&typeof e=="object"&&"format"in e&&"source"in e&&"url"in e),hg=(e,t,n)=>{const i=e.subtitles;if(!Array.isArray(i)||i.length===0)return null;const o=t??n;if(o){const r=i.find(a=>a.language===o&&typeof a.translatedFromLanguage=="string");if(r)return r;const s=i.find(a=>a.language===o);if(s)return s}return i[0]??null},fg=e=>{const t=_.getPoToken();if(!t)return e;const i=_.getDeviceParams().replace(/^[?&]+/u,"");try{const o=new URL(e);if(o.searchParams.set("potc","1"),o.searchParams.set("pot",t),i){const r=new URLSearchParams(i);for(const[s,a]of r.entries())o.searchParams.set(s,a);}return o.toString()}catch{const o=e.includes("?")?"&":"?",r=i?`&${i}`:"";return `${e}${o}potc=1&pot=${encodeURIComponent(t)}${r}`}},Io=(e,t)=>e-t,ke=(e,t)=>et?1:0,pg=(e,t)=>{const n=Math.min(e.length,t.length);for(let i=0;ie?t===0?n?1:0:n?0:1:0,mg=(e,t,n,i)=>!e||!t||n===i?0:1,Po=(e,t)=>{const n=e.source==="yandex",i=n?0:1,o=e.language===Rn?0:1,r=!!e.translatedFromLanguage,s=t&&e.language===t?0:1,a=gg(n,s,r),l=mg(n,r,e.translatedFromLanguage,t),c=n&&!r?s:0,d=n?0:+!!e.isAutoGenerated;return [i,o,a,l,c,d]},vg=(e,t)=>{const n=e.map((i,o)=>({descriptor:i,index:o}));return n.sort((i,o)=>{const r=Po(i.descriptor,t),s=Po(o.descriptor,t),a=pg(r,s);if(a!==0)return a;const l=ke(i.descriptor.language,o.descriptor.language)||ke(i.descriptor.translatedFromLanguage??"",o.descriptor.translatedFromLanguage??"")||ke(i.descriptor.source,o.descriptor.source)||ke(i.descriptor.url,o.descriptor.url)||Io(+!!i.descriptor.isAutoGenerated,+!!o.descriptor.isAutoGenerated);return l!==0?l:Io(i.index,o.index)}),n.map(i=>i.descriptor)},bg=(e,t)=>typeof e=="boolean"?e:!!t.trim(),yg=e=>{if(!e||typeof e!="object")return {text:"",startMs:0,durationMs:0,isWordLike:false};const t=e,n=typeof t.text=="string"?t.text:"";return {text:n,startMs:typeof t.startMs=="number"?t.startMs:0,durationMs:typeof t.durationMs=="number"?t.durationMs:0,isWordLike:bg(t.isWordLike,n)}},wg=e=>{if(!e||typeof e!="object")return {text:"",startMs:0,durationMs:0,speakerId:"0",tokens:[]};const t=e,n=Array.isArray(t.tokens)?t.tokens.map(yg):[];return {text:typeof t.text=="string"?t.text:"",startMs:typeof t.startMs=="number"?t.startMs:0,durationMs:typeof t.durationMs=="number"?t.durationMs:0,speakerId:typeof t.speakerId=="string"?t.speakerId:"0",tokens:n}},kg=e=>{if(!e||typeof e!="object")return {subtitles:[]};const t=e;return {subtitles:Array.isArray(t.subtitles)?t.subtitles.map(wg):[]}},xg=/<(?:\d{1,2}:)?\d{2}:\d{2}(?:[.,]\d{1,3})?>/gu,Sg=120,Tg=e=>{if(!e.includes("<"))return e;if(typeof document<"u"){const t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}return e.replace(/<\/?[^>]+>/gu,"")},Ag=(e,t)=>!t||e.tStartMs+e.dDurationMs<=t.tStartMs?Math.max(0,e.dDurationMs):Math.max(0,t.tStartMs-e.tStartMs),Lg=(e,t,n)=>{const i=[];let o="",r=n;for(let s=0;se.durationMs>0,ds=e=>e.text?e.text:e.tokens.length?e.tokens.map(t=>t.text).join(""):"",us=(e,t,n)=>{if(!e.length)return [];const i=Math.max(0,n),o=e.map(l=>Math.max(l.length,1)),r=o.reduce((l,c)=>l+c,0),s=new Array(o.length+1).fill(0);for(let l=0;l{const n=[];for(const i of e){if(!i.text||!Ig(i))continue;const o=cs(i.text,t).filter(s=>s.isWordLike&&s.text.trim());if(!o.length)continue;const r=us(o.map(s=>s.text),i.startMs,i.durationMs);n.push(...r);}return n},Cg=(e,t)=>{const n=ds(e);if(!n)return [];const i=t.language,o=cs(n,i);if(!o.length)return [];const r=us(o.map(d=>d.text),e.startMs,e.durationMs),s=o.map((d,u)=>({text:d.text,startMs:r[u]?.startMs??e.startMs,durationMs:r[u]?.durationMs??0,isWordLike:d.isWordLike})),a=Pg(e.tokens??[],i);if(!a.length)return s;const l=s.reduce((d,u,h)=>(u.isWordLike&&u.text.trim()&&d.push(h),d),[]);if(!l.length)return s;const c=l.length;for(let d=0;d{const n=await tt(e,{timeout:7e3});if(t==="vtt"||t==="srt"){const i=await n.text();return er(i,"json")}return n.json()},Vg=(e,t)=>{if(t.source==="youtube")return de.formatYoutubeSubtitles(e,!!t.isAutoGenerated);const n=kg(e);return t.source==="vk"?de.cleanJsonSubtitles(n):n},Mg=(e,t)=>({subtitles:de.processTokens(e,t)}),_g=e=>{const t=[],n=new Set;for(const i of e.subtitles??[])i.language&&!n.has(i.language)&&(n.add(i.language),t.push({source:"yandex",format:"json",language:i.language,url:i.url})),i.translatedLanguage&&t.push({source:"yandex",format:"json",language:i.translatedLanguage,translatedFromLanguage:i.language,url:i.translatedUrl??i.url});return t},de={processTokens(e,t){const n=[];for(const i of e.subtitles){const o=ds(i),r=Cg({...i,text:o},t);n.push({...i,text:o,tokens:r});}return n},formatYoutubeSubtitles(e,t=false){const n=e.events??[];if(!n.length)return console.error("[VOT] Invalid YouTube subtitles format:",e),{subtitles:[]};const i=[];for(let o=0;oTg(a.replace(xg,"")).replace(/\s+([,.:;!?])/gu,"$1").replace(/[ \t]*\n[ \t]*/gu,` `).replace(/[ \t]{2,}/gu," ").replace(/\n{3,}/gu,` `).trim(),n=a=>a.toLowerCase().replace(/\s+/gu," ").trim(),i=a=>a.startMs+Math.max(0,a.durationMs),o=a=>a.reduce((l,c)=>l+c.text.length,0),r=e.subtitles.map(a=>({...a,text:t(a.text),tokens:a.tokens.map(l=>({...l,text:t(l.text)})).filter(l=>l.text.length>0)})).filter(a=>a.text.length>0),s=[];for(const a of r){const l=n(a.text);if(!l)continue;const c=s.at(-1);if(!c){s.push(a);continue}const d=n(c.text),u=i(c),h=i(a),m=d===l,v=a.startMs<=u+Sg;if(!m||!v){s.push(a);continue}const b=Math.min(c.startMs,a.startMs),y=Math.max(u,h),k=o(c.tokens),A=o(a.tokens)>=k?a.tokens:c.tokens;s[s.length-1]={...c,startMs:b,durationMs:Math.max(0,y-b),tokens:A};}return {subtitles:s}},async fetchSubtitles(e,t,n){const i=ug(e)?e:hg(e,t,n);if(!i)return {subtitles:[]};const{source:o,format:r}=i;let{url:s}=i;o==="youtube"&&(s=fg(s));try{const a=await Eg(s,r),l=Vg(a,i),c=Mg(l,i);return E.log("[VOT] Processed subtitles:",c),c}catch(a){return console.error("[VOT] Failed to process subtitles:",a),{subtitles:[]}}},async getSubtitles(e,t){const{host:n,url:i,detectedLanguage:o,videoId:r,duration:s,subtitles:a=[]}=t;try{const l={videoData:{host:n,url:i,videoId:r,duration:s},requestLang:o},d=await Promise.race([e.getSubtitles(l),vr(5e3,"Timeout")]);E.log("[VOT] Subtitles response:",d),d.waiting&&console.error("[VOT] Failed to get Yandex subtitles");const h=[..._g(d),...a];return vg(h,o)}catch(l){let c="Error in getSubtitles function";throw l instanceof Error&&l.message==="Timeout"&&(c="Failed to get Yandex subtitles: timeout"),console.error(`[VOT] ${c}`,l),l}}},Tn="https://vtrans.s3-private.mds.yandex.net/tts/prod/",_e="/video-translation/audio-proxy/",Co="https://brosubs.s3-private.mds.yandex.net/vtrans/",Og="/video-subtitles/subtitles-proxy/";function qn(e){return e??ie}function hs(e){return e.translateProxyEnabled===2}function Dg(e,t){return !hs(t)||!e.startsWith(Tn)?e:e.replace(Tn,`https://${qn(t.proxyWorkerHost)}${_e}`)}function Bg(e){const t=String(e||"");if(!t)return t;try{const n=new URL(t);return n.pathname.startsWith(_e)?(n.host="vtrans.s3-private.mds.yandex.net",n.pathname=`/tts/prod/${n.pathname.slice(_e.length).replace(/^\/+/,"")}`,n.protocol="https:",n.toString()):t}catch{return t}}function Rg(e,t){return e.startsWith(Tn)||e.startsWith(`https://${qn(t.proxyWorkerHost)}${_e}`)}function Ng(e,t){if(!hs(t)||!e.startsWith(Co))return e;const n=e.slice(Co.length);return `https://${qn(t.proxyWorkerHost)}${Og}${n}`}const Fg=new Set(["srt","vtt","json"]);function Hg(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.source!="string"||typeof t.language!="string"||typeof t.url!="string"||typeof t.format!="string"||!Fg.has(t.format)?null:{source:t.source,format:t.format,language:t.language,url:t.url,translatedFromLanguage:typeof t.translatedFromLanguage=="string"?t.translatedFromLanguage:void 0,isAutoGenerated:typeof t.isAutoGenerated=="boolean"?t.isAutoGenerated:void 0}}function Gn(e){const t=[];for(let n=0;nn.index===t)?.descriptor??null}function Eo(){return {label:p.get("VOTSubtitlesDisabled"),value:"disabled",selected:true,disabled:false}}function fs(e){return e[Symbol.iterator]().next().value}function Ug(e){const t=p.getLangLabel(e.language),n=e.translatedFromLanguage?` ${p.get("VOTTranslatedFrom")} ${p.getLangLabel(e.translatedFromLanguage)}`:"",i=e.source==="yandex"?"":`, ${globalThis.location.hostname}`,o=e.isAutoGenerated?` (${p.get("VOTAutogenerated")})`:"";return `${t}${n}${i}${o}`}function ue(e){return (e??"").toLowerCase()}function Oe(e){return ue(e).split(/[-_]/)[0]}function ut(e,t){if(!e||!t)return false;const n=ue(e),i=ue(t);return n===i||Oe(n)===Oe(i)}function Wg(e,t,n){if(!e.length)return null;const i=ue(t),o=ue(n),r=i==="auto"||i==="",s=Oe(i),a=Oe(o),l=x=>x.source==="yandex",c=x=>!!x.isAutoGenerated,d=(x,A,D)=>ut(x.language,D)?r?true:ut(x.translatedFromLanguage,A):false,u=(x,A)=>ut(x.language,A)?x.translatedFromLanguage?ut(x.translatedFromLanguage,A):true:false,h=x=>e.find(({descriptor:A})=>x(A))?.index??null,m=()=>{const x=h(A=>!l(A)&&ut(A.language,o)&&!c(A));return x??h(A=>!l(A)&&ut(A.language,o)&&c(A))},v=h(x=>l(x)&&d(x,i,o));if(v!=null)return v;if(!r&&s&&a&&s===a){const x=h($=>u($,o)&&!c($));if(x!=null)return x;const A=h($=>u($,o)&&c($));if(A!=null)return A;const D=m();if(D!=null)return D;const Y=h($=>l($)&&ut($.language,o));if(Y!=null)return Y}const b=h(x=>l(x)&&ut(x.language,o));if(b!=null)return b;const y=h(x=>!l(x)&&d(x,i,o));if(y!=null)return y;const k=m();return k??null}async function zg(e){const t=this.uiManager.votOverlayView;if(!t?.subtitlesSelect||!t.downloadSubtitlesButton)return this;if(t.subtitlesSelect.setSelectedValue(e),e==="disabled")return this.hasSubtitlesWidget()&&this.subtitlesWidget?.setContent(null),t.downloadSubtitlesButton.hidden=true,this.yandexSubtitles=null,this;const n=Number.parseInt(e,10),i=$g(this.subtitles,n);if(!i)return t.downloadSubtitlesButton.hidden=true,this.yandexSubtitles=null,this;let o={...i};const r=Ng(o.url,{translateProxyEnabled:this.data?.translateProxyEnabled,proxyWorkerHost:this.data?.proxyWorkerHost});return r!==o.url&&(o={...o,url:r},E.log(`[VOT] Subs proxied via ${o.url}`)),this.yandexSubtitles=await de.fetchSubtitles(o),this.getSubtitlesWidget().setContent(this.yandexSubtitles,o.language),t.downloadSubtitlesButton.hidden=false,this}async function qg(){const e=this.uiManager.votOverlayView;if(!e?.subtitlesSelect)return;const t=Gn(this.subtitles);if(t.length===0){const i=[Eo()];e.subtitlesSelect.updateItems(i),await this.changeSubtitlesLang(i[0].value);return}const n=[Eo(),...t.map(({descriptor:i,index:o})=>({label:Ug(i),value:String(o),selected:false,disabled:false}))];e.subtitlesSelect.updateItems(n),await this.changeSubtitlesLang(n[0].value);}async function Gg(){const e=this.uiManager.votOverlayView;if(!e?.subtitlesSelect)return this;if(!Array.isArray(this.subtitles)||this.subtitles.length===0)try{await this.loadSubtitles();}catch{return this}const t=this.videoData?.detectedLanguage??this.translateFromLang,n=this.videoData?.responseLanguage??this.translateToLang,i=Wg(Gn(this.subtitles),t,n);return i==null?this:fs(e.subtitlesSelect.selectedValues)===String(i)?this:(await this.changeSubtitlesLang(String(i)),this)}async function Kg(){const e=this.uiManager.votOverlayView;if(!e?.subtitlesSelect)return this;const t=fs(e.subtitlesSelect.selectedValues);return t&&t!=="disabled"?(await this.changeSubtitlesLang("disabled"),this):(await this.enableSubtitlesForCurrentLangPair(),this)}async function Yg(){if(!this.videoData?.videoId){console.error(`[VOT] ${p.getDefault("VOTNoVideoIDFound")}`),this.subtitles=[];return}const e=this.getSubtitlesCacheKey(this.videoData.videoId,this.videoData.detectedLanguage,this.videoData.responseLanguage);try{let t=this.cacheManager.getSubtitles(e);if(!t){let n=this.subtitlesLoadPromises.get(e);n===void 0&&(n=de.getSubtitles(this.votClient,this.videoData),this.subtitlesLoadPromises.set(e,n));try{t=await n,this.cacheManager.setSubtitles(e,t);}finally{this.subtitlesLoadPromises.get(e)===n&&this.subtitlesLoadPromises.delete(e);}}this.subtitles=t;}catch(t){console.error("[VOT] Failed to load subtitles:",t),this.subtitles=[];}await this.updateSubtitlesLangSelect();}const De={tickMs:50,thresholdOnRms:.012,thresholdOffRms:.009,rmsAttackTauMs:60,rmsReleaseTauMs:240,holdMs:520,attackTauMs:110,releaseTauMs:600,maxDownPerSec:3.5,maxUpPerSec:.9,rmsMissingGraceMs:200,maxDtMs:250,externalBaselineDelta01:.02,unduckTolerance01:.01,volumeStep01:Ee,applyDeltaThreshold01:Ee/2};function Kn(e){return {isDucked:false,speechGateOpen:false,rmsEnvelope:0,baseline:zt(e),lastApplied:void 0,lastTickAt:0,lastSoundAt:0,rmsMissingSinceAt:null}}function Jg(){return Kn()}function Xg(e,t,n=De){const i=jg(t),o=zt(e.volumeOnStart);if(!e.translationActive||!e.enabledAutoVolume)return {kind:"stop",runtime:i,restoreVolume:i.baseline??o};const r=Number.isFinite(e.nowMs)?e.nowMs:Date.now(),s=i.lastTickAt||r,a=N(r-s,0,n.maxDtMs),l=a/1e3;i.lastTickAt=r;const c=vt(e.rms),d=c&&typeof e.rms=="number"?N(e.rms,0,1):0,u=N(i.rmsEnvelope,0,1),h=d>u?n.rmsAttackTauMs:n.rmsReleaseTauMs,m=h>0?1-Math.exp(-a/h):1;i.rmsEnvelope=N(u+(d-u)*m,0,1);let v=i.speechGateOpen;e.smartEnabled?e.audioIsPlaying&&!c?(i.rmsMissingSinceAt??=r,v&&(i.lastSoundAt=r),i.rmsMissingSinceAt!==null&&r-i.rmsMissingSinceAt>=n.rmsMissingGraceMs&&(v=true,i.lastSoundAt=r)):(i.rmsMissingSinceAt=null,v?e.audioIsPlaying&&i.rmsEnvelope>=n.thresholdOffRms?i.lastSoundAt=r:r-i.lastSoundAt>n.holdMs&&(v=false):e.audioIsPlaying&&i.rmsEnvelope>=n.thresholdOnRms&&(v=true,i.lastSoundAt=r)):(v=true,i.lastSoundAt=r,i.rmsMissingSinceAt=null),i.speechGateOpen=v;const b=zt(e.currentVideoVolume);if(!vt(b))return {kind:"noop",runtime:i};i.isDucked&&vt(i.lastApplied)&&Math.abs(b-i.lastApplied)>n.externalBaselineDelta01&&(i.baseline=b),i.isDucked||(i.baseline=b);const y=i.baseline??o??b;if(i.baseline=y,!e.hostVideoActive)return i.lastApplied=b,{kind:"noop",runtime:i};const k=zt(e.duckingTarget01)??y,x=Math.min(y,k);let A=y;v?(i.isDucked||(i.baseline=y,i.isDucked=true),A=x):i.isDucked&&Math.abs(y-b)0?1-Math.exp(-a/D):1;let $=b+(A-b)*Y;const St=(A0&&($=N($,b-St,b+St)),$=N($,0,1);const Ot=Zh($,b,A,n.volumeStep01);return !vt(i.lastApplied)||Math.abs(Ot-i.lastApplied)>=n.applyDeltaThreshold01?(i.lastApplied=Ot,{kind:"apply",runtime:i,volume01:Ot}):{kind:"noop",runtime:i}}function jg(e){return {isDucked:!!e.isDucked,speechGateOpen:!!e.speechGateOpen,rmsEnvelope:N(e.rmsEnvelope??0,0,1),baseline:zt(e.baseline),lastApplied:zt(e.lastApplied),lastTickAt:vt(e.lastTickAt)?e.lastTickAt:0,lastSoundAt:vt(e.lastSoundAt)?e.lastSoundAt:0,rmsMissingSinceAt:vt(e.rmsMissingSinceAt)?e.rmsMissingSinceAt:null}}function zt(e){if(vt(e))return N(e,0,1)}function vt(e){return typeof e=="number"&&Number.isFinite(e)}const Be=new WeakMap;function cn(e){if(!e||typeof e!="object")return false;const t=e;return typeof t.connect=="function"&&typeof t.disconnect=="function"}function Zg(e){return e?.audio??e?.audioElement}async function Vo(e){const t=e.audioPlayer?.audioContext;if(!t||t.state!=="suspended")return "not-needed";const n=1500,i=(async()=>{try{return await t.resume(),"resumed"}catch{return "failed"}})();let o;const r=new Promise(a=>{o=setTimeout(()=>a("timeout"),n);}),s=await Promise.race([i,r]);return o!==void 0&&clearTimeout(o),s}async function xe(e,t){if(!t||!e.audioPlayer)return;const n=e.audioPlayer.player,i=String(n.currentSrc||n.src||""),o=e.proxifyAudio(e.unproxifyAudio(i)),r=e.proxifyAudio(e.unproxifyAudio(t));if(o===r)try{await n.clear(),n.src="",E.log("[updateTranslation] cleared stale partially-applied source");}catch{}}function Qg(e){return e.audioPlayer?.audioContext??e.audioContext}function ps(e){if(e.connectedInputNode&&e.analyser)try{e.connectedInputNode.disconnect(e.analyser);}catch{}if(e.connectedInputNode=void 0,e.createdMediaSource)try{e.createdMediaSource.disconnect();}catch{}if(e.createdMediaSource=void 0,e.analyser)try{e.analyser.disconnect();}catch{}e.analyser=void 0,e.analyserFloatData=void 0,e.analyserData=void 0,e.mediaElement=void 0,e.audioContext=void 0,e.mediaSourceCreationFailed=false;}function tm(e){const t=Be.get(e);t&&(ps(t),Be.delete(e));}function em(e,t,n,i){if(cn(e?.gainNode))return e.gainNode;if(cn(e?.audioSource))return e.audioSource;if(cn(e?.mediaElementSource))return e.mediaElementSource;if(!(i.mediaSourceCreationFailed&&i.mediaElement===t&&i.audioContext===n)){if(i.createdMediaSource&&i.mediaElement===t&&i.audioContext===n)return i.createdMediaSource;try{const o=n.createMediaElementSource(t);return i.createdMediaSource=o,i.mediaSourceCreationFailed=!1,o}catch{i.mediaSourceCreationFailed=true;return}}}function nm(e,t,n){const i=Qg(e);if(!i)return;let o=Be.get(e);if(o||(o={},Be.set(e,o)),(o.mediaElement&&o.mediaElement!==n||o.audioContext&&o.audioContext!==i)&&ps(o),o.mediaElement=n,o.audioContext=i,!o.analyser){const a=i.createAnalyser();a.fftSize=512,o.analyser=a;}const r=em(t,n,i,o),s=o.analyser;if(!(!r||!s)){if(o.connectedInputNode!==r){if(o.connectedInputNode)try{o.connectedInputNode.disconnect(s);}catch{}try{r.connect(s),o.connectedInputNode=r;}catch{return}}return {analyser:s,state:o}}}function im(e){return {isDucked:e.smartVolumeIsDucked,speechGateOpen:e.smartVolumeSpeechGateOpen,rmsEnvelope:e.smartVolumeRmsEnvelope,baseline:e.smartVolumeDuckingBaseline,lastApplied:e.smartVolumeLastApplied,lastTickAt:e.smartVolumeLastTickAt,lastSoundAt:e.smartVolumeLastSoundAt,rmsMissingSinceAt:e.smartVolumeRmsMissingSinceAt}}function he(e,t){e.smartVolumeIsDucked=t.isDucked,e.smartVolumeSpeechGateOpen=t.speechGateOpen,e.smartVolumeRmsEnvelope=t.rmsEnvelope,e.smartVolumeDuckingBaseline=t.baseline,e.smartVolumeLastApplied=t.lastApplied,e.smartVolumeLastTickAt=t.lastTickAt,e.smartVolumeLastSoundAt=t.lastSoundAt,e.smartVolumeRmsMissingSinceAt=t.rmsMissingSinceAt;}function Yn(e,t={}){const{restoreVolume:n}=t;typeof e.smartVolumeDuckingInterval=="number"&&(clearInterval(e.smartVolumeDuckingInterval),e.smartVolumeDuckingInterval=void 0);const i=typeof n=="number"?n:e.smartVolumeDuckingBaseline??e.volumeOnStart;if(typeof i=="number"&&(typeof n=="number"||e.smartVolumeIsDucked))try{e.setVideoVolume(i);}catch{}tm(e),he(e,Jg());}function om(e){if(typeof globalThis>"u"||typeof e.smartVolumeDuckingInterval=="number")return;const t=e.getVideoVolume(),n=typeof e.smartVolumeDuckingBaseline=="number"?e.smartVolumeDuckingBaseline:t,i=Kn(n);if(Number.isFinite(t)&&Number.isFinite(n)&&t{sm(e);},De.tickMs);}function rm(e,t){const n=e.audioPlayer?.player,i=nm(e,n,t);if(!i)return;const{analyser:o,state:r}=i;try{if(typeof o.getFloatTimeDomainData=="function"){let l=r.analyserFloatData;l?.length!==o.fftSize&&(l=new Float32Array(o.fftSize),r.analyserFloatData=l),o.getFloatTimeDomainData(l);let c=0;for(const d of l)c+=d*d;return N(Math.sqrt(c/l.length),0,1)}let s=r.analyserData;s?.length!==o.fftSize&&(s=new Uint8Array(o.fftSize),r.analyserData=s),o.getByteTimeDomainData(s);let a=0;for(const l of s){const c=(l-128)/128;a+=c*c;}return N(Math.sqrt(a/s.length),0,1)}catch{return}}function sm(e){const t=e.audioPlayer?.player,n=Zg(t),i=!!e.data?.syncVolume,o=!!e.data?.enabledAutoVolume&&!i,r=(e.data?.enabledSmartDucking??true)&&!i;if(o&&!r){ms.call(e);return}const s=!!n&&!n.paused&&!n.muted&&(n.volume??1)>.001,a=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),l=e.getVideoVolume(),c=e.video,d=!(c&&(c.paused||c.ended)),u=N(e.data?.autoVolume??Fe,0,100)/100;e.smartVolumeDuckingTarget=u;const h=s&&n?rm(e,n):0,m=Xg({nowMs:a,translationActive:e.hasActiveSource(),enabledAutoVolume:o,smartEnabled:r,audioIsPlaying:s,rms:h,currentVideoVolume:l,hostVideoActive:d,duckingTarget01:u,volumeOnStart:e.volumeOnStart},im(e),De);switch(m.kind){case "stop":Yn(e,{restoreVolume:m.restoreVolume});return;case "apply":e.setVideoVolume(m.volume01),he(e,m.runtime);return;case "noop":he(e,m.runtime);return;default:throw new TypeError("Unhandled smart ducking decision")}}async function am(e,t){if(this.isActionStale(t))return e;try{const n=this.isMultiMethodS3(e)?{method:"HEAD"}:{headers:{range:"bytes=0-0"}},i=await tt(e,n);if(this.isActionStale(t))return e;if(E.log("Test audio response",i),i.ok)return E.log("Valid audioUrl",e),e;if(E.log("Yandex returned not valid audio, trying to fix..."),!this.videoData)return E.log("Skip audio fix - videoData is not available"),e;if(this.isActionStale(t))return e;const o=this.videoData.detectedLanguage||this.translateFromLang,r=await Vr(this.translationHandler,{videoData:this.videoData,requestLang:o,responseLang:this.translateToLang,translationHelp:this.videoData.translationHelp,useAudioDownload:!!this.data?.useAudioDownload,signal:this.actionsAbortController.signal});if(!r)return E.log("Failed to retranslate audio - using original url"),e;this.setSelectMenuValues(this.videoData.detectedLanguage,this.videoData.responseLanguage),this.scheduleTranslationRefresh(),e=r.url,E.log("Fixed audio audioUrl",e);}catch{}return e}function lm(){if(!this.videoData||this.videoData.isStream||!this.hasActiveSource())return;clearTimeout(this.translationRefreshTimeout);const e=Math.max(3e4,mn-300*1e3);this.translationRefreshTimeout=setTimeout(()=>{this.refreshTranslationAudio().catch(t=>{});},e);}async function gs(e,t){const n=await Ah({requester:e.translationHandler,request:{videoData:t.videoData,requestLang:t.requestLang,responseLang:t.responseLang,translationHelp:t.translationHelp,useAudioDownload:!!e.data?.useAudioDownload,signal:e.actionsAbortController.signal},actionContext:t.actionContext,isActionStale:i=>e.isActionStale(i),updateTranslation:(i,o)=>e.updateTranslation(i,o),scheduleTranslationRefresh:()=>e.scheduleTranslationRefresh()});return n?(t.onBeforeCache&&await t.onBeforeCache(n),Lh({cacheKey:t.cacheKey,setTranslation:(i,o)=>e.cacheManager.setTranslation(i,o),videoId:t.cacheVideoId,requestLang:t.cacheRequestLang,responseLang:t.cacheResponseLang,fallbackUrl:n.url,downloadTranslationUrl:e.downloadTranslationUrl,usedLivelyVoice:n.usedLivelyVoice}),n):null}async function cm(){if(!this.videoData||this.videoData.isStream||!this.hasActiveSource()||this.isRefreshingTranslation)return;const e=this.videoData.videoId;if(!e)return;this.actionsAbortController?.signal?.aborted&&this.resetActionsAbortController("refreshTranslationAudio"),this.isRefreshingTranslation=true;const t={gen:this.actionsGeneration,videoId:e},n=Fn(this.videoData.translationHelp);try{if(!await gs(this,{videoData:this.videoData,requestLang:this.translateFromLang,responseLang:this.translateToLang,translationHelp:n,actionContext:t,cacheKey:this.getTranslationCacheKey(e,this.translateFromLang,this.translateToLang,n),cacheVideoId:e,cacheRequestLang:this.translateFromLang,cacheResponseLang:this.translateToLang}))return}finally{this.isRefreshingTranslation=false;}}function dm(e){return Dg(e,{translateProxyEnabled:this.data?.translateProxyEnabled,proxyWorkerHost:this.data?.proxyWorkerHost})}function um(e){return Bg(e)}async function hm(e="proxySettingsChanged"){try{this.cacheManager.clear(),this.activeTranslation=null;}catch{}try{await this.stopTranslation();}catch{}}function fm(e){return Rg(e,{proxyWorkerHost:this.data?.proxyWorkerHost})}async function pm(e,t){if(await this.waitForPendingStopTranslate(),this.isActionStale(t))return;this.audioPlayer||this.createPlayer(),this.audioPlayer.audioContext?.state==="closed"&&this.createPlayer();const n=this.proxifyAudio(this.unproxifyAudio(e)),i=this.audioPlayer.player.currentSrc||this.audioPlayer.player.src||"",o=this.proxifyAudio(this.unproxifyAudio(i));let r=n;if(n!==o&&(r=await this.validateAudioUrl(n,t)),this.isActionStale(t))return;const s=this.audioPlayer.player.src!==r;let a=null;s&&(this.audioPlayer.player.src=r,a=r);let l;try{if(s&&await this.audioPlayer.init(),this.isActionStale(t)){await xe(this,a);return}const c=await Vo(this);if(c==="timeout"?E.log("[updateTranslation] continuing after AudioContext resume timeout"):c==="failed"&&E.log("[updateTranslation] AudioContext resume failed, continue without deferred resume"),this.isActionStale(t)){await xe(this,a);return}!this.video.paused&&this.audioPlayer.player.src&&this.audioPlayer.player.lipSync("play");}catch(c){l=c;}if(l&&s&&!this.isActionStale(t)){const c=this.unproxifyAudio(r);if(c!==r)try{E.log("[updateTranslation] proxied audio init failed, retrying direct URL");const d=await this.validateAudioUrl(c,t);if(this.isActionStale(t)){await xe(this,a);return}this.audioPlayer.player.src=d,a=d,r=d,await this.audioPlayer.init();const u=await Vo(this);(u==="timeout"||u==="failed")&&E.log("[updateTranslation] AudioContext not resumed after direct URL fallback",u),!this.video.paused&&this.audioPlayer.player.src&&this.audioPlayer.player.lipSync("play"),l=void 0;}catch(d){l=d;}}if(l){await xe(this,a);const c=l instanceof Error?l.message:String(l);this.transformBtn("error",c);return}this.setupAudioSettings(),this.transformBtn("success",p.get("disableTranslate")),this.afterUpdateTranslation(r);}async function gm(e,t,n,i,o){await this.waitForPendingStopTranslate(),await this.videoValidator(),this.actionsAbortController?.signal?.aborted&&this.resetActionsAbortController("translateFunc");const r=this.uiManager.votOverlayView;if(!r?.votButton)return;if(r.votButton.loading=true,this.hadAsyncWait=false,this.volumeOnStart=this.getVideoVolume(),!e){await this.updateTranslationErrorMsg(new it("VOTNoVideoIDFound"),this.actionsAbortController.signal);return}const s=this.videoData;if(!s){await this.updateTranslationErrorMsg(new it("VOTNoVideoIDFound"),this.actionsAbortController.signal);return}const a=Fn(o),l=this.getTranslationCacheKey(e,n,i,a),c=`video_${l}`;if(this.activeTranslation?.key===c){await this.activeTranslation.promise;return}const d={gen:this.actionsGeneration,videoId:e},u=(async()=>{if(this.isActionStale(d))return;const h=n,m=i,v=async k=>await Mr({url:k,actionContext:d,isActionStale:x=>this.isActionStale(x),updateTranslation:(x,A)=>this.updateTranslation(x,A),scheduleTranslationRefresh:()=>this.scheduleTranslationRefresh()}),b=this.cacheManager.getTranslation(l);if(b?.url)return await v(b.url),void 0;await gs(this,{videoData:s,requestLang:h,responseLang:m,translationHelp:a,actionContext:d,cacheKey:l,cacheVideoId:e,cacheRequestLang:n,cacheResponseLang:i,onBeforeCache:async()=>{const k=this.videoData?this.getSubtitlesCacheKey(e,this.videoData.detectedLanguage,this.videoData.responseLanguage):null;(k?this.cacheManager.getSubtitles(k):null)?.some(A=>A.source==="yandex"&&A.translatedFromLanguage===s.detectedLanguage&&A.language===s.responseLanguage)||(k&&this.cacheManager.deleteSubtitles(k),this.subtitles=[]);}});})();this.activeTranslation={key:c,promise:u};try{return await u}catch(h){throw this.hadAsyncWait=_r({aborted:this.actionsAbortController.signal.aborted,translateApiErrorsEnabled:!!this.data?.translateAPIErrors,hadAsyncWait:this.hadAsyncWait,videoId:e,error:h,notify:m=>this.notifier.translationFailed(m)}),h}finally{this.activeTranslation?.promise===u&&(this.activeTranslation=null);const h=this.uiManager.votOverlayView?.votButton;!this.activeTranslation&&h?.loading&&!this.hasActiveSource()&&this.transformBtn("none",p.get("translateVideo"));}}function mm(){return of(this.site.host)}function ms(){typeof this.data?.defaultVolume=="number"&&(this.audioPlayer.player.volume=this.data.defaultVolume/100);const e=!!this.data?.enabledAutoVolume&&!this.data?.syncVolume,t=this.data?.enabledSmartDucking??true;if(!e){Yn(this,{restoreVolume:this.smartVolumeDuckingBaseline??this.volumeOnStart});return}const n=N(this.data.autoVolume??Fe,0,100)/100;if(this.smartVolumeDuckingTarget=n,!this.hasActiveSource())return;if(t){om(this);return}typeof this.smartVolumeDuckingInterval=="number"&&(clearInterval(this.smartVolumeDuckingInterval),this.smartVolumeDuckingInterval=void 0),typeof this.smartVolumeDuckingBaseline!="number"&&(this.smartVolumeDuckingBaseline=this.getVideoVolume());const i=this.smartVolumeDuckingBaseline??this.getVideoVolume();this.setVideoVolume(Math.min(i,n)),he(this,Kn(this.smartVolumeDuckingBaseline)),this.smartVolumeIsDucked=true;}const vm=new Set(In),bm=e=>vm.has(e);class ym{video;container;site;translateFromLang="auto";translateToLang=Te;data;videoData;firstPlay=true;audioContext;votClient;audioPlayer;abortController;actionsAbortController;actionsGeneration=0;notifier=new Fp;cacheManager;subtitlesLoadPromises=new Map;downloadTranslationUrl=null;translationRefreshTimeout;isRefreshingTranslation=false;autoRetry;votOpts;volumeOnStart;volumeLinkState={initialized:false,lastVideoPercent:0,lastTranslationPercent:0};internalVideoVolumeSetAt=0;internalVideoVolumeSetPercent=null;internalVideoVolumeSuppressionMs=250;internalVideoVolumeSetHistory=[];internalVideoVolumeSetHistoryLimit=48;smartVolumeDuckingInterval;smartVolumeDuckingTarget=.2;smartVolumeDuckingBaseline;smartVolumeLastApplied;smartVolumeLastTickAt=0;smartVolumeLastSoundAt=0;smartVolumeRmsMissingSinceAt=null;smartVolumeRmsEnvelope=0;smartVolumeSpeechGateOpen=false;smartVolumeIsDucked=false;longWaitingResCount=0;hadAsyncWait=false;subtitles=[];subtitlesWidget;activeTranslation=null;stopTranslatePromise=null;interactionChecker;uiManager;overlayVisibility;overlayVisibilityTargetsAbortController;translationOrchestrator;lifecycleController;translationHandler;videoManager;yandexSubtitles=null;resizeObserver;syncVolumeObserver;initialized=false;mountCache;errorTranslationCache=new Map;getOverlayMountPoints(t=this.container){const n=this.site.host==="youtube"&&this.site.additionalData!=="mobile"?t.parentElement??t:t,i=this.mountCache;if(i?.container===t&&i.base===n&&(i.root.isConnected??document.documentElement.contains(i.root)))return {root:i.root,portalContainer:i.portalContainer};const o=th(n),r=o;return this.mountCache={container:t,base:n,root:o,portalContainer:r},{root:o,portalContainer:r}}getOverlayMount(t=this.container){const{root:n,portalContainer:i}=this.getOverlayMountPoints(t);return {root:n,portalContainer:i,tooltipLayoutRoot:this.tooltipLayoutRoot}}getTranslationCacheKey(t,n,i,o){const r=this.getRequestLangForTranslation(n,i),s=this.isLivelyVoiceAllowed(r,i)&&this.data?.useLivelyVoice,a=o==null?"":Mc(o),l=a?_c(a):"0";return `${t}_${r}_${i}_${s}_${l}`}getSubtitlesCacheKey(t,n,i){return `${t}_${n}_${i}_${!!this.data?.useLivelyVoice}`}isActionStale(t){return t?this.actionsGeneration!==t.gen||this.videoData?.videoId!==t.videoId:false}resetActionsAbortController(t){try{this.actionsAbortController?.abort(t);}catch{}this.actionsAbortController=new AbortController,this.actionsGeneration++,this.data&&this.initVOTClient();}constructor(t,n,i){this.video=t,this.container=n,this.site=i,this.abortController=new AbortController,this.actionsAbortController=new AbortController,this.cacheManager=new Zu,this.interactionChecker=zn(),this.interactionChecker.start();const o=()=>this,r=this.getOverlayMount(n);this.uiManager=new Ep({mount:r,data:this.data,videoHandler:this,intervalIdleChecker:this.interactionChecker}),this.overlayVisibility=new Vp({checker:this.interactionChecker,getOverlayView:()=>this.uiManager.votOverlayView??null,getAutoHideDelay:()=>this.getAutoHideDelay(),isInteractiveNode:a=>this.isOverlayInteractiveNode(a)}),this.translationOrchestrator=new Eh({isFirstPlay:()=>this.firstPlay,setFirstPlay:a=>{this.firstPlay=a;},isAutoTranslateEnabled:()=>!!this.data?.autoTranslate,getVideoId:()=>this.videoData?.videoId,scheduleAutoTranslate:()=>this.runAutoTranslate(),isMobileYouTubeMuted:()=>this.site.host==="youtube"&&this.site.additionalData==="mobile"&&this.video.muted,setMuteWatcher:a=>{let l=false;const c=()=>{l||(l=true,this.video.removeEventListener("volumechange",d),a());},d=()=>{this.video.muted||c();};this.video.addEventListener("volumechange",d,{signal:this.abortController.signal}),queueMicrotask(()=>{this.video.muted||c();});}});const s={get video(){return o().video},get site(){return o().site},get container(){return o().container},set container(a){o().container=a,o().uiManager.updateMount(o().getOverlayMount(a));},get firstPlay(){return o().firstPlay},set firstPlay(a){o().firstPlay=a;},stopTranslation:()=>this.stopTranslation(),get uiManager(){return o().uiManager},getVideoData:()=>this.getVideoData(),cacheManager:{getSubtitles:a=>o().cacheManager.getSubtitles(a)??[]},getSubtitlesCacheKey:(a,l,c)=>this.getSubtitlesCacheKey(a,l,c),updateSubtitlesLangSelect:()=>this.updateSubtitlesLangSelect(),enableSubtitlesForCurrentLangPair:()=>this.enableSubtitlesForCurrentLangPair(),setSelectMenuValues:(a,l)=>this.setSelectMenuValues(a,l),get translateToLang(){return o().translateToLang},set translateToLang(a){bm(a)&&(o().translateToLang=a);},get data(){return o().data??{}},get subtitles(){return o().subtitles},set subtitles(a){o().subtitles=a;},get videoData(){return o().videoData},set videoData(a){o().videoData=a;},get actionsAbortController(){return o().actionsAbortController},set actionsAbortController(a){o().actionsAbortController=a;},resetActionsAbortController:a=>this.resetActionsAbortController(a),initVOTClient:()=>this.initVOTClient(),translationOrchestrator:this.translationOrchestrator,resetSubtitlesWidget:()=>this.resetSubtitlesWidget(),queueOverlayAutoHide:()=>this.overlayVisibility?.queueAutoHide()};this.lifecycleController=new Mh(s),this.translationHandler=new Ch(this),this.videoManager=new df(this);}getSubtitlesWidget(){if(!this.subtitlesWidget){const t=this.uiManager.votOverlayView?.votOverlayPortal;if(!t)throw new Error("VOT UI is not initialized yet (missing overlay portal)");this.subtitlesWidget=new jf(this.video,this.portalContainer,t,this.interactionChecker,this.tooltipLayoutRoot),this.data&&(this.subtitlesWidget.setSmartLayout(typeof this.data.subtitlesSmartLayout=="boolean"?this.data.subtitlesSmartLayout:true),typeof this.data.subtitlesMaxLength=="number"&&this.subtitlesWidget.setMaxLength(this.data.subtitlesMaxLength),typeof this.data.highlightWords=="boolean"&&this.subtitlesWidget.setHighlightWords(this.data.highlightWords),typeof this.data.subtitlesFontSize=="number"&&this.subtitlesWidget.setFontSize(this.data.subtitlesFontSize),typeof this.data.subtitlesOpacity=="number"&&this.subtitlesWidget.setOpacity(this.data.subtitlesOpacity));}return this.subtitlesWidget}hasSubtitlesWidget(){return !!this.subtitlesWidget}resetSubtitlesWidget(){this.hasSubtitlesWidget()&&(this.subtitlesWidget?.release(),this.subtitlesWidget=void 0);}get uiRoot(){return this.getOverlayMountPoints().root}get portalContainer(){return this.getOverlayMountPoints().portalContainer}get tooltipLayoutRoot(){switch(this.site.host){case "kickstarter":return document.getElementById("react-project-header")??void 0;case "custom":return;default:return this.container}}getEventContainer(){return this.site.eventSelector?document.querySelector(this.site.eventSelector)??this.container:this.container}async runAutoTranslate(){await this.videoManager.videoValidator(),await this.uiManager.handleTranslationBtnClick();}getAudioContext(){if(this.audioContext)return this.audioContext;if(this.isAudioContextSupported)try{return this.audioContext=Vn(),this.audioContext}catch(t){console.warn("[VOT] Failed to init AudioContext, falling back:",t);return}}get isAudioContextSupported(){return globalThis.AudioContext!==void 0||globalThis.webkitAudioContext!==void 0}getPreferAudio(){return !this.getAudioContext()||!this.data||!this.data.newAudioPlayer||this.videoData?.isStream?true:this.data.newAudioPlayer&&!this.data.onlyBypassMediaCSP?false:!this.site.needBypassCSP}createPlayer(){const t=this.getPreferAudio();return this.audioPlayer=new ql({video:this.video,debug:false,fetchFn:tt,fetchOpts:{timeout:0},preferAudio:t}),this}isLikelyInternalVideoVolumeChange(t){const n=Date.now();if(this.internalVideoVolumeSetHistory.length>0){this.internalVideoVolumeSetHistory=this.internalVideoVolumeSetHistory.filter(o=>n-o.at<=o.suppressMs);for(const o of this.internalVideoVolumeSetHistory)if(Math.abs(t-o.percent)<=1)return true;return false}return this.internalVideoVolumeSetPercent===null||n-this.internalVideoVolumeSetAt>this.internalVideoVolumeSuppressionMs?false:Math.abs(t-this.internalVideoVolumeSetPercent)<=1}callModule(t,...n){return t.call(this,...n)}async callModuleAsync(t,...n){return await t.call(this,...n)}async init(){return await og.call(this)}initVOTClient(){return this.votOpts={fetchFn:tt,fetchOpts:{signal:this.actionsAbortController.signal},apiToken:this.data?.account?.token,hostVOT:kc,host:this.data?.translateProxyEnabled?this.data?.proxyWorkerHost??ie:yc},this.votClient=new(this.data?.translateProxyEnabled?fa:ha)(this.votOpts),this}transformBtn(t,n){return this.uiManager.transformBtn(t,n),this}hasActiveSource(){return !!this.audioPlayer?.player?.src}initExtraEvents(){return this.callModule(jp)}rebindOverlayVisibilityTargets=Zp;setCanPlay(){return this.lifecycleController.setCanPlay()}isOverlayInteractiveNode(t){return this.callModule(Qp,t)}getAutoHideDelay(){return this.callModule(tg)}changeSubtitlesLang=zg;updateSubtitlesLangSelect=qg;loadSubtitles=Yg;async enableSubtitlesForCurrentLangPair(){return await this.callModuleAsync(Gg)}async toggleSubtitlesForCurrentLangPair(){return await this.callModuleAsync(Kg)}getRequestLangForTranslation(t,n){return this.data?.useLivelyVoice&&this.data?.account?.token&&n==="ru"?"en":t}isLivelyVoiceAllowed(t=this.videoData?.detectedLanguage??"auto",n=this.videoData?.responseLanguage??this.translateToLang){return !(this.getRequestLangForTranslation(t,n)!=="en"||n!=="ru"||!this.data?.account?.token)}getVideoVolume(){return this.videoManager.getVideoVolume()}setVideoVolume(t,n={}){const i=Et(t),o=typeof n.suppressSyncMs=="number"&&Number.isFinite(n.suppressSyncMs)?Math.max(0,n.suppressSyncMs):this.internalVideoVolumeSuppressionMs,r=Date.now(),s=Nr(i);return this.internalVideoVolumeSetAt=r,this.internalVideoVolumeSetPercent=s,this.internalVideoVolumeSetHistory.push({at:r,percent:s,suppressMs:o}),this.internalVideoVolumeSetHistory.length>this.internalVideoVolumeSetHistoryLimit&&this.internalVideoVolumeSetHistory.splice(0,this.internalVideoVolumeSetHistory.length-this.internalVideoVolumeSetHistoryLimit),this.videoManager.setVideoVolume(i),this}onVideoVolumeSliderSynced(t){const n=dt(t);if(!this.volumeLinkState.initialized){rn(this.volumeLinkState,n);return}this.data?.syncVolume&&this.hasActiveSource()&&!this.isLikelyInternalVideoVolumeChange(n)||rn(this.volumeLinkState,n);}onTranslationVolumeSliderSynced(t){if(!this.volumeLinkState.initialized){sn(this.volumeLinkState,t);return}sn(this.volumeLinkState,t);}resetVolumeLinkState(t,n){rn(this.volumeLinkState,t),sn(this.volumeLinkState,n),this.volumeLinkState.initialized=true;}isMuted(){return this.videoManager.isMuted()}syncVideoVolumeSlider(){this.videoManager.syncVideoVolumeSlider();}setSelectMenuValues(t,n){this.videoManager.setSelectMenuValues(t,n);}syncVolumeWrapper(t,n){const i=this.uiManager.votOverlayView;if(!i?.isInitialized())return;const o=i.videoVolumeSlider,r=i.translationVolumeSlider;if(!o||!r)return;const{nextVideo:s,nextTranslation:a}=Wp({state:this.volumeLinkState,fromType:t,newVolume:n,currentVideo:Number(o.value),currentTranslation:Number(r.value),translationMin:r.min,translationMax:r.max});if(typeof a=="number"){r.value=a,this.audioPlayer?.player&&(this.audioPlayer.player.volume=a/100);return}typeof s=="number"&&(o.value=s,this.setVideoVolume(s/100));}async getVideoData(){return await this.videoManager.getVideoData()}async videoValidator(){return await this.videoManager.videoValidator()}stopTranslate(){if(this.stopTranslatePromise)return this.stopTranslatePromise;const n=(async()=>{if(this.audioPlayer?.player){try{this.audioPlayer.player.removeVideoEvents(),this.audioPlayer.player.src="",await this.audioPlayer.player.clear();}catch{}E.log("audioPlayer after stopTranslate",this.audioPlayer);}this.activeTranslation=null;const i=this.uiManager.votOverlayView;i&&(i.videoVolumeSlider&&(i.videoVolumeSlider.hidden=true),i.translationVolumeSlider&&(i.translationVolumeSlider.hidden=true),i.downloadTranslationButton&&(i.downloadTranslationButton.hidden=true)),this.downloadTranslationUrl=null,this.longWaitingResCount=0,this.hadAsyncWait=false,this.transformBtn("none",p.get("translateVideo")),E.log(`Volume on start: ${this.volumeOnStart}`);const o=typeof this.smartVolumeDuckingBaseline=="number"?this.smartVolumeDuckingBaseline:this.volumeOnStart;Yn(this,{restoreVolume:o}),this.volumeOnStart=void 0,this.autoRetry!==void 0&&(clearTimeout(this.autoRetry),this.autoRetry=void 0),this.translationRefreshTimeout!==void 0&&(clearTimeout(this.translationRefreshTimeout),this.translationRefreshTimeout=void 0),this.resetActionsAbortController("stopTranslate");})().finally(()=>{this.stopTranslatePromise===n&&(this.stopTranslatePromise=null);});return this.stopTranslatePromise=n,n}waitForPendingStopTranslate(){return this.stopTranslatePromise??Promise.resolve()}async updateTranslationErrorMsg(t,n){if(n?.aborted)return;const i=p.get("translationTake"),o=p.lang;if(this.longWaitingResCount=t===p.get("translationTakeAboutMinute")?this.longWaitingResCount+1:0,E.log("longWaitingResCount",this.longWaitingResCount),this.longWaitingResCount>Ac&&(t=new it("TranslationDelayed")),t?.name==="VOTLocalizedError")this.transformBtn("error",t.localizedMessage);else if(t instanceof Error)this.transformBtn("error",t?.message);else if(this.data?.translateAPIErrors&&o!=="ru"&&!t?.includes(i)){const r=this.uiManager.votOverlayView;if(!r?.votButton)return;const s=Array.isArray(t)?t.join(" "):String(t),a=`${o}:${s}`,l=this.errorTranslationCache.get(a);if(l)this.transformBtn("error",l);else {r.votButton.loading=true;const c=await bn(s,"ru",o),d=Array.isArray(c)?c.join(` `):String(c);if(n?.aborted)return;if(this.errorTranslationCache.set(a,d),this.errorTranslationCache.size>50){const u=this.errorTranslationCache.keys().next().value;u&&this.errorTranslationCache.delete(u);}this.transformBtn("error",d);}if(n?.aborted)return}else {const r=Array.isArray(t)?t.join(` `):String(t??"");this.transformBtn("error",r);}n?.aborted||["Подготавливаем перевод","Видео передано в обработку","Ожидаем перевод видео","Загружаем переведенное аудио"].includes(t)&&this.uiManager.votOverlayView?.votButton&&(this.uiManager.votOverlayView.votButton.loading=true);}afterUpdateTranslation(t){const n=this.uiManager.votOverlayView;if(!n?.votButton)return;const i=n.votButton.container.dataset.status==="success";n.videoVolumeSlider&&(n.videoVolumeSlider.hidden=!this.data?.showVideoSlider||!i),n.translationVolumeSlider&&(n.translationVolumeSlider.hidden=!i),n.videoVolumeSlider&&n.translationVolumeSlider?(this.volumeLinkState.lastVideoPercent=Number(n.videoVolumeSlider.value),this.volumeLinkState.lastTranslationPercent=Number(n.translationVolumeSlider.value),this.volumeLinkState.initialized=true):this.volumeLinkState.initialized=false,this.videoData&&!this.videoData.isStream&&(n.downloadTranslationButton&&(n.downloadTranslationButton.hidden=false),this.downloadTranslationUrl=t),E.log("afterUpdateTranslation downloadTranslationUrl",this.downloadTranslationUrl),this.data?.sendNotifyOnComplete&&this.hadAsyncWait&&i&&(this.notifier.translationCompleted(globalThis.location.hostname),this.hadAsyncWait=false);}async validateAudioUrl(t,n){return await this.callModuleAsync(am,t,n)}scheduleTranslationRefresh(){this.callModule(lm);}refreshTranslationAudio=cm;proxifyAudio(t){return this.callModule(dm,t)}unproxifyAudio(t){return this.callModule(um,t)}handleProxySettingsChanged=hm;isMultiMethodS3(t){return this.callModule(fm,t)}updateTranslation=pm;async translateFunc(t,n,i,o,r){return await gm.call(this,t,n,i,o,r)}isYouTubeHosts(){return this.callModule(mm)}setupAudioSettings(){return this.callModule(ms)}stopTranslation=async()=>{this.translationOrchestrator?.reset(),this.overlayVisibility?.cancel(),await this.stopTranslate(),this.syncVideoVolumeSlider();};handleSrcChanged(){return this.lifecycleController.handleSrcChanged()}async release(){this.initialized=false;try{await this.stopTranslation();}catch{}this.lifecycleController?.teardown(),this.abortController?.abort(),this.abortController=new AbortController,this.overlayVisibility?.release(),this.releaseExtraEvents(),this.hasSubtitlesWidget()&&(this.subtitlesWidget?.release(),this.subtitlesWidget=void 0),this.interactionChecker?.destroy(),this.uiManager.release();}collectReportInfo(){const t=os(),n=this.videoData?.detectedLanguage??"unknown",i=this.videoData?.responseLanguage??"unknown",o=`
Autogenerated by VOT:
  • OS: ${t.os}
  • Browser: ${t.browser}
  • Loader: ${t.loader}
  • Script version: ${t.scriptVersion}
  • URL: ${t.url}
  • Lang: ${n} -> ${i} (Lively voice: ${this.data?.useLivelyVoice??false} | Audio download: ${this.data?.useAudioDownload??false})
  • Player: ${this.data?.newAudioPlayer?"New":"Old"} (CSP only: ${this.data?.onlyBypassMediaCSP??false})
  • Proxying mode: ${this.data?.translateProxyEnabled??0}
`;return {assignees:"ilyhalight",template:`1-bug-report-${p.lang==="ru"?"ru":"en"}.yml`,os:t.os,"script-version":t.scriptVersion,"additional-info":o}}releaseExtraEvents=eg}const wm=zn(),Mo=new Ut(wm),km=new WeakMap;let dn=null;const ht=bc();function xm(){return {frame:On()?"iframe":"top",host:globalThis.location.hostname||"unknown",path:globalThis.location.pathname||"/"}}function At(e,t){const n=xm(),i={host:n.host,path:n.path};t&&Object.assign(i,t),console.log(`[VOT][bootstrap][${n.frame}] ${e}`,i);}function Sm(){return dn||(dn=$l()),dn}function Tm(e,t){if(!e.selector)return t.parentElement;const n=Ir(t,e.selector);return e.shadowRoot,n||null}async function Am(){const e=ju({isIframe:On(),href:String(globalThis.location.href||""),origin:globalThis.location.origin,hash:globalThis.location.hash,iframeHash:_n});if(e==="iframe-helper")return At("Starting iframe helper runtime"),pc();if(e==="skip"){At("Skipping bootstrap for non-runnable iframe");return}At("Loading extension"),e==="top-full"?await Ji("top-frame",At):At("Lazy iframe bootstrap enabled; waiting for video detection"),Ju({videoObserver:Mo,videosWrappers:km,ensureRuntimeActivated:async t=>await Ji(t,At),getServicesCached:Sm,findContainer:Tm,createVideoHandler:(t,n,i)=>new ym(t,n,i)}),Mo.enable();}if(ht.status==="booting"||ht.status==="booted")At("bootstrap already initialized, skipping duplicate run",{status:ht.status});else {const e=async()=>{try{await Am(),ht.status="booted";}catch(t){ht.status="failed",ht.error=t,console.error("[VOT]",t);}};ht.status="booting",ht.promise=e();} }) }; })); System.register("./__vite-browser-external-BIHI7g3E-DUmwvnCo.js", [], (function (exports, module) { 'use strict'; return { execute: (function () { const e=exports("default", {}); }) }; })); System.import("./__entry.js", "./");