@vkontakte/videoplayer-statistics 1.0.107-dev.eddfe39b7.0 → 1.0.107
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs +3 -3
- package/es2015.esm.js +3 -3
- package/esnext.cjs +3 -3
- package/esnext.esm.js +3 -3
- package/evergreen.esm.js +3 -3
- package/package.json +3 -3
- package/types/oneStat/Api.d.ts +32 -3
- package/types/oneStat/ApiTransport.d.ts +4 -0
- package/types/oneStat/Logger.d.ts +6 -9
- package/types/oneStat/OneStat.d.ts +3 -1
- package/types/oneStat/config.d.ts +2 -0
- package/types/thinOneStat/Api.d.ts +37 -5
- package/types/thinOneStat/ApiTransport.d.ts +14 -2
- package/types/thinOneStat/BatchQueue.d.ts +61 -0
- package/types/thinOneStat/Logger.d.ts +7 -29
- package/types/thinOneStat/ThinOneStat.d.ts +19 -11
- package/types/thinOneStat/config.d.ts +6 -1
- package/types/thinOneStat/utils/errors.d.ts +28 -0
- package/types/thinOneStat/values.d.ts +1 -1
package/es2015.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.107
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.107
|
|
3
|
+
* Thu, 21 May 2026 13:05:02 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-107/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`},_={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},v={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`};import{fillWithDefault as y}from"@vkontakte/videoplayer-shared/es2015";var b=`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:``},S={apiEnv:`vk_alias`,apiKey:b,apiBaseUrl:null,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},ee=e=>y(e,S);function te(){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 ne,combine as re,fromEvent as ie,isNonNullable as C,isNullable as ae,merge as oe,now as w,observableFrom as se,once as ce,safeStorage as le,Subject as ue,Subscription as de,ValueSubject as T}from"@vkontakte/videoplayer-shared/es2015";import{Logger as fe,detectEmbed as pe}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as me}from"@vkontakte/videoplayer-shared/es2015";var he=()=>me(Math.floor(Math.random()*2**32).toString(36),13,`0`),ge=()=>me(Math.floor(Math.random()*2**64).toString(36),13,`0`);class E{static getVSID(){return E.vsid}static generateVSID(e){return E.vsid=e?ge():he(),E.vsid}}e(E,`vsid`,void 0);import{promiseFinally as _e}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as ve}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as ye}from"@vkontakte/videoplayer-shared/es2015";var be=e=>{let{operation:n,custom:r}=e,i=ye(ve(r).map(([e,t])=>{let n=g[e]??e,r=t;return t&&(e===`mode`?r=v[t]??t:e===`quality`&&(r=_[t]??t)),[n,r]}));return t(t({},e),{},{operation:h[n]??n,custom:i})},D=`1.0.107-dev.eddfe39b7.0`;import{ValueSubject as xe,getExponentialDelay as Se,ErrorCategory as O}from"@vkontakte/videoplayer-shared/es2015";var Ce=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class we{constructor(t){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 xe(!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:O.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:O.EXTERNAL_API,message:`${r} error`,data:i});return}}});return function(t){return e.apply(this,arguments)}}();return o(e)})()}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return n(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=_e(e.params.refreshAuthToken(),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${D}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=window.navigator;n=Ce.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(be):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Se(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(()=>{_e(this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:O.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:D.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=_e(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>((!t||!t.session_key)&&e.params.error$.next({id:`AuthorizeFailed`,category:O.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:O.EXTERNAL_API,message:`authorize error`,data:t}):e.params.error$.next({id:`AuthorizeUnknown`,category:O.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})()}}import{fetchPolyfilled as Te}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ee}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as De}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as k,now as Oe}from"@vkontakte/videoplayer-shared/es2015";class ke{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??x[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 Te(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(!window.Blob||!window.navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=new window.Blob([r.toString()],{type:`application/x-www-form-urlencoded`});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}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,r){var i=this;return n(function*(){let n=Oe(),a=a=>{if(a instanceof TypeError&&Ee([`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:r,time:Oe()-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),Te(`${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=Oe()-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)})()}_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),De(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}import{arrayIncludes as Ae}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as je}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Me,now as Ne,safeStorage as A,debounceFn as Pe}from"@vkontakte/videoplayer-shared/es2015";var j=`onestat_events`,Fe=e=>t=>t.timestamp+e>=Ne();class Ie{constructor(t){e(this,`params`,void 0),e(this,`api`,void 0),e(this,`error$`,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,`loggerDebugLog`,void 0),e(this,`isUrgent`,e=>{let{operation:t}=e;return Ae([`action_play`,`watch_coverage_record`,`watch_coverage_live`],t)}),this.params=t,this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.loggerDebugLog=t.debugLogger.createComponentLog(`stat logger`),this.firstFlush=Pe(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let n=A.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Pe(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:n}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:Me.WTF,message:e?String(e):`Unknown logger error`,thrown:e})}}readFromStorage(){let e=A.get(j);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let n=this.readFromStorage(),r=(n[this.userSalt]??[]).filter(Fe(this.params.config.storageExpiration));A.set(j,JSON.stringify(t(t({},n),{},{[this.userSalt]:[...r,e]})))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(Fe(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],A.set(j,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of je(e)){let r=n.filter(Fe(this.params.config.storageExpiration));r.length?e[t]=r:delete e[t],this.loggerDebugLog({message:`${n.length} retrieved from storage, ${r.length} of them actual`})}A.set(j,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid===e.custom.vsid?this.debouncedFlush():this.firstFlush(),this.lastVsid=e.custom.vsid)}flush({wantBeacon:e,clearStorage:t}={wantBeacon:!1,clearStorage:!0}){let n=this.getFromStorage();n.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${n.length} events through beacon`}),this.api.logBeacon(n)):(this.loggerDebugLog({message:`Flushing ${n.length} events`}),this.api.logRequest(n)),t&&this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}import{HttpConnectionType as Le,Surface as M,VideoFormat as N,VideoQuality as P}from"@vkontakte/videoplayer-core/es2015";import{assertNever as Re}from"@vkontakte/videoplayer-shared/es2015";var ze=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],Be=e=>e&&{[Le.HTTP1]:`http1`,[Le.HTTP2]:`http2`,[Le.QUIC]:`http3`}[e],Ve=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 Re(e)}},He=(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 Re(e)}},Ue=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class We{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 Ge}from"@vkontakte/videoplayer-core/es2015";import{filter as Ke,filterChanged as qe,fromEvent as Je,isNullable as Ye,map as Xe,merge as F,Observable as Ze,Subject as Qe,Subscription as $e,ValueSubject as et}from"@vkontakte/videoplayer-shared/es2015";var tt=(e,t)=>new Ze(n=>{let r=new $e,i=F(Je(window,`beforeunload`),e.events.willDestruct$),a=new et(void 0),o;r.add(e.info.isLive$.pipe(qe()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(Xe(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(Ke(()=>e.info.playbackState$.getValue()===Ge.PLAYING)),d=e.events.seeked$.pipe(Ke(()=>e.info.playbackState$.getValue()===Ge.PLAYING)),f=!1,p=new Qe;r.add(u.subscribe(()=>{f||p.next(),f=!0})),r.add(d.subscribe(()=>f=!1));let m=new Qe,h=new Qe,g=()=>t.watchCoverageExactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,_=F(s,d,m).pipe(Xe(()=>g())),v=F(l,F(c,p,i,h).pipe(Xe(()=>g()))),y,b=e=>{y=e},x=e=>{let t=e;Ye(y)||y===t||Ye(t)||(n.next({from:y,to:t}),y=void 0)},S=()=>{h.next(),m.next()};if(r.add(_.subscribe(b)),r.add(v.subscribe(x)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(_.subscribe(()=>{n(),e=window.setTimeout(S,t.forceInterval)})),r.add(v.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(_.subscribe(()=>e=window.setTimeout(S,t.forceInterval))),r.add(v.subscribe(()=>window.clearTimeout(e)))}return r});import{Surface as I}from"@vkontakte/videoplayer-core/es2015";import{debounce as nt,filterChanged as rt,Subject as it}from"@vkontakte/videoplayer-shared/es2015";var at=(e,t,n)=>{let r=new it,i=r.pipe(nt(0),rt()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?I.PIP:o?I.FULLSCREEN:s?I.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?I.FULLSCREEN:a?I.PIP:s?I.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case I.SECOND_SCREEN:case I.NONE:case I.INLINE:!o&&!a&&(e===I.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},ot=`_one-stat_deviceId`,st=()=>{let e=new de;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class ct{get vsid$(){return new T(E.getVSID())}constructor(t,n){e(this,`api`,void 0),e(this,`logger`,void 0),e(this,`config`,void 0),e(this,`subscription`,new de),e(this,`beforeunloadSubscription`,void 0),e(this,`timeSynchronisation`,void 0),e(this,`debugLogger`,new fe),e(this,`oneStatDebugLog`,this.debugLogger.createComponentLog(`onestat`)),e(this,`loopCounter`,0),e(this,`disabled`,!1),e(this,`experimental`,void 0),e(this,`isid$`,new T(void 0)),e(this,`zenUid$`,new T(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 T(`unknown`)),e(this,`deviceId`,void 0),this.statContext=t,this.config=ee(n.config??{}),C(n.apiEnv)&&(this.config.apiEnv=n.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new We);let r=new ue;this.experimental={error$:r};let i=le.get(ot);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=te(),le.set(ot,this.deviceId)),this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??ge()),this.zenUid$.next(n.zenUid);let a=new ke({config:this.config,error$:r,timeSynchronisation:this.timeSynchronisation});this.api=new we({config:this.config,apiTransport:a,refreshAuthToken:n.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:r,vktvVersion:n.vktvVersion}),this.logger=new Ie({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:r,userSalt:n.userSalt});let{isEmbed:o,topOrigin:s}=pe();this.isEmbed=o,this.embedParent=s?new URL(s).hostname:void 0,this.subscribe()}updateContext(e){this.statContext=t(t({},this.statContext),e)}attachTo(e){let t=new de,n=(e,n)=>t.add(e.subscribe(n));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.seeked$,()=>{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(tt(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)});let r;n(e.info.isStalled$,e=>{e?r=w():(C(r)&&this.logEmptyBuffer({duration:w()-r}),r=void 0)});let i=!1;t.add(e.events.fatalError$.pipe(ce()).subscribe(()=>i=!0)),n(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let e=C(r)?w()-r:void 0;this.logCloseAtEmptyBuffer({duration:e??0}),r=void 0}else i||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})});let a,o,s=!1;n(e.events.firstBytes$,e=>{a=w(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>o=w()),n(e.info.currentBuffer$,e=>{!s&&e&&e.end-e.start>0&&C(a)&&(this.logPlayerReady({duration:w()-a}),s=!0)}),n(e.events.firstFrame$,()=>{C(a)&&!s&&(this.logPlayerReady({duration:w()-a}),s=!0),C(o)&&this.logFirstFrame({time:w()-o})});let c;n(e.info.currentVideoStream$,e=>{e&&(c&&e.id!==c&&this.logTrackSwitch(e),c=e.id)});let l;n(e.info.currentAudioStream$,e=>{e&&(l&&e.id!==l&&this.logTrackSwitch(e),l=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(re({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=ze(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:Ve(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let u;return n(e.info.hostname$,e=>{let t=u!==void 0&&u!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),u=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Be(e)}),this.updateContext({connectionType:Be(e)})}),n(e.info.httpConnectionReused$,e=>{ae(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:He(e,this.statContext.isPreviewPlayerView)})}),n(re({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}=st();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}=at(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:He(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}=st();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}=st();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 this.api.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.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:`VSID reset`}),E.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)})}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=window.navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(oe(ie(e,`change`),se([`init`])).subscribe(()=>this.updateContext({network:Ue(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=ie(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))})}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()??w(),o=this.vsid$.getValue();ne(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||ae(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,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 lt={};o(lt,{VERSION:()=>D,ThinOneStat:()=>Rn,ActionSeekType:()=>Ot});import{objectValues as ut}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as dt}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as ft,detectEmbed as pt,fromEvent as mt,Logger as ht,merge as gt,combine as L,filter as R,filterChanged as _t,once as vt,skip as yt,debounce as bt,safeStorage as xt,getWindow as St,Subject as Ct,Subscription as wt,ValueSubject as Tt,ErrorCategory as z}from"@vkontakte/videoplayer-shared/es2015";import{clientChecker as B}from"@vkontakte/videoplayer-core/es2015";import{fillWithDefault as Et}from"@vkontakte/videoplayer-shared/es2015";var Dt;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(Dt||={});var Ot;(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`})(Ot||={});var kt=`CIOPGQJGDIHBABABA`,At={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:``},jt={apiKey:kt,apiEnv:`okcdn`,apiBaseUrl:null,requestRetryCount:3,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*60*1e3,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchCoverageHeartbeatInterval:3e4,watchCoverageExactTime:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},Mt=e=>Et(e,jt);import{arrayIncludes as Nt}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Pt}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as V,ValueSubject as Ft}from"@vkontakte/videoplayer-shared/es2015";class It{constructor(t){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),this.params=t,this.authorized$=new Ft(!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.error$.next({id:`ThinOneStat:Api:LogRequestNoSession`,category:V.NETWORK,message:`No session key available for log request`});return}yield t.params.apiTransport.sendRequest(n,r,e,i)}catch(i){yield t.handleLogRequestError(i,n,r),yield t.retryLogRequestAfterSessionRecovery(e,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=i.getErrorCode(e);if(n===void 0){i.params.error$.next({id:`ThinOneStat:Api:LogRequestUnknown`,category:V.NETWORK,message:`Unknown ${t} error`,thrown:e,data:{params:r}});return}if(i.isSessionExpiredError(n)){i.params.error$.next({id:`ThinOneStat:Api:LogRequestSessionError#${n}`,category:V.EXTERNAL_API,message:`Session error: ${n}`,data:{error:e,code:n}}),i.authorized$.next(!1),i.sessionKey=void 0,yield i.doAuthorize();return}if(n===401){i.params.error$.next({id:`ThinOneStat:Api:LogRequestAuthLogin#${n}`,category:V.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();return}i.params.error$.next({id:`ThinOneStat:Api:LogRequest#${n}`,category:V.EXTERNAL_API,message:`${t} error`,data:{error:e,code:n,params:r}})})()}retryLogRequestAfterSessionRecovery(e,t,r){var i=this;return n(function*(){let e=i.sessionKey;if(!e){i.params.error$?.next({id:`ThinOneStat:Api:LogRequestRetryFailed`,category:V.NETWORK,message:`Cannot retry log request: no session key after recovery`});return}try{yield i.params.apiTransport.sendRequest(t,r,e)}catch(e){let t=i.getErrorCode(e);i.params.error$?.next({id:`ThinOneStat:Api:LogRequestRetryFailed#${t??`unknown`}`,category:V.EXTERNAL_API,message:`Log request failed after session recovery`,thrown:e,data:{originalError:e,retryCode:t}})}})()}getErrorCode(e){if(e&&typeof e==`object`&&`error_code`in e)return e.error_code}isSessionExpiredError(e){return!!e&&Nt([102,103,104],e)}doAuthorize(){var e=this;return n(function*(){if(e.authorizePromise)return e.authorizePromise;e.sessionKey=void 0,e.authorized$.next(!1);let t=e.buildAuthParams();return e.authorizePromise=Pt(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>{if(!t?.session_key){e.params.error$?.next({id:`ThinOneStat:Api:AuthorizeFailed`,category:V.EXTERNAL_API,message:`No session key in response`,data:t});return}return e.sessionKey=t.session_key,e.sessionKey}).catch(function(){var t=n(function*(t){let n=e.getErrorCode(t);if(n===401&&e.params.refreshAuthToken)return e.params.error$?.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:V.EXTERNAL_API,message:`Auth token expired during authorization`,data:{error:t,code:n}}),e.authToken=yield e.refreshAuthToken(),e.authorizePromise=void 0,e.doAuthorize();n?e.params.error$?.next({id:`ThinOneStat:Api:Authorize#${n}`,category:V.EXTERNAL_API,message:`Authorize error`,data:{error:t,code:n}}):e.params.error$?.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:V.NETWORK,message:`Authorize error`,thrown:t})});return function(e){return t.apply(this,arguments)}}()),()=>{e.authorizePromise=void 0,e.authorized$.next(e.sessionKey!==void 0)}),e.authorizePromise})()}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 D}refreshAuthToken(){var e=this;return n(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Pt(e.params.refreshAuthToken().catch(t=>{throw e.params.error$?.next({id:`ThinOneStat:Api:RefreshAuthTokenFailed`,category:V.NETWORK,message:`Failed to refresh auth token`,thrown:t}),t}),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){return{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${this.getClientVersion()}`,platform:e[0].platform,product:e[0].product,events:e})}}destroy(){this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0}}import{AbortControllerPolyfilled as Lt}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as Rt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as H}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as zt}from"@vkontakte/videoplayer-shared/es2015";import{now as U,getWindow as W,getExponentialDelay as Bt,isAbortError as Vt,ErrorCategory as Ht}from"@vkontakte/videoplayer-shared/es2015";class Ut{constructor(t){e(this,`params`,void 0),e(this,`apiKey`,void 0),e(this,`apiBaseUrl`,void 0),e(this,`apiEnv`,void 0),e(this,`isApiBaseUrlFetched`,void 0),e(this,`timeSynchronisation`,void 0),e(this,`fetchTimeout`,3e4),e(this,`retryConfig`,void 0),this.params=t,this.apiKey=t.config.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=t.config.apiBaseUrl??At[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1,this.retryConfig={maxAttempts:t.config.requestRetryCount??3,baseDelay:1e3,maxDelay:1e4,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(!window.Blob||!window.navigator.sendBeacon)return!1;let r=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=new window.Blob([r.toString()],{type:`application/x-www-form-urlencoded`});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:`ThinOneStat:ApiTransport:sendBeacon`,category:Ht.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){var o=this;return n(function*(){let n=U();try{return yield o.executeRequest(e,t,r,i,n,a)}catch(s){if(o.shouldRetry(s,a)){let n=Bt(a,{start:o.retryConfig.baseDelay,max:o.retryConfig.maxDelay,factor:2,random:.2});return o.logRetryAttempt(e,a,s,n),yield o.sleep(n),o.sendRequestWithRetry(e,t,r,i,a+1)}throw o.handleFinalError(e,t,r,n,s,a),s}})()}executeRequest(e,r,i,a,o,s){var c=this;return n(function*(){let n=o??U();c.apiBaseUrl=yield c.resolveApiBaseUrl();try{let o=yield c.fetchWithTimeout(`${c.apiBaseUrl}/fb.do`,{method:`post`,headers:t({"Content-type":`application/x-www-form-urlencoded`},a),body:c.prepareQueryParams({method:e,queryParams:r,sessionKey:i})});return yield c.processResponse(o,n)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:s,url:`${c.apiBaseUrl}/fb.do`}),t}})()}fetchWithTimeout(e,r){return n(function*(e,n,r=this.fetchTimeout){let i=new Lt,a=W().setTimeout(()=>i.abort(),r);try{let r=yield Rt(e,t(t({},n),{},{signal:i.signal}));return W().clearTimeout(a),r}catch(e){if(W().clearTimeout(a),Vt(e)){let e=Error(`Request timeout`);throw e.isTimeout=!0,e}throw e}}).apply(this,arguments)}processResponse(e,t){var r=this;return n(function*(){if(!e.ok){let t=Error(`HTTP ${e.status}: ${e.statusText}`);throw t.status=e.status,t.statusText=e.statusText,t.response=e,t}let n=new Date(e.headers.get(`date`)??``).getTime(),i=U()-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){let e=Error(o.error_msg);throw e.errorData=o,e}return o})()}shouldRetry(e,t){if(t>=this.retryConfig.maxAttempts)return!1;if(e instanceof Error&&e.isTimeout)return!0;if(e instanceof Error&&e.status){let t=e.status;if(H(this.retryConfig.retryableStatuses,t))return!0}return!!(e instanceof Error&&(H(this.retryConfig.retryableErrors,e.message)||H(e.message,`network`)||H(e.message,`timeout`)||H(e.message,`connection`)))}logRetryAttempt(e,t,n,r){let i=n instanceof Error?n.message:String(n);this.params.error$?.next({id:`ThinOneStat:ApiTransport:retry`,category:Ht.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=Ht.NETWORK;this.params.error$?.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:U()-r,maxAttempts:this.retryConfig.maxAttempts,attempts:a}})}sleep(e){return new Promise(t=>W().setTimeout(t,e))}resolveApiBaseUrl(){var e=this;return n(function*(){if(e.apiEnv!==`auto`||e.isApiBaseUrlFetched)return e.apiBaseUrl;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 i}catch(t){return e.params.error$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:Ht.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),At.vk_alias}finally{e.isApiBaseUrlFetched=!0}})()}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}}import{arrayIncludes as Wt}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Gt}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Kt}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as G,now as qt,safeStorage as K,debounceFn as Jt}from"@vkontakte/videoplayer-shared/es2015";var Yt=`thinonestat_events`,Xt=e=>t=>(t.client_time??qt())+e>=qt();class Zt{constructor(t){e(this,`params`,void 0),e(this,`api`,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,`loggerDebugLog`,void 0),e(this,`flushPromise`,null),e(this,`urgentEvents`,[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`]),e(this,`STORAGE_MAX_ATTEMPTS`,3),e(this,`isUrgent`,e=>Wt(this.urgentEvents,e.event_name)),this.params=t,this.api=t.api,this.userSalt=t.userSalt,this.loggerDebugLog=t.debugLogger.createComponentLog(`stat logger`),this.firstFlush=Jt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let n=K.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Jt(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:n}),this.subscription=this.api.authorized$.subscribe(e=>{e&&(this.loggerDebugLog({message:`Authorized, triggering flush`}),this.debouncedFlush())}),this.housekeepStorage()}safeFlush(){if(this.flushPromise){this.loggerDebugLog({message:`Flush already in progress, skipping`});return}this.flushPromise=Gt(this.flush(),()=>{this.flushPromise=null})}isStorageAvailable(){let e=K.isPersistent?.call(K)??!1;return e||this.loggerDebugLog({message:`Storage not available`}),e}readFromStorage(){if(!this.isStorageAvailable())return{};try{let e=K.get(Yt),t=e?JSON.parse(e):{};return this.loggerDebugLog({message:`Read ${Object.keys(t).length} users from storage`}),t}catch(e){return this.params.error$.next({id:`ThinOneStat:Logger:ReadStorageError`,category:G.WTF,message:`Failed to read from storage`,thrown:e}),this.loggerDebugLog({message:`Failed to read from storage`}),{}}}writeToStorage(e){if(!this.isStorageAvailable())return!1;try{return K.set(Yt,JSON.stringify(e)),this.loggerDebugLog({message:`Written ${Object.keys(e).length} users to storage`}),!0}catch(e){return this.params.error$.next({id:`ThinOneStat:Logger:WriteStorageError`,category:G.WTF,message:`Failed to write to storage`,thrown:e}),this.loggerDebugLog({message:`Failed to write to storage`}),!1}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e),this.loggerDebugLog({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]??[]).filter(Xt(this.params.config.storageExpiration));if(this.loggerDebugLog({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.error$.next({id:`ThinOneStat:Logger:AddToStorageFailed`,category:G.WTF,message:`Failed to add item to storage after retries`,thrown:t,data:{item:e,attempt:n}}),this.loggerDebugLog({message:`Failed to add item to storage after retries`}))}}getFromStorage(){if(!this.userSalt)return this.loggerDebugLog({message:`Retrieved ${this.unsaltedStorage.length} items from unsalted storage`}),this.unsaltedStorage;let e=this.readFromStorage(),n=e[this.userSalt]??[],r=n.filter(Xt(this.params.config.storageExpiration));if(this.loggerDebugLog({message:`Retrieved from storage for user ${this.userSalt}`}),r.length!==n.length){this.loggerDebugLog({message:`Cleaning ${n.length-r.length} expired items from storage`});let i=t({},e);r.length?i[this.userSalt]=r:delete i[this.userSalt],this.writeToStorage(i)}return r}markStorageSent(){if(!this.userSalt){let e=this.unsaltedStorage.length;this.unsaltedStorage=[],this.loggerDebugLog({message:`Cleared unsalted storage, removed ${e} items`});return}for(let e=0;e<this.STORAGE_MAX_ATTEMPTS;e++)try{let e=this.readFromStorage(),t=e[this.userSalt]?.length??0;if(delete e[this.userSalt],this.writeToStorage(e)){this.loggerDebugLog({message:`Marked storage as sent for user ${this.userSalt}, removed ${t} items`});return}}catch(t){e===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.error$.next({id:`ThinOneStat:Logger:MarkStorageSentFailed`,category:G.WTF,message:`Failed to mark storage as sent after retries`,thrown:t}),this.loggerDebugLog({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 Kt(e)){let a=i.filter(Xt(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.loggerDebugLog({message:`${i.length} retrieved from storage, ${a.length} of them actual for ${r}`})}t?(this.loggerDebugLog({message:`Housekeeping completed, removed ${n} expired items total`}),this.writeToStorage(e)):this.loggerDebugLog({message:`Housekeeping completed, no changes needed`})}catch(e){this.params.error$.next({id:`ThinOneStat:Logger:HousekeepStorageError`,category:G.WTF,message:`Failed to housekeep storage`,thrown:e}),this.loggerDebugLog({message:`Failed to housekeep storage`})}}log(e){try{if(this.loggerDebugLog({message:`Logging item: ${e.event_name}`}),this.addToStorage(e),this.isPaused){this.loggerDebugLog({message:`Logger paused, skipping flush`});return}this.isUrgent(e)?(this.loggerDebugLog({message:`Urgent item, flushing immediately`}),this.safeFlush()):this.lastVsid===e.vsid?(this.loggerDebugLog({message:`Same VSID, scheduling debounced flush`}),this.debouncedFlush()):(this.loggerDebugLog({message:`VSID changed, triggering first flush`}),this.firstFlush()),this.lastVsid=e.vsid}catch(t){this.params.error$.next({id:`ThinOneStat:Logger:LogError`,category:G.WTF,message:`Failed to log item`,thrown:t,data:{item:e}}),this.loggerDebugLog({message:`Failed to log item`})}}flush(){var e=this;return n(function*({wantBeacon:t,clearStorage:n}={wantBeacon:!1,clearStorage:!0}){if(e.flushPromise)return e.loggerDebugLog({message:`Flush already in progress, waiting`}),e.flushPromise;e.loggerDebugLog({message:`Starting flush`});try{let r=e.getFromStorage();if(r.length===0){e.loggerDebugLog({message:`No items to flush`});return}let i=e.api.authorized$.getValue();if(e.loggerDebugLog({message:`Authorization status: ${i}`}),!i){e.loggerDebugLog({message:`Not authorized, triggering authorization`}),e.api.authorize().catch(t=>{e.params.error$.next({id:`ThinOneStat:Logger:AuthorizeOnFlushError`,category:G.NETWORK,message:`Failed to authorize during flush`,thrown:t}),e.loggerDebugLog({message:`Authorization failed during flush`})});return}if(t&&e.params.config.useBeacon)e.loggerDebugLog({message:`Flushing ${r.length} events through beacon`}),e.api.logBeacon(r),n&&e.markStorageSent();else{e.loggerDebugLog({message:`Flushing ${r.length} events`});try{yield e.api.logRequest(r),e.loggerDebugLog({message:`Flush completed successfully`}),n&&e.markStorageSent()}catch(t){throw e.params.error$.next({id:`ThinOneStat:Logger:FlushRequestError`,category:G.NETWORK,message:`Failed to send events, will retry later`,thrown:t,data:{itemsCount:r.length}}),e.loggerDebugLog({message:`Flush failed, will retry later`}),t}}}finally{e.loggerDebugLog({message:`Cancelling scheduled flushes`}),e.firstFlush.cancel(),e.debouncedFlush.cancel()}}).apply(this,arguments)}pause(){this.loggerDebugLog({message:`Logger paused`}),this.isPaused=!0,this.debouncedFlush.cancel(),this.firstFlush.cancel()}resume(){this.loggerDebugLog({message:`Logger resumed`}),this.isPaused=!1,this.debouncedFlush()}destroy(){var e=this;return n(function*(){e.loggerDebugLog({message:`Destroying logger`}),e.flushPromise&&(e.loggerDebugLog({message:`Waiting for ongoing flush to complete`}),yield e.flushPromise),e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel(),e.flushPromise=null,e.loggerDebugLog({message:`Logger destroyed`})})()}}function Qt(){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 $t{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 en}from"@vkontakte/videoplayer-core/es2015";import{Observable as tn,Subscription as nn,ValueSubject as rn,Subject as an,fromEvent as on,isNullable as sn,map as cn,merge as q,filter as ln,filterChanged as un,getWindow as dn}from"@vkontakte/videoplayer-shared/es2015";var fn=(e,t,n)=>new tn(r=>{let i=new nn,a=new rn(void 0),o;i.add(e.info.isLive$.pipe(un()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(cn(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(ln(()=>e.info.playbackState$.getValue()===en.PLAYING)),f=e.events.seeked$.pipe(ln(()=>e.info.playbackState$.getValue()===en.PLAYING)),p=!1,m=new an;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=q(on(dn(),`beforeunload`),e.events.willDestruct$),g,_=e=>{g=e},v=e=>{let t=e;sn(g)||sn(t)||g===t||(r.next({from:g,to:t}),g=void 0)},y=new an,b=new an,x=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,S=q(s,f,y).pipe(cn(()=>x())),ee=q(u,q(c,m,h,l,b).pipe(cn(()=>x()))),te=t.started$&&t.ended$?q(S,t.ended$):S,ne=t.started$&&t.ended$?q(ee,t.started$):ee;if(i.add(te.subscribe(_)).add(ne.subscribe(v)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{b.next(),y.next()};i.add(te.subscribe(()=>{let r=dn().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(ne.subscribe(()=>{e.forEach(e=>{dn().clearTimeout(e)}),e=[]}))}return i});import{Subscription as pn}from"@vkontakte/videoplayer-core/es2015";import{Observable as mn,merge as hn}from"@vkontakte/videoplayer-shared/es2015";var gn=(e,t)=>new mn(n=>{let r=new pn;return r.add(hn(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 _n}from"@vkontakte/videoplayer-core/es2015";import{Observable as vn,filter as yn,getWindow as bn}from"@vkontakte/videoplayer-shared/es2015";var xn=(e,{maxTimeWindow:t})=>new vn(n=>{let r=new _n,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(bn().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=bn().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(yn(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 Sn,Subscription as Cn,merge as wn}from"@vkontakte/videoplayer-shared/es2015";var Tn=e=>new Sn(t=>{let n=new Cn,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$:_,willDestruct$:v}=e.events,{currentPlaybackRate$:y}=e.info;return n.add(g.subscribe(d)).add(wn(p,m).subscribe(l)).add(wn(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),e}),n});import{Observable as En,Subscription as Dn,merge as On}from"@vkontakte/videoplayer-shared/es2015";var kn=(e,t)=>new En(n=>{let r=new Dn,i=0;return r.add(On(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 An}from"@vkontakte/videoplayer-shared/es2015";import{HttpConnectionType as jn,Surface as J,VideoFormat as Y,VideoQuality as X}from"@vkontakte/videoplayer-core/es2015";var Mn=e=>e&&{[jn.HTTP1]:`http1`,[jn.HTTP2]:`http2`,[jn.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 An(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 An(e)}},Nn=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}},Pn=(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`}},Fn=e=>{switch(e){case void 0:return;case J.INVISIBLE:return`background`;default:return`foreground`}},In=`_thin-one-stat_deviceId`,Ln=()=>{let e=new wt;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Rn{get vsid$(){return new Tt(E.getVSID())}constructor(t,n){e(this,`api`,void 0),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 ht),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,`position`,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,`seekAction$`,new Tt(`unknown`)),e(this,`isid$`,new Tt(void 0)),e(this,`getTotalViewTime`,()=>0),this.statContext=t,this.config=Mt(n.config??{}),this.subscription=new wt,this.config.synchronizeTime&&(this.timeSynchronisation=new $t);let r=new Ct,i=xt.get(In);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=Qt(),xt.set(In,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??ge());let a=new Ut({error$:r,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new It({config:this.config,apiTransport:a,error$:r,deviceId:this.deviceId,refreshAuthToken:n.refreshAuthToken}),this.logger=new Zt({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:r,userSalt:n.userSalt});let{isEmbed:o,topOrigin:s}=pt();this.isEmbed=o,this.embedHostname=s?new URL(s).hostname:void 0}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext=t(t({},this.statContext),e)}attachTo(e,n){let r=new wt,i=(e,t)=>r.add(e.subscribe(t));i(Tn(e),e=>{this.getTotalViewTime=e}),i(e.info.isLive$,e=>this.isLive=e),i(e.info.hostname$.pipe(R(e=>e!==void 0)),e=>{this.cdnHostname=e});let a;i(L({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(R(({hostname:e})=>e!==void 0),R(({connectionType:e})=>e!==void 0),R(({connectionReused:e})=>e!==void 0)),({hostname:t,connectionType:n,connectionReused:r})=>{if(a!==void 0&&a!==t){let i={cdn_host:t,connection_type:Mn(n),connection_reused:r,content_type:Z(e.info.currentFormat$.getValue())};this.logFailover(i)}this.cdnHostname=a=t}),i(e.info.httpConnectionType$,e=>{this.connectionType=Mn(e)}),i(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),i(fn(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(kn(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),i(gn(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),i(e.events.willReady$,()=>{if(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(L({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(R(({connectionType:e})=>e!==void 0),R(({connectionReused:e})=>e!==void 0),vt()),()=>{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(L({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(R(({connectionType:e})=>e!==void 0),R(({connectionReused:e})=>e!==void 0),vt()),()=>{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.firstBytesReceived$,()=>{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(gt(e.events.willStart$,e.events.looped$),t=>{t&&this.resetViewSession();let n={isid:this.isid$.getValue(),stream_profile:Nn(Z(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*B.display.pixelRatio,web_layout:this.statContext.isMobile||B.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(n.iframe_host=this.embedHostname??`unknown`),this.logStartSession(n)}),i(e.events.started$,()=>{this.isStarted=!0;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:this.statContext.playerSize?.width??this.playerSize.width,player_height:this.statContext.playerSize?.height??this.playerSize.height,muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:Pn(o,this.statContext.isPreviewPlayerView),visibility:Fn(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,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d)}),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.willStop$,()=>{this.isStarted=!1,this.logStop()}),i(gt(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let o=e=>{switch(e){case z.NETWORK:return`network`;case z.VIDEO_PIPELINE:return`video_pipeline`;case z.EXTERNAL_API:return`external_api`;case z.PARSER:return`parser`;case z.DOM:return`dom`;default:return`wtf`}},s=e=>z.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()}),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)}),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()}),i(L({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(R(({connectionReused:e})=>e!==void 0),R(({connectionMetrics:e})=>e!==void 0),_t((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={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:t?.dnsResolveTime,tcp_handshake_time:t?.tcpHandshakeTime,tls_handshake_time:t?.tlsHandshakeTime};this.logConnectionEstablished(o)}),i(xn(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})}),i(e.info.currentBuffer$.pipe(R(e=>!!this.calcBufferTime(e)),vt()),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(L({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(R(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),R(({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=Pn(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),u=Fn(e),l!==u&&(this.isStarted&&this.logVisibilityChanged({visibility:u}),l=Fn(e))}),i(L({muted:e.info.muted$,volume:e.info.volume$}).pipe(bt(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(R(e=>e!==void 0),yt(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(R(e=>e!==void 0),yt(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),i(e.info.currentVideoStream$.pipe(R(e=>e!==void 0),yt(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToUi(e){this.uiEvents=e;let{subscribe:n,subscription:r}=Ln();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:e,player_height: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}=at(this.uiEvents,n,this.player);return n(i,e=>{this.isStarted&&this.logModeChanged({mode:Pn(e)})}),n(e.actionQuality$,e=>{var t,n,r;let i=e=>dt(ut(Dt),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.resubscribeBeforeunload(),this.subscription.add(r),r}attachToAds(e){let{subscription:t,subscribe:n}=Ln();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.resubscribeBeforeunload(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),E.generateVSID(this.config.useVsid64),this.eventNumber=0}destroy(){this.api.destroy()}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,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}isValidPlatform(e=``){return dt([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();ft(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:${D}`,platform:this.isValidPlatform(this.statContext.platform)?this.statContext.platform:`web:${this.statContext.isMobile||B.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:`2.1.3`,browser:this.statContext.browser??B.browser.current,browser_version:this.statContext.browserVersion??String(B.browser.currentVersion),os:this.statContext.os??B.device.os.name,os_version:this.statContext.osVersion??B.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||B.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??B.device.details.vendor,device_model:this.statContext.deviceModel??B.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(dt(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)}logStop(){this.log(`stop`)}logBufferStarvation(e){this.log(`buffer_starvation`,e)}logShowLoader(){this.log(`show_loader`)}logQualityChangeRequested(e){this.log(`quality_change_requested`,e)}logQualityChanged(e){this.log(`quality_changed`,e)}logCdnHostChanged(e){this.log(`cdn_host_changed`,e)}logViewPortChanged(e){this.log(`view_port_changed`,e)}logModeChanged(e){this.log(`mode_changed`,e)}logVisibilityChanged(e){this.log(`visibility_changed`,e)}logAudioTrackSwitched(e){this.log(`audio_track_switched`,e)}logVideoTrackSwitched(e){this.log(`video_track_switched`,e)}logSubtitlesSwitched(e){this.log(`subtitles_switched`,e)}logSoundChanged(e){this.log(`sound_changed`,e)}logFailover(e){this.log(`failover`,e)}logContentTypeChange(e){this.log(`content_type_change`,e)}logError(e){this.log(`error`,e,!0)}logCannotPlay(){this.log(`cannot_play`,{},!0)}logDownloadBytes(e){this.log(`download_bytes`,e)}logTelemetry(e){this.log(`telemetry`,e)}logAdvConfiguration(e){this.log(`adv_configuration`,e)}logAdvRequest(e){this.log(`adv_request`,e)}logAdvBreakStarted(e){this.log(`adv_break_started`,e)}logAdvBreakEnded(e){this.log(`adv_break_ended`,e)}logAdvError(e){this.log(`adv_error`,e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=mt(St(),`beforeunload`).subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}}import{cancelIdleCallbackPolyfilled as zn}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Bn}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as Vn,Subscription as Hn}from"@vkontakte/videoplayer-core/es2015";import{Logger as Un}from"@vkontakte/videoplayer-shared/es2015";class Wn{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 Gn=()=>window.Image?new Image:document.createElement(`img`);class Kn{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 Wn),e(this,`subscription`,new Hn),this.params=t,this.log=new Un().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=>zn(e)),this.send(`stop`)}onPlaybackState(e){e===Vn.PLAYING?this.started?this.play():this.start():e===Vn.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(Bn(()=>Gn().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{D as VERSION,lt as ThinOneStat,p as SeekAction,u as Quality,ct as OneStat,Kn as MediascopePixel,m as InteractiveInterfaceClick,d as ContentType,f as ConnectionType,l as ApiEnv};
|
|
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`},_={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},v={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`};import{fillWithDefault as y}from"@vkontakte/videoplayer-shared/es2015";var b=`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:``},S={apiEnv:`vk_alias`,apiKey:b,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},ee=e=>y(e,S);function te(){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 ne,combine as re,fromEvent as ie,isNonNullable as C,isNullable as ae,merge as oe,now as w,observableFrom as se,once as ce,safeStorage as le,Subject as ue,Subscription as de,ValueSubject as fe,getWindow as pe}from"@vkontakte/videoplayer-shared/es2015";import{Logger as me,detectEmbed as he,ErrorCategory as ge}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as _e}from"@vkontakte/videoplayer-shared/es2015";var ve=()=>_e(Math.floor(Math.random()*2**32).toString(36),13,`0`),ye=()=>_e(Math.floor(Math.random()*2**64).toString(36),13,`0`);class T{static getVSID(){return T.vsid}static generateVSID(e){return T.vsid=e?ye():ve(),T.vsid}}e(T,`vsid`,void 0);import{promiseFinally as be}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as xe}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as Se}from"@vkontakte/videoplayer-shared/es2015";var Ce=e=>{let{operation:n,custom:r}=e,i=Se(xe(r).map(([e,t])=>{let n=g[e]??e,r=t;return t&&(e===`mode`?r=v[t]??t:e===`quality`&&(r=_[t]??t)),[n,r]}));return t(t({},e),{},{operation:h[n]??n,custom:i})},E=`1.0.107`;import{ValueSubject as we,getExponentialDelay as Te,ErrorCategory as D,getWindow as Ee}from"@vkontakte/videoplayer-shared/es2015";var De=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class Oe{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 we(!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:D.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:D.EXTERNAL_API,message:`${r} error`,data:i});return}}});return function(t){return e.apply(this,arguments)}}();return o(e)})()}destroy(){Ee().clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return n(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=be(e.params.refreshAuthToken(),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${E}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=Ee().navigator;n=De.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(Ce):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=Ee().setTimeout(()=>{be(this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:D.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})),()=>this.backoffTimeoutId=0)},e)})}_authorize(){var e=this;return 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:E.split(`-`)[0],client_type:`SDK_JS`}};return e.authToken!==void 0&&(t.session_data.auth_token=e.authToken,t.session_data.version=3),e.authorizePromise=be(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>((!t||!t.session_key)&&e.params.error$.next({id:`AuthorizeFailed`,category:D.EXTERNAL_API,message:`No session key`,data:t}),e.sessionKey=t?.session_key??void 0,e.sessionKey)).catch(function(){var t=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:D.EXTERNAL_API,message:`authorize error`,data:t}):e.params.error$.next({id:`AuthorizeUnknown`,category:D.NETWORK,message:`authorize error`,thrown:t})});return function(e){return t.apply(this,arguments)}}()),()=>{e.authorizePromise=void 0,e.consequentAuthErrors=e.sessionKey?0:e.consequentAuthErrors+1,e.authorized$.next(e.sessionKey!==void 0)}),e.authorizePromise})()}}class ke{constructor(t){e(this,`id`,`uvrest`),e(this,`authorized$`,new we(!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=be(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:D.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return 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:D.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.error$.next({id:`OneStat:UvRestApi:AuthorizeFailed`,category:D.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return n(function*(){let n=e?.status;return n===401?(t.params.error$.next({id:`OneStat:UvRestApi:TokenExpired`,category:D.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.error$.next({id:`OneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:D.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return n(function*(){let n=t.statToken;if(!n){t.params.error$.next({id:`OneStat:UvRestApi:RetryNoToken`,category:D.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.error$.next({id:`OneStat:UvRestApi:RetryFailed`,category:D.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${E}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=Ee().navigator;n=De.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(Ce):e}]}}import{fetchPolyfilled as Ae}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as je}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Me}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as O,now as k,getWindow as Ne}from"@vkontakte/videoplayer-shared/es2015";class Pe{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??x[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 Ae(atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),{method:`GET`,mode:`cors`,cache:`no-cache`})).json(),n=e==null||(t=e.Answer[0])==null?void 0:t.data;if(!n)throw Error(`Wrong DNS response`);return n}catch(t){return e.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:O.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),x.vk_alias}finally{e.isApiBaseUrlFetched=!0}})()}sendBeacon(e,t,n){if(!Ne().Blob||!Ne().navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=Ne().Blob,a=new i([r.toString()],{type:`application/x-www-form-urlencoded`});try{return Ne().navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:O.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,r){var i=this;return n(function*(){let n=k(),a=a=>{if(a instanceof TypeError&&je([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],a.message)){i.params.error$.next({id:`Network`,category:O.NETWORK,message:`Request failed`,thrown:a});return}i.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:O.NETWORK,message:`Unhandled request error`,thrown:a,data:{method:e,params:t,sessionKey:r,time:k()-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),Ae(`${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=k()-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{Ae(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:O.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:O.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequest(e,r,i){var a=this;return n(function*(){let n=k(),o=t=>{if(t instanceof TypeError&&je([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],t.message)){a.params.error$.next({id:`Network`,category:O.NETWORK,message:`JSON request failed`,thrown:t});return}a.params.error$.next({id:`OneStat:ApiTransport:sendJsonRequest`,category:O.NETWORK,message:`Unhandled JSON request error`,thrown:t,data:{path:e,time:k()-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),Ae(`${a.apiBaseUrl}${e}`,s).then(e=>{let t=Number(e.headers.get(`content-length`))===0,r=new Date(e.headers.get(`date`)??``).getTime(),i=k()-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),Me(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}import{arrayIncludes as Fe}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Ie}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Le,now as Re,safeStorage as A,debounceFn as ze}from"@vkontakte/videoplayer-shared/es2015";var Be=e=>t=>t.timestamp+e>=Re();class Ve{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 Fe([`action_play`,`watch_coverage_record`,`watch_coverage_live`],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=ze(()=>this.safeFlushQueue(a),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime}),r=A.isPersistent()?this.params.config.flushMaxWait:0,i=ze(()=>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:Le.WTF,message:t?String(t):`Unknown logger error`,thrown:t,data:{storageKey:e.storageKey}})}}readFromStorage(e){let t=A.get(e);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(e,n){if(!this.userSalt){e.unsaltedStorage.push(n);return}let r=this.readFromStorage(e.storageKey),i=(r[this.userSalt]??[]).filter(Be(this.params.config.storageExpiration));A.set(e.storageKey,JSON.stringify(t(t({},r),{},{[this.userSalt]:[...i,n]})))}getFromStorage(e){return this.userSalt?(this.readFromStorage(e.storageKey)[this.userSalt]??[]).filter(Be(this.params.config.storageExpiration)):e.unsaltedStorage}markStorageSent(e){if(!this.userSalt){e.unsaltedStorage=[];return}let t=this.readFromStorage(e.storageKey);delete t[this.userSalt],A.set(e.storageKey,JSON.stringify(t))}housekeepStorage(){for(let e of this.queues){let t=this.readFromStorage(e.storageKey);for(let[n,r]of Ie(t)){let i=r.filter(Be(this.params.config.storageExpiration));i.length?t[n]=i:delete t[n],this.loggerDebugLog({message:`${r.length} retrieved from storage, ${i.length} of them actual (${e.storageKey})`})}A.set(e.storageKey,JSON.stringify(t))}}log(e){for(let t of this.queues)this.addToStorage(t,e),!this.isPaused&&(this.isUrgent(e)?this.flushQueue(t):t.lastVsid===e.custom.vsid?t.debouncedFlush():t.firstFlush(),t.lastVsid=e.custom.vsid)}flush(e={wantBeacon:!1,clearStorage:!0}){for(let t of this.queues)this.flushQueue(t,e)}flushQueue(e,{wantBeacon:t,clearStorage:n}={wantBeacon:!1,clearStorage:!0}){let r=this.getFromStorage(e);r.length!==0&&(e.api.authorized$.getValue()?(t&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${r.length} events through beacon (${e.storageKey})`}),e.api.logBeacon(r)):(this.loggerDebugLog({message:`Flushing ${r.length} events (${e.storageKey})`}),e.api.logRequest(r)),n&&this.markStorageSent(e)):e.api.authorize(),e.firstFlush.cancel(),e.debouncedFlush.cancel())}pause(){this.isPaused=!0;for(let e of this.queues)e.debouncedFlush.cancel()}resume(){this.isPaused=!1;for(let e of this.queues)e.debouncedFlush()}destroy(){for(let e of this.queues)e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel();this.queues=[]}}import{HttpConnectionType as He,Surface as j,VideoFormat as M,VideoQuality as N}from"@vkontakte/videoplayer-core/es2015";import{assertNever as Ue}from"@vkontakte/videoplayer-shared/es2015";var We=e=>e&&{[N.INVARIANT]:`unknown`,[N.Q_144P]:`mobile`,[N.Q_240P]:`lowest`,[N.Q_360P]:`low`,[N.Q_480P]:`medium`,[N.Q_576P]:`unknown`,[N.Q_720P]:`high`,[N.Q_1080P]:`fullhd`,[N.Q_1440P]:`quadhd`,[N.Q_2160P]:`ultrahd`,[N.Q_4320P]:`unknown`}[e],Ge=e=>e&&{[He.HTTP1]:`http1`,[He.HTTP2]:`http2`,[He.QUIC]:`http3`}[e],Ke=e=>{if(e!==void 0)switch(e){case M.MPEG:return`mp4`;case M.DASH:case M.DASH_LIVE:case M.DASH_STREAMS:return`dash`;case M.DASH_SEP:return`dash_sep`;case M.DASH_ONDEMAND:return`ondemand_dash`;case M.DASH_WEBM:case M.DASH_LIVE_WEBM:return`webm`;case M.DASH_WEBM_AV1:return`av1`;case M.DASH_LIVE_CMAF:return`ondemand_dash_live`;case M.HLS:case M.HLS_LIVE:return`hls`;case M.HLS_FMP4:return`hls_fmp4`;case M.HLS_ONDEMAND:return`ondemand_hls`;case M.HLS_LIVE_CMAF:return`ondemand_hls_live`;case M.WEB_RTC_LIVE:return`webrtc`;default:return Ue(e)}},qe=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case j.NONE:case j.INLINE:return;case j.FULLSCREEN:return`fullscreen`;case j.SECOND_SCREEN:return`chromecast`;case j.PIP:return`pip`;case j.INVISIBLE:return`invisible`;default:return Ue(e)}},Je=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class Ye{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 Xe}from"@vkontakte/videoplayer-core/es2015";import{filter as Ze,filterChanged as Qe,fromEvent as $e,isNullable as et,map as tt,merge as nt,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=nt($e(window,`beforeunload`),e.events.willDestruct$),a=new ot(void 0),o;r.add(e.info.isLive$.pipe(Qe()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(tt(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(Ze(()=>e.info.playbackState$.getValue()===Xe.PLAYING)),d=e.events.seeked$.pipe(Ze(()=>e.info.playbackState$.getValue()===Xe.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,_=nt(s,d,m).pipe(tt(()=>g())),v=nt(l,nt(c,p,i,h).pipe(tt(()=>g()))),y,b=e=>{y=e},x=e=>{let t=e;et(y)||y===t||et(t)||(n.next({from:y,to:t}),y=void 0)},S=()=>{h.next(),m.next()};if(r.add(_.subscribe(b)),r.add(v.subscribe(x)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(_.subscribe(()=>{n(),e=window.setTimeout(S,t.forceInterval)})),r.add(v.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(_.subscribe(()=>e=window.setTimeout(S,t.forceInterval))),r.add(v.subscribe(()=>window.clearTimeout(e)))}return r});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=()=>{let e=new de;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class mt{get vsid$(){return new fe(T.getVSID())}constructor(t,n){e(this,`apis`,void 0),e(this,`logger`,void 0),e(this,`config`,void 0),e(this,`subscription`,new de),e(this,`beforeunloadSubscription`,void 0),e(this,`timeSynchronisation`,void 0),e(this,`debugLogger`,new me),e(this,`oneStatDebugLog`,this.debugLogger.createComponentLog(`onestat`)),e(this,`loopCounter`,0),e(this,`disabled`,!1),e(this,`experimental`,void 0),e(this,`isid$`,new fe(void 0)),e(this,`zenUid$`,new fe(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 fe(`unknown`)),e(this,`deviceId`,void 0),this.statContext=t,this.config=ee(n.config??{}),C(n.apiEnv)&&(this.config.apiEnv=n.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Ye);let r=new ue;this.experimental={error$:r};let i=le.get(ft);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=te(),le.set(ft,this.deviceId)),this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??ye()),this.zenUid$.next(n.zenUid);let a=new Pe({config:this.config,error$:r,timeSynchronisation:this.timeSynchronisation}),o=[];this.config.apiForticom&&o.push(new Oe({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 ke({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:ge.WTF,message:`oldStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.apis=o,this.logger=new Ve({config:this.config,debugLogger:this.debugLogger,apis:this.apis,error$:r,userSalt:n.userSalt});let{isEmbed:s,topOrigin:c}=he();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 de,n=(e,n)=>t.add(e.subscribe(n));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.seeked$,()=>{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)});let r;n(e.info.isStalled$,e=>{e?r=w():(C(r)&&this.logEmptyBuffer({duration:w()-r}),r=void 0)});let i=!1;t.add(e.events.fatalError$.pipe(ce()).subscribe(()=>i=!0)),n(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let e=C(r)?w()-r:void 0;this.logCloseAtEmptyBuffer({duration:e??0}),r=void 0}else i||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})});let a,o,s=!1;n(e.events.firstBytes$,e=>{a=w(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>o=w()),n(e.info.currentBuffer$,e=>{!s&&e&&e.end-e.start>0&&C(a)&&(this.logPlayerReady({duration:w()-a}),s=!0)}),n(e.events.firstFrame$,()=>{C(a)&&!s&&(this.logPlayerReady({duration:w()-a}),s=!0),C(o)&&this.logFirstFrame({time:w()-o})});let c;n(e.info.currentVideoStream$,e=>{e&&(c&&e.id!==c&&this.logTrackSwitch(e),c=e.id)});let l;n(e.info.currentAudioStream$,e=>{e&&(l&&e.id!==l&&this.logTrackSwitch(e),l=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(re({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=We(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:Ke(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let u;return n(e.info.hostname$,e=>{let t=u!==void 0&&u!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),u=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Ge(e)}),this.updateContext({connectionType:Ge(e)})}),n(e.info.httpConnectionReused$,e=>{ae(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:qe(e,this.statContext.isPreviewPlayerView)})}),n(re({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}=pt();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:qe(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}=pt();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}=pt();return n(e.click$,e=>this.logInterfaceClick(e)),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}authorize(e){return Promise.all(this.apis.map(t=>t.authorize(e)))}pause(){this.logger.pause(),this.oneStatDebugLog({message:`paused`})}resume(){this.logger.resume(),this.oneStatDebugLog({message:`resumed`})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.apis.forEach(e=>e.destroy()),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:`VSID reset`}),T.generateVSID(this.config.useVsid64)}getDeviceId(){return this.deviceId}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:`player_ready`,param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:`play_toggle`})}logPlaying(){this.log({operation:`playing`})}logPause(e){this.log({operation:`pause`,param:String(Math.round(e.position))})}logSeek(e){this.log({operation:`seek`,param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:`first_bytes`,param:String(e.time)})}logFirstFrame(e){this.log({operation:`first_frame`,param:String(e.time)})}logError(e){this.log({operation:`content_error`,param:`${e.fatal?`fatal`:`recoverable`}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:`watch_coverage_record`,param:`${e.start}-${e.end}`},{in_history:this.statContext.inHistory?1:void 0})}logWatchCoverageLive(e){let t=this.timeSynchronisation?.getOffset()??0,n=e.start+t,r=e.end+t;this.log({operation:`watch_coverage_live`,param:`${n}-${r}`},{in_history:this.statContext.inHistory?1:void 0,latency:e.latency,buffer_latency:e.bufferLatency})}logEmptyBuffer(e){this.log({operation:`empty_buffer`,param:String(e.duration)})}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=pe().navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(oe(ie(e,`change`),se([`init`])).subscribe(()=>this.updateContext({network:Je(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=ie(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))})}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()??w(),o=this.vsid$.getValue();ne(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||ae(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,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 ht={};o(ht,{VERSION:()=>E,ThinOneStat:()=>Zn,ActionSeekType:()=>Pt});import{objectValues as gt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as _t}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as vt,detectEmbed as yt,fromEvent as bt,Logger as xt,merge as St,combine as F,filter as I,filterChanged as Ct,once as wt,skip as Tt,debounce as Et,safeStorage as Dt,getWindow as Ot,Subject as kt,Subscription as At,ValueSubject as jt,ErrorCategory as L}from"@vkontakte/videoplayer-shared/es2015";import{clientChecker as R}from"@vkontakte/videoplayer-core/es2015";import{fillWithDefault as Mt}from"@vkontakte/videoplayer-shared/es2015";var Nt;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(Nt||={});var Pt;(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`})(Pt||={});var Ft=`CIOPGQJGDIHBABABA`,It={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:``},Lt={apiKey:Ft,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},Rt=e=>Mt(e,Lt);import{arrayIncludes as zt}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Bt}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as z,ValueSubject as Vt}from"@vkontakte/videoplayer-shared/es2015";function Ht(e){let t=Error(`HTTP ${e.status}: ${e.statusText}`);return t.status=e.status,t.statusText=e.statusText,t.response=e,t}function Ut(){let e=Error(`Request timeout`);return e.isTimeout=!0,e}function Wt(e){let t=Error(e.error_msg);return t.errorData=e,t}function Gt(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 Kt{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 Vt(!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=Gt(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=Gt(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&&zt([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=Bt(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=Gt(n);if(r===401&&t.params.refreshAuthToken){if(t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:z.EXTERNAL_API,message:`Auth token expired during authorization`,data:{error:n,code:r,attempt:e}}),e>=2){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeMaxAttemptsReached`,category:z.EXTERNAL_API,message:`Authorization failed after ${e} attempts`,data:{error:n,code:r}});return}return t.authToken=yield t.refreshAuthToken(),t.doAuthorize(e+1)}r?t.params.errors$.next({id:`ThinOneStat:Api:Authorize#${r}`,category:z.EXTERNAL_API,message:`Authorize error`,data:{error:n,code:r}}):t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:z.NETWORK,message:`Authorize error`,thrown:n});return}})()}buildAuthParams(){let e={session_data:{version:2,device_id:this.params.deviceId,client_version:this.getClientVersion(),client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),e}getClientVersion(){return E}refreshAuthToken(){var e=this;return n(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Bt(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 qt{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 Vt(!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=Bt(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 Jt}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Yt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as B}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Xt}from"@vkontakte/videoplayer-shared/es2015";import{now as V,getWindow as H,getExponentialDelay as Zt,isAbortError as Qt,ErrorCategory as U}from"@vkontakte/videoplayer-shared/es2015";class $t{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??It[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 Ut();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{Jt(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 Ut();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 Yt,a=H().setTimeout(()=>i.abort(),r);try{let r=yield Jt(e,t(t({},n),{},{signal:i.signal}));return H().clearTimeout(a),r}catch(e){throw H().clearTimeout(a),Qt(e)?Ut():e}}).apply(this,arguments)}processResponse(e,t){var r=this;return n(function*(){if(!e.ok){let t=Ht(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 Wt(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===It.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}),It.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),Xt(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:Zt(t,{start:this.retryConfig.baseDelay,max:this.retryConfig.maxDelay,factor:2,random:.2})}}import{promiseAllSettled as en}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as tn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as nn}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as rn}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as an}from"@vkontakte/videoplayer-shared/es2015";import{now as on,debounceFn as sn,getWindow as W,safeStorage as G,ErrorCategory as K}from"@vkontakte/videoplayer-shared/es2015";var cn=e=>t=>(t.client_time??on())+e>=on();class ln{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=>nn(this.urgentEvents,e.event_name)),this.params=t,this.userSalt=t.userSalt,this.debugLog=t.debugLogger.createComponentLog(`batch-queue:${t.storageKey}`),this.firstFlush=sn(()=>this.safeFlush(),this.params.config.flushFirstTime,{maxWait:this.params.config.flushFirstTime});let n=G.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=sn(()=>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=rn(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(cn(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 an(e)){let a=i.filter(cn(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=rn(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 un{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 ln({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:tn.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 en(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 en(e.queues.map(e=>e.destroy())),e.queues=[]})()}}function dn(){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 fn{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 pn}from"@vkontakte/videoplayer-core/es2015";import{Observable as mn,Subscription as hn,ValueSubject as gn,Subject as _n,fromEvent as vn,isNullable as yn,map as bn,merge as q,filter as xn,filterChanged as Sn,getWindow as Cn}from"@vkontakte/videoplayer-shared/es2015";var wn=(e,t,n)=>new mn(r=>{let i=new hn,a=new gn(void 0),o;i.add(e.info.isLive$.pipe(Sn()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(bn(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(xn(()=>e.info.playbackState$.getValue()===pn.PLAYING)),f=e.events.seeked$.pipe(xn(()=>e.info.playbackState$.getValue()===pn.PLAYING)),p=!1,m=new _n;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=q(vn(Cn(),`beforeunload`),e.events.willDestruct$),g,_=e=>{g=e},v=e=>{let t=e;yn(g)||yn(t)||g===t||(r.next({from:g,to:t}),g=void 0)},y=new _n,b=new _n,x=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,S=q(s,f,y).pipe(bn(()=>x())),ee=q(u,q(c,m,h,l,b).pipe(bn(()=>x()))),te=t.started$&&t.ended$?q(S,t.ended$):S,ne=t.started$&&t.ended$?q(ee,t.started$):ee;if(i.add(te.subscribe(_)).add(ne.subscribe(v)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{b.next(),y.next()};i.add(te.subscribe(()=>{let r=Cn().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(ne.subscribe(()=>{e.forEach(e=>{Cn().clearTimeout(e)}),e=[]}))}return i});import{Subscription as Tn}from"@vkontakte/videoplayer-core/es2015";import{Observable as En,merge as Dn}from"@vkontakte/videoplayer-shared/es2015";var On=(e,t)=>new En(n=>{let r=new Tn;return r.add(Dn(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 kn}from"@vkontakte/videoplayer-core/es2015";import{Observable as An,filter as jn,getWindow as Mn}from"@vkontakte/videoplayer-shared/es2015";var Nn=(e,{maxTimeWindow:t})=>new An(n=>{let r=new kn,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(Mn().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=Mn().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(jn(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 Pn,Subscription as Fn,merge as In}from"@vkontakte/videoplayer-shared/es2015";var Ln=e=>new Pn(t=>{let n=new Fn,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$:_,willDestruct$:v}=e.events,{currentPlaybackRate$:y}=e.info;return n.add(g.subscribe(d)).add(In(p,m).subscribe(l)).add(In(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),Math.round(e)}),n});import{Observable as Rn,Subscription as zn,merge as Bn}from"@vkontakte/videoplayer-shared/es2015";var Vn=(e,t)=>new Rn(n=>{let r=new zn,i=0;return r.add(Bn(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 Hn}from"@vkontakte/videoplayer-shared/es2015";import{HttpConnectionType as Un,Surface as J,VideoFormat as Y,VideoQuality as X}from"@vkontakte/videoplayer-core/es2015";var Wn=e=>e&&{[Un.HTTP1]:`http1`,[Un.HTTP2]:`http2`,[Un.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 Hn(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 Hn(e)}},Gn=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}},Kn=(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`}},qn=e=>{switch(e){case void 0:return;case J.INVISIBLE:return`background`;default:return`foreground`}},Jn=`_thin-one-stat_deviceId`,Yn=`2.2.0`,Xn=()=>{let e=new At;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Zn{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 xt),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 jt(`unknown`)),e(this,`vsid$`,new jt(void 0)),e(this,`isid$`,new jt(void 0)),e(this,`errors$`,new kt),e(this,`getTotalViewTime`,()=>0),this.statContext=t,this.config=Rt(n.config??{}),this.subscription=new At,this.config.synchronizeTime&&(this.timeSynchronisation=new fn),this.subscription.add(this.errors$.subscribe(e=>{this.thinOneStatDebugLog({message:`[${e.category}] ${e.id}: ${e.message}`})}));let r=Dt.get(Jn);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=dn(),Dt.set(Jn,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??ye());let i=new $t({errors$:this.errors$,config:this.config,timeSynchronisation:this.timeSynchronisation});this.config.apiForticom&&this.apis.push(new Kt({config:this.config,apiTransport:i,errors$:this.errors$,deviceId:this.deviceId,refreshAuthToken:n.refreshAuthToken})),this.config.apiUvRest&&(n.getUvRestAuthToken?this.apis.push(new qt({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 un({config:this.config,debugLogger:this.debugLogger,apis:this.apis,errors$:this.errors$,userSalt:n.userSalt});let{isEmbed:a,topOrigin:o}=yt();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 At,i=(e,t)=>r.add(e.subscribe(t));i(Ln(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:Wn(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=Wn(e)}),i(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),i(wn(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(Vn(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),i(On(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),i(e.events.willReady$,()=>{let t={isid:this.isid$.getValue(),stream_profile:Gn(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),wt()),()=>{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),wt()),()=>{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(St(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:Kn(o,this.statContext.isPreviewPlayerView),visibility:qn(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(St(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),Ct((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(Nn(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)),wt()),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=Kn(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),u=qn(e),l!==u&&(this.isStarted&&this.logVisibilityChanged({visibility:u}),l=qn(e))}),i(F({muted:e.info.muted$,volume:e.info.volume$}).pipe(Et(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),Tt(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),Tt(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),Tt(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}=Xn();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:Kn(e)})}),n(e.actionQuality$,e=>{var t,n,r;let i=e=>_t(gt(Nt),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}=Xn();return n(e.init$,e=>{let t={slot:e};this.logAdvConfiguration(t)}),n(e.slotRequested$,e=>{let t={adv_section:e};this.logAdvRequest(t)}),n(e.started$,e=>{let t={adv_section:e};this.logAdvBreakStarted(t)}),n(e.ended$,({section:e,ordIds:t})=>{let n={adv_section:e,erids:t.join(`,`)};this.logAdvBreakEnded(n)}),n(e.error$,e=>{let t={error_message:e};this.logAdvError(t)}),this.adsSubscription=t,this.resubscribeBeforeunload(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),T.generateVSID(this.config.useVsid64),this.vsid$.next(T.getVSID()),this.eventNumber=0}destroy(){var e=this;return 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 _t([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();vt(t);let n=this.eventNumber++,r=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,i={vsid:t,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${E}`,platform:this.isValidPlatform(this.statContext.platform)?this.statContext.platform:`web:${this.statContext.isMobile||R.device.isMobile?`mobile`:`desktop`}`,product:this.statContext.product,event_number:n,playback_position:Math.round(r),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let e of this.config.disabledParams)delete i[e];return i}createRequiredFatParams(){let e={stats_version:Yn,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(_t(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=bt(Ot(),`beforeunload`).subscribe(()=>{this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload}).catch(()=>{})}),this.subscription.add(this.beforeunloadSubscription)}}import{cancelIdleCallbackPolyfilled as Qn}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as $n}from"@vkontakte/videoplayer-shared/es2015";import{PlaybackState as er,Subscription as tr}from"@vkontakte/videoplayer-core/es2015";import{Logger as nr}from"@vkontakte/videoplayer-shared/es2015";class rr{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 ir=()=>window.Image?new Image:document.createElement(`img`);class ar{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 rr),e(this,`subscription`,new tr),this.params=t,this.log=new nr().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=>Qn(e)),this.send(`stop`)}onPlaybackState(e){e===er.PLAYING?this.started?this.play():this.start():e===er.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($n(()=>ir().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{E as VERSION,ht as ThinOneStat,p as SeekAction,u as Quality,mt as OneStat,ar as MediascopePixel,m as InteractiveInterfaceClick,d as ContentType,f as ConnectionType,l as ApiEnv};
|