@vkontakte/videoplayer-statistics 1.0.109-dev.c64982d44.0 → 1.0.109-dev.c8b4dec46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs +3 -3
- package/es2015.esm.js +3 -3
- package/esnext.cjs +3 -3
- package/esnext.esm.js +3 -3
- package/evergreen.esm.js +3 -3
- package/package.json +3 -3
package/es2015.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.109-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.109-dev.c8b4dec46.0
|
|
3
|
+
* Tue, 16 Jun 2026 15:56:54 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-109/doc/
|
|
5
5
|
*/
|
|
6
|
-
import e from"@oxc-project/runtime/helpers/defineProperty";import t from"@oxc-project/runtime/helpers/objectSpread2";import n from"@oxc-project/runtime/helpers/asyncToGenerator";var r=Object.defineProperty,i=e=>e;function a(e,t){this[e]=i.bind(null,t)}var o=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0,configurable:!0,set:a.bind(t,n)})};import{arrayIncludes as s}from"@vkontakte/videoplayer-shared/es2015";import{urlCanParsePolyfilled as c}from"@vkontakte/videoplayer-shared/es2015";var l;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(l||={});var u;(e=>{e.Q144P=`mobile`,e.Q240P=`lowest`,e.Q360P=`low`,e.Q480P=`medium`,e.Q720P=`high`,e.Q1080P=`fullhd`,e.Q1440P=`quadhd`,e.Q2160P=`ultrahd`,e.UNKNOWN=`unknown`})(u||={});var d;(e=>{e.MP4=`mp4`,e.DASH=`dash`,e.DASH_SEP=`dash_sep`,e.ONDEMAND_DASH=`ondemand_dash`,e.HLS=`hls`,e.HLS_FMP4=`hls_fmp4`,e.ONDEMAND_HLS=`ondemand_hls`,e.WEBM=`webm`,e.AV1=`av1`,e.ONDEMAND_DASH_LIVE=`ondemand_dash_live`,e.ONDEMAND_HLS_LIVE=`ondemand_hls_live`,e.WEBRTC=`webrtc`,e.UNKNOWN=`unknown`,e.RTMP=`rtmp`})(d||={});var f;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(f||={});var p;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(p||={});var m;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(m||={});var h={action_play:`ap`,action_play_interactive:`api`,first_bytes:`fb`,player_ready:`pr`,first_frame:`ff`,seek:`sk`,watch_coverage_record:`wr`,watch_coverage_live:`wl`,empty_buffer:`eb`,action_stop:`as`,close_at_empty_buffer:`cb`,content_error:`er`,player_interface_click:`pc`,next_movie:`nm`,track_switch:`ts`,failover:`fo`,quality:`qt`},g={vsid:`si`,isid:`is`,vid:`vi`,place:`pl`,quality:`qt`,cdn_host:`ch`,stat_type:`st`,param:`pm`,vk_app_id:`va`,track_code:`tc`,connection_type:`cnt`,connection_reused:`cr`,cached_data:`cd`,live:`lv`,muted:`mu`,mode:`mo`,subtitles:`sb`,failover:`fo`,download_speed:`ds`,manual_quality:`mq`,ref_domain:`rd`,direct_url:`du`},ee={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},_={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`};import{fillWithDefault as v}from"@vkontakte/videoplayer-shared/es2015";var y=`CIOPGQJGDIHBABABA`,b={prod:`https://api.ok.ru`,vk_alias:`https://api.mycdn.me`,videotest:`https://videotestapi.ok.ru/api`,test:`https://apitest.ok.ru`,okcdn:`https://api.okcdn.ru`,auto:``},te={apiEnv:`vk_alias`,apiKey:y,apiBaseUrl:null,apiForticom:!0,apiUvRest:!1,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*60*1e3,watchCoverageInterval:15e3,disabledOperations:[`quality`],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,clearStorageAtUnload:!0,useVKComIsMobileLogic:!1,backoff:{start:1e3,factor:1.5,max:300*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!0,watchCoverageExactTime:!1},x=e=>v(e,te);function ne(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}import{assertNonNullable as re,combine as ie,fromEvent as ae,isNonNullable as S,isNullable as oe,merge as se,now as C,observableFrom as ce,once as le,safeStorage as ue,Subject as de,Subscription as fe,ValueSubject as pe,getWindow as me}from"@vkontakte/videoplayer-shared/es2015";import{Logger as he,detectEmbed as ge,ErrorCategory as _e}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as ve}from"@vkontakte/videoplayer-shared/es2015";var ye=()=>ve(Math.floor(Math.random()*2**32).toString(36),13,`0`),be=()=>ve(Math.floor(Math.random()*2**64).toString(36),13,`0`);class w{static getVSID(){return w.vsid}static generateVSID(e){return w.vsid=e?be():ye(),w.vsid}}e(w,`vsid`,void 0);import{promiseFinally as xe}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Se}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as Ce}from"@vkontakte/videoplayer-shared/es2015";var we=e=>{let{operation:n,custom:r}=e,i=Ce(Se(r).map(([e,t])=>{let n=g[e]??e,r=t;return t&&(e===`mode`?r=_[t]??t:e===`quality`&&(r=ee[t]??t)),[n,r]}));return t(t({},e),{},{operation:h[n]??n,custom:i})},T=`1.0.109-dev.c64982d44.0`;import{ValueSubject as Te,getExponentialDelay as Ee,ErrorCategory as E,getWindow as De}from"@vkontakte/videoplayer-shared/es2015";var Oe=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class ke{constructor(t){e(this,`id`,`forticom`),e(this,`params`,void 0),e(this,`authToken`,void 0),e(this,`sessionKey`,void 0),e(this,`authorizePromise`,void 0),e(this,`refreshAuthTokenPromise`,void 0),e(this,`consequentAuthErrors`,0),e(this,`authorized$`,new Te(!1)),e(this,`backoffTimeoutId`,void 0),this.params=t}authorize(e){var t=this;return n(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t._authorizeWithBackoff()})()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return n(function*(){let r=`log.externalLog`,i=t.createLogParams(e),a=t.sessionKey??(yield t._authorizeWithBackoff());if(!a)return;let o=function(){var e=n(function*(e,n=t.params.config.requestRetryCount){try{return yield t.params.apiTransport.sendRequest(r,i,a)}catch(i){if(!i||!(`error_code`in i)){t.params.error$.next({id:`logRequestUnknown`,category:E.NETWORK,message:`Unknown ${r} error`,thrown:i});return}let a=i?.error_code;switch(a){case 102:case 103:case 104:return t.authorized$.next(!1),t.sessionKey=yield t._authorizeWithBackoff(),n>0?o(e,n-1):void 0;case 401:return t.authorized$.next(!1),t.authToken=yield t.refreshAuthToken(),t.sessionKey=yield t._authorizeWithBackoff(),n>0?o(e,n-1):void 0;default:t.params.error$.next({id:`LogRequest#${a}`,category:E.EXTERNAL_API,message:`${r} error`,data:i});return}}});return function(t){return e.apply(this,arguments)}}();return o(e)})()}destroy(){De().clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return n(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=xe(e.params.refreshAuthToken(),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${T}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=De().navigator;n=Oe.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(we):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ee(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=De().setTimeout(()=>{xe(this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:E.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})),()=>this.backoffTimeoutId=0)},e)})}_authorize(){var e=this;return n(function*(){if(e.authorizePromise)return e.authorizePromise;e.sessionKey=void 0,e.authorized$.next(!1);let t={session_data:{version:2,device_id:e.params.deviceId,client_version:T.split(`-`)[0],client_type:`SDK_JS`}};return e.authToken!==void 0&&(t.session_data.auth_token=e.authToken,t.session_data.version=3),e.authorizePromise=xe(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>((!t||!t.session_key)&&e.params.error$.next({id:`AuthorizeFailed`,category:E.EXTERNAL_API,message:`No session key`,data:t}),e.sessionKey=t?.session_key??void 0,e.sessionKey)).catch(function(){var t=n(function*(t){e.sessionKey=void 0;let n=t?.error_code;switch(n){case 401:return e.authToken=yield e.refreshAuthToken(),e._authorizeWithBackoff()}n?e.params.error$.next({id:`Authorize#${n}`,category:E.EXTERNAL_API,message:`authorize error`,data:t}):e.params.error$.next({id:`AuthorizeUnknown`,category:E.NETWORK,message:`authorize error`,thrown:t})});return function(e){return t.apply(this,arguments)}}()),()=>{e.authorizePromise=void 0,e.consequentAuthErrors=e.sessionKey?0:e.consequentAuthErrors+1,e.authorized$.next(e.sessionKey!==void 0)}),e.authorizePromise})()}}class Ae{constructor(t){e(this,`id`,`uvrest`),e(this,`authorized$`,new Te(!1)),e(this,`params`,void 0),e(this,`statToken`,void 0),e(this,`authorizePromise`,void 0),e(this,`isDestroyed`,!1),this.params=t}authorize(e){var t=this;return n(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=xe(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return n(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.error$.next({id:`OneStat:UvRestApi:LogRequestNoToken`,category:E.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return n(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return n(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.error$.next({id:`OneStat:UvRestApi:NoToken`,category:E.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.error$.next({id:`OneStat:UvRestApi:AuthorizeFailed`,category:E.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return n(function*(){let n=e?.status;return n===401?(t.params.error$.next({id:`OneStat:UvRestApi:TokenExpired`,category:E.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.error$.next({id:`OneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:E.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return n(function*(){let n=t.statToken;if(!n){t.params.error$.next({id:`OneStat:UvRestApi:RetryNoToken`,category:E.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.error$.next({id:`OneStat:UvRestApi:RetryFailed`,category:E.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${T}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=De().navigator;n=Oe.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),[{application:r,platform:t,user_id:this.params.userId,items:this.params.config.shorten?e.map(we):e}]}}import{fetchPolyfilled as je}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Me}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Ne}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as D,now as O,getWindow as Pe}from"@vkontakte/videoplayer-shared/es2015";class Fe{constructor(t){e(this,`apiKey`,void 0),e(this,`apiBaseUrl`,void 0),e(this,`apiEnv`,void 0),e(this,`timeSynchronisation`,void 0),e(this,`isApiBaseUrlFetched`,void 0),e(this,`params`,void 0),this.params=t,this.apiKey=t.config.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=t.config.apiBaseUrl??b[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){var e=this;return n(function*(){if(e.apiEnv!==`auto`||e.isApiBaseUrlFetched)return e.apiBaseUrl;try{var t;let e=yield(yield je(atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),{method:`GET`,mode:`cors`,cache:`no-cache`})).json(),n=e==null||(t=e.Answer[0])==null?void 0:t.data;if(!n)throw Error(`Wrong DNS response`);return n}catch(t){return e.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:D.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),b.vk_alias}finally{e.isApiBaseUrlFetched=!0}})()}sendBeacon(e,t,n){if(!Pe().Blob||!Pe().navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=Pe().Blob,a=new i([r.toString()],{type:`application/x-www-form-urlencoded`});try{return Pe().navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:D.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,r){var i=this;return n(function*(){let n=O(),a=a=>{if(a instanceof TypeError&&Me([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],a.message)){i.params.error$.next({id:`Network`,category:D.NETWORK,message:`Request failed`,thrown:a});return}i.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:D.NETWORK,message:`Unhandled request error`,thrown:a,data:{method:e,params:t,sessionKey:r,time:O()-n}})};i.apiBaseUrl=yield i.resolveApiBaseUrl();let o={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:i._prepareQueryParams({method:e,queryParams:t,sessionKey:r})};return i.params.config.useKeepalive&&(o.keepalive=!0),je(`${i.apiBaseUrl}/fb.do`,o).then(e=>{let t=Number(e.headers.get(`content-length`))===0,r=new Date(e.headers.get(`date`)??``).getTime(),o=O()-n;if(isFinite(r)&&i.timeSynchronisation?.addServerTime(r,o),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)})()}sendJsonBeacon(e,n,r){let i=`${this.apiBaseUrl}${e}`;try{je(i,{method:`POST`,headers:t({"Content-Type":`application/json`},r),body:JSON.stringify(n),keepalive:!0}).catch(t=>{this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:D.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:D.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequest(e,r,i){var a=this;return n(function*(){let n=O(),o=t=>{if(t instanceof TypeError&&Me([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],t.message)){a.params.error$.next({id:`Network`,category:D.NETWORK,message:`JSON request failed`,thrown:t});return}a.params.error$.next({id:`OneStat:ApiTransport:sendJsonRequest`,category:D.NETWORK,message:`Unhandled JSON request error`,thrown:t,data:{path:e,time:O()-n}})};a.apiBaseUrl=yield a.resolveApiBaseUrl();let s={method:`POST`,headers:t({"Content-Type":`application/json`},i),body:JSON.stringify(r)};return a.params.config.useKeepalive&&(s.keepalive=!0),je(`${a.apiBaseUrl}${e}`,s).then(e=>{let t=Number(e.headers.get(`content-length`))===0,r=new Date(e.headers.get(`date`)??``).getTime(),i=O()-n;if(isFinite(r)&&a.timeSynchronisation?.addServerTime(r,i),!e.ok)return Promise.reject({status:e.status,statusText:e.statusText});if(!t)return e.json().catch(o)},o)})()}_prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Ne(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}import{arrayIncludes as Ie}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Le}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Re,now as ze,safeStorage as k,debounceFn as Be}from"@vkontakte/videoplayer-shared/es2015";var Ve=e=>t=>t.timestamp+e>=ze();class He{constructor(t){e(this,`params`,void 0),e(this,`error$`,void 0),e(this,`userSalt`,void 0),e(this,`isPaused`,!1),e(this,`loggerDebugLog`,void 0),e(this,`queues`,[]),e(this,`isUrgent`,e=>{let{operation:t}=e;return Ie([`action_play`,`action_play_interactive`,`watch_coverage_record`,`watch_coverage_live`,`action_stop`,`close_at_empty_buffer`],t)}),this.params=t,this.error$=t.error$,this.userSalt=t.userSalt,this.loggerDebugLog=t.debugLogger.createComponentLog(`stat logger`);for(let e of t.apis)this.queues.push(this.createQueueState(e));this.housekeepStorage()}createQueueState(e){let t=`onestat_events_${e.id}`,n=Be(()=>this.safeFlushQueue(a),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime}),r=k.isPersistent()?this.params.config.flushMaxWait:0,i=Be(()=>this.safeFlushQueue(a),this.params.config.flushDebounceTime,{maxWait:r}),a={api:e,storageKey:t,unsaltedStorage:[],lastVsid:void 0,firstFlush:n,debouncedFlush:i,subscription:e.authorized$.subscribe(e=>{e&&i()})};return a}safeFlushQueue(e){try{this.flushQueue(e)}catch(t){this.error$.next({id:`LoggerError`,category:Re.WTF,message:t?String(t):`Unknown logger error`,thrown:t,data:{storageKey:e.storageKey}})}}readFromStorage(e){let t=k.get(e);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(e,n){if(!this.userSalt){e.unsaltedStorage.push(n);return}let r=this.readFromStorage(e.storageKey),i=(r[this.userSalt]??[]).filter(Ve(this.params.config.storageExpiration));k.set(e.storageKey,JSON.stringify(t(t({},r),{},{[this.userSalt]:[...i,n]})))}getFromStorage(e){return this.userSalt?(this.readFromStorage(e.storageKey)[this.userSalt]??[]).filter(Ve(this.params.config.storageExpiration)):e.unsaltedStorage}markStorageSent(e){if(!this.userSalt){e.unsaltedStorage=[];return}let t=this.readFromStorage(e.storageKey);delete t[this.userSalt],k.set(e.storageKey,JSON.stringify(t))}housekeepStorage(){for(let e of this.queues){let t=this.readFromStorage(e.storageKey);for(let[n,r]of Le(t)){let i=r.filter(Ve(this.params.config.storageExpiration));i.length?t[n]=i:delete t[n],this.loggerDebugLog({message:`${r.length} retrieved from storage, ${i.length} of them actual (${e.storageKey})`})}k.set(e.storageKey,JSON.stringify(t))}}log(e){for(let t of this.queues)this.addToStorage(t,e),!this.isPaused&&(this.isUrgent(e)?this.flushQueue(t):t.lastVsid===e.custom.vsid?t.debouncedFlush():t.firstFlush(),t.lastVsid=e.custom.vsid)}flush(e={wantBeacon:!1,clearStorage:!0}){for(let t of this.queues)this.flushQueue(t,e)}flushQueue(e,{wantBeacon:t,clearStorage:n}={wantBeacon:!1,clearStorage:!0}){let r=this.getFromStorage(e);r.length!==0&&(e.api.authorized$.getValue()?(t&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${r.length} events through beacon (${e.storageKey})`}),e.api.logBeacon(r)):(this.loggerDebugLog({message:`Flushing ${r.length} events (${e.storageKey})`}),e.api.logRequest(r)),n&&this.markStorageSent(e)):e.api.authorize(),e.firstFlush.cancel(),e.debouncedFlush.cancel())}pause(){this.isPaused=!0;for(let e of this.queues)e.debouncedFlush.cancel()}resume(){this.isPaused=!1;for(let e of this.queues)e.debouncedFlush()}destroy(){for(let e of this.queues)e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel();this.queues=[]}}import{HttpConnectionType as Ue,Surface as A,VideoFormat as j,VideoQuality as M}from"@vkontakte/videoplayer-core/es2015";import{assertNever as We}from"@vkontakte/videoplayer-shared/es2015";var Ge=e=>e&&{[M.INVARIANT]:`unknown`,[M.Q_144P]:`mobile`,[M.Q_240P]:`lowest`,[M.Q_360P]:`low`,[M.Q_480P]:`medium`,[M.Q_576P]:`unknown`,[M.Q_720P]:`high`,[M.Q_1080P]:`fullhd`,[M.Q_1440P]:`quadhd`,[M.Q_2160P]:`ultrahd`,[M.Q_4320P]:`unknown`}[e],Ke=e=>e&&{[Ue.HTTP1]:`http1`,[Ue.HTTP2]:`http2`,[Ue.QUIC]:`http3`}[e],qe=e=>{if(e!==void 0)switch(e){case j.MPEG:return`mp4`;case j.DASH:case j.DASH_LIVE:case j.DASH_STREAMS:return`dash`;case j.DASH_SEP:return`dash_sep`;case j.DASH_ONDEMAND:return`ondemand_dash`;case j.DASH_WEBM:case j.DASH_LIVE_WEBM:return`webm`;case j.DASH_WEBM_AV1:return`av1`;case j.DASH_LIVE_CMAF:return`ondemand_dash_live`;case j.HLS:case j.HLS_LIVE:return`hls`;case j.HLS_FMP4:return`hls_fmp4`;case j.HLS_ONDEMAND:return`ondemand_hls`;case j.HLS_LIVE_CMAF:return`ondemand_hls_live`;case j.WEB_RTC_LIVE:return`webrtc`;default:return We(e)}},Je=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case A.NONE:case A.INLINE:return;case A.FULLSCREEN:return`fullscreen`;case A.SECOND_SCREEN:return`chromecast`;case A.PIP:return`pip`;case A.INVISIBLE:return`invisible`;default:return We(e)}},Ye=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class Xe{constructor(t){e(this,`offset`,void 0),this.offset=t}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}import{PlaybackState as Ze}from"@vkontakte/videoplayer-core/es2015";import{filter as Qe,filterChanged as $e,fromEvent as et,isNullable as tt,map as nt,merge as N,Observable as rt,Subject as it,Subscription as at,ValueSubject as ot}from"@vkontakte/videoplayer-shared/es2015";var st=(e,t)=>new rt(n=>{let r=new at,i=N(et(window,`beforeunload`),e.events.willDestruct$),a=new ot(void 0),o;r.add(e.info.isLive$.pipe($e()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(nt(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c,looped$:l}=e.events,u=e.events.willSeek$.pipe(Qe(()=>e.info.playbackState$.getValue()===Ze.PLAYING)),d=e.events.seeked$.pipe(Qe(()=>e.info.playbackState$.getValue()===Ze.PLAYING)),f=!1,p=new it;r.add(u.subscribe(()=>{f||p.next(),f=!0})),r.add(d.subscribe(()=>f=!1));let m=new it,h=new it,g=()=>t.watchCoverageExactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,ee=e.info.stallStartTime$.pipe($e(),Qe(e=>e>0)),_=N(s,d,m).pipe(nt(()=>g())),v=N(l,N(c,p,i,h,ee).pipe(nt(()=>g()))),y,b=e=>{y=e},te=e=>{let t=e;tt(y)||y===t||tt(t)||(n.next({from:y,to:t}),y=void 0)},x=()=>{h.next(),m.next()};if(r.add(_.subscribe(b)),r.add(v.subscribe(te)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(_.subscribe(()=>{n(),e=window.setTimeout(x,t.forceInterval)})),r.add(v.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(_.subscribe(()=>e=window.setTimeout(x,t.forceInterval))),r.add(v.subscribe(()=>window.clearTimeout(e)))}return r});import{Surface as P}from"@vkontakte/videoplayer-core/es2015";import{debounce as ct,filterChanged as lt,Subject as ut}from"@vkontakte/videoplayer-shared/es2015";var dt=(e,t,n)=>{let r=new ut,i=r.pipe(ct(0),lt()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?P.PIP:o?P.FULLSCREEN:s?P.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?P.FULLSCREEN:a?P.PIP:s?P.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case P.SECOND_SCREEN:case P.NONE:case P.INLINE:!o&&!a&&(e===P.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},ft=`_one-stat_deviceId`,pt=(e,t)=>e&&t?`${e}_${t}`:e??t,mt=()=>{let e=new fe;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class ht{get vsid$(){return new pe(w.getVSID())}constructor(t,n){e(this,`apis`,void 0),e(this,`logger`,void 0),e(this,`config`,void 0),e(this,`subscription`,new fe),e(this,`beforeunloadSubscription`,void 0),e(this,`timeSynchronisation`,void 0),e(this,`debugLogger`,new he),e(this,`oneStatDebugLog`,this.debugLogger.createComponentLog(`onestat`)),e(this,`loopCounter`,0),e(this,`disabled`,!1),e(this,`experimental`,void 0),e(this,`isid$`,new pe(void 0)),e(this,`zenUid$`,new pe(void 0)),e(this,`statContext`,void 0),e(this,`isEmbed`,void 0),e(this,`embedParent`,void 0),e(this,`uiEvents`,void 0),e(this,`player`,void 0),e(this,`seekAction$`,new pe(`unknown`)),e(this,`deviceId`,void 0),this.statContext=t,this.config=x(n.config??{}),S(n.apiEnv)&&(this.config.apiEnv=n.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Xe);let r=new de;this.experimental={error$:r};let i=ue.get(ft);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=ne(),ue.set(ft,this.deviceId)),this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??be()),this.zenUid$.next(n.zenUid);let a=new Fe({config:this.config,error$:r,timeSynchronisation:this.timeSynchronisation}),o=[];this.config.apiForticom&&o.push(new ke({config:this.config,apiTransport:a,refreshAuthToken:n.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:r,vktvVersion:n.vktvVersion})),this.config.apiUvRest&&(n.getUvRestAuthToken?o.push(new Ae({config:this.config,apiTransport:a,error$:r,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken,mobile:this.statContext.mobile??!1,vktvVersion:n.vktvVersion})):r.next({id:`OneStat:Init:MissingGetUvRestAuthToken`,category:_e.WTF,message:`oldStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.apis=o,this.logger=new He({config:this.config,debugLogger:this.debugLogger,apis:this.apis,error$:r,userSalt:n.userSalt});let{isEmbed:s,topOrigin:c}=ge();this.isEmbed=s,this.embedParent=c?new URL(c).hostname:void 0,this.subscribe()}updateContext(e){this.statContext=t(t({},this.statContext),e)}attachTo(e){let t=new fe,n=(e,n)=>t.add(e.subscribe(n)),r,i,a,o=!1,s=!1,c=()=>{o||(o=!0,S(r)&&(r={startedAt:C(),liveAtStall:!!this.statContext.liveEdge}))};n(e.events.willStart$,()=>{let t=e.info.position$.getValue();this.logActionPlay({position:t}),this.statContext.projectId&&this.logActionPlayInteractive()}),n(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),n(e.events.willSeek$,()=>{S(r)&&o&&this.logEmptyBuffer({duration:C()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0,s=!0}),n(e.events.seeked$,()=>{!s&&S(r)&&o&&(this.logEmptyBuffer({duration:C()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0),s=!1;let t=this.seekAction$.getValue();this.logSeek({action:t===`rich`?`slider`:t,time:e.info.position$.getValue()}),this.seekAction$.next(`unknown`)}),n(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),n(e.events.willResume$,()=>{this.logPlay()}),n(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),n(e.events.playing$,()=>{this.logPlaying()}),n(st(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix,watchCoverageExactTime:this.config.watchCoverageExactTime}),t=>{let n=e.info.isLive$.getValue(),r=e.info.atLiveEdge$.getValue(),i={start:parseFloat(t.from.toFixed(3)),end:parseFloat(t.to.toFixed(3))};if(r){let t=e.info.liveLatency$.getValue()??0,n=e.info.currentBuffer$.getValue()?.end??0,r=e.info.liveBufferTime$.getValue()??0,a=Math.round((t-(n-r))*1e3),o=Math.round(t*1e3);a&&o&&(i.latency=a,i.bufferLatency=o)}n?this.logWatchCoverageLive(i):this.logWatchCoverageRecord(i)}),n(e.info.stallStartTime$,e=>{e>0?r={startedAt:e,liveAtStall:!!this.statContext.liveEdge}:(S(r)&&o&&this.logEmptyBuffer({duration:Math.round(C()-r.startedAt),liveAtStall:r.liveAtStall}),r=void 0)});let l=!1;t.add(e.events.fatalError$.pipe(le()).subscribe(()=>l=!0)),n(e.events.willStop$,()=>{if(e.info.isBuffering$.getValue()&&o){let e=S(r)?C()-r.startedAt:void 0;this.logCloseAtEmptyBuffer({duration:e??0,liveAtStall:r?.liveAtStall}),r=void 0}else l||this.logActionStop()}),n(e.events.managedError$,({id:e})=>{this.logError({fatal:!1,errorType:e})}),n(e.events.fatalError$,({id:e})=>{this.logError({fatal:!0,errorType:e})}),n(e.events.firstBytes$,e=>{i=C(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>a=C()),n(e.info.currentBuffer$,e=>{!o&&e&&e.end-e.start>0&&S(i)&&(this.logPlayerReady({duration:C()-i}),c())}),n(e.events.firstFrame$,()=>{S(i)&&!o&&(this.logPlayerReady({duration:C()-i}),c()),S(a)&&this.logFirstFrame({time:C()-a})});let u;n(e.info.currentVideoStream$,e=>{e&&(this.updateContext({videoCodec:e.codec}),u&&e.id!==u&&this.logTrackSwitch(e),u=e.id)});let d;n(e.info.currentAudioStream$,e=>{e&&(this.updateContext({audioCodec:e.codec}),d&&e.id!==d&&this.logTrackSwitch(e),d=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:e,volume:t})=>this.updateContext({audible:!e&&t>0})),n(e.info.currentQuality$,e=>{let t=Ge(e);this.updateContext({quality:t}),t&&this.logQuality(t)}),n(e.info.isAutoQualityEnabled$,e=>this.updateContext({autoQuality:e})),n(e.info.currentFormat$,e=>this.updateContext({contentType:qe(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let f;return n(e.info.hostname$,e=>{let t=f!==void 0&&f!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),f=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Ke(e)}),this.updateContext({connectionType:Ke(e)})}),n(e.info.httpConnectionReused$,e=>{oe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:Je(e,this.statContext.isPreviewPlayerView)})}),n(ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:e,available:t})=>{let n=t.find(({id:t})=>t===e),r=n&&(n.isAuto?`${n.language}_auto`:n.language);this.updateContext({subtitles:r?.split(`.`)[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscription:t,subscribe:n}=mt();if(!this.player)return t;n(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),n(e.actionSeek$,this.seekAction$);let{surface$:r}=dt(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:Je(e,this.statContext.isPreviewPlayerView)})}),n(e.actionSetSubtitle$,e=>this.updateContext({subtitles:e?.split(`.`)[0]})),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:t,subscribe:n}=mt();return n(e.slotRequested$,()=>this.logAdSlotRequest()),n(e.started$,e=>this.logAdStarted(e)),n(e.paused$,()=>this.logAdPaused()),n(e.resumed$,()=>this.logAdResumed()),n(e.ended$,()=>this.logAdEnded()),n(e.skipped$,()=>this.logAdSkipped()),n(e.clicked$,()=>this.logAdClicked()),n(e.error$,e=>this.logError({errorType:e,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToInteractive(e){let{subscription:t,subscribe:n}=mt();return n(e.click$,e=>this.logInterfaceClick(e)),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}authorize(e){return Promise.all(this.apis.map(t=>t.authorize(e)))}pause(){this.logger.pause(),this.oneStatDebugLog({message:`paused`})}resume(){this.logger.resume(),this.oneStatDebugLog({message:`resumed`})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.apis.forEach(e=>e.destroy()),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:`VSID reset`}),w.generateVSID(this.config.useVsid64)}getDeviceId(){return this.deviceId}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:`player_ready`,param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:`play_toggle`})}logPlaying(){this.log({operation:`playing`})}logPause(e){this.log({operation:`pause`,param:String(Math.round(e.position))})}logSeek(e){this.log({operation:`seek`,param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:`first_bytes`,param:String(e.time)})}logFirstFrame(e){this.log({operation:`first_frame`,param:String(e.time)})}logError(e){this.log({operation:`content_error`,param:`${e.fatal?`fatal`:`recoverable`}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:`watch_coverage_record`,param:`${e.start}-${e.end}`},{in_history:this.statContext.inHistory?1:void 0})}logWatchCoverageLive(e){let t=this.timeSynchronisation?.getOffset()??0,n=e.start+t,r=e.end+t;this.log({operation:`watch_coverage_live`,param:`${n}-${r}`},{in_history:this.statContext.inHistory?1:void 0,latency:e.latency,buffer_latency:e.bufferLatency})}logEmptyBuffer(e){this.log({operation:`empty_buffer`,param:String(e.duration)},S(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:`adv`,param:`slot_request`})}logAdStarted(e){this.log({operation:`adv`,param:e})}logAdPaused(){this.log({operation:`adv`,param:`pause`})}logAdResumed(){this.log({operation:`adv`,param:`resume`})}logAdEnded(){this.log({operation:`adv`,param:`ended`})}logAdSkipped(){this.log({operation:`adv`,param:`skip`})}logAdClicked(){this.log({operation:`adv`,param:`click`})}logInterfaceClick(e){this.log({operation:`player_interface_click`,param:e})}logNextMovie(e){this.log({operation:`next_movie`,param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=me().navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(se(ae(e,`change`),ce([`init`])).subscribe(()=>this.updateContext({network:Ye(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(e=>{console.debug(`%c stat `,`background:#fa6470;`,`component: ${e.component}.`,e.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=ae(window,`beforeunload`).subscribe(()=>this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload})),this.subscription.add(this.beforeunloadSubscription)}logPlayerReady(e){this.log({operation:`player_ready`,param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:`action_play`,param:String(Math.round(e.position))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:`action_play_interactive`,param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:`failover`,param:e})}logCloseAtEmptyBuffer(e){this.log({operation:`close_at_empty_buffer`,param:String(Math.round(e.duration))},S(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}logActionStop(){this.log({operation:`action_stop`})}logTrackSwitch(e){this.log({operation:`track_switch`,param:e.id})}logQuality(e){this.log({operation:`quality`,param:e})}log(e,t={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(s(this.config.disabledOperations,e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let n=this.createLogItem(e,t);this.logger.log(n)}createLogItem({operation:e,param:n,time:r},i={}){let a=this.timeSynchronisation?.now()??C(),o=this.vsid$.getValue();re(o);let l=this.isid$.getValue(),u=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,d=this.statContext.firstConnectionReused,f,p;if(this.isEmbed||this.statContext.place===`embed`){f=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>s(this.config.embedUrlParams,e));p=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;f=e&&c(URL,e)?new URL(e).hostname:e,p=location.href.substring(0,1024)}let m=t({vsid:o,isid:l,vid:this.statContext.movieId,uid:this.zenUid$.getValue(),ct:this.statContext.contentType,place:this.isEmbed?`embed`:this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?`auto`:this.statContext.autoplay===!1?``:void 0,param:n,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:u,connection_reused:d===!0?1:d===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:f,direct_url:p,rate:this.statContext.rate===1||oe(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,codec_info:pt(this.statContext.videoCodec,this.statContext.audioCodec),aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},i);for(let e of this.config.disabledCustomFields)delete m[e];return{operation:e,type:1,time:r,network:this.statContext.network,timestamp:a,custom:m}}}var gt={};o(gt,{VERSION:()=>T,ThinOneStat:()=>Qn,ActionSeekType:()=>Ft});import{objectValues as _t}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as vt}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as yt,detectEmbed as bt,fromEvent as xt,Logger as St,merge as Ct,combine as F,filter as I,filterChanged as wt,once as Tt,skip as Et,debounce as Dt,safeStorage as Ot,getWindow as kt,Subject as At,Subscription as jt,ValueSubject as Mt,ErrorCategory as L}from"@vkontakte/videoplayer-shared/es2015";import{clientChecker as R}from"@vkontakte/videoplayer-core/es2015";import{fillWithDefault as Nt}from"@vkontakte/videoplayer-shared/es2015";var Pt;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(Pt||={});var Ft;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(Ft||={});var It=`CIOPGQJGDIHBABABA`,Lt={prod:`https://api.ok.ru`,vk_alias:`https://api.mycdn.me`,videotest:`https://videotestapi.ok.ru/api`,test:`https://apitest.ok.ru`,okcdn:`https://api.okcdn.ru`,auto:``},Rt={apiKey:It,apiEnv:`okcdn`,apiBaseUrl:null,apiForticom:!0,apiUvRest:!1,requestRetryCount:3,useVsid64:!1,flushFirstTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,flushRetryFirstDelay:3e3,flushRetryMaxDelay:18e5,storageExpiration:2160*60*1e3,clearStorageAtUnload:!1,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchCoverageHeartbeatInterval:3e4,watchCoverageExactTime:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},zt=e=>Nt(e,Rt);import{arrayIncludes as Bt}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Vt}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as z,ValueSubject as Ht}from"@vkontakte/videoplayer-shared/es2015";function Ut(e){let t=Error(`HTTP ${e.status}: ${e.statusText}`);return t.status=e.status,t.statusText=e.statusText,t.response=e,t}function Wt(){let e=Error(`Request timeout`);return e.isTimeout=!0,e}function Gt(e){let t=Error(e.error_msg);return t.errorData=e,t}function Kt(e){if(!(!e||typeof e!=`object`)){if(`errorData`in e)return e.errorData?.error_code;if(`error_code`in e){let t=e.error_code;return typeof t==`number`?t:void 0}}}class qt{constructor(t){e(this,`id`,`forticom`),e(this,`authorized$`,void 0),e(this,`params`,void 0),e(this,`authToken`,void 0),e(this,`sessionKey`,void 0),e(this,`authorizePromise`,void 0),e(this,`refreshAuthTokenPromise`,void 0),e(this,`isDestroyed`,!1),this.params=t,this.authorized$=new Ht(!1)}authorize(e){var t=this;return n(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t.doAuthorize()})()}logBeacon(e){if(!e.length)return;let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return n(function*(){if(!e.length)return;let n=`log.logUvStat`,r=t.createLogParams(e),i={};try{let e=yield t.getValidSessionKey();if(!e){t.params.errors$.next({id:`ThinOneStat:Api:LogRequestNoSession`,category:z.NETWORK,message:`No session key available for log request`});return}yield t.params.apiTransport.sendRequest(n,r,e,i)}catch(e){(yield t.handleLogRequestError(e,n,r))&&(yield t.retryLogRequestAfterSessionRecovery(n,r))}})()}getValidSessionKey(){var e=this;return n(function*(){return e.sessionKey?e.sessionKey:e.doAuthorize()})()}handleLogRequestError(e,t,r){var i=this;return n(function*(){let n=Kt(e);return n===void 0?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestUnknown`,category:z.NETWORK,message:`Unknown ${t} error`,thrown:e,data:{params:r}}),!1):i.isSessionExpiredError(n)?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestSessionError#${n}`,category:z.EXTERNAL_API,message:`Session error: ${n}`,data:{error:e,code:n}}),i.authorized$.next(!1),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):n===401?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestAuthLogin#${n}`,category:z.EXTERNAL_API,message:`Auth token expired`,data:{error:e,code:n}}),i.authorized$.next(!1),i.authToken=yield i.refreshAuthToken(),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):(i.params.errors$.next({id:`ThinOneStat:Api:LogRequest#${n}`,category:z.EXTERNAL_API,message:`${t} error`,data:{error:e,code:n,params:r}}),!1)})()}retryLogRequestAfterSessionRecovery(e,t){var r=this;return n(function*(){let n=r.sessionKey;if(!n){r.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed`,category:z.NETWORK,message:`Cannot retry log request: no session key after recovery`});return}try{yield r.params.apiTransport.sendRequest(e,t,n)}catch(e){let t=Kt(e);r.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed#${t??`unknown`}`,category:z.EXTERNAL_API,message:`Log request failed after session recovery`,thrown:e,data:{originalError:e,retryCode:t}})}})()}isSessionExpiredError(e){return!!e&&Bt([102,103,104],e)}doAuthorize(e=1){var t=this;return n(function*(){if(!t.isDestroyed)return t.authorizePromise?t.authorizePromise:(t.sessionKey=void 0,t.authorized$.next(!1),t.authorizePromise=Vt(t.executeAuthorize(e),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.sessionKey!==void 0)}),t.authorizePromise)})()}executeAuthorize(e){var t=this;return n(function*(){let n=t.buildAuthParams();try{let e=yield t.params.apiTransport.sendRequest(`auth.anonymLogin`,n);if(t.isDestroyed)return;if(!e?.session_key){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeFailed`,category:z.EXTERNAL_API,message:`No session key in response`,data:e});return}return t.sessionKey=e.session_key,t.sessionKey}catch(n){if(t.isDestroyed)return;let r=Kt(n);if(r===401&&t.params.refreshAuthToken){if(t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:z.EXTERNAL_API,message:`Auth token expired during authorization`,data:{error:n,code:r,attempt:e}}),e>=2){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeMaxAttemptsReached`,category:z.EXTERNAL_API,message:`Authorization failed after ${e} attempts`,data:{error:n,code:r}});return}return t.authToken=yield t.refreshAuthToken(),t.doAuthorize(e+1)}r?t.params.errors$.next({id:`ThinOneStat:Api:Authorize#${r}`,category:z.EXTERNAL_API,message:`Authorize error`,data:{error:n,code:r}}):t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:z.NETWORK,message:`Authorize error`,thrown:n});return}})()}buildAuthParams(){let e={session_data:{version:2,device_id:this.params.deviceId,client_version:this.getClientVersion(),client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),e}getClientVersion(){return T}refreshAuthToken(){var e=this;return n(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Vt(e.params.refreshAuthToken().catch(t=>{throw e.params.errors$.next({id:`ThinOneStat:Api:RefreshAuthTokenFailed`,category:z.NETWORK,message:`Failed to refresh auth token`,thrown:t}),t}),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`@vkontakte/videoplayer-statistics:${this.getClientVersion()}`;return this.params.vktvVersion&&(t=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:t,platform:e[0].platform,product:e[0].product,events:e})}}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.sessionKey=void 0,this.authorized$.next(!1)}}class Jt{constructor(t){e(this,`id`,`uvrest`),e(this,`authorized$`,void 0),e(this,`params`,void 0),e(this,`statToken`,void 0),e(this,`authorizePromise`,void 0),e(this,`isDestroyed`,!1),this.params=t,this.authorized$=new Ht(!1)}authorize(e){var t=this;return n(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=Vt(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return n(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestNoToken`,category:z.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return n(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return n(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.errors$.next({id:`ThinOneStat:UvRestApi:NoToken`,category:z.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.errors$.next({id:`ThinOneStat:UvRestApi:AuthorizeFailed`,category:z.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return n(function*(){let n=e?.status;return n===401?(t.params.errors$.next({id:`ThinOneStat:UvRestApi:TokenExpired`,category:z.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:z.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return n(function*(){let n=t.statToken;if(!n){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryNoToken`,category:z.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryFailed`,category:z.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=e[0],n=t.application;return this.params.vktvVersion&&(n=this.params.vktvVersion),[{product:t.product,platform:t.platform,application:n,user_id:this.params.userId,events:e}]}}import{fetchPolyfilled as Yt}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Xt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as B}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Zt}from"@vkontakte/videoplayer-shared/es2015";import{now as V,getWindow as H,getExponentialDelay as Qt,isAbortError as $t,ErrorCategory as U}from"@vkontakte/videoplayer-shared/es2015";class en{constructor(t){e(this,`params`,void 0),e(this,`apiKey`,void 0),e(this,`apiBaseUrl`,void 0),e(this,`apiEnv`,void 0),e(this,`resolvedApiBaseUrl`,null),e(this,`resolveApiBaseUrlPromise`,null),e(this,`timeSynchronisation`,void 0),e(this,`fetchTimeout`,3e4),e(this,`maxTotalRequestTime`,6e4),e(this,`retryConfig`,void 0),this.params=t,this.apiKey=t.config.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=t.config.apiBaseUrl??Lt[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.retryConfig={maxAttempts:t.config.requestRetryCount??3,baseDelay:3e3,maxDelay:3e4,retryableErrors:[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`Request timeout`,`Network request failed`],retryableStatuses:[408,429,500,502,503,504]}}sendBeacon(e,t,n){if(!H().Blob||!H().navigator.sendBeacon)return!1;let r=this.resolvedApiBaseUrl??this.apiBaseUrl,i=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),a=H().Blob,o=new a([i.toString()],{type:`application/x-www-form-urlencoded`});try{return H().navigator.sendBeacon(`${r}/fb.do`,o)}catch(n){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendBeacon`,category:U.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,r,i){var a=this;return n(function*(){return a.sendRequestWithRetry(e,t,r,i)})()}sendRequestWithRetry(e,t,r,i,a=1,o){var s=this;return n(function*(){let n=V(),c=o??n+s.maxTotalRequestTime;if(V()>=c){let i=Error(`Request deadline exceeded`);throw s.handleFinalError(e,t,r,n,i,a),i}try{return yield s.executeRequest(e,t,r,i,n,a,c)}catch(o){if(s.shouldRetry(o,a)&&V()<c){let l=s.getRetryDelay(o,a);if(V()+l>=c)throw s.handleFinalError(e,t,r,n,o,a),o;return s.logRetryAttempt(e,a,o,l),yield s.sleep(l),s.sendRequestWithRetry(e,t,r,i,a+1,c)}throw s.handleFinalError(e,t,r,n,o,a),o}})()}executeRequest(e,r,i,a,o,s,c){var l=this;return n(function*(){let n=o??V(),u=yield l.resolveApiBaseUrl(),d=c===void 0?l.fetchTimeout:c-V();if(d<=0)throw Wt();try{let o=yield l.fetchWithTimeout(`${u}/fb.do`,{method:`post`,headers:t({"Content-type":`application/x-www-form-urlencoded`},a),body:l.prepareQueryParams({method:e,queryParams:r,sessionKey:i})},Math.min(l.fetchTimeout,d));return yield l.processResponse(o,n)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:s,url:`${u}/fb.do`}),t}})()}sendJsonRequest(e,t,r){var i=this;return n(function*(){return i.sendJsonRequestWithRetry(e,t,r)})()}sendJsonBeacon(e,n,r){let i=`${this.resolvedApiBaseUrl??this.apiBaseUrl}${e}`;try{Yt(i,{method:`POST`,headers:t({"Content-Type":`application/json`},r),body:JSON.stringify(n),keepalive:!0}).catch(t=>{this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:U.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:U.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequestWithRetry(e,t,r,i=1,a){var o=this;return n(function*(){let n=V(),s=a??n+o.maxTotalRequestTime;if(V()>=s){let t=Error(`Request deadline exceeded`);throw o.handleJsonFinalError(e,n,t,i),t}try{return yield o.executeJsonRequest(e,t,r,n,i,s)}catch(a){if(o.shouldRetry(a,i)&&V()<s){let c=o.getRetryDelay(a,i);if(V()+c>=s)throw o.handleJsonFinalError(e,n,a,i),a;return o.logRetryAttempt(e,i,a,c),yield o.sleep(c),o.sendJsonRequestWithRetry(e,t,r,i+1,s)}throw o.handleJsonFinalError(e,n,a,i),a}})()}executeJsonRequest(e,r,i,a,o,s){var c=this;return n(function*(){let n=a??V(),l=yield c.resolveApiBaseUrl(),u=s===void 0?c.fetchTimeout:s-V();if(u<=0)throw Wt();let d=`${l}${e}`;try{let e=yield c.fetchWithTimeout(d,{method:`POST`,headers:t({"Content-Type":`application/json`},i),body:JSON.stringify(r)},Math.min(c.fetchTimeout,u));return yield c.processResponse(e,n)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:o,url:d}),t}})()}fetchWithTimeout(e,r){return n(function*(e,n,r=this.fetchTimeout){let i=new Xt,a=H().setTimeout(()=>i.abort(),r);try{let r=yield Yt(e,t(t({},n),{},{signal:i.signal}));return H().clearTimeout(a),r}catch(e){throw H().clearTimeout(a),$t(e)?Wt():e}}).apply(this,arguments)}processResponse(e,t){var r=this;return n(function*(){if(!e.ok){let t=Ut(e),n=r.parseRetryAfter(e);throw n!==void 0&&(t.retryAfter=n),t}let n=new Date(e.headers.get(`date`)??``).getTime(),i=V()-t;isFinite(n)&&r.timeSynchronisation?.addServerTime(n,i);let a=e.headers.get(`content-length`);if(a!==null&&Number(a)===0)return{};let o=yield e.json();if(o&&typeof o==`object`&&`error_msg`in o)throw Gt(o);return o})()}shouldRetry(e,t){if(t>=this.retryConfig.maxAttempts||!(e instanceof Error))return!1;let n=e;return!!(n.isTimeout||n.status&&B(this.retryConfig.retryableStatuses,n.status)||B(this.retryConfig.retryableErrors,e.message)||B(e.message,`network`)||B(e.message,`timeout`)||B(e.message,`connection`))}logRetryAttempt(e,t,n,r){let i=n instanceof Error?n.message:String(n);this.params.errors$.next({id:`ThinOneStat:ApiTransport:retry`,category:U.NETWORK,message:`Retrying request (attempt ${t}/${this.retryConfig.maxAttempts}) after ${Math.round(r)}ms`,thrown:n,data:{method:e,attempt:t,delay:r,errorMessage:i}})}handleFinalError(e,t,n,r,i,a){let o=U.NETWORK;this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:o,message:i instanceof Error?i.message:`Request failed after retries`,thrown:i,data:{method:e,params:t,sessionKey:n,time:V()-r,maxAttempts:this.retryConfig.maxAttempts,attempts:a}})}handleJsonFinalError(e,t,n,r){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonRequest`,category:U.NETWORK,message:n instanceof Error?n.message:`JSON request failed after retries`,thrown:n,data:{path:e,time:V()-t,maxAttempts:this.retryConfig.maxAttempts,attempts:r}})}sleep(e){return new Promise(t=>H().setTimeout(t,e))}resolveApiBaseUrl(){return this.apiEnv===`auto`?(this.resolveApiBaseUrlPromise||=this.fetchApiBaseUrl().then(e=>(e===Lt.vk_alias&&(this.resolveApiBaseUrlPromise=null),e)),this.resolveApiBaseUrlPromise):Promise.resolve(this.apiBaseUrl)}fetchApiBaseUrl(){var e=this;return n(function*(){try{var t;let n=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),r=yield(yield e.fetchWithTimeout(n,{method:`GET`,mode:`cors`,cache:`no-cache`},5e3)).json(),i=r==null||(t=r.Answer[0])==null?void 0:t.data;if(!i)throw Error(`Wrong DNS response`);return e.resolvedApiBaseUrl=i,i}catch(t){return e.params.errors$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:U.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),Lt.vk_alias}})()}prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Zt(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}parseRetryAfter(e){let t=e.headers.get(`Retry-After`);if(!t)return;let n=Number(t);if(!isNaN(n)&&n>=0)return n*1e3;let r=new Date(t).getTime();if(!isNaN(r))return Math.max(0,r-Date.now())}getRetryDelay(e,t){let n=e;return n?.retryAfter!==void 0&&n.retryAfter>0?n.retryAfter:Qt(t,{start:this.retryConfig.baseDelay,max:this.retryConfig.maxDelay,factor:2,random:.2})}}import{promiseAllSettled as tn}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as nn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as rn}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as an}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as on}from"@vkontakte/videoplayer-shared/es2015";import{now as sn,debounceFn as cn,getWindow as W,safeStorage as G,ErrorCategory as K}from"@vkontakte/videoplayer-shared/es2015";var ln=e=>t=>(t.client_time??sn())+e>=sn();class un{constructor(t){e(this,`params`,void 0),e(this,`subscription`,void 0),e(this,`userSalt`,void 0),e(this,`unsaltedStorage`,[]),e(this,`lastVsid`,void 0),e(this,`isPaused`,!1),e(this,`firstFlush`,void 0),e(this,`debouncedFlush`,void 0),e(this,`flushRetryCount`,0),e(this,`retryFlushTimerId`,void 0),e(this,`debugLog`,void 0),e(this,`flushPromise`,null),e(this,`flushSnapshotLength`,0),e(this,`onlineListener`,void 0),e(this,`urgentEvents`,[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`]),e(this,`STORAGE_MAX_ATTEMPTS`,3),e(this,`isUrgent`,e=>rn(this.urgentEvents,e.event_name)),this.params=t,this.userSalt=t.userSalt,this.debugLog=t.debugLogger.createComponentLog(`batch-queue:${t.storageKey}`),this.firstFlush=cn(()=>this.safeFlush(),this.params.config.flushFirstTime,{maxWait:this.params.config.flushFirstTime});let n=G.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=cn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:n}),this.subscription=this.params.canSend$.subscribe(e=>{e&&(this.debugLog({message:`Can send, triggering flush`}),this.debouncedFlush())}),this.onlineListener=()=>{this.debugLog({message:`Network online, triggering flush`}),this.cancelRetry(),this.safeFlush()},W().addEventListener(`online`,this.onlineListener),this.housekeepStorage()}scheduleRetry(){this.retryFlushTimerId!==void 0&&W().clearTimeout(this.retryFlushTimerId);let e=this.params.config.flushRetryFirstDelay,t=this.params.config.flushRetryMaxDelay,n=Math.min(e*2**this.flushRetryCount,t);this.flushRetryCount++,this.debugLog({message:`Scheduling flush retry #${this.flushRetryCount} in ${n}ms`}),this.retryFlushTimerId=W().setTimeout(()=>{this.retryFlushTimerId=void 0,this.safeFlush()},n)}cancelRetry(){this.retryFlushTimerId!==void 0&&(W().clearTimeout(this.retryFlushTimerId),this.retryFlushTimerId=void 0),this.flushRetryCount=0}safeFlush(){if(this.flushPromise){this.debugLog({message:`Flush already in progress, skipping`});return}this.flushPromise=an(this.flush(),()=>{this.flushPromise=null})}isStorageAvailable(){let e=G.isPersistent?.call(G)??!1;return e||this.debugLog({message:`Storage not available`}),e}readFromStorage(){if(!this.isStorageAvailable())return{};try{let e=G.get(this.params.storageKey),t=e?JSON.parse(e):{};return this.debugLog({message:`Read ${Object.keys(t).length} users from storage`}),t}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:ReadStorageError`,category:K.WTF,message:`Failed to read from storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to read from storage`}),{}}}writeToStorage(e){if(!this.isStorageAvailable())return!1;try{return G.set(this.params.storageKey,JSON.stringify(e)),this.debugLog({message:`Written ${Object.keys(e).length} users to storage`}),!0}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:WriteStorageError`,category:K.WTF,message:`Failed to write to storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to write to storage`}),!1}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e),this.debugLog({message:`Added item to unsalted storage, total: ${this.unsaltedStorage.length}`});return}for(let n=0;n<this.STORAGE_MAX_ATTEMPTS;n++)try{let n=this.readFromStorage(),r=n[this.userSalt]??[];if(this.debugLog({message:`Adding item to storage for user ${this.userSalt}`}),this.writeToStorage(t(t({},n),{},{[this.userSalt]:[...r,e]})))return}catch(t){n===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:AddToStorageFailed`,category:K.WTF,message:`Failed to add item to storage after retries`,thrown:t,data:{item:e,attempt:n,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to add item to storage after retries`}))}}getFromStorage(){if(!this.userSalt)return this.debugLog({message:`Retrieved ${this.unsaltedStorage.length} items from unsalted storage`}),this.flushSnapshotLength=this.unsaltedStorage.length,this.unsaltedStorage.slice();let e=this.readFromStorage(),n=e[this.userSalt]??[],r=n.filter(ln(this.params.config.storageExpiration));if(this.debugLog({message:`Retrieved from storage for user ${this.userSalt}`}),r.length!==n.length){let i=n.length-r.length;this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:K.WTF,message:`Dropped ${i} expired events from storage`,data:{droppedCount:i,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}}),this.debugLog({message:`Cleaning ${i} expired items from storage`});let a=t({},e);r.length?a[this.userSalt]=r:delete a[this.userSalt],this.writeToStorage(a)}return this.flushSnapshotLength=r.length,r}markStorageSent(){if(!this.userSalt){let e=this.unsaltedStorage.splice(0,this.flushSnapshotLength);this.debugLog({message:`Cleared unsalted storage, removed ${e.length} items, ${this.unsaltedStorage.length} new items kept`}),this.flushSnapshotLength=0;return}let e=this.flushSnapshotLength;this.flushSnapshotLength=0;for(let n=0;n<this.STORAGE_MAX_ATTEMPTS;n++)try{let n=this.readFromStorage(),r=(n[this.userSalt]??[]).slice(e),i=t({},n);if(r.length?i[this.userSalt]=r:delete i[this.userSalt],this.writeToStorage(i)){this.debugLog({message:`Marked storage as sent for user ${this.userSalt}, removed ${e} items, ${r.length} kept`});return}}catch(e){n===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:MarkStorageSentFailed`,category:K.WTF,message:`Failed to mark storage as sent after retries`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to mark storage as sent after retries`}))}}housekeepStorage(){if(this.isStorageAvailable())try{let e=this.readFromStorage(),t=!1,n=0;for(let[r,i]of on(e)){let a=i.filter(ln(this.params.config.storageExpiration)),o=i.length-a.length;n+=o,a.length?a.length!==i.length&&(e[r]=a,t=!0):(delete e[r],t=!0),this.debugLog({message:`${i.length} retrieved from storage, ${a.length} of them actual for ${r}`})}t?(this.debugLog({message:`Housekeeping completed, removed ${n} expired items total`}),this.writeToStorage(e),n>0&&this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:K.WTF,message:`Dropped ${n} expired events during housekeeping`,data:{droppedCount:n,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}})):this.debugLog({message:`Housekeeping completed, no changes needed`})}catch(e){this.params.errors$.next({id:`ThinOneStat:BatchQueue:HousekeepStorageError`,category:K.WTF,message:`Failed to housekeep storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to housekeep storage`})}}log(e){try{if(this.debugLog({message:`Logging item: ${e.event_name}`}),this.addToStorage(e),this.isPaused){this.debugLog({message:`Queue paused, skipping flush`});return}this.isUrgent(e)?(this.debugLog({message:`Urgent item, flushing immediately`}),this.safeFlush()):this.lastVsid===e.vsid?(this.debugLog({message:`Same VSID, scheduling debounced flush`}),this.debouncedFlush()):(this.debugLog({message:`VSID changed, triggering first flush`}),this.firstFlush()),this.lastVsid=e.vsid}catch(t){this.params.errors$.next({id:`ThinOneStat:BatchQueue:LogError`,category:K.WTF,message:`Failed to log item`,thrown:t,data:{item:e,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to log item`})}}flush(e={wantBeacon:!1,clearStorage:!0}){return this.flushPromise?(this.debugLog({message:`Flush already in progress, waiting`}),this.flushPromise):(this.flushPromise=an(this.flushInternal(e),()=>{this.flushPromise=null}),this.flushPromise)}flushInternal({wantBeacon:e,clearStorage:t}){var r=this;return n(function*(){r.debugLog({message:`Starting flush`});let n=r.getFromStorage();if(n.length===0){r.debugLog({message:`No items to flush`});return}let i=r.params.canSend$.getValue();if(r.debugLog({message:`Can send status: ${i}`}),!i){r.debugLog({message:`Cannot send, requesting ready state`}),r.params.requestReady();return}if(e&&r.params.config.useBeacon){r.debugLog({message:`Flushing ${n.length} events through beacon`}),r.params.sendBeacon(n),t&&r.markStorageSent(),r.firstFlush.cancel(),r.debouncedFlush.cancel();return}r.debugLog({message:`Flushing ${n.length} events`});try{yield r.params.send(n),r.debugLog({message:`Flush completed successfully`}),r.cancelRetry(),t&&r.markStorageSent(),r.firstFlush.cancel(),r.debouncedFlush.cancel()}catch(e){throw r.params.errors$.next({id:`ThinOneStat:BatchQueue:FlushRequestError`,category:K.NETWORK,message:`Failed to send events, will retry later`,thrown:e,data:{itemsCount:n.length,storageKey:r.params.storageKey}}),r.debugLog({message:`Flush failed, scheduling retry`}),r.scheduleRetry(),e}})()}pause(){this.debugLog({message:`Queue paused`}),this.isPaused=!0,this.debouncedFlush.cancel(),this.firstFlush.cancel(),this.cancelRetry()}resume(){this.debugLog({message:`Queue resumed`}),this.isPaused=!1,this.debouncedFlush()}destroy(){var e=this;return n(function*(){e.debugLog({message:`Destroying queue`}),e.flushPromise&&(e.debugLog({message:`Waiting for ongoing flush to complete`}),yield e.flushPromise),e.cancelRetry(),e.onlineListener&&=(W().removeEventListener(`online`,e.onlineListener),void 0),e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel(),e.flushPromise=null,e.debugLog({message:`Queue destroyed`})})()}}class dn{constructor(t){e(this,`params`,void 0),e(this,`queues`,[]),this.params=t;for(let e of t.apis)this.queues.push(this.createQueueForApi(e))}createQueueForApi(e){let t=this.getStorageKeyForApi(e.id);return new un({config:this.params.config,storageKey:t,debugLogger:this.params.debugLogger,errors$:this.params.errors$,userSalt:this.params.userSalt,send:t=>e.logRequest(t),sendBeacon:t=>e.logBeacon(t),canSend$:e.authorized$,requestReady:()=>{e.authorize().catch(e=>{this.params.errors$.next({id:`ThinOneStat:Logger:RequestReadyFailed`,category:nn.NETWORK,message:`Failed to authorize on requestReady`,thrown:e,data:{storageKey:t}})})}})}getStorageKeyForApi(e){return`thinonestat_events_${e}`}log(e){this.queues.forEach(t=>t.log(e))}flush(e){var t=this;return n(function*(){let n=yield tn(t.queues.map(t=>t.flush(e)));if(n.length>0&&n.every(e=>e.status===`rejected`))throw n.find(e=>e.status===`rejected`).reason})()}pause(){this.queues.forEach(e=>e.pause())}resume(){this.queues.forEach(e=>e.resume())}destroy(){var e=this;return n(function*(){yield tn(e.queues.map(e=>e.destroy())),e.queues=[]})()}}function fn(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}class pn{constructor(t){e(this,`offset`,void 0),this.offset=t}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}import{PlaybackState as mn}from"@vkontakte/videoplayer-core/es2015";import{Observable as hn,Subscription as gn,ValueSubject as _n,Subject as vn,fromEvent as yn,isNullable as bn,map as xn,merge as q,filter as Sn,filterChanged as Cn,getWindow as wn}from"@vkontakte/videoplayer-shared/es2015";var Tn=(e,t,n)=>new hn(r=>{let i=new gn,a=new _n(void 0),o;i.add(e.info.isLive$.pipe(Cn()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(xn(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),i.add(o)}));let{playing$:s,paused$:c,ended$:l,looped$:u}=e.events,d=e.events.willSeek$.pipe(Sn(()=>e.info.playbackState$.getValue()===mn.PLAYING)),f=e.events.seeked$.pipe(Sn(()=>e.info.playbackState$.getValue()===mn.PLAYING)),p=!1,m=new vn;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=q(yn(wn(),`beforeunload`),e.events.willDestruct$),g,ee=e=>{g=e},_=e=>{let t=e;bn(g)||bn(t)||g===t||(r.next({from:g,to:t}),g=void 0)},v=new vn,y=new vn,b=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,te=q(s,f,v).pipe(xn(()=>b())),x=q(u,q(c,m,h,l,y).pipe(xn(()=>b()))),ne=t.started$&&t.ended$?q(te,t.ended$):te,re=t.started$&&t.ended$?q(x,t.started$):x;if(i.add(ne.subscribe(ee)).add(re.subscribe(_)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{y.next(),v.next()};i.add(ne.subscribe(()=>{let r=wn().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(re.subscribe(()=>{e.forEach(e=>{wn().clearTimeout(e)}),e=[]}))}return i});import{Subscription as En}from"@vkontakte/videoplayer-core/es2015";import{Observable as Dn,merge as On}from"@vkontakte/videoplayer-shared/es2015";var kn=(e,t)=>new Dn(n=>{let r=new En;return r.add(On(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>=t.targetDuration&&(n.next({target_duration:t.targetDuration,current_tvt:e}),r.unsubscribe())})),r});import{Subscription as An}from"@vkontakte/videoplayer-core/es2015";import{Observable as jn,filter as Mn,getWindow as Nn}from"@vkontakte/videoplayer-shared/es2015";var Pn=(e,{maxTimeWindow:t})=>new jn(n=>{let r=new An,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(Nn().clearTimeout(a.timeoutId),null)},s=()=>{a.bytes=0,a.startTime=0,a.lastEmitTime=0,o()},c=e=>{if(a.bytes<i.minBytesThreshold||e-a.lastEmitTime<i.minTimeWindow&&a.lastEmitTime>0)return!1;let t=(a.startTime>0?e-a.startTime:0)>=i.maxTimeWindow,n=a.bytes>=i.maxBytesThreshold;return t||n},l=(e=!1)=>{let t=Date.now();if(!e&&!c(t))return;o();let r=a.startTime>0?t-a.startTime:Math.max(i.minTimeWindow,1),l=a.bytes/(r/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(l)}),a.lastEmitTime=t,s()},u=()=>{if(o(),a.startTime>0&&a.bytes>=i.minBytesThreshold){let e=Date.now()-a.startTime,t=i.maxTimeWindow-e;t>100?a.timeoutId=Nn().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(Mn(e=>e!==void 0)).subscribe(e=>{let t=Date.now();a.startTime===0&&(a.startTime=t),a.bytes+=e.bytes,c(t)?l():u()})),r.add(()=>{if(o(),a.bytes>0){let e=Date.now(),t=a.startTime>0?e-a.startTime:i.minTimeWindow,r=a.bytes/(t/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(r)})}s()}),r});import{Observable as Fn,Subscription as In,merge as Ln}from"@vkontakte/videoplayer-shared/es2015";var Rn=e=>new Fn(t=>{let n=new In,r=0,i=1,a=0,o=!1,s=!1,c=()=>{if(!o)return;let e=Date.now();a+=(e-r)*i,r=e},l=()=>{(!o||s)&&(r=Date.now(),o=!0,s=!1)},u=()=>{o&&=(c(),!1)},d=()=>{o&&(c(),o=!1,s=!0)},f=e=>{o&&c(),i=e,r=Date.now()},{started$:p,playing$:m,paused$:h,willSeek$:g,ended$:ee,willDestruct$:_}=e.events,{currentPlaybackRate$:v}=e.info;return n.add(g.subscribe(d)).add(Ln(p,m).subscribe(l)).add(Ln(h,ee,_).subscribe(u)).add(v.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),Math.round(e)}),n});import{Observable as zn,Subscription as Bn,merge as Vn}from"@vkontakte/videoplayer-shared/es2015";var Hn=(e,t)=>new zn(n=>{let r=new Bn,i=0;return r.add(Vn(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>i&&Math.floor(e/t.interval)>Math.floor(i/t.interval)&&(i=e,n.next())})),r});import{assertNever as Un}from"@vkontakte/videoplayer-shared/es2015";import{HttpConnectionType as Wn,Surface as J,VideoFormat as Y,VideoQuality as X}from"@vkontakte/videoplayer-core/es2015";var Gn=e=>e&&{[Wn.HTTP1]:`http1`,[Wn.HTTP2]:`http2`,[Wn.QUIC]:`http3`}[e],Z=e=>{if(e!==void 0)switch(e){case Y.MPEG:return`MP4`;case Y.DASH:case Y.DASH_LIVE:return`DASH`;case Y.DASH_SEP:return`DASH_SEP`;case Y.DASH_ONDEMAND:return`ONDEMAND_DASH`;case Y.HLS_ONDEMAND:return`ONDEMAND_HLS`;case Y.HLS:case Y.HLS_LIVE:return`HLS`;case Y.HLS_FMP4:return`HLS_FMP4`;case Y.DASH_WEBM:case Y.DASH_LIVE_WEBM:return`WEBM`;case Y.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case Y.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case Y.WEB_RTC_LIVE:return`WEBRTC`;case Y.DASH_WEBM_AV1:return`AV1`;case Y.DASH_STREAMS:return`MULTI_DASH`;default:return Un(e)}},Q=e=>{if(e!==void 0)switch(e){case X.Q_144P:return`144p`;case X.Q_240P:return`240p`;case X.Q_360P:return`360p`;case X.Q_480P:return`480p`;case X.Q_720P:return`720p`;case X.Q_1080P:return`1080p`;case X.Q_1440P:return`1440p`;case X.Q_2160P:return`2160p`;case X.INVARIANT:case X.Q_576P:case X.Q_4320P:return`UNKNOWN`;default:return Un(e)}},Kn=e=>{if(e!==void 0)switch(e){case`MP4`:case`ONDEMAND_DASH`:case`ONDEMAND_DASH_LIVE`:case`ONDEMAND_HLS`:case`ONDEMAND_HLS_LIVE`:case`MULTI_DASH`:case`WEBM`:case`AV1`:return`vod`;case`DASH`:case`HLS`:case`HLS_FMP4`:case`WEBRTC`:return`live`;default:return}},$=(e,t,n)=>{if(e&&t)switch(e){case Y.MPEG:return n&&t[e]&&t[e][n];default:return t[e]?.url}},qn=(e,t=!1)=>{if(t)return`minimal`;switch(e){case void 0:case J.NONE:return;case J.INLINE:return`inline`;case J.FULLSCREEN:return`fullscreen`;case J.SECOND_SCREEN:return`chromecast`;case J.PIP:return`pip_external`}},Jn=e=>{switch(e){case void 0:return;case J.INVISIBLE:return`background`;default:return`foreground`}},Yn=`_thin-one-stat_deviceId`,Xn=`2.2.0`,Zn=()=>{let e=new jt;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Qn{constructor(t,n){e(this,`apis`,[]),e(this,`logger`,void 0),e(this,`config`,void 0),e(this,`subscription`,void 0),e(this,`beforeunloadSubscription`,void 0),e(this,`timeSynchronisation`,void 0),e(this,`statContext`,void 0),e(this,`deviceId`,void 0),e(this,`targetDuration`,void 0),e(this,`debugLogger`,new St),e(this,`thinOneStatDebugLog`,this.debugLogger.createComponentLog(`ThinOneStat`)),e(this,`eventNumber`,1),e(this,`isStarted`,void 0),e(this,`wasPaused`,void 0),e(this,`isLive`,void 0),e(this,`cdnHostname`,void 0),e(this,`isEmbed`,void 0),e(this,`embedHostname`,void 0),e(this,`connectionType`,void 0),e(this,`connectionReused`,void 0),e(this,`player`,void 0),e(this,`playerSize`,{width:0,height:0}),e(this,`currentSubtitle`,void 0),e(this,`userQuality`,void 0),e(this,`downloadQuality`,void 0),e(this,`downloadSpeed`,void 0),e(this,`networkType`,void 0),e(this,`uiEvents`,void 0),e(this,`playerSubscription`,void 0),e(this,`uiSubscription`,void 0),e(this,`adsSubscription`,void 0),e(this,`seekAction$`,new Mt(`unknown`)),e(this,`vsid$`,new Mt(void 0)),e(this,`isid$`,new Mt(void 0)),e(this,`errors$`,new At),e(this,`getTotalViewTime`,()=>0),this.statContext=t,this.config=zt(n.config??{}),this.subscription=new jt,this.config.synchronizeTime&&(this.timeSynchronisation=new pn),this.subscription.add(this.errors$.subscribe(e=>{this.thinOneStatDebugLog({message:`[${e.category}] ${e.id}: ${e.message}`})}));let r=Ot.get(Yn);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=fn(),Ot.set(Yn,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??be());let i=new en({errors$:this.errors$,config:this.config,timeSynchronisation:this.timeSynchronisation});this.config.apiForticom&&this.apis.push(new qt({config:this.config,apiTransport:i,errors$:this.errors$,deviceId:this.deviceId,refreshAuthToken:n.refreshAuthToken})),this.config.apiUvRest&&(n.getUvRestAuthToken?this.apis.push(new Jt({config:this.config,apiTransport:i,errors$:this.errors$,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken})):this.errors$.next({id:`ThinOneStat:Init:MissingGetUvRestAuthToken`,category:L.WTF,message:`thinStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.logger=new dn({config:this.config,debugLogger:this.debugLogger,apis:this.apis,errors$:this.errors$,userSalt:n.userSalt});let{isEmbed:a,topOrigin:o}=bt();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){this.apis.forEach(t=>{t.authorize(e).catch(()=>{})})}updateContext(e){this.statContext=t(t({},this.statContext),e)}attachTo(e,n){this.playerSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to player, unsubscribing from previous`}),this.playerSubscription.unsubscribe());let r=new jt,i=(e,t)=>r.add(e.subscribe(t));i(Rn(e),e=>{this.getTotalViewTime=e}),i(e.info.isLive$,e=>this.isLive=e),i(e.info.hostname$.pipe(I(e=>e!==void 0)),e=>{this.cdnHostname=e});let a;i(F({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(I(({hostname:e})=>e!==void 0),I(({connectionType:e})=>e!==void 0),I(({connectionReused:e})=>e!==void 0)),({hostname:t,connectionType:n,connectionReused:r})=>{if(a!==void 0&&a!==t){let i={cdn_host:t,connection_type:Gn(n),connection_reused:r,content_type:Z(e.info.currentFormat$.getValue())};this.logFailover(i),this.logTelemetry(this.collectTelemetryData())}this.cdnHostname=a=t}),i(e.info.httpConnectionType$,e=>{this.connectionType=Gn(e)}),i(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),i(Tn(e,n,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval,exactTime:this.config.watchCoverageExactTime}),n=>{let r={watch_interval:`${Math.round(n.from*1e3)}-${Math.round(n.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:Z(e.info.currentFormat$.getValue()),playback_quality:Q(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(r);else{let n=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive(t(t({},r),{},{live:!!n}))}}),i(Hn(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),i(kn(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),i(e.events.willReady$,()=>{let t={isid:this.isid$.getValue(),stream_profile:Kn(Z(e.info.currentFormat$.getValue())),dpi:Math.round(this.statContext.dpi??96*R.display.pixelRatio),web_layout:this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};if(this.isEmbed&&(t.iframe_host=this.embedHostname??`unknown`),this.logStartSession(t),this.statContext.preload){let t=e.info.currentFormat$.getValue(),n=e.info.availableSources$.getValue(),r=e.info.currentBuffer$.getValue(),i=e.info.currentQuality$.getValue(),a={target_buffer_time:this.calcBufferTime(r),playback_url:$(t,n,i),playback_quality:Q(i)};this.logPreloadStarted(a)}}),i(F({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(I(({connectionType:e})=>e!==void 0),I(({connectionReused:e})=>e!==void 0),Tt()),()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(t)}),i(F({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(I(({connectionType:e})=>e!==void 0),I(({connectionReused:e})=>e!==void 0),Tt()),()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(t)}),i(e.events.manifestReceived$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(t)}),i(e.events.firstBytesRequested$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(t)}),i(e.events.firstBytes$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(t)}),i(Ct(e.events.willStart$,e.events.looped$),e=>{e&&this.resetViewSession(),this.isStarted=!0}),i(e.events.started$,()=>{let t=e.info.currentBuffer$.getValue(),n=e.info.currentQuality$.getValue(),r=e.info.isAutoQualityEnabled$.getValue(),i=e.info.muted$.getValue(),a=e.info.volume$.getValue(),o=e.info.surface$.getValue(),s=e.info.availableTextTracks$.getValue(),c=e.info.currentTextTrack$.getValue(),l=e.info.currentAudioStream$.getValue(),u=e.info.currentPlaybackRate$.getValue(),d={playback_quality:Q(n),user_quality:r?`auto`:Q(n),player_width:Math.round(this.statContext.playerSize?.width??this.playerSize.width),player_height:Math.round(this.statContext.playerSize?.height??this.playerSize.height),muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:qn(o,this.statContext.isPreviewPlayerView),visibility:Jn(o),subtitles_enabled:c?!!c:this.currentSubtitle?.enabled,auto_subtitles:s.find(({id:e})=>e===c)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:l?.language,playback_rate:u*100,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d),this.logTelemetry(this.collectTelemetryData())}),i(e.events.willStart$,()=>{this.logPlay()}),i(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.wasPaused&&this.logResume()}),i(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),i(e.events.ended$,()=>{this.logContentEndReached()}),i(e.events.willStop$,()=>{this.isStarted=!1,this.logStop()}),i(Ct(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let o=e=>{switch(e){case L.NETWORK:return`network`;case L.VIDEO_PIPELINE:return`video_pipeline`;case L.EXTERNAL_API:return`external_api`;case L.PARSER:return`parser`;case L.DOM:return`dom`;default:return`wtf`}},s=e=>L.FATAL===e?`critical`:`informative`;i(e.events.fetcherRecoverableError$,({id:t,category:n,data:r,message:i,httpCode:a,UVBackendErrorCode:c})=>{let l={error_severity:s(n),error_category:o(n),player_error_code:t,player_error_trace:r,http_error_code:a,uv_backend_error_code_subcode:c,error_message:i,content_type:Z(e.info.currentFormat$.getValue())};this.logError(l),s(n)===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(e.events.managedError$,({id:t,category:n,data:r,message:i})=>{let a={error_severity:s(n),error_category:o(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Z(e.info.currentFormat$.getValue())};this.logError(a),this.logTelemetry(this.collectTelemetryData())}),i(e.events.fatalError$,({id:t,category:n,data:r,message:i})=>{let a={error_severity:`critical`,error_category:o(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Z(e.info.currentFormat$.getValue())};this.logError(a),this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(F({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(I(({connectionReused:e})=>e!==void 0),I(({connectionMetrics:e})=>e!==void 0),wt((e,t)=>e.connectionType===t.connectionType)),({connectionMetrics:t})=>{let n=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),i=e.info.currentQuality$.getValue(),a=e.info.rttEstimation$.getValue();this.networkType=this.statContext.networkType??t?.networkType;let o=t?.dnsResolveTime,s=t?.tcpHandshakeTime,c=t?.tlsHandshakeTime,l={playback_url:$(n,r,i),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:a?Math.round(a):void 0,network_type:this.networkType,dns_resolve_time:o?Math.round(o):void 0,tcp_handshake_time:s?Math.round(s):void 0,tls_handshake_time:c?Math.round(c):void 0};this.logConnectionEstablished(l)}),i(Pn(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),i(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),i(e.events.willSeek$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),i(e.events.seeked$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),i(e.info.isStalled$,t=>{let n=e.info.currentBuffer$.getValue(),r=this.calcBufferTime(n);t&&r&&r>0&&(this.logBufferStarvation({buffer_time:r}),this.logTelemetry(this.collectTelemetryData()))}),i(e.info.currentBuffer$.pipe(I(e=>!!this.calcBufferTime(e)),Tt()),e=>{let t=this.calcBufferTime(e);if(this.statContext.preload){let e={buffer_time:t};this.logPreloadEnded(e)}this.logReady({buffer_time:t})});let c;i(F({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(I(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),I(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(c!==r){if(this.userQuality=e.info.isAutoQualityEnabled$.getValue()?`auto`:Q(r),this.downloadQuality=Q(r),this.isStarted){let e=t?.codec,r=n?.codec,i={user_quality:this.userQuality,playback_quality:Q(c),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}c=r}});let l,u;return i(e.info.surface$,e=>{let t=qn(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),u=Jn(e),l!==u&&(this.isStarted&&this.logVisibilityChanged({visibility:u}),l=Jn(e))}),i(F({muted:e.info.muted$,volume:e.info.volume$}).pipe(Dt(300)),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),i(e.info.currentFormat$.pipe(I(e=>e!==void 0),Et(1)),e=>{let t={content_type:Z(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),i(e.info.currentAudioStream$.pipe(I(e=>e!==void 0),Et(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),i(e.info.currentVideoStream$.pipe(I(e=>e!==void 0),Et(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.playerSubscription=r,this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToUi(e){this.uiSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to UI, unsubscribing from previous`}),this.uiSubscription.unsubscribe()),this.uiEvents=e;let{subscribe:n,subscription:r}=Zn();n(e.actionSeek$,this.seekAction$),n(e.playerSize$,({width:e,height:t})=>{e&&t&&(this.playerSize={width:e,height:t},this.isStarted&&this.logViewPortChanged({player_width:Math.round(e),player_height:Math.round(t)}))}),n(e.isLoaderVisible$,e=>{e&&this.isStarted&&this.logShowLoader()}),n(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle=t({},e),this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:i}=dt(this.uiEvents,n,this.player);return n(i,e=>{this.isStarted&&this.logModeChanged({mode:qn(e)})}),n(e.actionQuality$,e=>{var t,n,r;let i=e=>vt(_t(Pt),e),a=(t=this.player)==null||(t=t.info.currentVideoStream$.getValue())==null?void 0:t.codec,o=(n=this.player)==null||(n=n.info.currentAudioStream$.getValue())==null?void 0:n.codec,s={user_quality:i(e)?`auto`:Q(e),playback_quality:Q(this.player?.info.currentQuality$.getValue()),download_quality:i(e)?Q((r=this.player)==null||(r=r.info.currentQuality$)==null?void 0:r.getValue()):Q(e),codec_info:this.genCodecInfo(a,o)};this.logQualityChangeRequested(s)}),this.uiSubscription=r,this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToAds(e){this.adsSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to ads, unsubscribing from previous`}),this.adsSubscription.unsubscribe());let{subscription:t,subscribe:n}=Zn();return n(e.init$,e=>{let t={slot:e};this.logAdvConfiguration(t)}),n(e.slotRequested$,e=>{let t={adv_section:e};this.logAdvRequest(t)}),n(e.started$,e=>{let t={adv_section:e};this.logAdvBreakStarted(t)}),n(e.ended$,({section:e,ordIds:t})=>{let n={adv_section:e,erids:t.join(`,`)};this.logAdvBreakEnded(n)}),n(e.error$,e=>{let t={error_message:e};this.logAdvError(t)}),this.adsSubscription=t,this.resubscribeBeforeunload(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),w.generateVSID(this.config.useVsid64),this.vsid$.next(w.getVSID()),this.eventNumber=0}destroy(){var e=this;return n(function*(){e.thinOneStatDebugLog({message:`Destroying ThinOneStat`}),e.subscription.unsubscribe(),yield e.logger.destroy(),e.apis.forEach(e=>e.destroy()),e.thinOneStatDebugLog({message:`ThinOneStat destroyed`})})()}calcBufferTime(e){return e?Math.round((e.end??0)-(e.start??0))*1e3:void 0}genCodecInfo(e,t){return e&&t?`${e},${t}`:void 0}getLatencyInfo(){let e=this.player?.info.atLiveEdge$.getValue(),t={client_time:Date.now(),live:e};return JSON.stringify(t)}collectTelemetryData(){if(!this.player)return{};let e=this.player.info.currentBuffer$.getValue(),t=this.player.experimental.element$.getValue(),n=0,r=0;t&&(n=t.getVideoPlaybackQuality().droppedVideoFrames,r=t.getVideoPlaybackQuality().totalVideoFrames);let i=Z(this.player.info.currentFormat$.getValue()),a=this.player.info.currentVideoStream$.getValue()?.codec,o=this.player.info.currentAudioStream$.getValue()?.codec,s=this.player.info.videoBitrate$.getValue(),c=this.player.info.rttEstimation$.getValue();return{buffer_time:this.calcBufferTime(e),dropped_frames_count:n,rendered_frames_count:r,content_type:i,user_quality:this.userQuality,playback_quality:Q(this.player.info.currentQuality$.getValue()),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(a,o),bandwidth_from_manifest:s?Math.round(s):void 0,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed?Math.round(this.downloadSpeed):void 0,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}isValidPlatform(e=``){return vt([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();yt(t);let n=this.eventNumber++,r=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,i={vsid:t,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${T}`,platform:this.isValidPlatform(this.statContext.platform)?this.statContext.platform:`web:${this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`}`,product:this.statContext.product,event_number:n,playback_position:Math.round(r),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let e of this.config.disabledParams)delete i[e];return i}createRequiredFatParams(){let e={stats_version:Xn,browser:this.statContext.browser??R.browser.current,browser_version:this.statContext.browserVersion??String(R.browser.currentVersion),os:this.statContext.os??R.device.os.name,os_version:this.statContext.osVersion??R.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??R.device.details.vendor,device_model:this.statContext.deviceModel??R.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,n,r=!1){if(vt(this.config.disabledEvents,e))return;let i=this.createRequiredParams(e),a={};r&&(a=this.createRequiredFatParams()),this.logger.log(t(t(t({},i),a),n))}logWatchCoverage(e){this.log(`watch_coverage`,e,!0)}logWatchCoverageLive(e){this.log(`watch_coverage_live`,e,!0)}logWatchedN(e){this.log(`watched_n`,e,!0)}logStartSession(e){this.log(`start_session`,e,!0)}logPreloadStarted(e){this.log(`preload_started`,e)}logPreloadEnded(e){this.log(`preload_ended`,e)}logPreloadError(){this.log(`preload_error`)}logPlaybackStarted(e){this.log(`playback_started`,e,!0)}logPlay(){this.log(`play`)}logManifestRequest(e){this.log(`manifest_request`,e)}logFirstByteManifest(e){this.log(`first_byte_manifest`,e)}logFirstMediaRequest(e){this.log(`first_media_request`,e)}logFirstByteMedia(e){this.log(`first_byte_media`,e)}logManifestReceived(e){this.log(`manifest_received`,e)}logConnectionEstablished(e){this.log(`connection_established`,e)}logFirstVideoFrameDecoded(){this.log(`first_video_frame_decoded`)}logReady(e){this.log(`ready`,e)}logPlaying(e){this.log(`playing`,e)}logPause(){this.log(`pause`)}logResume(){this.log(`resume`)}logSeeking(e){this.log(`seeking`,e)}logSeeked(e){this.log(`seeked`,e)}logContentEndReached(){this.log(`content_end_reached`)}logStop(){this.log(`stop`)}logBufferStarvation(e){this.log(`buffer_starvation`,e)}logShowLoader(){this.log(`show_loader`)}logQualityChangeRequested(e){this.log(`quality_change_requested`,e)}logQualityChanged(e){this.log(`quality_changed`,e)}logCdnHostChanged(e){this.log(`cdn_host_changed`,e)}logViewPortChanged(e){this.log(`view_port_changed`,e)}logModeChanged(e){this.log(`mode_changed`,e)}logVisibilityChanged(e){this.log(`visibility_changed`,e)}logAudioTrackSwitched(e){this.log(`audio_track_switched`,e)}logVideoTrackSwitched(e){this.log(`video_track_switched`,e)}logSubtitlesSwitched(e){this.log(`subtitles_switched`,e)}logSoundChanged(e){this.log(`sound_changed`,e)}logFailover(e){this.log(`failover`,e)}logContentTypeChange(e){this.log(`content_type_change`,e)}logError(e){this.log(`error`,e,!0)}logCannotPlay(){this.log(`cannot_play`,{},!0)}logDownloadBytes(e){this.log(`download_bytes`,e)}logTelemetry(e){this.log(`telemetry`,e)}logAdvConfiguration(e){this.log(`adv_configuration`,e)}logAdvRequest(e){this.log(`adv_request`,e)}logAdvBreakStarted(e){this.log(`adv_break_started`,e)}logAdvBreakEnded(e){this.log(`adv_break_ended`,e)}logAdvError(e){this.log(`adv_error`,e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=xt(kt(),`beforeunload`).subscribe(()=>{this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload}).catch(()=>{})}),this.subscription.add(this.beforeunloadSubscription)}}import{cancelIdleCallbackPolyfilled as $n}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as er}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as tr,Subscription as nr}from"@vkontakte/videoplayer-core/es2015";import{Logger as rr}from"@vkontakte/videoplayer-shared/es2015";class ir{constructor(){e(this,`startTime`,null),e(this,`stopTime`,null),e(this,`accumulatedTime`,0)}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime===null?this.startTime=this.now():(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null))}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}}var ar=()=>window.Image?new Image:document.createElement(`img`);class or{constructor(t){e(this,`params`,void 0),e(this,`position`,0),e(this,`started`,!1),e(this,`isActiveLive`,void 0),e(this,`heartbeatPixels`,[]),e(this,`heartbeatLastTimeSent`,{}),e(this,`heartbeatInterval`,void 0),e(this,`heartbeatFirstTimeoutId`,void 0),e(this,`idleCallbackIds`,[]),e(this,`log`,void 0),e(this,`stopwatch`,new ir),e(this,`subscription`,new nr),this.params=t,this.log=new rr().createComponentLog(`MediascopePixel`)}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(e=>this.onPlaybackState(e))).add(e.info.position$.subscribe(e=>this.onPosition(e))).add(e.info.atLiveEdge$.subscribe(e=>this.isActiveLive=e)),this.subscription.add(e.events.willSeek$.subscribe(()=>this.onWillSeek())).add(e.events.seeked$.subscribe(()=>this.onSeeked())).add(e.events.ended$.subscribe(()=>this.onEnded()))}destroy(){this.stopwatch.reset(),this.subscription.unsubscribe(),window.clearTimeout(this.heartbeatFirstTimeoutId),this.idleCallbackIds.forEach(e=>$n(e)),this.send(`stop`)}onPlaybackState(e){e===tr.PLAYING?this.started?this.play():this.start():e===tr.PAUSED&&this.pause()}start(){this.started=!0,this.stopwatch.start(),this.send(`start`),this.heartbeatPixels=this.prepareHeartbeatPixels(),this.heartbeatInterval=this.heartbeatPixels[0]?.interval;let e=this.heartbeatPixels[0]?.url,t=this.heartbeatPixels[0]?.delay;if(t!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},t*1e3)}catch(e){this.log({message:e.message})}}play(){this.stopwatch.start(),this.send(`resume`)}pause(){this.stopwatch.stop(),this.send(`pause`)}onPosition(e){if(this.position=e,this.heartbeatInterval&&this.stopwatch.time!==0&&this.stopwatch.time%this.heartbeatInterval===0)for(let[e,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[e]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[e]=this.stopwatch.time,this.sendHeartbeat(t))}onWillSeek(){this.started&&this.send(`stop`)}onSeeked(){this.started&&this.send(`start`)}onEnded(){this.stopwatch.stop(),this.send(`stop`)}validatePixels(e,t){return e?.filter(e=>e.event===t.event&&t.keys.every(t=>!!e[t]))}getFrameTimestamp(){let e;if(this.isActiveLive){let t=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-t}else e=this.position||0;return Math.floor(e)}getUTC(){return Math.floor(Date.now()/1e3)}prepareUrl(e){return e.replace(`{@fts_fake_sec}`,String(this.getFrameTimestamp())).replace(`{@utc_sec}`,String(this.getUTC())).split(`&`).filter(e=>!/={@[a-zA-Z_]+}/.test(e)).join(`&`)}preparePixels(e){return this.validatePixels(this.params.pixels,{event:e,keys:[`url`]})}prepareHeartbeatPixels(){return this.validatePixels(this.params.pixels,{event:`heartbeat`,keys:[`url`,`interval`]})}call(e){try{this.idleCallbackIds.push(er(()=>ar().src=this.prepareUrl(e)))}catch(e){this.log({message:e.message})}}send(e){let t=this.preparePixels(e);for(let{url:e}of t)this.call(e)}sendHeartbeat(e){this.call(e)}}export{T as VERSION,gt as ThinOneStat,p as SeekAction,u as Quality,ht as OneStat,or as MediascopePixel,m as InteractiveInterfaceClick,d as ContentType,f as ConnectionType,l as ApiEnv};
|
|
6
|
+
import{arrayIncludes as _}from"@vkontakte/videoplayer-shared/es2015";import{urlCanParsePolyfilled as v}from"@vkontakte/videoplayer-shared/es2015";import{fillWithDefault as se}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as pe,combine as me,fromEvent as he,isNonNullable as C,isNullable as ge,merge as _e,now as w,observableFrom as ve,once as ye,safeStorage as be,Subject as xe,Subscription as Se,ValueSubject as Ce,getWindow as we}from"@vkontakte/videoplayer-shared/es2015";import{Logger as Te,detectEmbed as Ee,ErrorCategory as De}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as Oe}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as je}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Me}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as Ne}from"@vkontakte/videoplayer-shared/es2015";import{ValueSubject as Fe,getExponentialDelay as Ie,ErrorCategory as D,getWindow as Le}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as Ve}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as He}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Ue}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as O,now as k,getWindow as We}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ke}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as qe}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Je,now as Ye,safeStorage as A,debounceFn as Xe}from"@vkontakte/videoplayer-shared/es2015";import{HttpConnectionType as $e,Surface as j,VideoFormat as M,VideoQuality as N}from"@vkontakte/videoplayer-core/es2015";import{assertNever as et}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as st}from"@vkontakte/videoplayer-core/es2015";import{filter as ct,filterChanged as lt,fromEvent as ut,isNullable as dt,map as ft,merge as pt,Observable as mt,Subject as ht,Subscription as gt,ValueSubject as _t}from"@vkontakte/videoplayer-shared/es2015";import{Surface as P}from"@vkontakte/videoplayer-core/es2015";import{debounce as yt,filterChanged as bt,Subject as xt}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as Ot}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as kt}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as At,detectEmbed as jt,fromEvent as Mt,Logger as Nt,merge as Pt,combine as F,filter as I,filterChanged as Ft,once as It,skip as Lt,debounce as Rt,safeStorage as zt,getWindow as Bt,Subject as Vt,Subscription as Ht,ValueSubject as Ut,ErrorCategory as L}from"@vkontakte/videoplayer-shared/es2015";import{clientChecker as R}from"@vkontakte/videoplayer-core/es2015";import{fillWithDefault as Wt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Zt}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Qt}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as z,ValueSubject as $t}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as sn}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as cn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as B}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as ln}from"@vkontakte/videoplayer-shared/es2015";import{now as V,getWindow as H,getExponentialDelay as un,isAbortError as dn,ErrorCategory as U}from"@vkontakte/videoplayer-shared/es2015";import{promiseAllSettled as pn}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as mn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as hn}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as gn}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as _n}from"@vkontakte/videoplayer-shared/es2015";import{now as vn,debounceFn as yn,getWindow as W,safeStorage as G,ErrorCategory as K}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as Tn}from"@vkontakte/videoplayer-core/es2015";import{Observable as En,Subscription as Dn,ValueSubject as On,Subject as kn,fromEvent as An,isNullable as jn,map as Mn,merge as q,filter as Nn,filterChanged as Pn,getWindow as Fn}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as Ln}from"@vkontakte/videoplayer-core/es2015";import{Observable as Rn,merge as zn}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as Vn}from"@vkontakte/videoplayer-core/es2015";import{Observable as Hn,filter as Un,getWindow as Wn}from"@vkontakte/videoplayer-shared/es2015";import{Observable as Kn,Subscription as qn,merge as Jn}from"@vkontakte/videoplayer-shared/es2015";import{Observable as Xn,Subscription as Zn,merge as Qn}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as er}from"@vkontakte/videoplayer-shared/es2015";import{HttpConnectionType as tr,Surface as J,VideoFormat as Y,VideoQuality as X}from"@vkontakte/videoplayer-core/es2015";import{cancelIdleCallbackPolyfilled as ur}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as dr}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as fr,Subscription as pr}from"@vkontakte/videoplayer-core/es2015";import{Logger as mr}from"@vkontakte/videoplayer-shared/es2015";var _oxcModsitth1=function(){function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}var t=e;function n(e,n){if(t(e)!=`object`||!e)return e;var r=e[Symbol._oxc_toPrimitive];if(r!==void 0){var i=r.call(e,n||`default`);if(t(i)!=`object`)return i;throw TypeError(`@@_oxc_toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(e)}var t=e,r=n;function i(e){var n=r(e,`string`);return t(n)==`symbol`?n:n+``}var a=i;function o(e,t,n){return(t=a(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=o;function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?c(Object(n),!0).forEach(function(t){s(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function u(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function d(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){u(a,r,i,o,s,`next`,e)}function s(e){u(a,r,i,o,s,`throw`,e)}o(void 0)})}}var f=l,p=d,m=Object.defineProperty,h=e=>e;function g(e,t){this[e]=h.bind(null,t)}var ee=(e,t)=>{for(var n in t)m(e,n,{get:t[n],enumerable:!0,configurable:!0,set:g.bind(t,n)})};var y;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(y||={});var b;(e=>{e.Q144P=`mobile`,e.Q240P=`lowest`,e.Q360P=`low`,e.Q480P=`medium`,e.Q720P=`high`,e.Q1080P=`fullhd`,e.Q1440P=`quadhd`,e.Q2160P=`ultrahd`,e.UNKNOWN=`unknown`})(b||={});var x;(e=>{e.MP4=`mp4`,e.DASH=`dash`,e.DASH_SEP=`dash_sep`,e.ONDEMAND_DASH=`ondemand_dash`,e.HLS=`hls`,e.HLS_FMP4=`hls_fmp4`,e.ONDEMAND_HLS=`ondemand_hls`,e.WEBM=`webm`,e.AV1=`av1`,e.ONDEMAND_DASH_LIVE=`ondemand_dash_live`,e.ONDEMAND_HLS_LIVE=`ondemand_hls_live`,e.WEBRTC=`webrtc`,e.UNKNOWN=`unknown`,e.RTMP=`rtmp`})(x||={});var S;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(S||={});var te;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(te||={});var ne;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(ne||={});var re={action_play:`ap`,action_play_interactive:`api`,first_bytes:`fb`,player_ready:`pr`,first_frame:`ff`,seek:`sk`,watch_coverage_record:`wr`,watch_coverage_live:`wl`,empty_buffer:`eb`,action_stop:`as`,close_at_empty_buffer:`cb`,content_error:`er`,player_interface_click:`pc`,next_movie:`nm`,track_switch:`ts`,failover:`fo`,quality:`qt`},ie={vsid:`si`,isid:`is`,vid:`vi`,place:`pl`,quality:`qt`,cdn_host:`ch`,stat_type:`st`,param:`pm`,vk_app_id:`va`,track_code:`tc`,connection_type:`cnt`,connection_reused:`cr`,cached_data:`cd`,live:`lv`,muted:`mu`,mode:`mo`,subtitles:`sb`,failover:`fo`,download_speed:`ds`,manual_quality:`mq`,ref_domain:`rd`,direct_url:`du`},ae={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},oe={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`};var ce=`CIOPGQJGDIHBABABA`,le={prod:`https://api.ok.ru`,vk_alias:`https://api.mycdn.me`,videotest:`https://videotestapi.ok.ru/api`,test:`https://apitest.ok.ru`,okcdn:`https://api.okcdn.ru`,auto:``},ue={apiEnv:`vk_alias`,apiKey:ce,apiBaseUrl:null,apiForticom:!0,apiUvRest:!1,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*60*1e3,watchCoverageInterval:15e3,disabledOperations:[`quality`],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,clearStorageAtUnload:!0,useVKComIsMobileLogic:!1,backoff:{start:1e3,factor:1.5,max:300*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!0,watchCoverageExactTime:!1},de=e=>se(e,ue);function fe(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}var ke=()=>Oe(Math.floor(Math.random()*2**32).toString(36),13,`0`),Ae=()=>Oe(Math.floor(Math.random()*2**64).toString(36),13,`0`);class T{static getVSID(){return T.vsid}static generateVSID(e){return T.vsid=e?Ae():ke(),T.vsid}}T.vsid=void 0;var Pe=e=>{let{operation:t,custom:n}=e,r=Ne(Me(n).map(([e,t])=>{let n=ie[e]??e,r=t;return t&&(e===`mode`?r=oe[t]??t:e===`quality`&&(r=ae[t]??t)),[n,r]}));return f(f({},e),{},{operation:re[t]??t,custom:r})},E=`1.0.109-dev.c8b4dec46.0`;var Re=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class ze{constructor(e){this.id=`forticom`,this.params=void 0,this.authToken=void 0,this.sessionKey=void 0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.consequentAuthErrors=0,this.authorized$=new Fe(!1),this.backoffTimeoutId=void 0,this.params=e}authorize(e){var t=this;return p(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t._authorizeWithBackoff()})()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return p(function*(){let n=`log.externalLog`,r=t.createLogParams(e),i=t.sessionKey??(yield t._authorizeWithBackoff());if(!i)return;let a=function(){var e=p(function*(e,o=t.params.config.requestRetryCount){try{return yield t.params.apiTransport.sendRequest(n,r,i)}catch(r){if(!r||!(`error_code`in r)){t.params.error$.next({id:`logRequestUnknown`,category:D.NETWORK,message:`Unknown ${n} error`,thrown:r});return}let i=r?.error_code;switch(i){case 102:case 103:case 104:return t.authorized$.next(!1),t.sessionKey=yield t._authorizeWithBackoff(),o>0?a(e,o-1):void 0;case 401:return t.authorized$.next(!1),t.authToken=yield t.refreshAuthToken(),t.sessionKey=yield t._authorizeWithBackoff(),o>0?a(e,o-1):void 0;default:t.params.error$.next({id:`LogRequest#${i}`,category:D.EXTERNAL_API,message:`${n} error`,data:r});return}}});return function(t){return e.apply(this,arguments)}}();return a(e)})()}destroy(){Le().clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return p(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=je(e.params.refreshAuthToken(),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${E}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=Le().navigator;n=Re.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(Pe):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ie(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=Le().setTimeout(()=>{je(this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:D.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})),()=>this.backoffTimeoutId=0)},e)})}_authorize(){var e=this;return p(function*(){if(e.authorizePromise)return e.authorizePromise;e.sessionKey=void 0,e.authorized$.next(!1);let t={session_data:{version:2,device_id:e.params.deviceId,client_version:E.split(`-`)[0],client_type:`SDK_JS`}};return e.authToken!==void 0&&(t.session_data.auth_token=e.authToken,t.session_data.version=3),e.authorizePromise=je(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>((!t||!t.session_key)&&e.params.error$.next({id:`AuthorizeFailed`,category:D.EXTERNAL_API,message:`No session key`,data:t}),e.sessionKey=t?.session_key??void 0,e.sessionKey)).catch(function(){var t=p(function*(t){e.sessionKey=void 0;let n=t?.error_code;switch(n){case 401:return e.authToken=yield e.refreshAuthToken(),e._authorizeWithBackoff()}n?e.params.error$.next({id:`Authorize#${n}`,category:D.EXTERNAL_API,message:`authorize error`,data:t}):e.params.error$.next({id:`AuthorizeUnknown`,category:D.NETWORK,message:`authorize error`,thrown:t})});return function(e){return t.apply(this,arguments)}}()),()=>{e.authorizePromise=void 0,e.consequentAuthErrors=e.sessionKey?0:e.consequentAuthErrors+1,e.authorized$.next(e.sessionKey!==void 0)}),e.authorizePromise})()}}class Be{constructor(e){this.id=`uvrest`,this.authorized$=new Fe(!1),this.params=void 0,this.statToken=void 0,this.authorizePromise=void 0,this.isDestroyed=!1,this.params=e}authorize(e){var t=this;return p(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=je(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return p(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.error$.next({id:`OneStat:UvRestApi:LogRequestNoToken`,category:D.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return p(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return p(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.error$.next({id:`OneStat:UvRestApi:NoToken`,category:D.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.error$.next({id:`OneStat:UvRestApi:AuthorizeFailed`,category:D.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return p(function*(){let n=e?.status;return n===401?(t.params.error$.next({id:`OneStat:UvRestApi:TokenExpired`,category:D.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.error$.next({id:`OneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:D.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return p(function*(){let n=t.statToken;if(!n){t.params.error$.next({id:`OneStat:UvRestApi:RetryNoToken`,category:D.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.error$.next({id:`OneStat:UvRestApi:RetryFailed`,category:D.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${E}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=Le().navigator;n=Re.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),[{application:r,platform:t,user_id:this.params.userId,items:this.params.config.shorten?e.map(Pe):e}]}}class Ge{constructor(e){this.apiKey=void 0,this.apiBaseUrl=void 0,this.apiEnv=void 0,this.timeSynchronisation=void 0,this.isApiBaseUrlFetched=void 0,this.params=void 0,this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??le[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){var e=this;return p(function*(){if(e.apiEnv!==`auto`||e.isApiBaseUrlFetched)return e.apiBaseUrl;try{var t;let e=yield(yield Ve(atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),{method:`GET`,mode:`cors`,cache:`no-cache`})).json(),n=e==null||(t=e.Answer[0])==null?void 0:t.data;if(!n)throw Error(`Wrong DNS response`);return n}catch(t){return e.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:O.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),le.vk_alias}finally{e.isApiBaseUrlFetched=!0}})()}sendBeacon(e,t,n){if(!We().Blob||!We().navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=We().Blob,a=new i([r.toString()],{type:`application/x-www-form-urlencoded`});try{return We().navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:O.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n){var r=this;return p(function*(){let i=k(),a=a=>{if(a instanceof TypeError&&He([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],a.message)){r.params.error$.next({id:`Network`,category:O.NETWORK,message:`Request failed`,thrown:a});return}r.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:O.NETWORK,message:`Unhandled request error`,thrown:a,data:{method:e,params:t,sessionKey:n,time:k()-i}})};r.apiBaseUrl=yield r.resolveApiBaseUrl();let o={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:r._prepareQueryParams({method:e,queryParams:t,sessionKey:n})};return r.params.config.useKeepalive&&(o.keepalive=!0),Ve(`${r.apiBaseUrl}/fb.do`,o).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),o=k()-i;if(isFinite(n)&&r.timeSynchronisation?.addServerTime(n,o),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)})()}sendJsonBeacon(e,t,n){let r=`${this.apiBaseUrl}${e}`;try{Ve(r,{method:`POST`,headers:f({"Content-Type":`application/json`},n),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:O.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:O.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequest(e,t,n){var r=this;return p(function*(){let i=k(),a=t=>{if(t instanceof TypeError&&He([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],t.message)){r.params.error$.next({id:`Network`,category:O.NETWORK,message:`JSON request failed`,thrown:t});return}r.params.error$.next({id:`OneStat:ApiTransport:sendJsonRequest`,category:O.NETWORK,message:`Unhandled JSON request error`,thrown:t,data:{path:e,time:k()-i}})};r.apiBaseUrl=yield r.resolveApiBaseUrl();let o={method:`POST`,headers:f({"Content-Type":`application/json`},n),body:JSON.stringify(t)};return r.params.config.useKeepalive&&(o.keepalive=!0),Ve(`${r.apiBaseUrl}${e}`,o).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),o=k()-i;if(isFinite(n)&&r.timeSynchronisation?.addServerTime(n,o),!e.ok)return Promise.reject({status:e.status,statusText:e.statusText});if(!t)return e.json().catch(a)},a)})()}_prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Ue(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var Ze=e=>t=>t.timestamp+e>=Ye();class Qe{constructor(e){this.params=void 0,this.error$=void 0,this.userSalt=void 0,this.isPaused=!1,this.loggerDebugLog=void 0,this.queues=[],this.isUrgent=e=>{let{operation:t}=e;return Ke([`action_play`,`action_play_interactive`,`watch_coverage_record`,`watch_coverage_live`,`action_stop`,`close_at_empty_buffer`],t)},this.params=e,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`);for(let t of e.apis)this.queues.push(this.createQueueState(t));this.housekeepStorage()}createQueueState(e){let t=`onestat_events_${e.id}`,n=Xe(()=>this.safeFlushQueue(a),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime}),r=A.isPersistent()?this.params.config.flushMaxWait:0,i=Xe(()=>this.safeFlushQueue(a),this.params.config.flushDebounceTime,{maxWait:r}),a={api:e,storageKey:t,unsaltedStorage:[],lastVsid:void 0,firstFlush:n,debouncedFlush:i,subscription:e.authorized$.subscribe(e=>{e&&i()})};return a}safeFlushQueue(e){try{this.flushQueue(e)}catch(t){this.error$.next({id:`LoggerError`,category:Je.WTF,message:t?String(t):`Unknown logger error`,thrown:t,data:{storageKey:e.storageKey}})}}readFromStorage(e){let t=A.get(e);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(e,t){if(!this.userSalt){e.unsaltedStorage.push(t);return}let n=this.readFromStorage(e.storageKey),r=(n[this.userSalt]??[]).filter(Ze(this.params.config.storageExpiration));A.set(e.storageKey,JSON.stringify(f(f({},n),{},{[this.userSalt]:[...r,t]})))}getFromStorage(e){return this.userSalt?(this.readFromStorage(e.storageKey)[this.userSalt]??[]).filter(Ze(this.params.config.storageExpiration)):e.unsaltedStorage}markStorageSent(e){if(!this.userSalt){e.unsaltedStorage=[];return}let t=this.readFromStorage(e.storageKey);delete t[this.userSalt],A.set(e.storageKey,JSON.stringify(t))}housekeepStorage(){for(let e of this.queues){let t=this.readFromStorage(e.storageKey);for(let[n,r]of qe(t)){let i=r.filter(Ze(this.params.config.storageExpiration));i.length?t[n]=i:delete t[n],this.loggerDebugLog({message:`${r.length} retrieved from storage, ${i.length} of them actual (${e.storageKey})`})}A.set(e.storageKey,JSON.stringify(t))}}log(e){for(let t of this.queues)this.addToStorage(t,e),!this.isPaused&&(this.isUrgent(e)?this.flushQueue(t):t.lastVsid===e.custom.vsid?t.debouncedFlush():t.firstFlush(),t.lastVsid=e.custom.vsid)}flush(e={wantBeacon:!1,clearStorage:!0}){for(let t of this.queues)this.flushQueue(t,e)}flushQueue(e,{wantBeacon:t,clearStorage:n}={wantBeacon:!1,clearStorage:!0}){let r=this.getFromStorage(e);r.length!==0&&(e.api.authorized$.getValue()?(t&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${r.length} events through beacon (${e.storageKey})`}),e.api.logBeacon(r)):(this.loggerDebugLog({message:`Flushing ${r.length} events (${e.storageKey})`}),e.api.logRequest(r)),n&&this.markStorageSent(e)):e.api.authorize(),e.firstFlush.cancel(),e.debouncedFlush.cancel())}pause(){this.isPaused=!0;for(let e of this.queues)e.debouncedFlush.cancel()}resume(){this.isPaused=!1;for(let e of this.queues)e.debouncedFlush()}destroy(){for(let e of this.queues)e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel();this.queues=[]}}var tt=e=>e&&{[N.INVARIANT]:`unknown`,[N.Q_144P]:`mobile`,[N.Q_240P]:`lowest`,[N.Q_360P]:`low`,[N.Q_480P]:`medium`,[N.Q_576P]:`unknown`,[N.Q_720P]:`high`,[N.Q_1080P]:`fullhd`,[N.Q_1440P]:`quadhd`,[N.Q_2160P]:`ultrahd`,[N.Q_4320P]:`unknown`}[e],nt=e=>e&&{[$e.HTTP1]:`http1`,[$e.HTTP2]:`http2`,[$e.QUIC]:`http3`}[e],rt=e=>{if(e!==void 0)switch(e){case M.MPEG:return`mp4`;case M.DASH:case M.DASH_LIVE:case M.DASH_STREAMS:return`dash`;case M.DASH_SEP:return`dash_sep`;case M.DASH_ONDEMAND:return`ondemand_dash`;case M.DASH_WEBM:case M.DASH_LIVE_WEBM:return`webm`;case M.DASH_WEBM_AV1:return`av1`;case M.DASH_LIVE_CMAF:return`ondemand_dash_live`;case M.HLS:case M.HLS_LIVE:return`hls`;case M.HLS_FMP4:return`hls_fmp4`;case M.HLS_ONDEMAND:return`ondemand_hls`;case M.HLS_LIVE_CMAF:return`ondemand_hls_live`;case M.WEB_RTC_LIVE:return`webrtc`;default:return et(e)}},it=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case j.NONE:case j.INLINE:return;case j.FULLSCREEN:return`fullscreen`;case j.SECOND_SCREEN:return`chromecast`;case j.PIP:return`pip`;case j.INVISIBLE:return`invisible`;default:return et(e)}},at=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class ot{constructor(e){this.offset=void 0,this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}var vt=(e,t)=>new mt(n=>{let r=new gt,i=pt(ut(window,`beforeunload`),e.events.willDestruct$),a=new _t(void 0),o;r.add(e.info.isLive$.pipe(lt()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(ft(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c,looped$:l}=e.events,u=e.events.willSeek$.pipe(ct(()=>e.info.playbackState$.getValue()===st.PLAYING)),d=e.events.seeked$.pipe(ct(()=>e.info.playbackState$.getValue()===st.PLAYING)),f=!1,p=new ht;r.add(u.subscribe(()=>{f||p.next(),f=!0})),r.add(d.subscribe(()=>f=!1));let m=new ht,h=new ht,g=()=>t.watchCoverageExactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,ee=e.info.stallStartTime$.pipe(lt(),ct(e=>e>0)),_=pt(s,d,m).pipe(ft(()=>g())),v=pt(l,pt(c,p,i,h,ee).pipe(ft(()=>g()))),y,b=e=>{y=e},x=e=>{let t=e;dt(y)||y===t||dt(t)||(n.next({from:y,to:t}),y=void 0)},S=()=>{h.next(),m.next()};if(r.add(_.subscribe(b)),r.add(v.subscribe(x)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(_.subscribe(()=>{n(),e=window.setTimeout(S,t.forceInterval)})),r.add(v.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(_.subscribe(()=>e=window.setTimeout(S,t.forceInterval))),r.add(v.subscribe(()=>window.clearTimeout(e)))}return r});var St=(e,t,n)=>{let r=new xt,i=r.pipe(yt(0),bt()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?P.PIP:o?P.FULLSCREEN:s?P.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?P.FULLSCREEN:a?P.PIP:s?P.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case P.SECOND_SCREEN:case P.NONE:case P.INLINE:!o&&!a&&(e===P.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},Ct=`_one-stat_deviceId`,wt=(e,t)=>e&&t?`${e}_${t}`:e??t,Tt=()=>{let e=new Se;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Et{get vsid$(){return new Ce(T.getVSID())}constructor(e,t){this.apis=void 0,this.logger=void 0,this.config=void 0,this.subscription=new Se,this.beforeunloadSubscription=void 0,this.timeSynchronisation=void 0,this.debugLogger=new Te,this.oneStatDebugLog=this.debugLogger.createComponentLog(`onestat`),this.loopCounter=0,this.disabled=!1,this.experimental=void 0,this.isid$=new Ce(void 0),this.zenUid$=new Ce(void 0),this.statContext=void 0,this.isEmbed=void 0,this.embedParent=void 0,this.uiEvents=void 0,this.player=void 0,this.seekAction$=new Ce(`unknown`),this.deviceId=void 0,this.statContext=e,this.config=de(t.config??{}),C(t.apiEnv)&&(this.config.apiEnv=t.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new ot);let n=new xe;this.experimental={error$:n};let r=be.get(Ct);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=fe(),be.set(Ct,this.deviceId)),this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??Ae()),this.zenUid$.next(t.zenUid);let i=new Ge({config:this.config,error$:n,timeSynchronisation:this.timeSynchronisation}),a=[];this.config.apiForticom&&a.push(new ze({config:this.config,apiTransport:i,refreshAuthToken:t.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:n,vktvVersion:t.vktvVersion})),this.config.apiUvRest&&(t.getUvRestAuthToken?a.push(new Be({config:this.config,apiTransport:i,error$:n,userId:this.statContext.userId,getAuthToken:t.getUvRestAuthToken,mobile:this.statContext.mobile??!1,vktvVersion:t.vktvVersion})):n.next({id:`OneStat:Init:MissingGetUvRestAuthToken`,category:De.WTF,message:`oldStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.apis=a,this.logger=new Qe({config:this.config,debugLogger:this.debugLogger,apis:this.apis,error$:n,userSalt:t.userSalt});let{isEmbed:o,topOrigin:s}=Ee();this.isEmbed=o,this.embedParent=s?new URL(s).hostname:void 0,this.subscribe()}updateContext(e){this.statContext=f(f({},this.statContext),e)}attachTo(e){let t=new Se,n=(e,n)=>t.add(e.subscribe(n)),r,i,a,o=!1,s=!1,c=()=>{o||(o=!0,C(r)&&(r={startedAt:w(),liveAtStall:!!this.statContext.liveEdge}))};n(e.events.willStart$,()=>{let t=e.info.position$.getValue();this.logActionPlay({position:t}),this.statContext.projectId&&this.logActionPlayInteractive()}),n(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),n(e.events.willSeek$,()=>{C(r)&&o&&this.logEmptyBuffer({duration:w()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0,s=!0}),n(e.events.seeked$,()=>{!s&&C(r)&&o&&(this.logEmptyBuffer({duration:w()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0),s=!1;let t=this.seekAction$.getValue();this.logSeek({action:t===`rich`?`slider`:t,time:e.info.position$.getValue()}),this.seekAction$.next(`unknown`)}),n(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),n(e.events.willResume$,()=>{this.logPlay()}),n(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),n(e.events.playing$,()=>{this.logPlaying()}),n(vt(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix,watchCoverageExactTime:this.config.watchCoverageExactTime}),t=>{let n=e.info.isLive$.getValue(),r=e.info.atLiveEdge$.getValue(),i={start:parseFloat(t.from.toFixed(3)),end:parseFloat(t.to.toFixed(3))};if(r){let t=e.info.liveLatency$.getValue()??0,n=e.info.currentBuffer$.getValue()?.end??0,r=e.info.liveBufferTime$.getValue()??0,a=Math.round((t-(n-r))*1e3),o=Math.round(t*1e3);a&&o&&(i.latency=a,i.bufferLatency=o)}n?this.logWatchCoverageLive(i):this.logWatchCoverageRecord(i)}),n(e.info.stallStartTime$,e=>{e>0?r={startedAt:e,liveAtStall:!!this.statContext.liveEdge}:(C(r)&&o&&this.logEmptyBuffer({duration:Math.round(w()-r.startedAt),liveAtStall:r.liveAtStall}),r=void 0)});let l=!1;t.add(e.events.fatalError$.pipe(ye()).subscribe(()=>l=!0)),n(e.events.willStop$,()=>{if(e.info.isBuffering$.getValue()&&o){let e=C(r)?w()-r.startedAt:void 0;this.logCloseAtEmptyBuffer({duration:e??0,liveAtStall:r?.liveAtStall}),r=void 0}else l||this.logActionStop()}),n(e.events.managedError$,({id:e})=>{this.logError({fatal:!1,errorType:e})}),n(e.events.fatalError$,({id:e})=>{this.logError({fatal:!0,errorType:e})}),n(e.events.firstBytes$,e=>{i=w(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>a=w()),n(e.info.currentBuffer$,e=>{!o&&e&&e.end-e.start>0&&C(i)&&(this.logPlayerReady({duration:w()-i}),c())}),n(e.events.firstFrame$,()=>{C(i)&&!o&&(this.logPlayerReady({duration:w()-i}),c()),C(a)&&this.logFirstFrame({time:w()-a})});let u;n(e.info.currentVideoStream$,e=>{e&&(this.updateContext({videoCodec:e.codec}),u&&e.id!==u&&this.logTrackSwitch(e),u=e.id)});let d;n(e.info.currentAudioStream$,e=>{e&&(this.updateContext({audioCodec:e.codec}),d&&e.id!==d&&this.logTrackSwitch(e),d=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(me({muted:e.info.muted$,volume:e.info.volume$}),({muted:e,volume:t})=>this.updateContext({audible:!e&&t>0})),n(e.info.currentQuality$,e=>{let t=tt(e);this.updateContext({quality:t}),t&&this.logQuality(t)}),n(e.info.isAutoQualityEnabled$,e=>this.updateContext({autoQuality:e})),n(e.info.currentFormat$,e=>this.updateContext({contentType:rt(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let f;return n(e.info.hostname$,e=>{let t=f!==void 0&&f!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),f=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:nt(e)}),this.updateContext({connectionType:nt(e)})}),n(e.info.httpConnectionReused$,e=>{ge(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:it(e,this.statContext.isPreviewPlayerView)})}),n(me({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:e,available:t})=>{let n=t.find(({id:t})=>t===e),r=n&&(n.isAuto?`${n.language}_auto`:n.language);this.updateContext({subtitles:r?.split(`.`)[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscription:t,subscribe:n}=Tt();if(!this.player)return t;n(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),n(e.actionSeek$,this.seekAction$);let{surface$:r}=St(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:it(e,this.statContext.isPreviewPlayerView)})}),n(e.actionSetSubtitle$,e=>this.updateContext({subtitles:e?.split(`.`)[0]})),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:t,subscribe:n}=Tt();return n(e.slotRequested$,()=>this.logAdSlotRequest()),n(e.started$,e=>this.logAdStarted(e)),n(e.paused$,()=>this.logAdPaused()),n(e.resumed$,()=>this.logAdResumed()),n(e.ended$,()=>this.logAdEnded()),n(e.skipped$,()=>this.logAdSkipped()),n(e.clicked$,()=>this.logAdClicked()),n(e.error$,e=>this.logError({errorType:e,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToInteractive(e){let{subscription:t,subscribe:n}=Tt();return n(e.click$,e=>this.logInterfaceClick(e)),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}authorize(e){return Promise.all(this.apis.map(t=>t.authorize(e)))}pause(){this.logger.pause(),this.oneStatDebugLog({message:`paused`})}resume(){this.logger.resume(),this.oneStatDebugLog({message:`resumed`})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.apis.forEach(e=>e.destroy()),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:`VSID reset`}),T.generateVSID(this.config.useVsid64)}getDeviceId(){return this.deviceId}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:`player_ready`,param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:`play_toggle`})}logPlaying(){this.log({operation:`playing`})}logPause(e){this.log({operation:`pause`,param:String(Math.round(e.position))})}logSeek(e){this.log({operation:`seek`,param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:`first_bytes`,param:String(e.time)})}logFirstFrame(e){this.log({operation:`first_frame`,param:String(e.time)})}logError(e){this.log({operation:`content_error`,param:`${e.fatal?`fatal`:`recoverable`}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:`watch_coverage_record`,param:`${e.start}-${e.end}`},{in_history:this.statContext.inHistory?1:void 0})}logWatchCoverageLive(e){let t=this.timeSynchronisation?.getOffset()??0,n=e.start+t,r=e.end+t;this.log({operation:`watch_coverage_live`,param:`${n}-${r}`},{in_history:this.statContext.inHistory?1:void 0,latency:e.latency,buffer_latency:e.bufferLatency})}logEmptyBuffer(e){this.log({operation:`empty_buffer`,param:String(e.duration)},C(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:`adv`,param:`slot_request`})}logAdStarted(e){this.log({operation:`adv`,param:e})}logAdPaused(){this.log({operation:`adv`,param:`pause`})}logAdResumed(){this.log({operation:`adv`,param:`resume`})}logAdEnded(){this.log({operation:`adv`,param:`ended`})}logAdSkipped(){this.log({operation:`adv`,param:`skip`})}logAdClicked(){this.log({operation:`adv`,param:`click`})}logInterfaceClick(e){this.log({operation:`player_interface_click`,param:e})}logNextMovie(e){this.log({operation:`next_movie`,param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=we().navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(_e(he(e,`change`),ve([`init`])).subscribe(()=>this.updateContext({network:at(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(e=>{console.debug(`%c stat `,`background:#fa6470;`,`component: ${e.component}.`,e.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=he(window,`beforeunload`).subscribe(()=>this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload})),this.subscription.add(this.beforeunloadSubscription)}logPlayerReady(e){this.log({operation:`player_ready`,param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:`action_play`,param:String(Math.round(e.position))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:`action_play_interactive`,param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:`failover`,param:e})}logCloseAtEmptyBuffer(e){this.log({operation:`close_at_empty_buffer`,param:String(Math.round(e.duration))},C(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}logActionStop(){this.log({operation:`action_stop`})}logTrackSwitch(e){this.log({operation:`track_switch`,param:e.id})}logQuality(e){this.log({operation:`quality`,param:e})}log(e,t={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(_(this.config.disabledOperations,e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let n=this.createLogItem(e,t);this.logger.log(n)}createLogItem({operation:e,param:t,time:n},r={}){let i=this.timeSynchronisation?.now()??w(),a=this.vsid$.getValue();pe(a);let o=this.isid$.getValue(),s=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,l,u;if(this.isEmbed||this.statContext.place===`embed`){l=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>_(this.config.embedUrlParams,e));u=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;l=e&&v(URL,e)?new URL(e).hostname:e,u=location.href.substring(0,1024)}let d=f({vsid:a,isid:o,vid:this.statContext.movieId,uid:this.zenUid$.getValue(),ct:this.statContext.contentType,place:this.isEmbed?`embed`:this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?`auto`:this.statContext.autoplay===!1?``:void 0,param:t,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:s,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:l,direct_url:u,rate:this.statContext.rate===1||ge(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,codec_info:wt(this.statContext.videoCodec,this.statContext.audioCodec),aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},r);for(let e of this.config.disabledCustomFields)delete d[e];return{operation:e,type:1,time:n,network:this.statContext.network,timestamp:i,custom:d}}}var Dt={};ee(Dt,{VERSION:()=>E,ThinOneStat:()=>lr,ActionSeekType:()=>Kt});var Gt;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(Gt||={});var Kt;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(Kt||={});var qt=`CIOPGQJGDIHBABABA`,Jt={prod:`https://api.ok.ru`,vk_alias:`https://api.mycdn.me`,videotest:`https://videotestapi.ok.ru/api`,test:`https://apitest.ok.ru`,okcdn:`https://api.okcdn.ru`,auto:``},Yt={apiKey:qt,apiEnv:`okcdn`,apiBaseUrl:null,apiForticom:!0,apiUvRest:!1,requestRetryCount:3,useVsid64:!1,flushFirstTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,flushRetryFirstDelay:3e3,flushRetryMaxDelay:18e5,storageExpiration:2160*60*1e3,clearStorageAtUnload:!1,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchCoverageHeartbeatInterval:3e4,watchCoverageExactTime:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},Xt=e=>Wt(e,Yt);function en(e){let t=Error(`HTTP ${e.status}: ${e.statusText}`);return t.status=e.status,t.statusText=e.statusText,t.response=e,t}function tn(){let e=Error(`Request timeout`);return e.isTimeout=!0,e}function nn(e){let t=Error(e.error_msg);return t.errorData=e,t}function rn(e){if(!(!e||typeof e!=`object`)){if(`errorData`in e)return e.errorData?.error_code;if(`error_code`in e){let t=e.error_code;return typeof t==`number`?t:void 0}}}class an{constructor(e){this.id=`forticom`,this.authorized$=void 0,this.params=void 0,this.authToken=void 0,this.sessionKey=void 0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.isDestroyed=!1,this.params=e,this.authorized$=new $t(!1)}authorize(e){var t=this;return p(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t.doAuthorize()})()}logBeacon(e){if(!e.length)return;let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return p(function*(){if(!e.length)return;let n=`log.logUvStat`,r=t.createLogParams(e),i={};try{let e=yield t.getValidSessionKey();if(!e){t.params.errors$.next({id:`ThinOneStat:Api:LogRequestNoSession`,category:z.NETWORK,message:`No session key available for log request`});return}yield t.params.apiTransport.sendRequest(n,r,e,i)}catch(e){(yield t.handleLogRequestError(e,n,r))&&(yield t.retryLogRequestAfterSessionRecovery(n,r))}})()}getValidSessionKey(){var e=this;return p(function*(){return e.sessionKey?e.sessionKey:e.doAuthorize()})()}handleLogRequestError(e,t,n){var r=this;return p(function*(){let i=rn(e);return i===void 0?(r.params.errors$.next({id:`ThinOneStat:Api:LogRequestUnknown`,category:z.NETWORK,message:`Unknown ${t} error`,thrown:e,data:{params:n}}),!1):r.isSessionExpiredError(i)?(r.params.errors$.next({id:`ThinOneStat:Api:LogRequestSessionError#${i}`,category:z.EXTERNAL_API,message:`Session error: ${i}`,data:{error:e,code:i}}),r.authorized$.next(!1),r.sessionKey=void 0,(yield r.doAuthorize())!==void 0):i===401?(r.params.errors$.next({id:`ThinOneStat:Api:LogRequestAuthLogin#${i}`,category:z.EXTERNAL_API,message:`Auth token expired`,data:{error:e,code:i}}),r.authorized$.next(!1),r.authToken=yield r.refreshAuthToken(),r.sessionKey=void 0,(yield r.doAuthorize())!==void 0):(r.params.errors$.next({id:`ThinOneStat:Api:LogRequest#${i}`,category:z.EXTERNAL_API,message:`${t} error`,data:{error:e,code:i,params:n}}),!1)})()}retryLogRequestAfterSessionRecovery(e,t){var n=this;return p(function*(){let r=n.sessionKey;if(!r){n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed`,category:z.NETWORK,message:`Cannot retry log request: no session key after recovery`});return}try{yield n.params.apiTransport.sendRequest(e,t,r)}catch(e){let t=rn(e);n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed#${t??`unknown`}`,category:z.EXTERNAL_API,message:`Log request failed after session recovery`,thrown:e,data:{originalError:e,retryCode:t}})}})()}isSessionExpiredError(e){return!!e&&Zt([102,103,104],e)}doAuthorize(e=1){var t=this;return p(function*(){if(!t.isDestroyed)return t.authorizePromise?t.authorizePromise:(t.sessionKey=void 0,t.authorized$.next(!1),t.authorizePromise=Qt(t.executeAuthorize(e),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.sessionKey!==void 0)}),t.authorizePromise)})()}executeAuthorize(e){var t=this;return p(function*(){let n=t.buildAuthParams();try{let e=yield t.params.apiTransport.sendRequest(`auth.anonymLogin`,n);if(t.isDestroyed)return;if(!e?.session_key){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeFailed`,category:z.EXTERNAL_API,message:`No session key in response`,data:e});return}return t.sessionKey=e.session_key,t.sessionKey}catch(n){if(t.isDestroyed)return;let r=rn(n);if(r===401&&t.params.refreshAuthToken){if(t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:z.EXTERNAL_API,message:`Auth token expired during authorization`,data:{error:n,code:r,attempt:e}}),e>=2){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeMaxAttemptsReached`,category:z.EXTERNAL_API,message:`Authorization failed after ${e} attempts`,data:{error:n,code:r}});return}return t.authToken=yield t.refreshAuthToken(),t.doAuthorize(e+1)}r?t.params.errors$.next({id:`ThinOneStat:Api:Authorize#${r}`,category:z.EXTERNAL_API,message:`Authorize error`,data:{error:n,code:r}}):t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:z.NETWORK,message:`Authorize error`,thrown:n});return}})()}buildAuthParams(){let e={session_data:{version:2,device_id:this.params.deviceId,client_version:this.getClientVersion(),client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),e}getClientVersion(){return E}refreshAuthToken(){var e=this;return p(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Qt(e.params.refreshAuthToken().catch(t=>{throw e.params.errors$.next({id:`ThinOneStat:Api:RefreshAuthTokenFailed`,category:z.NETWORK,message:`Failed to refresh auth token`,thrown:t}),t}),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`@vkontakte/videoplayer-statistics:${this.getClientVersion()}`;return this.params.vktvVersion&&(t=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:t,platform:e[0].platform,product:e[0].product,events:e})}}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.sessionKey=void 0,this.authorized$.next(!1)}}class on{constructor(e){this.id=`uvrest`,this.authorized$=void 0,this.params=void 0,this.statToken=void 0,this.authorizePromise=void 0,this.isDestroyed=!1,this.params=e,this.authorized$=new $t(!1)}authorize(e){var t=this;return p(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=Qt(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return p(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestNoToken`,category:z.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return p(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return p(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.errors$.next({id:`ThinOneStat:UvRestApi:NoToken`,category:z.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.errors$.next({id:`ThinOneStat:UvRestApi:AuthorizeFailed`,category:z.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return p(function*(){let n=e?.status;return n===401?(t.params.errors$.next({id:`ThinOneStat:UvRestApi:TokenExpired`,category:z.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:z.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return p(function*(){let n=t.statToken;if(!n){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryNoToken`,category:z.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryFailed`,category:z.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=e[0],n=t.application;return this.params.vktvVersion&&(n=this.params.vktvVersion),[{product:t.product,platform:t.platform,application:n,user_id:this.params.userId,events:e}]}}class fn{constructor(e){this.params=void 0,this.apiKey=void 0,this.apiBaseUrl=void 0,this.apiEnv=void 0,this.resolvedApiBaseUrl=null,this.resolveApiBaseUrlPromise=null,this.timeSynchronisation=void 0,this.fetchTimeout=3e4,this.maxTotalRequestTime=6e4,this.retryConfig=void 0,this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Jt[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.retryConfig={maxAttempts:e.config.requestRetryCount??3,baseDelay:3e3,maxDelay:3e4,retryableErrors:[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`Request timeout`,`Network request failed`],retryableStatuses:[408,429,500,502,503,504]}}sendBeacon(e,t,n){if(!H().Blob||!H().navigator.sendBeacon)return!1;let r=this.resolvedApiBaseUrl??this.apiBaseUrl,i=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),a=H().Blob,o=new a([i.toString()],{type:`application/x-www-form-urlencoded`});try{return H().navigator.sendBeacon(`${r}/fb.do`,o)}catch(n){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendBeacon`,category:U.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n,r){var i=this;return p(function*(){return i.sendRequestWithRetry(e,t,n,r)})()}sendRequestWithRetry(e,t,n,r,i=1,a){var o=this;return p(function*(){let s=V(),c=a??s+o.maxTotalRequestTime;if(V()>=c){let r=Error(`Request deadline exceeded`);throw o.handleFinalError(e,t,n,s,r,i),r}try{return yield o.executeRequest(e,t,n,r,s,i,c)}catch(a){if(o.shouldRetry(a,i)&&V()<c){let l=o.getRetryDelay(a,i);if(V()+l>=c)throw o.handleFinalError(e,t,n,s,a,i),a;return o.logRetryAttempt(e,i,a,l),yield o.sleep(l),o.sendRequestWithRetry(e,t,n,r,i+1,c)}throw o.handleFinalError(e,t,n,s,a,i),a}})()}executeRequest(e,t,n,r,i,a,o){var s=this;return p(function*(){let c=i??V(),l=yield s.resolveApiBaseUrl(),u=o===void 0?s.fetchTimeout:o-V();if(u<=0)throw tn();try{let i=yield s.fetchWithTimeout(`${l}/fb.do`,{method:`post`,headers:f({"Content-type":`application/x-www-form-urlencoded`},r),body:s.prepareQueryParams({method:e,queryParams:t,sessionKey:n})},Math.min(s.fetchTimeout,u));return yield s.processResponse(i,c)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:a,url:`${l}/fb.do`}),t}})()}sendJsonRequest(e,t,n){var r=this;return p(function*(){return r.sendJsonRequestWithRetry(e,t,n)})()}sendJsonBeacon(e,t,n){let r=`${this.resolvedApiBaseUrl??this.apiBaseUrl}${e}`;try{sn(r,{method:`POST`,headers:f({"Content-Type":`application/json`},n),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:U.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:U.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequestWithRetry(e,t,n,r=1,i){var a=this;return p(function*(){let o=V(),s=i??o+a.maxTotalRequestTime;if(V()>=s){let t=Error(`Request deadline exceeded`);throw a.handleJsonFinalError(e,o,t,r),t}try{return yield a.executeJsonRequest(e,t,n,o,r,s)}catch(i){if(a.shouldRetry(i,r)&&V()<s){let c=a.getRetryDelay(i,r);if(V()+c>=s)throw a.handleJsonFinalError(e,o,i,r),i;return a.logRetryAttempt(e,r,i,c),yield a.sleep(c),a.sendJsonRequestWithRetry(e,t,n,r+1,s)}throw a.handleJsonFinalError(e,o,i,r),i}})()}executeJsonRequest(e,t,n,r,i,a){var o=this;return p(function*(){let s=r??V(),c=yield o.resolveApiBaseUrl(),l=a===void 0?o.fetchTimeout:a-V();if(l<=0)throw tn();let u=`${c}${e}`;try{let e=yield o.fetchWithTimeout(u,{method:`POST`,headers:f({"Content-Type":`application/json`},n),body:JSON.stringify(t)},Math.min(o.fetchTimeout,l));return yield o.processResponse(e,s)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:i,url:u}),t}})()}fetchWithTimeout(e,t){return p(function*(e,t,n=this.fetchTimeout){let r=new cn,i=H().setTimeout(()=>r.abort(),n);try{let n=yield sn(e,f(f({},t),{},{signal:r.signal}));return H().clearTimeout(i),n}catch(e){throw H().clearTimeout(i),dn(e)?tn():e}}).apply(this,arguments)}processResponse(e,t){var n=this;return p(function*(){if(!e.ok){let t=en(e),r=n.parseRetryAfter(e);throw r!==void 0&&(t.retryAfter=r),t}let r=new Date(e.headers.get(`date`)??``).getTime(),i=V()-t;isFinite(r)&&n.timeSynchronisation?.addServerTime(r,i);let a=e.headers.get(`content-length`);if(a!==null&&Number(a)===0)return{};let o=yield e.json();if(o&&typeof o==`object`&&`error_msg`in o)throw nn(o);return o})()}shouldRetry(e,t){if(t>=this.retryConfig.maxAttempts||!(e instanceof Error))return!1;let n=e;return!!(n.isTimeout||n.status&&B(this.retryConfig.retryableStatuses,n.status)||B(this.retryConfig.retryableErrors,e.message)||B(e.message,`network`)||B(e.message,`timeout`)||B(e.message,`connection`))}logRetryAttempt(e,t,n,r){let i=n instanceof Error?n.message:String(n);this.params.errors$.next({id:`ThinOneStat:ApiTransport:retry`,category:U.NETWORK,message:`Retrying request (attempt ${t}/${this.retryConfig.maxAttempts}) after ${Math.round(r)}ms`,thrown:n,data:{method:e,attempt:t,delay:r,errorMessage:i}})}handleFinalError(e,t,n,r,i,a){let o=U.NETWORK;this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:o,message:i instanceof Error?i.message:`Request failed after retries`,thrown:i,data:{method:e,params:t,sessionKey:n,time:V()-r,maxAttempts:this.retryConfig.maxAttempts,attempts:a}})}handleJsonFinalError(e,t,n,r){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonRequest`,category:U.NETWORK,message:n instanceof Error?n.message:`JSON request failed after retries`,thrown:n,data:{path:e,time:V()-t,maxAttempts:this.retryConfig.maxAttempts,attempts:r}})}sleep(e){return new Promise(t=>H().setTimeout(t,e))}resolveApiBaseUrl(){return this.apiEnv===`auto`?(this.resolveApiBaseUrlPromise||=this.fetchApiBaseUrl().then(e=>(e===Jt.vk_alias&&(this.resolveApiBaseUrlPromise=null),e)),this.resolveApiBaseUrlPromise):Promise.resolve(this.apiBaseUrl)}fetchApiBaseUrl(){var e=this;return p(function*(){try{var t;let n=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),r=yield(yield e.fetchWithTimeout(n,{method:`GET`,mode:`cors`,cache:`no-cache`},5e3)).json(),i=r==null||(t=r.Answer[0])==null?void 0:t.data;if(!i)throw Error(`Wrong DNS response`);return e.resolvedApiBaseUrl=i,i}catch(t){return e.params.errors$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:U.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),Jt.vk_alias}})()}prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),ln(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}parseRetryAfter(e){let t=e.headers.get(`Retry-After`);if(!t)return;let n=Number(t);if(!isNaN(n)&&n>=0)return n*1e3;let r=new Date(t).getTime();if(!isNaN(r))return Math.max(0,r-Date.now())}getRetryDelay(e,t){let n=e;return n?.retryAfter!==void 0&&n.retryAfter>0?n.retryAfter:un(t,{start:this.retryConfig.baseDelay,max:this.retryConfig.maxDelay,factor:2,random:.2})}}var bn=e=>t=>(t.client_time??vn())+e>=vn();class xn{constructor(e){this.params=void 0,this.subscription=void 0,this.userSalt=void 0,this.unsaltedStorage=[],this.lastVsid=void 0,this.isPaused=!1,this.firstFlush=void 0,this.debouncedFlush=void 0,this.flushRetryCount=0,this.retryFlushTimerId=void 0,this.debugLog=void 0,this.flushPromise=null,this.flushSnapshotLength=0,this.onlineListener=void 0,this.urgentEvents=[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`],this.STORAGE_MAX_ATTEMPTS=3,this.isUrgent=e=>hn(this.urgentEvents,e.event_name),this.params=e,this.userSalt=e.userSalt,this.debugLog=e.debugLogger.createComponentLog(`batch-queue:${e.storageKey}`),this.firstFlush=yn(()=>this.safeFlush(),this.params.config.flushFirstTime,{maxWait:this.params.config.flushFirstTime});let t=G.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=yn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.params.canSend$.subscribe(e=>{e&&(this.debugLog({message:`Can send, triggering flush`}),this.debouncedFlush())}),this.onlineListener=()=>{this.debugLog({message:`Network online, triggering flush`}),this.cancelRetry(),this.safeFlush()},W().addEventListener(`online`,this.onlineListener),this.housekeepStorage()}scheduleRetry(){this.retryFlushTimerId!==void 0&&W().clearTimeout(this.retryFlushTimerId);let e=this.params.config.flushRetryFirstDelay,t=this.params.config.flushRetryMaxDelay,n=Math.min(e*2**this.flushRetryCount,t);this.flushRetryCount++,this.debugLog({message:`Scheduling flush retry #${this.flushRetryCount} in ${n}ms`}),this.retryFlushTimerId=W().setTimeout(()=>{this.retryFlushTimerId=void 0,this.safeFlush()},n)}cancelRetry(){this.retryFlushTimerId!==void 0&&(W().clearTimeout(this.retryFlushTimerId),this.retryFlushTimerId=void 0),this.flushRetryCount=0}safeFlush(){if(this.flushPromise){this.debugLog({message:`Flush already in progress, skipping`});return}this.flushPromise=gn(this.flush(),()=>{this.flushPromise=null})}isStorageAvailable(){let e=G.isPersistent?.call(G)??!1;return e||this.debugLog({message:`Storage not available`}),e}readFromStorage(){if(!this.isStorageAvailable())return{};try{let e=G.get(this.params.storageKey),t=e?JSON.parse(e):{};return this.debugLog({message:`Read ${Object.keys(t).length} users from storage`}),t}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:ReadStorageError`,category:K.WTF,message:`Failed to read from storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to read from storage`}),{}}}writeToStorage(e){if(!this.isStorageAvailable())return!1;try{return G.set(this.params.storageKey,JSON.stringify(e)),this.debugLog({message:`Written ${Object.keys(e).length} users to storage`}),!0}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:WriteStorageError`,category:K.WTF,message:`Failed to write to storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to write to storage`}),!1}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e),this.debugLog({message:`Added item to unsalted storage, total: ${this.unsaltedStorage.length}`});return}for(let t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),n=t[this.userSalt]??[];if(this.debugLog({message:`Adding item to storage for user ${this.userSalt}`}),this.writeToStorage(f(f({},t),{},{[this.userSalt]:[...n,e]})))return}catch(n){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:AddToStorageFailed`,category:K.WTF,message:`Failed to add item to storage after retries`,thrown:n,data:{item:e,attempt:t,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to add item to storage after retries`}))}}getFromStorage(){if(!this.userSalt)return this.debugLog({message:`Retrieved ${this.unsaltedStorage.length} items from unsalted storage`}),this.flushSnapshotLength=this.unsaltedStorage.length,this.unsaltedStorage.slice();let e=this.readFromStorage(),t=e[this.userSalt]??[],n=t.filter(bn(this.params.config.storageExpiration));if(this.debugLog({message:`Retrieved from storage for user ${this.userSalt}`}),n.length!==t.length){let r=t.length-n.length;this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:K.WTF,message:`Dropped ${r} expired events from storage`,data:{droppedCount:r,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}}),this.debugLog({message:`Cleaning ${r} expired items from storage`});let i=f({},e);n.length?i[this.userSalt]=n:delete i[this.userSalt],this.writeToStorage(i)}return this.flushSnapshotLength=n.length,n}markStorageSent(){if(!this.userSalt){let e=this.unsaltedStorage.splice(0,this.flushSnapshotLength);this.debugLog({message:`Cleared unsalted storage, removed ${e.length} items, ${this.unsaltedStorage.length} new items kept`}),this.flushSnapshotLength=0;return}let e=this.flushSnapshotLength;this.flushSnapshotLength=0;for(let t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),n=(t[this.userSalt]??[]).slice(e),r=f({},t);if(n.length?r[this.userSalt]=n:delete r[this.userSalt],this.writeToStorage(r)){this.debugLog({message:`Marked storage as sent for user ${this.userSalt}, removed ${e} items, ${n.length} kept`});return}}catch(e){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:MarkStorageSentFailed`,category:K.WTF,message:`Failed to mark storage as sent after retries`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to mark storage as sent after retries`}))}}housekeepStorage(){if(this.isStorageAvailable())try{let e=this.readFromStorage(),t=!1,n=0;for(let[r,i]of _n(e)){let a=i.filter(bn(this.params.config.storageExpiration)),o=i.length-a.length;n+=o,a.length?a.length!==i.length&&(e[r]=a,t=!0):(delete e[r],t=!0),this.debugLog({message:`${i.length} retrieved from storage, ${a.length} of them actual for ${r}`})}t?(this.debugLog({message:`Housekeeping completed, removed ${n} expired items total`}),this.writeToStorage(e),n>0&&this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:K.WTF,message:`Dropped ${n} expired events during housekeeping`,data:{droppedCount:n,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}})):this.debugLog({message:`Housekeeping completed, no changes needed`})}catch(e){this.params.errors$.next({id:`ThinOneStat:BatchQueue:HousekeepStorageError`,category:K.WTF,message:`Failed to housekeep storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to housekeep storage`})}}log(e){try{if(this.debugLog({message:`Logging item: ${e.event_name}`}),this.addToStorage(e),this.isPaused){this.debugLog({message:`Queue paused, skipping flush`});return}this.isUrgent(e)?(this.debugLog({message:`Urgent item, flushing immediately`}),this.safeFlush()):this.lastVsid===e.vsid?(this.debugLog({message:`Same VSID, scheduling debounced flush`}),this.debouncedFlush()):(this.debugLog({message:`VSID changed, triggering first flush`}),this.firstFlush()),this.lastVsid=e.vsid}catch(t){this.params.errors$.next({id:`ThinOneStat:BatchQueue:LogError`,category:K.WTF,message:`Failed to log item`,thrown:t,data:{item:e,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to log item`})}}flush(e={wantBeacon:!1,clearStorage:!0}){return this.flushPromise?(this.debugLog({message:`Flush already in progress, waiting`}),this.flushPromise):(this.flushPromise=gn(this.flushInternal(e),()=>{this.flushPromise=null}),this.flushPromise)}flushInternal({wantBeacon:e,clearStorage:t}){var n=this;return p(function*(){n.debugLog({message:`Starting flush`});let r=n.getFromStorage();if(r.length===0){n.debugLog({message:`No items to flush`});return}let i=n.params.canSend$.getValue();if(n.debugLog({message:`Can send status: ${i}`}),!i){n.debugLog({message:`Cannot send, requesting ready state`}),n.params.requestReady();return}if(e&&n.params.config.useBeacon){n.debugLog({message:`Flushing ${r.length} events through beacon`}),n.params.sendBeacon(r),t&&n.markStorageSent(),n.firstFlush.cancel(),n.debouncedFlush.cancel();return}n.debugLog({message:`Flushing ${r.length} events`});try{yield n.params.send(r),n.debugLog({message:`Flush completed successfully`}),n.cancelRetry(),t&&n.markStorageSent(),n.firstFlush.cancel(),n.debouncedFlush.cancel()}catch(e){throw n.params.errors$.next({id:`ThinOneStat:BatchQueue:FlushRequestError`,category:K.NETWORK,message:`Failed to send events, will retry later`,thrown:e,data:{itemsCount:r.length,storageKey:n.params.storageKey}}),n.debugLog({message:`Flush failed, scheduling retry`}),n.scheduleRetry(),e}})()}pause(){this.debugLog({message:`Queue paused`}),this.isPaused=!0,this.debouncedFlush.cancel(),this.firstFlush.cancel(),this.cancelRetry()}resume(){this.debugLog({message:`Queue resumed`}),this.isPaused=!1,this.debouncedFlush()}destroy(){var e=this;return p(function*(){e.debugLog({message:`Destroying queue`}),e.flushPromise&&(e.debugLog({message:`Waiting for ongoing flush to complete`}),yield e.flushPromise),e.cancelRetry(),e.onlineListener&&=(W().removeEventListener(`online`,e.onlineListener),void 0),e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel(),e.flushPromise=null,e.debugLog({message:`Queue destroyed`})})()}}class Sn{constructor(e){this.params=void 0,this.queues=[],this.params=e;for(let t of e.apis)this.queues.push(this.createQueueForApi(t))}createQueueForApi(e){let t=this.getStorageKeyForApi(e.id);return new xn({config:this.params.config,storageKey:t,debugLogger:this.params.debugLogger,errors$:this.params.errors$,userSalt:this.params.userSalt,send:t=>e.logRequest(t),sendBeacon:t=>e.logBeacon(t),canSend$:e.authorized$,requestReady:()=>{e.authorize().catch(e=>{this.params.errors$.next({id:`ThinOneStat:Logger:RequestReadyFailed`,category:mn.NETWORK,message:`Failed to authorize on requestReady`,thrown:e,data:{storageKey:t}})})}})}getStorageKeyForApi(e){return`thinonestat_events_${e}`}log(e){this.queues.forEach(t=>t.log(e))}flush(e){var t=this;return p(function*(){let n=yield pn(t.queues.map(t=>t.flush(e)));if(n.length>0&&n.every(e=>e.status===`rejected`))throw n.find(e=>e.status===`rejected`).reason})()}pause(){this.queues.forEach(e=>e.pause())}resume(){this.queues.forEach(e=>e.resume())}destroy(){var e=this;return p(function*(){yield pn(e.queues.map(e=>e.destroy())),e.queues=[]})()}}function Cn(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}class wn{constructor(e){this.offset=void 0,this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}var In=(e,t,n)=>new En(r=>{let i=new Dn,a=new On(void 0),o;i.add(e.info.isLive$.pipe(Pn()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(Mn(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),i.add(o)}));let{playing$:s,paused$:c,ended$:l,looped$:u}=e.events,d=e.events.willSeek$.pipe(Nn(()=>e.info.playbackState$.getValue()===Tn.PLAYING)),f=e.events.seeked$.pipe(Nn(()=>e.info.playbackState$.getValue()===Tn.PLAYING)),p=!1,m=new kn;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=q(An(Fn(),`beforeunload`),e.events.willDestruct$),g,ee=e=>{g=e},_=e=>{let t=e;jn(g)||jn(t)||g===t||(r.next({from:g,to:t}),g=void 0)},v=new kn,y=new kn,b=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,x=q(s,f,v).pipe(Mn(()=>b())),S=q(u,q(c,m,h,l,y).pipe(Mn(()=>b()))),te=t.started$&&t.ended$?q(x,t.ended$):x,ne=t.started$&&t.ended$?q(S,t.started$):S;if(i.add(te.subscribe(ee)).add(ne.subscribe(_)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{y.next(),v.next()};i.add(te.subscribe(()=>{let r=Fn().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(ne.subscribe(()=>{e.forEach(e=>{Fn().clearTimeout(e)}),e=[]}))}return i});var Bn=(e,t)=>new Rn(n=>{let r=new Ln;return r.add(zn(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>=t.targetDuration&&(n.next({target_duration:t.targetDuration,current_tvt:e}),r.unsubscribe())})),r});var Gn=(e,{maxTimeWindow:t})=>new Hn(n=>{let r=new Vn,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(Wn().clearTimeout(a.timeoutId),null)},s=()=>{a.bytes=0,a.startTime=0,a.lastEmitTime=0,o()},c=e=>{if(a.bytes<i.minBytesThreshold||e-a.lastEmitTime<i.minTimeWindow&&a.lastEmitTime>0)return!1;let t=(a.startTime>0?e-a.startTime:0)>=i.maxTimeWindow,n=a.bytes>=i.maxBytesThreshold;return t||n},l=(e=!1)=>{let t=Date.now();if(!e&&!c(t))return;o();let r=a.startTime>0?t-a.startTime:Math.max(i.minTimeWindow,1),l=a.bytes/(r/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(l)}),a.lastEmitTime=t,s()},u=()=>{if(o(),a.startTime>0&&a.bytes>=i.minBytesThreshold){let e=Date.now()-a.startTime,t=i.maxTimeWindow-e;t>100?a.timeoutId=Wn().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(Un(e=>e!==void 0)).subscribe(e=>{let t=Date.now();a.startTime===0&&(a.startTime=t),a.bytes+=e.bytes,c(t)?l():u()})),r.add(()=>{if(o(),a.bytes>0){let e=Date.now(),t=a.startTime>0?e-a.startTime:i.minTimeWindow,r=a.bytes/(t/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(r)})}s()}),r});var Yn=e=>new Kn(t=>{let n=new qn,r=0,i=1,a=0,o=!1,s=!1,c=()=>{if(!o)return;let e=Date.now();a+=(e-r)*i,r=e},l=()=>{(!o||s)&&(r=Date.now(),o=!0,s=!1)},u=()=>{o&&=(c(),!1)},d=()=>{o&&(c(),o=!1,s=!0)},f=e=>{o&&c(),i=e,r=Date.now()},{started$:p,playing$:m,paused$:h,willSeek$:g,ended$:ee,willDestruct$:_}=e.events,{currentPlaybackRate$:v}=e.info;return n.add(g.subscribe(d)).add(Jn(p,m).subscribe(l)).add(Jn(h,ee,_).subscribe(u)).add(v.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),Math.round(e)}),n});var $n=(e,t)=>new Xn(n=>{let r=new Zn,i=0;return r.add(Qn(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>i&&Math.floor(e/t.interval)>Math.floor(i/t.interval)&&(i=e,n.next())})),r});var nr=e=>e&&{[tr.HTTP1]:`http1`,[tr.HTTP2]:`http2`,[tr.QUIC]:`http3`}[e],Z=e=>{if(e!==void 0)switch(e){case Y.MPEG:return`MP4`;case Y.DASH:case Y.DASH_LIVE:return`DASH`;case Y.DASH_SEP:return`DASH_SEP`;case Y.DASH_ONDEMAND:return`ONDEMAND_DASH`;case Y.HLS_ONDEMAND:return`ONDEMAND_HLS`;case Y.HLS:case Y.HLS_LIVE:return`HLS`;case Y.HLS_FMP4:return`HLS_FMP4`;case Y.DASH_WEBM:case Y.DASH_LIVE_WEBM:return`WEBM`;case Y.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case Y.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case Y.WEB_RTC_LIVE:return`WEBRTC`;case Y.DASH_WEBM_AV1:return`AV1`;case Y.DASH_STREAMS:return`MULTI_DASH`;default:return er(e)}},Q=e=>{if(e!==void 0)switch(e){case X.Q_144P:return`144p`;case X.Q_240P:return`240p`;case X.Q_360P:return`360p`;case X.Q_480P:return`480p`;case X.Q_720P:return`720p`;case X.Q_1080P:return`1080p`;case X.Q_1440P:return`1440p`;case X.Q_2160P:return`2160p`;case X.INVARIANT:case X.Q_576P:case X.Q_4320P:return`UNKNOWN`;default:return er(e)}},rr=e=>{if(e!==void 0)switch(e){case`MP4`:case`ONDEMAND_DASH`:case`ONDEMAND_DASH_LIVE`:case`ONDEMAND_HLS`:case`ONDEMAND_HLS_LIVE`:case`MULTI_DASH`:case`WEBM`:case`AV1`:return`vod`;case`DASH`:case`HLS`:case`HLS_FMP4`:case`WEBRTC`:return`live`;default:return}},$=(e,t,n)=>{if(e&&t)switch(e){case Y.MPEG:return n&&t[e]&&t[e][n];default:return t[e]?.url}},ir=(e,t=!1)=>{if(t)return`minimal`;switch(e){case void 0:case J.NONE:return;case J.INLINE:return`inline`;case J.FULLSCREEN:return`fullscreen`;case J.SECOND_SCREEN:return`chromecast`;case J.PIP:return`pip_external`}},ar=e=>{switch(e){case void 0:return;case J.INVISIBLE:return`background`;default:return`foreground`}},or=`_thin-one-stat_deviceId`,sr=`2.2.0`,cr=()=>{let e=new Ht;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class lr{constructor(e,t){this.apis=[],this.logger=void 0,this.config=void 0,this.subscription=void 0,this.beforeunloadSubscription=void 0,this.timeSynchronisation=void 0,this.statContext=void 0,this.deviceId=void 0,this.targetDuration=void 0,this.debugLogger=new Nt,this.thinOneStatDebugLog=this.debugLogger.createComponentLog(`ThinOneStat`),this.eventNumber=1,this.isStarted=void 0,this.wasPaused=void 0,this.isLive=void 0,this.cdnHostname=void 0,this.isEmbed=void 0,this.embedHostname=void 0,this.connectionType=void 0,this.connectionReused=void 0,this.player=void 0,this.playerSize={width:0,height:0},this.currentSubtitle=void 0,this.userQuality=void 0,this.downloadQuality=void 0,this.downloadSpeed=void 0,this.networkType=void 0,this.uiEvents=void 0,this.playerSubscription=void 0,this.uiSubscription=void 0,this.adsSubscription=void 0,this.seekAction$=new Ut(`unknown`),this.vsid$=new Ut(void 0),this.isid$=new Ut(void 0),this.errors$=new Vt,this.getTotalViewTime=()=>0,this.statContext=e,this.config=Xt(t.config??{}),this.subscription=new Ht,this.config.synchronizeTime&&(this.timeSynchronisation=new wn),this.subscription.add(this.errors$.subscribe(e=>{this.thinOneStatDebugLog({message:`[${e.category}] ${e.id}: ${e.message}`})}));let n=zt.get(or);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:n?this.deviceId=n:(this.deviceId=Cn(),zt.set(or,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??Ae());let r=new fn({errors$:this.errors$,config:this.config,timeSynchronisation:this.timeSynchronisation});this.config.apiForticom&&this.apis.push(new an({config:this.config,apiTransport:r,errors$:this.errors$,deviceId:this.deviceId,refreshAuthToken:t.refreshAuthToken})),this.config.apiUvRest&&(t.getUvRestAuthToken?this.apis.push(new on({config:this.config,apiTransport:r,errors$:this.errors$,userId:this.statContext.userId,getAuthToken:t.getUvRestAuthToken})):this.errors$.next({id:`ThinOneStat:Init:MissingGetUvRestAuthToken`,category:L.WTF,message:`thinStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.logger=new Sn({config:this.config,debugLogger:this.debugLogger,apis:this.apis,errors$:this.errors$,userSalt:t.userSalt});let{isEmbed:i,topOrigin:a}=jt();this.isEmbed=i,this.embedHostname=a?new URL(a).hostname:void 0}authorize(e){this.apis.forEach(t=>{t.authorize(e).catch(()=>{})})}updateContext(e){this.statContext=f(f({},this.statContext),e)}attachTo(e,t){this.playerSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to player, unsubscribing from previous`}),this.playerSubscription.unsubscribe());let n=new Ht,r=(e,t)=>n.add(e.subscribe(t));r(Yn(e),e=>{this.getTotalViewTime=e}),r(e.info.isLive$,e=>this.isLive=e),r(e.info.hostname$.pipe(I(e=>e!==void 0)),e=>{this.cdnHostname=e});let i;r(F({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(I(({hostname:e})=>e!==void 0),I(({connectionType:e})=>e!==void 0),I(({connectionReused:e})=>e!==void 0)),({hostname:t,connectionType:n,connectionReused:r})=>{if(i!==void 0&&i!==t){let i={cdn_host:t,connection_type:nr(n),connection_reused:r,content_type:Z(e.info.currentFormat$.getValue())};this.logFailover(i),this.logTelemetry(this.collectTelemetryData())}this.cdnHostname=i=t}),r(e.info.httpConnectionType$,e=>{this.connectionType=nr(e)}),r(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),r(In(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval,exactTime:this.config.watchCoverageExactTime}),t=>{let n={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:Z(e.info.currentFormat$.getValue()),playback_quality:Q(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(n);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive(f(f({},n),{},{live:!!t}))}}),r($n(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),r(Bn(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),r(e.events.willReady$,()=>{let t={isid:this.isid$.getValue(),stream_profile:rr(Z(e.info.currentFormat$.getValue())),dpi:Math.round(this.statContext.dpi??96*R.display.pixelRatio),web_layout:this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};if(this.isEmbed&&(t.iframe_host=this.embedHostname??`unknown`),this.logStartSession(t),this.statContext.preload){let t=e.info.currentFormat$.getValue(),n=e.info.availableSources$.getValue(),r=e.info.currentBuffer$.getValue(),i=e.info.currentQuality$.getValue(),a={target_buffer_time:this.calcBufferTime(r),playback_url:$(t,n,i),playback_quality:Q(i)};this.logPreloadStarted(a)}}),r(F({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(I(({connectionType:e})=>e!==void 0),I(({connectionReused:e})=>e!==void 0),It()),()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(t)}),r(F({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(I(({connectionType:e})=>e!==void 0),I(({connectionReused:e})=>e!==void 0),It()),()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(t)}),r(e.events.manifestReceived$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(t)}),r(e.events.firstBytesRequested$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(t)}),r(e.events.firstBytes$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(t)}),r(Pt(e.events.willStart$,e.events.looped$),e=>{e&&this.resetViewSession(),this.isStarted=!0}),r(e.events.started$,()=>{let t=e.info.currentBuffer$.getValue(),n=e.info.currentQuality$.getValue(),r=e.info.isAutoQualityEnabled$.getValue(),i=e.info.muted$.getValue(),a=e.info.volume$.getValue(),o=e.info.surface$.getValue(),s=e.info.availableTextTracks$.getValue(),c=e.info.currentTextTrack$.getValue(),l=e.info.currentAudioStream$.getValue(),u=e.info.currentPlaybackRate$.getValue(),d={playback_quality:Q(n),user_quality:r?`auto`:Q(n),player_width:Math.round(this.statContext.playerSize?.width??this.playerSize.width),player_height:Math.round(this.statContext.playerSize?.height??this.playerSize.height),muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:ir(o,this.statContext.isPreviewPlayerView),visibility:ar(o),subtitles_enabled:c?!!c:this.currentSubtitle?.enabled,auto_subtitles:s.find(({id:e})=>e===c)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:l?.language,playback_rate:u*100,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d),this.logTelemetry(this.collectTelemetryData())}),r(e.events.willStart$,()=>{this.logPlay()}),r(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.wasPaused&&this.logResume()}),r(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),r(e.events.ended$,()=>{this.logContentEndReached()}),r(e.events.willStop$,()=>{this.isStarted=!1,this.logStop()}),r(Pt(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let a=e=>{switch(e){case L.NETWORK:return`network`;case L.VIDEO_PIPELINE:return`video_pipeline`;case L.EXTERNAL_API:return`external_api`;case L.PARSER:return`parser`;case L.DOM:return`dom`;default:return`wtf`}},o=e=>L.FATAL===e?`critical`:`informative`;r(e.events.fetcherRecoverableError$,({id:t,category:n,data:r,message:i,httpCode:s,UVBackendErrorCode:c})=>{let l={error_severity:o(n),error_category:a(n),player_error_code:t,player_error_trace:r,http_error_code:s,uv_backend_error_code_subcode:c,error_message:i,content_type:Z(e.info.currentFormat$.getValue())};this.logError(l),o(n)===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),r(e.events.managedError$,({id:t,category:n,data:r,message:i})=>{let s={error_severity:o(n),error_category:a(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Z(e.info.currentFormat$.getValue())};this.logError(s),this.logTelemetry(this.collectTelemetryData())}),r(e.events.fatalError$,({id:t,category:n,data:r,message:i})=>{let o={error_severity:`critical`,error_category:a(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Z(e.info.currentFormat$.getValue())};this.logError(o),this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),r(F({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(I(({connectionReused:e})=>e!==void 0),I(({connectionMetrics:e})=>e!==void 0),Ft((e,t)=>e.connectionType===t.connectionType)),({connectionMetrics:t})=>{let n=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),i=e.info.currentQuality$.getValue(),a=e.info.rttEstimation$.getValue();this.networkType=this.statContext.networkType??t?.networkType;let o=t?.dnsResolveTime,s=t?.tcpHandshakeTime,c=t?.tlsHandshakeTime,l={playback_url:$(n,r,i),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:a?Math.round(a):void 0,network_type:this.networkType,dns_resolve_time:o?Math.round(o):void 0,tcp_handshake_time:s?Math.round(s):void 0,tls_handshake_time:c?Math.round(c):void 0};this.logConnectionEstablished(l)}),r(Gn(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),r(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),r(e.events.willSeek$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),r(e.events.seeked$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),r(e.info.isStalled$,t=>{let n=e.info.currentBuffer$.getValue(),r=this.calcBufferTime(n);t&&r&&r>0&&(this.logBufferStarvation({buffer_time:r}),this.logTelemetry(this.collectTelemetryData()))}),r(e.info.currentBuffer$.pipe(I(e=>!!this.calcBufferTime(e)),It()),e=>{let t=this.calcBufferTime(e);if(this.statContext.preload){let e={buffer_time:t};this.logPreloadEnded(e)}this.logReady({buffer_time:t})});let s;r(F({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(I(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),I(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(s!==r){let i=e.info.isAutoQualityEnabled$.getValue();if(this.userQuality=i?`auto`:Q(r),this.downloadQuality=Q(r),this.isStarted){let e=t?.codec,r=n?.codec,i={user_quality:this.userQuality,playback_quality:Q(s),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}s=r}});let c,l;return r(e.info.surface$,e=>{let t=ir(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),l=ar(e),c!==l&&(this.isStarted&&this.logVisibilityChanged({visibility:l}),c=ar(e))}),r(F({muted:e.info.muted$,volume:e.info.volume$}).pipe(Rt(300)),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),r(e.info.currentFormat$.pipe(I(e=>e!==void 0),Lt(1)),e=>{let t={content_type:Z(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),r(e.info.currentAudioStream$.pipe(I(e=>e!==void 0),Lt(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),r(e.info.currentVideoStream$.pipe(I(e=>e!==void 0),Lt(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.playerSubscription=n,this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToUi(e){this.uiSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to UI, unsubscribing from previous`}),this.uiSubscription.unsubscribe()),this.uiEvents=e;let{subscribe:t,subscription:n}=cr();t(e.actionSeek$,this.seekAction$),t(e.playerSize$,({width:e,height:t})=>{e&&t&&(this.playerSize={width:e,height:t},this.isStarted&&this.logViewPortChanged({player_width:Math.round(e),player_height:Math.round(t)}))}),t(e.isLoaderVisible$,e=>{e&&this.isStarted&&this.logShowLoader()}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle=f({},e),this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:r}=St(this.uiEvents,t,this.player);return t(r,e=>{this.isStarted&&this.logModeChanged({mode:ir(e)})}),t(e.actionQuality$,e=>{var t,n,r;let i=e=>kt(Ot(Gt),e),a=(t=this.player)==null||(t=t.info.currentVideoStream$.getValue())==null?void 0:t.codec,o=(n=this.player)==null||(n=n.info.currentAudioStream$.getValue())==null?void 0:n.codec,s={user_quality:i(e)?`auto`:Q(e),playback_quality:Q(this.player?.info.currentQuality$.getValue()),download_quality:i(e)?Q((r=this.player)==null||(r=r.info.currentQuality$)==null?void 0:r.getValue()):Q(e),codec_info:this.genCodecInfo(a,o)};this.logQualityChangeRequested(s)}),this.uiSubscription=n,this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToAds(e){this.adsSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to ads, unsubscribing from previous`}),this.adsSubscription.unsubscribe());let{subscription:t,subscribe:n}=cr();return n(e.init$,e=>{let t={slot:e};this.logAdvConfiguration(t)}),n(e.slotRequested$,e=>{let t={adv_section:e};this.logAdvRequest(t)}),n(e.started$,e=>{let t={adv_section:e};this.logAdvBreakStarted(t)}),n(e.ended$,({section:e,ordIds:t})=>{let n={adv_section:e,erids:t.join(`,`)};this.logAdvBreakEnded(n)}),n(e.error$,e=>{let t={error_message:e};this.logAdvError(t)}),this.adsSubscription=t,this.resubscribeBeforeunload(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),T.generateVSID(this.config.useVsid64),this.vsid$.next(T.getVSID()),this.eventNumber=0}destroy(){var e=this;return p(function*(){e.thinOneStatDebugLog({message:`Destroying ThinOneStat`}),e.subscription.unsubscribe(),yield e.logger.destroy(),e.apis.forEach(e=>e.destroy()),e.thinOneStatDebugLog({message:`ThinOneStat destroyed`})})()}calcBufferTime(e){return e?Math.round((e.end??0)-(e.start??0))*1e3:void 0}genCodecInfo(e,t){return e&&t?`${e},${t}`:void 0}getLatencyInfo(){let e=this.player?.info.atLiveEdge$.getValue();return JSON.stringify({client_time:Date.now(),live:e})}collectTelemetryData(){if(!this.player)return{};let e=this.player.info.currentBuffer$.getValue(),t=this.player.experimental.element$.getValue(),n=0,r=0;t&&(n=t.getVideoPlaybackQuality().droppedVideoFrames,r=t.getVideoPlaybackQuality().totalVideoFrames);let i=Z(this.player.info.currentFormat$.getValue()),a=this.player.info.currentVideoStream$.getValue()?.codec,o=this.player.info.currentAudioStream$.getValue()?.codec,s=this.player.info.videoBitrate$.getValue(),c=this.player.info.rttEstimation$.getValue();return{buffer_time:this.calcBufferTime(e),dropped_frames_count:n,rendered_frames_count:r,content_type:i,user_quality:this.userQuality,playback_quality:Q(this.player.info.currentQuality$.getValue()),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(a,o),bandwidth_from_manifest:s?Math.round(s):void 0,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed?Math.round(this.downloadSpeed):void 0,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}isValidPlatform(e=``){return kt([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();At(t);let n=this.eventNumber++,r=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,i={vsid:t,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${E}`,platform:this.isValidPlatform(this.statContext.platform)?this.statContext.platform:`web:${this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`}`,product:this.statContext.product,event_number:n,playback_position:Math.round(r),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let e of this.config.disabledParams)delete i[e];return i}createRequiredFatParams(){let e={stats_version:sr,browser:this.statContext.browser??R.browser.current,browser_version:this.statContext.browserVersion??String(R.browser.currentVersion),os:this.statContext.os??R.device.os.name,os_version:this.statContext.osVersion??R.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??R.device.details.vendor,device_model:this.statContext.deviceModel??R.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,n=!1){if(kt(this.config.disabledEvents,e))return;let r=this.createRequiredParams(e),i={};n&&(i=this.createRequiredFatParams()),this.logger.log(f(f(f({},r),i),t))}logWatchCoverage(e){this.log(`watch_coverage`,e,!0)}logWatchCoverageLive(e){this.log(`watch_coverage_live`,e,!0)}logWatchedN(e){this.log(`watched_n`,e,!0)}logStartSession(e){this.log(`start_session`,e,!0)}logPreloadStarted(e){this.log(`preload_started`,e)}logPreloadEnded(e){this.log(`preload_ended`,e)}logPreloadError(){this.log(`preload_error`)}logPlaybackStarted(e){this.log(`playback_started`,e,!0)}logPlay(){this.log(`play`)}logManifestRequest(e){this.log(`manifest_request`,e)}logFirstByteManifest(e){this.log(`first_byte_manifest`,e)}logFirstMediaRequest(e){this.log(`first_media_request`,e)}logFirstByteMedia(e){this.log(`first_byte_media`,e)}logManifestReceived(e){this.log(`manifest_received`,e)}logConnectionEstablished(e){this.log(`connection_established`,e)}logFirstVideoFrameDecoded(){this.log(`first_video_frame_decoded`)}logReady(e){this.log(`ready`,e)}logPlaying(e){this.log(`playing`,e)}logPause(){this.log(`pause`)}logResume(){this.log(`resume`)}logSeeking(e){this.log(`seeking`,e)}logSeeked(e){this.log(`seeked`,e)}logContentEndReached(){this.log(`content_end_reached`)}logStop(){this.log(`stop`)}logBufferStarvation(e){this.log(`buffer_starvation`,e)}logShowLoader(){this.log(`show_loader`)}logQualityChangeRequested(e){this.log(`quality_change_requested`,e)}logQualityChanged(e){this.log(`quality_changed`,e)}logCdnHostChanged(e){this.log(`cdn_host_changed`,e)}logViewPortChanged(e){this.log(`view_port_changed`,e)}logModeChanged(e){this.log(`mode_changed`,e)}logVisibilityChanged(e){this.log(`visibility_changed`,e)}logAudioTrackSwitched(e){this.log(`audio_track_switched`,e)}logVideoTrackSwitched(e){this.log(`video_track_switched`,e)}logSubtitlesSwitched(e){this.log(`subtitles_switched`,e)}logSoundChanged(e){this.log(`sound_changed`,e)}logFailover(e){this.log(`failover`,e)}logContentTypeChange(e){this.log(`content_type_change`,e)}logError(e){this.log(`error`,e,!0)}logCannotPlay(){this.log(`cannot_play`,{},!0)}logDownloadBytes(e){this.log(`download_bytes`,e)}logTelemetry(e){this.log(`telemetry`,e)}logAdvConfiguration(e){this.log(`adv_configuration`,e)}logAdvRequest(e){this.log(`adv_request`,e)}logAdvBreakStarted(e){this.log(`adv_break_started`,e)}logAdvBreakEnded(e){this.log(`adv_break_ended`,e)}logAdvError(e){this.log(`adv_error`,e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Mt(Bt(),`beforeunload`).subscribe(()=>{this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload}).catch(()=>{})}),this.subscription.add(this.beforeunloadSubscription)}}class hr{constructor(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime===null?this.startTime=this.now():(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null))}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}}var gr=()=>window.Image?new Image:document.createElement(`img`);class _r{constructor(e){this.params=void 0,this.position=0,this.started=!1,this.isActiveLive=void 0,this.heartbeatPixels=[],this.heartbeatLastTimeSent={},this.heartbeatInterval=void 0,this.heartbeatFirstTimeoutId=void 0,this.idleCallbackIds=[],this.log=void 0,this.stopwatch=new hr,this.subscription=new pr,this.params=e;let t=new mr;this.log=t.createComponentLog(`MediascopePixel`)}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(e=>this.onPlaybackState(e))).add(e.info.position$.subscribe(e=>this.onPosition(e))).add(e.info.atLiveEdge$.subscribe(e=>this.isActiveLive=e)),this.subscription.add(e.events.willSeek$.subscribe(()=>this.onWillSeek())).add(e.events.seeked$.subscribe(()=>this.onSeeked())).add(e.events.ended$.subscribe(()=>this.onEnded()))}destroy(){this.stopwatch.reset(),this.subscription.unsubscribe(),window.clearTimeout(this.heartbeatFirstTimeoutId),this.idleCallbackIds.forEach(e=>ur(e)),this.send(`stop`)}onPlaybackState(e){e===fr.PLAYING?this.started?this.play():this.start():e===fr.PAUSED&&this.pause()}start(){this.started=!0,this.stopwatch.start(),this.send(`start`),this.heartbeatPixels=this.prepareHeartbeatPixels(),this.heartbeatInterval=this.heartbeatPixels[0]?.interval;let e=this.heartbeatPixels[0]?.url,t=this.heartbeatPixels[0]?.delay;if(t!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},t*1e3)}catch(e){this.log({message:e.message})}}play(){this.stopwatch.start(),this.send(`resume`)}pause(){this.stopwatch.stop(),this.send(`pause`)}onPosition(e){if(this.position=e,this.heartbeatInterval&&this.stopwatch.time!==0&&this.stopwatch.time%this.heartbeatInterval===0)for(let[e,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[e]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[e]=this.stopwatch.time,this.sendHeartbeat(t))}onWillSeek(){this.started&&this.send(`stop`)}onSeeked(){this.started&&this.send(`start`)}onEnded(){this.stopwatch.stop(),this.send(`stop`)}validatePixels(e,t){return e?.filter(e=>e.event===t.event&&t.keys.every(t=>!!e[t]))}getFrameTimestamp(){let e;if(this.isActiveLive){let t=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-t}else e=this.position||0;return Math.floor(e)}getUTC(){return Math.floor(Date.now()/1e3)}prepareUrl(e){return e.replace(`{@fts_fake_sec}`,String(this.getFrameTimestamp())).replace(`{@utc_sec}`,String(this.getUTC())).split(`&`).filter(e=>!/={@[a-zA-Z_]+}/.test(e)).join(`&`)}preparePixels(e){return this.validatePixels(this.params.pixels,{event:e,keys:[`url`]})}prepareHeartbeatPixels(){return this.validatePixels(this.params.pixels,{event:`heartbeat`,keys:[`url`,`interval`]})}call(e){try{this.idleCallbackIds.push(dr(()=>gr().src=this.prepareUrl(e)))}catch(e){this.log({message:e.message})}}send(e){let t=this.preparePixels(e);for(let{url:e}of t)this.call(e)}sendHeartbeat(e){this.call(e)}};return{E,Dt,te,b,Et,_r,ne,x,S,y};}();var{E:_oxcModsitth1_E,Dt:_oxcModsitth1_Dt,te:_oxcModsitth1_te,b:_oxcModsitth1_b,Et:_oxcModsitth1_Et,_r:_oxcModsitth1__r,ne:_oxcModsitth1_ne,x:_oxcModsitth1_x,S:_oxcModsitth1_S,y:_oxcModsitth1_y}=_oxcModsitth1;export{_oxcModsitth1_E as VERSION,_oxcModsitth1_Dt as ThinOneStat,_oxcModsitth1_te as SeekAction,_oxcModsitth1_b as Quality,_oxcModsitth1_Et as OneStat,_oxcModsitth1__r as MediascopePixel,_oxcModsitth1_ne as InteractiveInterfaceClick,_oxcModsitth1_x as ContentType,_oxcModsitth1_S as ConnectionType,_oxcModsitth1_y as ApiEnv};
|