@vkontakte/videoplayer-statistics 1.0.109-dev.53fc4c12e.0 → 1.0.109-dev.5f4dee4ba.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.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.109-dev.53fc4c12e.0
3
- * Mon, 08 Jun 2026 14:16:06 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.109-dev.5f4dee4ba.0
3
+ * Mon, 15 Jun 2026 13:12:10 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.53fc4c12e.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
+ const e=[`application`,`platform`,`product`];import t from"@oxc-project/runtime/helpers/defineProperty";import n from"@oxc-project/runtime/helpers/objectSpread2";import r from"@oxc-project/runtime/helpers/asyncToGenerator";import i from"@oxc-project/runtime/helpers/objectWithoutProperties";var a=Object.defineProperty,o=e=>e;function s(e,t){this[e]=o.bind(null,t)}var c=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0,configurable:!0,set:s.bind(t,n)})};import{arrayIncludes as l}from"@vkontakte/videoplayer-shared/es2015";import{urlCanParsePolyfilled as u}from"@vkontakte/videoplayer-shared/es2015";var d;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(d||={});var f;(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`})(f||={});var p;(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`})(p||={});var m;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(m||={});var h;(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`})(h||={});var g;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(g||={});var ee={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`},_={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`},v={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},y={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`};import{fillWithDefault as b}from"@vkontakte/videoplayer-shared/es2015";var te=`CIOPGQJGDIHBABABA`,x={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:``},ne={apiEnv:`vk_alias`,apiKey:te,apiBaseUrl:null,apiUvRestBaseUrl:`https://uvapi.okcdn.ru`,apiCollector:`ok.mobile.apps.video`,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},re=e=>b(e,ne);function ie(){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 ae,combine as oe,fromEvent as se,isNonNullable as S,isNullable as ce,merge as le,now as C,observableFrom as ue,once as de,safeStorage as fe,Subject as pe,Subscription as me,ValueSubject as he,getWindow as ge}from"@vkontakte/videoplayer-shared/es2015";import{Logger as _e,detectEmbed as ve,ErrorCategory as ye}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as be}from"@vkontakte/videoplayer-shared/es2015";var xe=()=>be(Math.floor(Math.random()*2**32).toString(36),13,`0`),Se=()=>be(Math.floor(Math.random()*2**64).toString(36),13,`0`);class w{static getVSID(){return w.vsid}static generateVSID(e){return w.vsid=e?Se():xe(),w.vsid}}t(w,`vsid`,void 0);import{promiseFinally as Ce}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as we}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as Te}from"@vkontakte/videoplayer-shared/es2015";var Ee=e=>{let{operation:t,custom:r}=e,i=Te(we(r).map(([e,t])=>{let n=_[e]??e,r=t;return t&&(e===`mode`?r=y[t]??t:e===`quality`&&(r=v[t]??t)),[n,r]}));return n(n({},e),{},{operation:ee[t]??t,custom:i})},T=`1.0.109-dev.5f4dee4ba.0`;import{ValueSubject as De,getExponentialDelay as Oe,ErrorCategory as E,getWindow as D}from"@vkontakte/videoplayer-shared/es2015";var ke=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class Ae{constructor(e){t(this,`id`,`forticom`),t(this,`params`,void 0),t(this,`authToken`,void 0),t(this,`sessionKey`,void 0),t(this,`authorizePromise`,void 0),t(this,`refreshAuthTokenPromise`,void 0),t(this,`consequentAuthErrors`,0),t(this,`authorized$`,new De(!1)),t(this,`backoffTimeoutId`,void 0),this.params=e}authorize(e){var t=this;return r(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 r(function*(){let n=`log.externalLog`,i=t.createLogParams(e),a=t.sessionKey??(yield t._authorizeWithBackoff());if(!a)return;let o=function(){var e=r(function*(e,r=t.params.config.requestRetryCount){try{return yield t.params.apiTransport.sendRequest(n,i,a)}catch(i){if(!i||!(`error_code`in i)){t.params.error$.next({id:`logRequestUnknown`,category:E.NETWORK,message:`Unknown ${n} 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(),r>0?o(e,r-1):void 0;case 401:return t.authorized$.next(!1),t.authToken=yield t.refreshAuthToken(),t.sessionKey=yield t._authorizeWithBackoff(),r>0?o(e,r-1):void 0;default:t.params.error$.next({id:`LogRequest#${a}`,category:E.EXTERNAL_API,message:`${n} error`,data:i});return}}});return function(t){return e.apply(this,arguments)}}();return o(e)})()}destroy(){D().clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return r(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Ce(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}=D().navigator;n=ke.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:this.params.config.apiCollector,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(Ee):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Oe(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=D().setTimeout(()=>{Ce(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 r(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=Ce(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=r(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 je{constructor(e){t(this,`id`,`uvrest`),t(this,`authorized$`,new De(!1)),t(this,`params`,void 0),t(this,`statToken`,void 0),t(this,`authorizePromise`,void 0),t(this,`isDestroyed`,!1),this.params=e}authorize(e){var t=this;return r(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=Ce(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return r(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 r(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return r(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 r(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 r(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}=D().navigator;n=ke.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(Ee):e}]}}import{fetchPolyfilled as O}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 k,now as A,getWindow as Pe}from"@vkontakte/videoplayer-shared/es2015";class Fe{constructor(e){t(this,`apiKey`,void 0),t(this,`apiBaseUrl`,void 0),t(this,`apiUvRestBaseUrl`,void 0),t(this,`apiEnv`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`isApiBaseUrlFetched`,void 0),t(this,`params`,void 0),this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??x[this.apiEnv],this.apiUvRestBaseUrl=e.config.apiUvRestBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){var e=this;return r(function*(){if(e.apiEnv!==`auto`||e.isApiBaseUrlFetched)return e.apiBaseUrl;try{var t;let e=yield(yield O(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:k.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),x.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:k.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n){var i=this;return r(function*(){let r=A(),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:k.NETWORK,message:`Request failed`,thrown:a});return}i.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:k.NETWORK,message:`Unhandled request error`,thrown:a,data:{method:e,params:t,sessionKey:n,time:A()-r}})};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:n})};return i.params.config.useKeepalive&&(o.keepalive=!0),O(`${i.apiBaseUrl}/fb.do`,o).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),o=A()-r;if(isFinite(n)&&i.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,r){let i=`${this.apiUvRestBaseUrl}${e}`;try{O(i,{method:`POST`,headers:n({"Content-Type":`application/json`},r),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:k.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:k.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequest(e,t,i){var a=this;return r(function*(){let r=A(),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:k.NETWORK,message:`JSON request failed`,thrown:t});return}a.params.error$.next({id:`OneStat:ApiTransport:sendJsonRequest`,category:k.NETWORK,message:`Unhandled JSON request error`,thrown:t,data:{path:e,time:A()-r}})},s={method:`POST`,headers:n({"Content-Type":`application/json`},i),body:JSON.stringify(t)};return a.params.config.useKeepalive&&(s.keepalive=!0),O(`${a.apiUvRestBaseUrl}${e}`,s).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),i=A()-r;if(isFinite(n)&&a.timeSynchronisation?.addServerTime(n,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 j,debounceFn as Be}from"@vkontakte/videoplayer-shared/es2015";var Ve=e=>t=>t.timestamp+e>=ze();class He{constructor(e){t(this,`params`,void 0),t(this,`error$`,void 0),t(this,`userSalt`,void 0),t(this,`isPaused`,!1),t(this,`loggerDebugLog`,void 0),t(this,`queues`,[]),t(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=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=Be(()=>this.safeFlushQueue(a),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime}),r=j.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=j.get(e);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(e,t){if(!this.userSalt){e.unsaltedStorage.push(t);return}let r=this.readFromStorage(e.storageKey),i=(r[this.userSalt]??[]).filter(Ve(this.params.config.storageExpiration));j.set(e.storageKey,JSON.stringify(n(n({},r),{},{[this.userSalt]:[...i,t]})))}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],j.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})`})}j.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 M,VideoFormat as N,VideoQuality as P}from"@vkontakte/videoplayer-core/es2015";import{assertNever as We}from"@vkontakte/videoplayer-shared/es2015";var Ge=e=>e&&{[P.INVARIANT]:`unknown`,[P.Q_144P]:`mobile`,[P.Q_240P]:`lowest`,[P.Q_360P]:`low`,[P.Q_480P]:`medium`,[P.Q_576P]:`unknown`,[P.Q_720P]:`high`,[P.Q_1080P]:`fullhd`,[P.Q_1440P]:`quadhd`,[P.Q_2160P]:`ultrahd`,[P.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 N.MPEG:return`mp4`;case N.DASH:case N.DASH_LIVE:case N.DASH_STREAMS:return`dash`;case N.DASH_SEP:return`dash_sep`;case N.DASH_ONDEMAND:return`ondemand_dash`;case N.DASH_WEBM:case N.DASH_LIVE_WEBM:return`webm`;case N.DASH_WEBM_AV1:return`av1`;case N.DASH_LIVE_CMAF:return`ondemand_dash_live`;case N.HLS:case N.HLS_LIVE:return`hls`;case N.HLS_FMP4:return`hls_fmp4`;case N.HLS_ONDEMAND:return`ondemand_hls`;case N.HLS_LIVE_CMAF:return`ondemand_hls_live`;case N.WEB_RTC_LIVE:return`webrtc`;default:return We(e)}},Je=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case M.NONE:case M.INLINE:return;case M.FULLSCREEN:return`fullscreen`;case M.SECOND_SCREEN:return`chromecast`;case M.PIP:return`pip`;case M.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(e){t(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)}}}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 rt,Observable as it,Subject as at,Subscription as ot,ValueSubject as st}from"@vkontakte/videoplayer-shared/es2015";var ct=(e,t)=>new it(n=>{let r=new ot,i=rt(et(window,`beforeunload`),e.events.willDestruct$),a=new st(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 at;r.add(u.subscribe(()=>{f||p.next(),f=!0})),r.add(d.subscribe(()=>f=!1));let m=new at,h=new at,g=()=>t.watchCoverageExactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,ee=e.info.stallStartTime$.pipe($e(),Qe(e=>e>0)),_=rt(s,d,m).pipe(nt(()=>g())),v=rt(l,rt(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 F}from"@vkontakte/videoplayer-core/es2015";import{debounce as lt,filterChanged as ut,Subject as dt}from"@vkontakte/videoplayer-shared/es2015";var ft=(e,t,n)=>{let r=new dt,i=r.pipe(lt(0),ut()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?F.PIP:o?F.FULLSCREEN:s?F.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?F.FULLSCREEN:a?F.PIP:s?F.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case F.SECOND_SCREEN:case F.NONE:case F.INLINE:!o&&!a&&(e===F.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},pt=`_one-stat_deviceId`,mt=(e,t)=>e&&t?`${e}_${t}`:e??t,ht=()=>{let e=new me;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class gt{get vsid$(){return new he(w.getVSID())}constructor(e,n){t(this,`apis`,void 0),t(this,`logger`,void 0),t(this,`config`,void 0),t(this,`subscription`,new me),t(this,`beforeunloadSubscription`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`debugLogger`,new _e),t(this,`oneStatDebugLog`,this.debugLogger.createComponentLog(`onestat`)),t(this,`loopCounter`,0),t(this,`disabled`,!1),t(this,`experimental`,void 0),t(this,`isid$`,new he(void 0)),t(this,`zenUid$`,new he(void 0)),t(this,`statContext`,void 0),t(this,`isEmbed`,void 0),t(this,`embedParent`,void 0),t(this,`uiEvents`,void 0),t(this,`player`,void 0),t(this,`seekAction$`,new he(`unknown`)),t(this,`deviceId`,void 0),this.statContext=e,this.config=re(n.config??{}),S(n.apiEnv)&&(this.config.apiEnv=n.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Xe);let r=new pe;this.experimental={error$:r};let i=fe.get(pt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=ie(),fe.set(pt,this.deviceId)),this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??Se()),this.zenUid$.next(n.zenUid);let a=new Fe({config:this.config,error$:r,timeSynchronisation:this.timeSynchronisation}),o=[];this.config.apiForticom&&o.push(new Ae({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 je({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:ye.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}=ve();this.isEmbed=s,this.embedParent=c?new URL(c).hostname:void 0,this.subscribe()}updateContext(e){this.statContext=n(n({},this.statContext),e)}attachTo(e){let t=new me,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(ct(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(de()).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(oe({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=>{ce(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(oe({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}=ht();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}=ft(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}=ht();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}=ht();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=ge().navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(le(se(e,`change`),ue([`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=se(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(l(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:r},i={}){let a=this.timeSynchronisation?.now()??C(),o=this.vsid$.getValue();ae(o);let s=this.isid$.getValue(),c=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])=>l(this.config.embedUrlParams,e));p=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;f=e&&u(URL,e)?new URL(e).hostname:e,p=location.href.substring(0,1024)}let m=n({vsid:o,isid:s,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:c,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||ce(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,codec_info:mt(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 _t={};c(_t,{VERSION:()=>T,ThinOneStat:()=>rr,ActionSeekType:()=>It});import{objectValues as vt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as yt}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as bt,detectEmbed as xt,fromEvent as St,Logger as Ct,merge as wt,combine as I,filter as L,filterChanged as Tt,once as Et,skip as Dt,debounce as Ot,safeStorage as kt,getWindow as At,Subject as jt,Subscription as Mt,ValueSubject as Nt,ErrorCategory as R}from"@vkontakte/videoplayer-shared/es2015";import{clientChecker as z}from"@vkontakte/videoplayer-core/es2015";import{fillWithDefault as Pt}from"@vkontakte/videoplayer-shared/es2015";var Ft;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(Ft||={});var It;(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`})(It||={});var Lt=`CIOPGQJGDIHBABABA`,Rt={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:``},zt={apiKey:Lt,apiEnv:`okcdn`,apiBaseUrl:null,apiUvRestBaseUrl:`https://uvapi.okcdn.ru`,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},Bt=e=>Pt(e,zt);import{arrayIncludes as Vt}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Ht}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as B,ValueSubject as Ut}from"@vkontakte/videoplayer-shared/es2015";function Wt(e){let t=Error(`HTTP ${e.status}: ${e.statusText}`);return t.status=e.status,t.statusText=e.statusText,t.response=e,t}function Gt(){let e=Error(`Request timeout`);return e.isTimeout=!0,e}function Kt(e){let t=Error(e.error_msg);return t.errorData=e,t}function qt(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}}}var Jt=t=>{let{application:n,platform:r,product:a}=t;return i(t,e)};class Yt{constructor(e){t(this,`id`,`forticom`),t(this,`authorized$`,void 0),t(this,`params`,void 0),t(this,`authToken`,void 0),t(this,`sessionKey`,void 0),t(this,`authorizePromise`,void 0),t(this,`refreshAuthTokenPromise`,void 0),t(this,`isDestroyed`,!1),this.params=e,this.authorized$=new Ut(!1)}authorize(e){var t=this;return r(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 r(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:B.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 r(function*(){return e.sessionKey?e.sessionKey:e.doAuthorize()})()}handleLogRequestError(e,t,n){var i=this;return r(function*(){let r=qt(e);return r===void 0?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestUnknown`,category:B.NETWORK,message:`Unknown ${t} error`,thrown:e,data:{params:n}}),!1):i.isSessionExpiredError(r)?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestSessionError#${r}`,category:B.EXTERNAL_API,message:`Session error: ${r}`,data:{error:e,code:r}}),i.authorized$.next(!1),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):r===401?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestAuthLogin#${r}`,category:B.EXTERNAL_API,message:`Auth token expired`,data:{error:e,code:r}}),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#${r}`,category:B.EXTERNAL_API,message:`${t} error`,data:{error:e,code:r,params:n}}),!1)})()}retryLogRequestAfterSessionRecovery(e,t){var n=this;return r(function*(){let r=n.sessionKey;if(!r){n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed`,category:B.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=qt(e);n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed#${t??`unknown`}`,category:B.EXTERNAL_API,message:`Log request failed after session recovery`,thrown:e,data:{originalError:e,retryCode:t}})}})()}isSessionExpiredError(e){return!!e&&Vt([102,103,104],e)}doAuthorize(e=1){var t=this;return r(function*(){if(!t.isDestroyed)return t.authorizePromise?t.authorizePromise:(t.sessionKey=void 0,t.authorized$.next(!1),t.authorizePromise=Ht(t.executeAuthorize(e),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.sessionKey!==void 0)}),t.authorizePromise)})()}executeAuthorize(e){var t=this;return r(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:B.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=qt(n);if(r===401&&t.params.refreshAuthToken){if(t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:B.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:B.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:B.EXTERNAL_API,message:`Authorize error`,data:{error:n,code:r}}):t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:B.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 r(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Ht(e.params.refreshAuthToken().catch(t=>{throw e.params.errors$.next({id:`ThinOneStat:Api:RefreshAuthTokenFailed`,category:B.NETWORK,message:`Failed to refresh auth token`,thrown:t}),t}),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=e[0],n=t.application??`@vkontakte/videoplayer-statistics:${this.getClientVersion()}`;return this.params.vktvVersion&&(n=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:n,platform:t.platform,product:t.product,events:e.map(Jt)})}}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.sessionKey=void 0,this.authorized$.next(!1)}}class Xt{constructor(e){t(this,`id`,`uvrest`),t(this,`authorized$`,void 0),t(this,`params`,void 0),t(this,`statToken`,void 0),t(this,`authorizePromise`,void 0),t(this,`isDestroyed`,!1),this.params=e,this.authorized$=new Ut(!1)}authorize(e){var t=this;return r(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=Ht(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return r(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:B.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 r(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return r(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.errors$.next({id:`ThinOneStat:UvRestApi:NoToken`,category:B.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:B.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return r(function*(){let n=e?.status;return n===401?(t.params.errors$.next({id:`ThinOneStat:UvRestApi:TokenExpired`,category:B.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:B.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return r(function*(){let n=t.statToken;if(!n){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryNoToken`,category:B.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:B.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.map(Jt)}]}}import{fetchPolyfilled as Zt}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Qt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as V}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as $t}from"@vkontakte/videoplayer-shared/es2015";import{now as H,getWindow as U,getExponentialDelay as en,isAbortError as tn,ErrorCategory as W}from"@vkontakte/videoplayer-shared/es2015";class nn{constructor(e){t(this,`params`,void 0),t(this,`apiKey`,void 0),t(this,`apiBaseUrl`,void 0),t(this,`apiUvRestBaseUrl`,void 0),t(this,`apiEnv`,void 0),t(this,`resolvedApiBaseUrl`,null),t(this,`resolveApiBaseUrlPromise`,null),t(this,`timeSynchronisation`,void 0),t(this,`fetchTimeout`,3e4),t(this,`maxTotalRequestTime`,6e4),t(this,`retryConfig`,void 0),this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Rt[this.apiEnv],this.apiUvRestBaseUrl=e.config.apiUvRestBaseUrl,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(!U().Blob||!U().navigator.sendBeacon)return!1;let r=this.resolvedApiBaseUrl??this.apiBaseUrl,i=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),a=U().Blob,o=new a([i.toString()],{type:`application/x-www-form-urlencoded`});try{return U().navigator.sendBeacon(`${r}/fb.do`,o)}catch(n){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendBeacon`,category:W.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n,i){var a=this;return r(function*(){return a.sendRequestWithRetry(e,t,n,i)})()}sendRequestWithRetry(e,t,n,i,a=1,o){var s=this;return r(function*(){let r=H(),c=o??r+s.maxTotalRequestTime;if(H()>=c){let i=Error(`Request deadline exceeded`);throw s.handleFinalError(e,t,n,r,i,a),i}try{return yield s.executeRequest(e,t,n,i,r,a,c)}catch(o){if(s.shouldRetry(o,a)&&H()<c){let l=s.getRetryDelay(o,a);if(H()+l>=c)throw s.handleFinalError(e,t,n,r,o,a),o;return s.logRetryAttempt(e,a,o,l),yield s.sleep(l),s.sendRequestWithRetry(e,t,n,i,a+1,c)}throw s.handleFinalError(e,t,n,r,o,a),o}})()}executeRequest(e,t,i,a,o,s,c){var l=this;return r(function*(){let r=o??H(),u=yield l.resolveApiBaseUrl(),d=c===void 0?l.fetchTimeout:c-H();if(d<=0)throw Gt();try{let o=yield l.fetchWithTimeout(`${u}/fb.do`,{method:`post`,headers:n({"Content-type":`application/x-www-form-urlencoded`},a),body:l.prepareQueryParams({method:e,queryParams:t,sessionKey:i})},Math.min(l.fetchTimeout,d));return yield l.processResponse(o,r)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:s,url:`${u}/fb.do`}),t}})()}sendJsonRequest(e,t,n){var i=this;return r(function*(){return i.sendJsonRequestWithRetry(e,t,n)})()}sendJsonBeacon(e,t,r){let i=`${this.apiUvRestBaseUrl}${e}`;try{Zt(i,{method:`POST`,headers:n({"Content-Type":`application/json`},r),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:W.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:W.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequestWithRetry(e,t,n,i=1,a){var o=this;return r(function*(){let r=H(),s=a??r+o.maxTotalRequestTime;if(H()>=s){let t=Error(`Request deadline exceeded`);throw o.handleJsonFinalError(e,r,t,i),t}try{return yield o.executeJsonRequest(e,t,n,r,i,s)}catch(a){if(o.shouldRetry(a,i)&&H()<s){let c=o.getRetryDelay(a,i);if(H()+c>=s)throw o.handleJsonFinalError(e,r,a,i),a;return o.logRetryAttempt(e,i,a,c),yield o.sleep(c),o.sendJsonRequestWithRetry(e,t,n,i+1,s)}throw o.handleJsonFinalError(e,r,a,i),a}})()}executeJsonRequest(e,t,i,a,o,s){var c=this;return r(function*(){let r=a??H(),l=s===void 0?c.fetchTimeout:s-H();if(l<=0)throw Gt();let u=`${c.apiUvRestBaseUrl}${e}`;try{let e=yield c.fetchWithTimeout(u,{method:`POST`,headers:n({"Content-Type":`application/json`},i),body:JSON.stringify(t)},Math.min(c.fetchTimeout,l));return yield c.processResponse(e,r)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:o,url:u}),t}})()}fetchWithTimeout(e,t){return r(function*(e,t,r=this.fetchTimeout){let i=new Qt,a=U().setTimeout(()=>i.abort(),r);try{let r=yield Zt(e,n(n({},t),{},{signal:i.signal}));return U().clearTimeout(a),r}catch(e){throw U().clearTimeout(a),tn(e)?Gt():e}}).apply(this,arguments)}processResponse(e,t){var n=this;return r(function*(){if(!e.ok){let t=Wt(e),r=n.parseRetryAfter(e);throw r!==void 0&&(t.retryAfter=r),t}let r=new Date(e.headers.get(`date`)??``).getTime(),i=H()-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 Kt(o);return o})()}shouldRetry(e,t){if(t>=this.retryConfig.maxAttempts||!(e instanceof Error))return!1;let n=e;return!!(n.isTimeout||n.status&&V(this.retryConfig.retryableStatuses,n.status)||V(this.retryConfig.retryableErrors,e.message)||V(e.message,`network`)||V(e.message,`timeout`)||V(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:W.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=W.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:H()-r,maxAttempts:this.retryConfig.maxAttempts,attempts:a}})}handleJsonFinalError(e,t,n,r){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonRequest`,category:W.NETWORK,message:n instanceof Error?n.message:`JSON request failed after retries`,thrown:n,data:{path:e,time:H()-t,maxAttempts:this.retryConfig.maxAttempts,attempts:r}})}sleep(e){return new Promise(t=>U().setTimeout(t,e))}resolveApiBaseUrl(){return this.apiEnv===`auto`?(this.resolveApiBaseUrlPromise||=this.fetchApiBaseUrl().then(e=>(e===Rt.vk_alias&&(this.resolveApiBaseUrlPromise=null),e)),this.resolveApiBaseUrlPromise):Promise.resolve(this.apiBaseUrl)}fetchApiBaseUrl(){var e=this;return r(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:W.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),Rt.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),$t(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:en(t,{start:this.retryConfig.baseDelay,max:this.retryConfig.maxDelay,factor:2,random:.2})}}import{promiseAllSettled as rn}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as an}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as on}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as sn}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as cn}from"@vkontakte/videoplayer-shared/es2015";import{now as ln,debounceFn as un,getWindow as G,safeStorage as K,ErrorCategory as q}from"@vkontakte/videoplayer-shared/es2015";var dn=e=>t=>(t.client_time??ln())+e>=ln();class fn{constructor(e){t(this,`params`,void 0),t(this,`subscription`,void 0),t(this,`userSalt`,void 0),t(this,`unsaltedStorage`,[]),t(this,`lastVsid`,void 0),t(this,`isPaused`,!1),t(this,`firstFlush`,void 0),t(this,`debouncedFlush`,void 0),t(this,`flushRetryCount`,0),t(this,`retryFlushTimerId`,void 0),t(this,`debugLog`,void 0),t(this,`flushPromise`,null),t(this,`flushSnapshotLength`,0),t(this,`onlineListener`,void 0),t(this,`urgentEvents`,[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`]),t(this,`STORAGE_MAX_ATTEMPTS`,3),t(this,`isUrgent`,e=>on(this.urgentEvents,e.event_name)),this.params=e,this.userSalt=e.userSalt,this.debugLog=e.debugLogger.createComponentLog(`batch-queue:${e.storageKey}`),this.firstFlush=un(()=>this.safeFlush(),this.params.config.flushFirstTime,{maxWait:this.params.config.flushFirstTime});let n=K.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=un(()=>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()},G().addEventListener(`online`,this.onlineListener),this.housekeepStorage()}scheduleRetry(){this.retryFlushTimerId!==void 0&&G().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=G().setTimeout(()=>{this.retryFlushTimerId=void 0,this.safeFlush()},n)}cancelRetry(){this.retryFlushTimerId!==void 0&&(G().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=sn(this.flush(),()=>{this.flushPromise=null})}isStorageAvailable(){let e=K.isPersistent?.call(K)??!1;return e||this.debugLog({message:`Storage not available`}),e}readFromStorage(){if(!this.isStorageAvailable())return{};try{let e=K.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:q.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 K.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:q.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(),r=t[this.userSalt]??[];if(this.debugLog({message:`Adding item to storage for user ${this.userSalt}`}),this.writeToStorage(n(n({},t),{},{[this.userSalt]:[...r,e]})))return}catch(n){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:AddToStorageFailed`,category:q.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]??[],r=t.filter(dn(this.params.config.storageExpiration));if(this.debugLog({message:`Retrieved from storage for user ${this.userSalt}`}),r.length!==t.length){let i=t.length-r.length;this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:q.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=n({},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 t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),r=(t[this.userSalt]??[]).slice(e),i=n({},t);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){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:MarkStorageSentFailed`,category:q.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 cn(e)){let a=i.filter(dn(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:q.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:q.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:q.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=sn(this.flushInternal(e),()=>{this.flushPromise=null}),this.flushPromise)}flushInternal({wantBeacon:e,clearStorage:t}){var n=this;return r(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:q.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 r(function*(){e.debugLog({message:`Destroying queue`}),e.flushPromise&&(e.debugLog({message:`Waiting for ongoing flush to complete`}),yield e.flushPromise),e.cancelRetry(),e.onlineListener&&=(G().removeEventListener(`online`,e.onlineListener),void 0),e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel(),e.flushPromise=null,e.debugLog({message:`Queue destroyed`})})()}}class pn{constructor(e){t(this,`params`,void 0),t(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 fn({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:an.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 r(function*(){let n=yield rn(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 r(function*(){yield rn(e.queues.map(e=>e.destroy())),e.queues=[]})()}}function mn(){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 hn{constructor(e){t(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)}}}import{PlaybackState as gn}from"@vkontakte/videoplayer-core/es2015";import{Observable as _n,Subscription as vn,ValueSubject as yn,Subject as bn,fromEvent as xn,isNullable as Sn,map as Cn,merge as J,filter as wn,filterChanged as Tn,getWindow as En}from"@vkontakte/videoplayer-shared/es2015";var Dn=(e,t,n)=>new _n(r=>{let i=new vn,a,o=new yn(void 0),s;i.add(e.info.isLive$.pipe(Tn()).subscribe(t=>{s&&(s.unsubscribe(),o.next(void 0)),a=void 0,s=t?e.info.liveTime$.pipe(Cn(e=>e&&e/1e3)).subscribe(o):e.info.position$.subscribe(o),i.add(s)}));let{playing$:c,paused$:l,ended$:u,looped$:d}=e.events,f=e.events.willSeek$.pipe(wn(()=>e.info.playbackState$.getValue()===gn.PLAYING)),p=e.events.seeked$.pipe(wn(()=>e.info.playbackState$.getValue()===gn.PLAYING)),m=e.info.isStalled$.pipe(wn(e=>e)),h=!1,g=new bn;i.add(f.subscribe(()=>{h||g.next(),h=!0})).add(p.subscribe(()=>h=!1));let ee=J(xn(En(),`beforeunload`),e.events.willDestruct$),_=e=>{a=e},v=e=>{let t=a;if(a=void 0,!(Sn(t)||Sn(e)||!isFinite(t)||!isFinite(e))){if(Math.round(e*1e3)<=Math.round(t*1e3)){a=e;return}r.next({from:t,to:e})}},y=new bn,b=new bn,te=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():o.getValue()??0,x=J(c,p,y).pipe(Cn(()=>te())),ne=J(d,J(l,g,ee,u,b,m).pipe(Cn(()=>te()))),re=t.started$&&t.ended$?J(x,t.ended$):x,ie=t.started$&&t.ended$?J(ne,t.started$):ne;if(i.add(re.subscribe(_)).add(ie.subscribe(v)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{b.next(),y.next()};i.add(re.subscribe(()=>{let r=En().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(ie.subscribe(()=>{e.forEach(e=>{En().clearTimeout(e)}),e=[]}))}return i});import{Subscription as On}from"@vkontakte/videoplayer-core/es2015";import{Observable as kn,merge as An}from"@vkontakte/videoplayer-shared/es2015";var jn=(e,t)=>new kn(n=>{let r=new On;return r.add(An(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 Mn}from"@vkontakte/videoplayer-core/es2015";import{Observable as Nn,filter as Pn,getWindow as Fn}from"@vkontakte/videoplayer-shared/es2015";var In=(e,{maxTimeWindow:t})=>new Nn(n=>{let r=new Mn,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(Fn().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=Fn().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(Pn(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 Ln,Subscription as Rn,merge as zn}from"@vkontakte/videoplayer-shared/es2015";var Bn=e=>new Ln(t=>{let n=new Rn,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(zn(p,m).subscribe(l)).add(zn(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 Vn,Subscription as Hn,merge as Un}from"@vkontakte/videoplayer-shared/es2015";var Wn=(e,t)=>new Vn(n=>{let r=new Hn,i=0;return r.add(Un(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 Gn,isNullable as Kn}from"@vkontakte/videoplayer-shared/es2015";import{HttpConnectionType as qn,Surface as Y,VideoFormat as X,VideoQuality as Z}from"@vkontakte/videoplayer-core/es2015";var Jn=e=>{if(!Kn(e)){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}},Yn=e=>e&&{[qn.HTTP1]:`http1`,[qn.HTTP2]:`http2`,[qn.QUIC]:`http3`}[e],Xn=e=>{if(e!==void 0)switch(e){case X.MPEG:return`MP4`;case X.DASH:case X.DASH_LIVE:return`DASH`;case X.DASH_SEP:return`DASH_SEP`;case X.DASH_ONDEMAND:return`ONDEMAND_DASH`;case X.HLS_ONDEMAND:return`ONDEMAND_HLS`;case X.HLS:case X.HLS_LIVE:return`HLS`;case X.HLS_FMP4:return`HLS_FMP4`;case X.DASH_WEBM:case X.DASH_LIVE_WEBM:return`WEBM`;case X.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case X.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case X.WEB_RTC_LIVE:return`WEBRTC`;case X.DASH_WEBM_AV1:return`AV1`;case X.DASH_STREAMS:return`MULTI_DASH`;default:return Gn(e)}},Q=e=>{if(e!==void 0)switch(e){case Z.Q_144P:return`144p`;case Z.Q_240P:return`240p`;case Z.Q_360P:return`360p`;case Z.Q_480P:return`480p`;case Z.Q_720P:return`720p`;case Z.Q_1080P:return`1080p`;case Z.Q_1440P:return`1440p`;case Z.Q_2160P:return`2160p`;case Z.INVARIANT:case Z.Q_576P:case Z.Q_4320P:return`UNKNOWN`;default:return Gn(e)}},Zn=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 X.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 Y.NONE:return;case Y.INLINE:return`inline`;case Y.FULLSCREEN:return`fullscreen`;case Y.SECOND_SCREEN:return`chromecast`;case Y.PIP:return`pip_external`}},$n=e=>{switch(e){case void 0:return;case Y.INVISIBLE:return`background`;default:return`foreground`}},er=`_thin-one-stat_deviceId`,tr=`2.2.0`,nr=()=>{let e=new Mt;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class rr{constructor(e,n){t(this,`apis`,[]),t(this,`logger`,void 0),t(this,`config`,void 0),t(this,`subscription`,void 0),t(this,`lifecycleFlushSubscription`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`statContext`,void 0),t(this,`deviceId`,void 0),t(this,`targetDuration`,void 0),t(this,`debugLogger`,new Ct),t(this,`thinOneStatDebugLog`,this.debugLogger.createComponentLog(`ThinOneStat`)),t(this,`eventNumber`,1),t(this,`isStarted`,void 0),t(this,`isSeeking`,void 0),t(this,`inBufferStarvation`,void 0),t(this,`firstByteManifestSent`,void 0),t(this,`firstMediaRequestSent`,void 0),t(this,`firstByteMediaSent`,void 0),t(this,`wasPaused`,void 0),t(this,`isLive`,void 0),t(this,`lastContentType`,void 0),t(this,`cdnHostname`,void 0),t(this,`isEmbed`,void 0),t(this,`embedHostname`,void 0),t(this,`connectionType`,void 0),t(this,`connectionReused`,void 0),t(this,`player`,void 0),t(this,`playerSize`,{width:0,height:0}),t(this,`currentSubtitle`,void 0),t(this,`userQuality`,void 0),t(this,`downloadQuality`,void 0),t(this,`downloadSpeed`,void 0),t(this,`networkType`,void 0),t(this,`uiEvents`,void 0),t(this,`playerSubscription`,void 0),t(this,`uiSubscription`,void 0),t(this,`adsSubscription`,void 0),t(this,`seekAction$`,new Nt(`unknown`)),t(this,`vsid$`,new Nt(void 0)),t(this,`isid$`,new Nt(void 0)),t(this,`errors$`,new jt),t(this,`getTotalViewTime`,()=>0),this.statContext=e,this.config=Bt(n.config??{}),this.subscription=new Mt,this.config.synchronizeTime&&(this.timeSynchronisation=new hn),this.subscription.add(this.errors$.subscribe(e=>{this.thinOneStatDebugLog({message:`[${e.category}] ${e.id}: ${e.message}`})}));let r=kt.get(er);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=mn(),kt.set(er,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??Se());let i=new nn({errors$:this.errors$,config:this.config,timeSynchronisation:this.timeSynchronisation});this.config.apiForticom&&this.apis.push(new Yt({config:this.config,apiTransport:i,errors$:this.errors$,deviceId:this.deviceId,refreshAuthToken:n.refreshAuthToken})),this.config.apiUvRest&&(n.getUvRestAuthToken?this.apis.push(new Xt({config:this.config,apiTransport:i,errors$:this.errors$,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken})):this.errors$.next({id:`ThinOneStat:Init:MissingGetUvRestAuthToken`,category:R.WTF,message:`thinStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.logger=new pn({config:this.config,debugLogger:this.debugLogger,apis:this.apis,errors$:this.errors$,userSalt:n.userSalt});let{isEmbed:a,topOrigin:o}=xt();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){this.apis.forEach(t=>{t.authorize(e).catch(()=>{})})}reportError(e){let t={error_severity:e.severity,error_category:this.mapErrorCategory(e.category),player_error_code:e.code,player_error_trace:e.trace,error_message:e.message,content_type:this.getCurrentContentType()};this.logError(t),e.severity===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}updateContext(e){this.statContext=n(n({},this.statContext),e)}attachTo(e,t){this.playerSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to player, unsubscribing from previous`}),this.playerSubscription.unsubscribe());let r=new Mt,i=(e,t)=>r.add(e.subscribe(t));i(Bn(e),e=>{this.getTotalViewTime=e}),i(e.info.isLive$,e=>this.isLive=e),i(e.info.currentFormat$,e=>{let t=Xn(e);t&&(this.lastContentType=t)}),i(e.info.hostname$.pipe(L(e=>e!==void 0)),e=>{this.cdnHostname=e});let a;i(I({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L(({hostname:e})=>e!==void 0),L(({connectionType:e})=>e!==void 0),L(({connectionReused:e})=>e!==void 0)),({hostname:e,connectionType:t,connectionReused:n})=>{if(a!==void 0&&a!==e){let r={cdn_host:e,connection_type:Yn(t),connection_reused:n,content_type:this.getCurrentContentType()};this.logFailover(r),this.logTelemetry(this.collectTelemetryData())}this.cdnHostname=a=e}),i(e.info.httpConnectionType$,e=>{this.connectionType=Yn(e)}),i(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),i(Dn(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval,exactTime:this.config.watchCoverageExactTime}),t=>{let r={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:this.getCurrentContentType(),playback_quality:Q(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(r);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive(n(n({},r),{},{live:!!t}))}}),i(Wn(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),i(jn(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),i(e.events.willReady$,()=>{let t={isid:this.isid$.getValue(),stream_profile:Zn(this.getCurrentContentType()),dpi:Math.round(this.statContext.dpi??96*z.display.pixelRatio),web_layout:this.statContext.isMobile||z.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(I({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L(({connectionType:e})=>e!==void 0),L(({connectionReused:e})=>e!==void 0),Et()),()=>{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(I({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(Et()),()=>{if(this.firstByteManifestSent)return;this.firstByteManifestSent=!0;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$,()=>{if(this.firstMediaRequestSent)return;this.firstMediaRequestSent=!0;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$,()=>{if(this.firstByteMediaSent)return;this.firstByteMediaSent=!0;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(wt(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:$n(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.inBufferStarvation=!1,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.isSeeking=!1,this.inBufferStarvation=!1,this.logStop()}),i(wt(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()}),i(e.events.fetcherRecoverableError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:this.mapErrorSeverity(t),error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Jn(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.mapErrorSeverity(t)===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(e.events.managedError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:this.mapErrorSeverity(t),error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Jn(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.logTelemetry(this.collectTelemetryData())}),i(e.events.fatalError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:`critical`,error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Jn(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(I({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(L(({connectionReused:e})=>e!==void 0),L(({connectionMetrics:e})=>e!==void 0),Tt((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(In(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),i(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),i(e.events.willSeek$,()=>{this.isSeeking=!0;let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),i(e.events.seeked$,()=>{this.isSeeking=!1;let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),i(e.info.stallStartTime$,t=>{if(t<=0){this.inBufferStarvation=!1;return}this.inBufferStarvation||(this.inBufferStarvation=!0,this.logBufferStarvation({buffer_time:this.calcBufferTime(e.info.currentBuffer$.getValue())}),this.logTelemetry(this.collectTelemetryData()))}),i(e.info.currentBuffer$.pipe(L(e=>!!this.calcBufferTime(e)),Et()),e=>{let t=this.calcBufferTime(e);if(this.statContext.preload){let e={buffer_time:t};this.logPreloadEnded(e)}this.logReady({buffer_time:t})});let o;i(I({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(L(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),L(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(o!==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(o),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}o=r}});let s,c;return i(e.info.surface$,e=>{let t=Qn(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),c=$n(e),s!==c&&(this.isStarted&&this.logVisibilityChanged({visibility:c}),s=$n(e))}),i(I({muted:e.info.muted$,volume:e.info.volume$}).pipe(Ot(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(L(e=>e!==void 0),Dt(1)),e=>{let t={content_type:Xn(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),i(e.info.currentAudioStream$.pipe(L(e=>e!==void 0),Dt(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),i(e.info.currentVideoStream$.pipe(L(e=>e!==void 0),Dt(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.playerSubscription=r,this.resubscribeLifecycleFlush(),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:t,subscription:r}=nr();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=>{if(!e){this.inBufferStarvation=!1;return}this.isStarted&&(this.logShowLoader(),!(this.isSeeking||this.inBufferStarvation||!this.player)&&(this.inBufferStarvation=!0,this.logBufferStarvation({buffer_time:this.calcBufferTime(this.player.info.currentBuffer$.getValue())}),this.logTelemetry(this.collectTelemetryData())))}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle=n({},e),this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:i}=ft(this.uiEvents,t,this.player);return t(i,e=>{this.isStarted&&this.logModeChanged({mode:Qn(e)})}),t(e.actionQuality$,e=>{var t,n,r;let i=e=>yt(vt(Ft),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.resubscribeLifecycleFlush(),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}=nr();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.resubscribeLifecycleFlush(),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,this.firstByteManifestSent=!1,this.firstMediaRequestSent=!1,this.firstByteMediaSent=!1}destroy(){var e=this;return r(function*(){e.thinOneStatDebugLog({message:`Destroying ThinOneStat`}),e.subscription.unsubscribe(),e.lifecycleFlushSubscription?.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}mapErrorCategory(e){switch(e){case R.NETWORK:return`network`;case R.VIDEO_PIPELINE:return`video_pipeline`;case R.EXTERNAL_API:return`external_api`;case R.PARSER:return`parser`;case R.DOM:return`dom`;default:return`wtf`}}mapErrorSeverity(e){return R.FATAL===e?`critical`:`informative`}getCurrentContentType(){let e=Xn(this.player?.info.currentFormat$.getValue());if(e)return e;if(this.lastContentType)return this.lastContentType;let t=this.player?.info.availableSources$.getValue();if(!t)return;let n=Object.keys(t)[0];return Xn(n)}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=this.getCurrentContentType(),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 yt([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();bt(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||z.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:tr,browser:this.statContext.browser??z.browser.current,browser_version:this.statContext.browserVersion??String(z.browser.currentVersion),os:this.statContext.os??z.device.os.name,os_version:this.statContext.osVersion??z.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||z.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??z.device.details.vendor,device_model:this.statContext.deviceModel??z.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,r=!1){if(yt(this.config.disabledEvents,e))return;let i=this.createRequiredParams(e),a={};r&&(a=this.createRequiredFatParams()),this.logger.log(n(n(n({},i),a),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)}resubscribeLifecycleFlush(){this.lifecycleFlushSubscription?.unsubscribe();let e=At(),t=()=>{this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload}).catch(()=>{})},n=new Mt;n.add(St(e,`beforeunload`).subscribe(t)),n.add(St(e,`pagehide`).subscribe(t)),n.add(St(e.document,`visibilitychange`).subscribe(e=>{e.target?.visibilityState===`hidden`&&t()})),this.lifecycleFlushSubscription=n}}import{cancelIdleCallbackPolyfilled as ir}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as ar}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as or,Subscription as sr}from"@vkontakte/videoplayer-core/es2015";import{Logger as cr}from"@vkontakte/videoplayer-shared/es2015";class lr{constructor(){t(this,`startTime`,null),t(this,`stopTime`,null),t(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 ur=()=>window.Image?new Image:document.createElement(`img`);class dr{constructor(e){t(this,`params`,void 0),t(this,`position`,0),t(this,`started`,!1),t(this,`isActiveLive`,void 0),t(this,`heartbeatPixels`,[]),t(this,`heartbeatLastTimeSent`,{}),t(this,`heartbeatInterval`,void 0),t(this,`heartbeatFirstTimeoutId`,void 0),t(this,`idleCallbackIds`,[]),t(this,`log`,void 0),t(this,`stopwatch`,new lr),t(this,`subscription`,new sr),this.params=e,this.log=new cr().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=>ir(e)),this.send(`stop`)}onPlaybackState(e){e===or.PLAYING?this.started?this.play():this.start():e===or.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(ar(()=>ur().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,_t as ThinOneStat,h as SeekAction,f as Quality,gt as OneStat,dr as MediascopePixel,g as InteractiveInterfaceClick,p as ContentType,m as ConnectionType,d as ApiEnv};