@vkontakte/videoplayer-statistics 1.0.100-dev.04f0bb5f.0 → 1.0.100-dev.319d6ebf.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/es2018.cjs +3 -3
  2. package/es2018.esm.js +3 -3
  3. package/es2024.cjs +3 -3
  4. package/es2024.esm.js +3 -3
  5. package/esnext.cjs +3 -3
  6. package/esnext.esm.js +3 -3
  7. package/evergreen.esm.js +3 -3
  8. package/package.json +3 -3
  9. package/types/ShareVSID.d.ts +3 -3
  10. package/types/index.d.ts +6 -5
  11. package/types/mediascopePixel/MediascopePixel.d.ts +36 -36
  12. package/types/mediascopePixel/Stopwatch.d.ts +10 -10
  13. package/types/mediascopePixel/types.d.ts +5 -5
  14. package/types/oneStat/Api.d.ts +35 -34
  15. package/types/oneStat/ApiTransport.d.ts +19 -19
  16. package/types/oneStat/Logger.d.ts +35 -35
  17. package/types/oneStat/OneStat.d.ts +309 -307
  18. package/types/oneStat/config.d.ts +32 -32
  19. package/types/oneStat/env.d.ts +3 -3
  20. package/types/oneStat/index.d.ts +9 -6
  21. package/types/oneStat/types.d.ts +43 -43
  22. package/types/oneStat/uiEvents.d.ts +19 -19
  23. package/types/oneStat/utils/mappers.d.ts +2 -2
  24. package/types/oneStat/utils/shorten.d.ts +1 -1
  25. package/types/oneStat/utils/timeSynchronisation.d.ts +8 -8
  26. package/types/oneStat/utils/watchCoverage.d.ts +4 -4
  27. package/types/oneStat/values.d.ts +63 -64
  28. package/types/shared/useModeController.d.ts +6 -5
  29. package/types/thinOneStat/Api.d.ts +32 -32
  30. package/types/thinOneStat/ApiTransport.d.ts +19 -19
  31. package/types/thinOneStat/Logger.d.ts +35 -35
  32. package/types/thinOneStat/ThinOneStat.d.ts +271 -271
  33. package/types/thinOneStat/config.d.ts +21 -20
  34. package/types/thinOneStat/env.d.ts +3 -3
  35. package/types/thinOneStat/events.d.ts +21 -21
  36. package/types/thinOneStat/index.d.ts +6 -4
  37. package/types/thinOneStat/types.d.ts +24 -24
  38. package/types/thinOneStat/utils/calculateTotalViewTime.d.ts +2 -2
  39. package/types/thinOneStat/utils/downloadBytes.d.ts +4 -4
  40. package/types/thinOneStat/utils/mappers.d.ts +3 -2
  41. package/types/thinOneStat/utils/timeSynchronisation.d.ts +8 -8
  42. package/types/thinOneStat/utils/watchCoverage.d.ts +4 -4
  43. package/types/thinOneStat/utils/watchedN.d.ts +5 -5
  44. package/types/thinOneStat/values.d.ts +67 -67
  45. package/es2015.cjs +0 -6
  46. package/es2015.esm.js +0 -6
package/evergreen.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.100-dev.04f0bb5f.0
3
- * Tue, 24 Feb 2026 12:54:15 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.100-dev.319d6ebf.0
3
+ * Wed, 04 Mar 2026 10:24:59 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-100/doc/
5
5
  */
6
- var Ot=Object.defineProperty;var Bt=(a,e)=>{for(var i in e)Ot(a,i,{get:e[i],enumerable:!0})};var H=(c=>(c.PROD="prod",c.VK_ALIAS="vk_alias",c.VIDEOTEST="videotest",c.TEST="test",c.OKCDN="okcdn",c.AUTO="auto",c))(H||{}),ge=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(ge||{}),me=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.HLS_FMP4="hls_fmp4",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(me||{});var be=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(be||{});var ve=(l=>(l.SLIDER="slider",l.RICH="rich",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(ve||{}),Ke=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(Ke||{}),ze={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"},je={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"},Ge={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Ye={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv",minimal:"minimal"};import{fillWithDefault as Ft}from"@vkontakte/videoplayer-shared/evergreen";var Xe="CIOPGQJGDIHBABABA",Ie={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:""};var Ut={apiEnv:"vk_alias",apiKey:Xe,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*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:5*60*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!1},Je=a=>Ft(a,Ut);function ye(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as oi,combine as ct,fromEvent as lt,isNonNullable as O,isNullable as ut,merge as ri,now as R,observableFrom as si,once as ni,safeStorage as ht,Subject as ai,Subscription as ke,ValueSubject as te}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as di,detectEmbed as ci}from"@vkontakte/videoplayer-shared/evergreen";var Ht=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),q=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0"),D=class a{static getVSID(){return a.vsid}static generateVSID(e){return a.vsid=e?q():Ht(),a.vsid}};var Ze=a=>{let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([o,n])=>{let c=je[o]??o,h=n;return n&&(o==="mode"?h=Ye[n]??n:o==="quality"&&(h=Ge[n]??n)),[c,h]}));return{...a,operation:ze[e]??e,custom:t}};var P="1.0.100-dev.04f0bb5f.0";import{ValueSubject as qt,getExponentialDelay as Wt,ErrorCategory as M}from"@vkontakte/videoplayer-shared/evergreen";var Qt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,W=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new qt(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e).catch(()=>{})}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let n=async(c,h=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:M.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let p=l?.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),h>0?n(c,h-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),h>0?n(c,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:M.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return n(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){let i="WEB",t=!1,o=`@vkontakte/videoplayer-statistics:${P}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:n}=window.navigator;t=Qt.test(n)}else this.params.mobile&&(t=!0);return t&&(i="M_WEB"),this.params.vktvVersion&&(i="SMART_TV",o=this.params.vktvVersion),{collector:"ok.mobile.apps.video",data:JSON.stringify({application:o,platform:i,items:this.params.config.shorten?e.map(Ze):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Wt(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:M.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.deviceId,client_version:P.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:M.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:M.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:M.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as Y,now as Se}from"@vkontakte/videoplayer-shared/evergreen";var Q=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ie[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:Y.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Ie.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:Y.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=Se(),n=h=>{if(h instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(h.message)){this.params.error$.next({id:"Network",category:Y.NETWORK,message:"Request failed",thrown:h});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:Y.NETWORK,message:"Unhandled request error",thrown:h,data:{method:e,params:i,sessionKey:t,time:Se()-o}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let c={method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})};return this.params.config.useKeepalive&&(c.keepalive=!0),fetch(`${this.apiBaseUrl}/fb.do`,c).then(h=>{let l=Number(h.headers.get("content-length"))===0,p=new Date(h.headers.get("date")??"").getTime(),g=Se()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,g),!l)return h.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Kt,now as zt,safeStorage as K,debounceFn as et}from"@vkontakte/videoplayer-shared/evergreen";var X="onestat_events",_e=a=>e=>e.timestamp+a>=zt(),J=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=et(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=K.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=et(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:Kt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=K.get(X);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(_e(this.params.config.storageExpiration));K.set(X,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(_e(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],K.set(X,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(_e(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}K.set(X,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush({wantBeacon:e,clearStorage:i}={wantBeacon:!1,clearStorage:!0}){let t=this.getFromStorage();t.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${t.length} events through beacon`}),this.api.logBeacon(t)):(this.loggerDebugLog({message:`Flushing ${t.length} events`}),this.api.logRequest(t)),i&&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 Pe,Surface as V,VideoFormat as y,VideoQuality as w}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as tt}from"@vkontakte/videoplayer-shared/evergreen";var it=a=>a&&{[w.INVARIANT]:"unknown",[w.Q_144P]:"mobile",[w.Q_240P]:"lowest",[w.Q_360P]:"low",[w.Q_480P]:"medium",[w.Q_576P]:"unknown",[w.Q_720P]:"high",[w.Q_1080P]:"fullhd",[w.Q_1440P]:"quadhd",[w.Q_2160P]:"ultrahd",[w.Q_4320P]:"unknown"}[a],Te=a=>a&&{[Pe.HTTP1]:"http1",[Pe.HTTP2]:"http2",[Pe.QUIC]:"http3"}[a],ot=a=>{if(a!==void 0)switch(a){case y.MPEG:return"mp4";case y.DASH:case y.DASH_LIVE:case y.DASH_STREAMS:return"dash";case y.DASH_SEP:return"dash_sep";case y.DASH_ONDEMAND:return"ondemand_dash";case y.DASH_WEBM:case y.DASH_LIVE_WEBM:return"webm";case y.DASH_WEBM_AV1:return"av1";case y.DASH_LIVE_CMAF:return"ondemand_dash_live";case y.HLS:case y.HLS_LIVE:return"hls";case y.HLS_FMP4:return"hls_fmp4";case y.HLS_ONDEMAND:return"ondemand_hls";case y.HLS_LIVE_CMAF:return"ondemand_hls_live";case y.WEB_RTC_LIVE:return"webrtc";default:return tt(a)}},Ee=(a,e)=>{if(e)return"minimal";switch(a){case void 0:case V.NONE:case V.INLINE:return;case V.FULLSCREEN:return"fullscreen";case V.SECOND_SCREEN:return"chromecast";case V.PIP:return"pip";case V.INVISIBLE:return"invisible";default:return tt(a)}},rt=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var Z=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};import{PlaybackState as st}from"@vkontakte/videoplayer-core/evergreen";import{filter as nt,filterChanged as jt,fromEvent as Gt,isNullable as at,map as Yt,merge as we,Observable as Xt,Subject as Ae,Subscription as Jt,ValueSubject as Zt}from"@vkontakte/videoplayer-shared/evergreen";var dt=(a,e)=>new Xt(i=>{let t=new Jt,o=we(Gt(window,"beforeunload"),a.events.willDestruct$),n=new Zt(void 0),c;t.add(a.info.isLive$.pipe(jt()).subscribe(b=>{c&&(c.unsubscribe(),n.next(void 0)),b?c=a.info.liveTime$.pipe(Yt(_=>_&&_/1e3)).subscribe(n):c=a.info.position$.subscribe(n),t.add(c)}));let{playing$:h,paused$:l}=a.events,p=a.events.willSeek$.pipe(nt(()=>a.info.playbackState$.getValue()===st.PLAYING)),g=a.events.seeked$.pipe(nt(()=>a.info.playbackState$.getValue()===st.PLAYING)),s=!1,r=new Ae;t.add(p.subscribe(()=>{s||r.next(),s=!0})),t.add(g.subscribe(()=>s=!1));let d=new Ae,u=new Ae,f=we(h,g,d),m=we(l,r,o,a.events.looped$,u),v,T=()=>v=n.getValue(),E=()=>{let b=n.getValue();at(v)||v===b||at(b)||(i.next({from:v,to:b}),v=void 0)},S=()=>{u.next(),d.next()};if(t.add(f.subscribe(T)),t.add(m.subscribe(E)),e.forceInterval&&isFinite(e.forceInterval))if(e.watchCoverageTimeoutFix){let b,_=()=>{b!==void 0&&(window.clearTimeout(b),b=void 0)};t.add(f.subscribe(()=>{_(),b=window.setTimeout(S,e.forceInterval)})),t.add(m.subscribe(()=>_())),t.add(()=>_())}else{let b=0;t.add(f.subscribe(()=>b=window.setTimeout(S,e.forceInterval))),t.add(m.subscribe(()=>window.clearTimeout(b)))}return t});import{Surface as C}from"@vkontakte/videoplayer-core/evergreen";import{debounce as ei,filterChanged as ti,Subject as ii}from"@vkontakte/videoplayer-shared/evergreen";var ee=(a,e,i)=>{let t=new ii,o=t.pipe(ei(0),ti()),n=!1,c=!1,h=!1;return e(a.inPiP$,l=>{n=l,t.next(l?C.PIP:c?C.FULLSCREEN:h?C.INLINE:void 0)}),e(a.inFullscreen$,l=>{c=l,t.next(l?C.FULLSCREEN:n?C.PIP:h?C.INLINE:void 0)}),i&&e(i.info.surface$,l=>{switch(l){case C.SECOND_SCREEN:case C.NONE:case C.INLINE:{!c&&!n&&(l===C.INLINE&&(h=!0),t.next(l));break}}}),{surface$:o}};var li="_one-stat_",pt=`${li}deviceId`,xe=()=>{let a=new ke;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Ce=class{constructor(e,i){this.subscription=new ke;this.debugLogger=new di;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.isid$=new te(void 0);this.zenUid$=new te(void 0);this.seekAction$=new te("unknown");this.statContext=e,this.config=Je(i.config??{}),O(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Z);let t=new ai;this.experimental={error$:t};let o=ht.get(pt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=ye(),ht.set(pt,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??q()),this.zenUid$.next(i.zenUid);let n=new Q({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new W({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new J({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,topOrigin:h}=ci();this.isEmbed=c,this.embedParent=h?new URL(h).hostname:void 0,this.subscribe()}get vsid$(){return new te(D.getVSID())}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new ke,t=(r,d)=>i.add(r.subscribe(d));t(e.events.willStart$,()=>{let r=e.info.position$.getValue();this.logActionPlay({position:r}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{let r=this.seekAction$.getValue();this.logSeek({action:r==="rich"?"slider":r,time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(dt(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),r=>{let d=e.info.isLive$.getValue(),u=e.info.atLiveEdge$.getValue(),f={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};if(u){let m=e.info.liveLatency$.getValue()??0,v=e.info.currentBuffer$.getValue()?.end??0,T=e.info.liveBufferTime$.getValue()??0,E=Math.round((m-(v-T))*1e3),S=Math.round(m*1e3);E&&S&&(f.latency=E,f.bufferLatency=S)}d?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,r=>{r?o=R():(O(o)&&this.logEmptyBuffer({duration:R()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(ni()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=O(o)?R()-o:void 0;this.logCloseAtEmptyBuffer({duration:d??0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),t(e.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let c,h,l=!1;t(e.events.firstBytes$,r=>{c=R(),this.logFirstBytes({time:r})}),t(e.events.willStart$,()=>h=R()),t(e.info.currentBuffer$,r=>{!l&&r&&r.end-r.start>0&&O(c)&&(this.logPlayerReady({duration:R()-c}),l=!0)}),t(e.events.firstFrame$,()=>{O(c)&&!l&&(this.logPlayerReady({duration:R()-c}),l=!0),O(h)&&this.logFirstFrame({time:R()-h})});let p;t(e.info.currentVideoStream$,r=>{r&&(p&&r.id!==p&&this.logTrackSwitch(r),p=r.id)});let g;t(e.info.currentAudioStream$,r=>{r&&(g&&r.id!==g&&this.logTrackSwitch(r),g=r.id)}),t(e.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),t(ct({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:d})=>this.updateContext({audible:!r&&d>0})),t(e.info.currentQuality$,r=>{let d=it(r);this.updateContext({quality:d}),d&&this.logQuality(d)}),t(e.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),t(e.info.currentFormat$,r=>this.updateContext({contentType:ot(r)})),t(e.info.currentPlaybackRate$,r=>this.updateContext({rate:r})),t(e.info.is3DVideo$,r=>this.updateContext({is3d:r}));let s;return t(e.info.hostname$,r=>{let d=s!==void 0&&s!==r;this.updateContext({cdnHostname:r,failover:d}),d&&this.logFailover(r),s=r}),t(e.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),t(e.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Te(r)}),this.updateContext({connectionType:Te(r)})}),t(e.info.httpConnectionReused$,r=>{ut(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),t(e.info.surface$,r=>{this.uiEvents||this.updateContext({mode:Ee(r,this.statContext.isPreviewPlayerView)})}),t(ct({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:r,available:d})=>{let u=d.find(({id:m})=>m===r),f=u&&(u.isAuto?`${u.language}_auto`:u.language);this.updateContext({subtitles:f?.split(".")[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=xe();if(!this.player)return i;t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$);let{surface$:o}=ee(this.uiEvents,t,this.player);return t(o,n=>{this.updateContext({mode:Ee(n,this.statContext.isPreviewPlayerView)})}),t(e.actionSetSubtitle$,n=>this.updateContext({subtitles:n?.split(".")[0]})),t(e.nextMovie$,n=>this.logNextMovie(n)),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToAds(e){let{subscription:i,subscribe:t}=xe();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),t(e.error$,o=>this.logError({errorType:o,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=xe();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}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"}),D.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 i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`},{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(ri(lt(e,"change"),si(["init"])).subscribe(()=>this.updateContext({network:rt(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=lt(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,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let n=this.timeSynchronisation?.now()??R(),c=this.vsid$.getValue();oi(c);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,g,s;if(this.isEmbed||this.statContext.place==="embed"){g=this.embedParent;let d=[...new URLSearchParams(location.search).entries()].filter(([u,f])=>this.config.embedUrlParams.includes(u));s=new URLSearchParams(d).toString()}else if(this.statContext.place==="direct"){let d=this.statContext.refDomain||document.referrer;d&&URL.canParse(d)?g=new URL(d).hostname:g=d,s=location.href.substring(0,1024)}let r={vsid:c,isid:h,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:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!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:g,direct_url:s,rate:this.statContext.rate===1||ut(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,...o};for(let d of this.config.disabledCustomFields)delete r[d];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:r}}};var Dt={};Bt(Dt,{ActionSeekType:()=>ie,ThinOneStat:()=>he,VERSION:()=>P});import{assertNonNullable as ki,detectEmbed as Ci,fromEvent as $i,Logger as Li,merge as Ct,combine as ue,filter as k,filterChanged as Ri,once as Di,skip as Fe,safeStorage as $t,getWindow as Ni,Subject as Mi,Subscription as He,ValueSubject as Ue,ErrorCategory as U}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as $}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as ui}from"@vkontakte/videoplayer-shared/evergreen";var $e=(t=>(t.AUTO="auto",t.AUTO_POOR="auto_poor",t.AUTO_RICH="auto_rich",t))($e||{});var ie=(l=>(l.SLIDER="slider",l.RICH="rich",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(ie||{});var gt="CIOPGQJGDIHBABABA",Le={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",okcdn:"https://api.okcdn.ru",auto:""};var hi={apiKey:gt,apiEnv:"okcdn",apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:3e4,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNDefaultTargetDuration:1e3,downloadBytesMaxTime:3e4},mt=a=>ui(a,hi);import{getExponentialDelay as pi,ErrorCategory as B,ValueSubject as fi}from"@vkontakte/videoplayer-shared/evergreen";var oe=class{constructor(e){this.params=e,this.authorized$=new fi(!1),this.consequentAuthErrors=0}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this.authorizeWithBackoff()}logBeacon(e){let i="log.logUvStat",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e).catch(()=>{})}async logRequest(e){let i="log.logUvStat",t=this.createLogParams(e),o={},n=this.sessionKey??await this.authorizeWithBackoff();if(!n)return;let c=async(h,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,n,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:B.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let g=p?.error_code;switch(g){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),l>0?c(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),l>0?c(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:B.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return c(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${P}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=pi(this.consequentAuthErrors);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(async()=>{try{let t=await this.doAuthorize();i(t)}catch(t){this.params.error$.next({id:"AuthorizeBackoff",category:B.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})}finally{this.backoffTimeoutId=0}},e))})}doAuthorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.deviceId,client_version:P.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:B.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this.authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:B.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:B.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{now as Re,ErrorCategory as re}from"@vkontakte/videoplayer-shared/evergreen";var se=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Le[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this.prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:re.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let n=Re(),c=h=>{if(h instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(h.message)){this.params.error$.next({id:"Network",category:re.NETWORK,message:"Request failed",thrown:h});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:re.NETWORK,message:"Unhandled request error",thrown:h,data:{method:e,params:i,sessionKey:t,time:Re()-n}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded",...o},body:this.prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(h=>{let l=Number(h.headers.get("content-length"))===0,p=new Date(h.headers.get("date")??"").getTime(),g=Re()-n;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,g),!l)return h.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,c)},c)}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"ThinOneStat:ApiTransport:resolveApiBaseUrl",category:re.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Le.vk_alias}finally{this.isApiBaseUrlFetched=!0}}prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as gi,now as mi,safeStorage as z,debounceFn as bt}from"@vkontakte/videoplayer-shared/evergreen";var ne="thinonestat_events",De=a=>e=>e.client_time+a>=mi(),ae=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{event_name:i}=e;return["watch_coverage","watch_coverage_live","watched_n","playback_started"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=bt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=z.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=bt(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:gi.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=z.get(ne);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(De(this.params.config.storageExpiration));z.set(ne,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(De(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],z.set(ne,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(De(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}z.set(ne,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.vsid)}flush({wantBeacon:e,clearStorage:i}={wantBeacon:!1,clearStorage:!0}){let t=this.getFromStorage();t.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${t.length} events through beacon`}),this.api.logBeacon(t)):(this.loggerDebugLog({message:`Flushing ${t.length} events`}),this.api.logRequest(t)),i&&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()}};function Ne(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}var de=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};import{PlaybackState as vt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as bi,Subscription as vi,ValueSubject as Ii,Subject as Me,fromEvent as yi,isNullable as It,merge as j,filter as yt,filterChanged as St,getWindow as Ve}from"@vkontakte/videoplayer-shared/evergreen";var _t=(a,e,i)=>new bi(t=>{let o=new vi,n=new Ii(void 0),c;o.add(a.info.isLive$.pipe(St()).subscribe(L=>{c&&(c.unsubscribe(),n.next(void 0)),L?c=a.info.liveTime$.pipe(St()).subscribe(n):c=a.info.position$.subscribe(n),o.add(c)}));let{playing$:h,paused$:l,ended$:p,looped$:g}=a.events,s=a.events.willSeek$.pipe(yt(()=>a.info.playbackState$.getValue()===vt.PLAYING)),r=a.events.seeked$.pipe(yt(()=>a.info.playbackState$.getValue()===vt.PLAYING)),d=!1,u=new Me;o.add(s.subscribe(()=>{d||u.next(),d=!0})).add(r.subscribe(()=>d=!1));let f=j(yi(Ve(),"beforeunload"),a.events.willDestruct$),m,v=()=>m=n.getValue(),T=()=>{let L=n.getValue();It(m)||It(L)||m===L||(t.next({from:m,to:L}),m=void 0)},E=new Me,S=new Me,b=j(h,r,E),_=j(l,u,f,p,g,S),We=e.started$&&e.ended$?j(b,e.ended$):b,Qe=e.started$&&e.ended$?j(_,e.started$):_;if(o.add(We.subscribe(v)).add(Qe.subscribe(T)),i.heartbeatInterval&&isFinite(i.heartbeatInterval)){let L=[],Vt=()=>{S.next(),E.next()};o.add(We.subscribe(()=>{let fe=Ve().setTimeout(Vt,i.heartbeatInterval);L.push(fe)})).add(Qe.subscribe(()=>{L.forEach(fe=>{Ve().clearTimeout(fe)}),L=[]}))}return o});import{Subscription as Si}from"@vkontakte/videoplayer-core/evergreen";import{Observable as _i,merge as Pi}from"@vkontakte/videoplayer-shared/evergreen";var Pt=(a,e)=>new _i(i=>{let t=new Si;return t.add(Pi(a.info.position$,a.info.liveTime$).subscribe(()=>{let o=e.getTotalViewTime();o>=e.targetDuration&&(i.next({target_duration:e.targetDuration,current_tvt:o}),t.unsubscribe())})),t});import{Subscription as Ti}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Ei,filter as wi,getWindow as Tt}from"@vkontakte/videoplayer-shared/evergreen";var Et=(a,{maxTimeWindow:e})=>new Ei(i=>{let t=new Ti,o={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:e,minTimeWindow:2e3},n={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},c=()=>{n.timeoutId&&(Tt().clearTimeout(n.timeoutId),n.timeoutId=null)},h=()=>{n.bytes=0,n.startTime=0,n.lastEmitTime=0,c()},l=s=>{if(n.bytes<o.minBytesThreshold||s-n.lastEmitTime<o.minTimeWindow&&n.lastEmitTime>0)return!1;let u=(n.startTime>0?s-n.startTime:0)>=o.maxTimeWindow,f=n.bytes>=o.maxBytesThreshold;return u||f},p=(s=!1)=>{let r=Date.now();if(!s&&!l(r))return;c();let d=n.startTime>0?r-n.startTime:Math.max(o.minTimeWindow,1),u=n.bytes/(d/1e3);i.next({download_bytes:Math.round(n.bytes),download_speed:Math.round(u)}),n.lastEmitTime=r,h()},g=()=>{if(c(),n.startTime>0&&n.bytes>=o.minBytesThreshold){let r=Date.now()-n.startTime,d=o.maxTimeWindow-r;d>100?n.timeoutId=Tt().setTimeout(()=>{n.timeoutId=null,p()},d):d>0&&p()}};return t.add(a.info.httpDownloadMetrics$.pipe(wi(s=>s!==void 0)).subscribe(s=>{let r=Date.now();n.startTime===0&&(n.startTime=r),n.bytes+=s.bytes,l(r)?p():g()})),t.add(()=>{if(c(),n.bytes>0){let s=Date.now(),r=n.startTime>0?s-n.startTime:o.minTimeWindow,d=n.bytes/(r/1e3);i.next({download_bytes:Math.round(n.bytes),download_speed:Math.round(d)})}h()}),t});import{Observable as Ai,Subscription as xi,merge as wt}from"@vkontakte/videoplayer-shared/evergreen";var At=a=>new Ai(e=>{let i=new xi,t=0,o=1,n=0,c=!1,h=!1,l=()=>{if(!c)return;let b=Date.now();n+=(b-t)*o,t=b},p=()=>{(!c||h)&&(t=Date.now(),c=!0,h=!1)},g=()=>{c&&(l(),c=!1)},s=()=>{c&&(l(),c=!1,h=!0)},r=b=>{c&&l(),o=b,t=Date.now()},{started$:d,playing$:u,paused$:f,willSeek$:m,ended$:v,willDestruct$:T}=a.events,{currentPlaybackRate$:E}=a.info;i.add(m.subscribe(s)).add(wt(d,u).subscribe(p)).add(wt(f,v,T).subscribe(g)).add(E.subscribe(r));let S=()=>{let b=n;return c&&(b+=(Date.now()-t)*o),b};return e.next(S),i});import{assertNever as xt}from"@vkontakte/videoplayer-shared/evergreen";import{HttpConnectionType as Oe,Surface as F,VideoFormat as I,VideoQuality as A}from"@vkontakte/videoplayer-core/evergreen";var Be=a=>a&&{[Oe.HTTP1]:"http1",[Oe.HTTP2]:"http2",[Oe.QUIC]:"http3"}[a],G=a=>{if(a!==void 0)switch(a){case I.MPEG:return"MP4";case I.DASH:case I.DASH_LIVE:return"DASH";case I.DASH_SEP:return"DASH_SEP";case I.DASH_ONDEMAND:return"ONDEMAND_DASH";case I.HLS_ONDEMAND:return"ONDEMAND_HLS";case I.HLS:case I.HLS_LIVE:return"HLS";case I.HLS_FMP4:return"HLS_FMP4";case I.DASH_WEBM:case I.DASH_LIVE_WEBM:return"WEBM";case I.DASH_LIVE_CMAF:return"ONDEMAND_DASH_LIVE";case I.HLS_LIVE_CMAF:return"ONDEMAND_HLS_LIVE";case I.WEB_RTC_LIVE:return"WEBRTC";case I.DASH_WEBM_AV1:return"AV1";case I.DASH_STREAMS:return"MULTI_DASH";default:return xt(a)}},x=a=>{if(a!==void 0)switch(a){case A.Q_144P:return"144p";case A.Q_240P:return"240p";case A.Q_360P:return"360p";case A.Q_480P:return"480p";case A.Q_720P:return"720p";case A.Q_1080P:return"1080p";case A.Q_1440P:return"1440p";case A.Q_2160P:return"2160p";case A.INVARIANT:case A.Q_576P:case A.Q_4320P:return"UNKNOWN";default:return xt(a)}},kt=a=>{if(a!==void 0)switch(a){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}},N=(a,e,i)=>{if(a&&e)switch(a){case I.MPEG:return i&&e[a]&&e[a][i];default:return e[a]?.url}},ce=(a,e=!1)=>{if(e)return"minimal";switch(a){case void 0:case F.NONE:return;case F.INLINE:return"inline";case F.FULLSCREEN:return"fullscreen";case F.SECOND_SCREEN:return"chromecast";case F.PIP:return"pip_external"}},le=a=>{switch(a){case void 0:return;case F.INVISIBLE:return"background";default:return"foreground"}};var Vi="_thin-one-stat_",Lt=`${Vi}deviceId`,Rt=()=>{let a=new He;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},he=class{constructor(e,i){this.debugLogger=new Li;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.playerSize={width:0,height:0};this.seekAction$=new Ue("unknown");this.isid$=new Ue(void 0);this.getTotalViewTime=()=>0;this.statContext=e,this.config=mt(i.config??{}),this.subscription=new He,this.config.synchronizeTime&&(this.timeSynchronisation=new de);let t=new Mi,o=$t.get(Lt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=Ne(),$t.set(Lt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??q());let n=new se({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new oe({config:this.config,apiTransport:n,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new ae({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,topOrigin:h}=Ci();this.isEmbed=c,this.embedHostname=h?new URL(h).hostname:void 0}get vsid$(){return new Ue(D.getVSID())}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,i){let t=new He,o=(s,r)=>t.add(s.subscribe(r));o(At(e),s=>{this.getTotalViewTime=s}),o(e.info.isLive$,s=>this.isLive=s);let n;o(ue({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(k(({hostname:s})=>s!==void 0),k(({connectionType:s})=>s!==void 0),k(({connectionReused:s})=>s!==void 0)),({hostname:s,connectionType:r,connectionReused:d})=>{if(n!==void 0&&n!==s){let f={cdn_host:s,connection_type:Be(r),connection_reused:d,content_type:G(e.info.currentFormat$.getValue())};this.logFailover(f)}this.cdnHostname=n=s}),o(e.info.httpConnectionType$,s=>{this.connectionType=Be(s)}),o(e.info.httpConnectionReused$,s=>{this.connectionReused=s}),o(_t(e,i,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),s=>{let r=Math.round(s.from*1e3),d=Math.round(s.to*1e3),u={watch_interval:`${r}-${d}`,in_history:!!this.statContext.inHistory,content_type:G(e.info.currentFormat$.getValue()),playback_quality:x(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(u);else{let m=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...u,live:!!m})}}),o(Pt(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),s=>{this.logWatchedN(s)}),o(e.events.willReady$,()=>{if(this.statContext.preload){let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentBuffer$.getValue(),u=e.info.currentQuality$.getValue(),f={target_buffer_time:this.calcBufferTime(d),playback_url:N(s,r,u),playback_quality:x(u)};this.logPreloadStarted(f)}}),o(e.events.manifestRequested$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(u)}),o(e.events.firstBytesManifest$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(u)}),o(e.events.manifestReceived$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(u)}),o(e.events.firstBytesRequested$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(u)}),o(e.events.firstBytesReceived$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(u)}),o(Ct(e.events.willStart$,e.events.looped$),s=>{s&&this.resetViewSession();let d={isid:this.isid$.getValue(),stream_profile:kt(G(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*$.display.pixelRatio,web_layout:this.statContext.isMobile||$.device.isMobile?"mobile":"desktop",preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(d.iframe_host=this.embedHostname??"unknown"),this.logStartSession(d)}),o(e.events.started$,()=>{this.isStarted=!0;let s=e.info.currentBuffer$.getValue(),r=e.info.currentQuality$.getValue(),d=e.info.isAutoQualityEnabled$.getValue(),u=e.info.muted$.getValue(),f=e.info.volume$.getValue(),m=e.info.surface$.getValue(),v=e.info.availableTextTracks$.getValue(),T=e.info.currentTextTrack$.getValue(),E=e.info.currentAudioStream$.getValue(),S=e.info.currentPlaybackRate$.getValue(),b={playback_quality:x(r),user_quality:d?"auto":x(r),player_width:this.statContext.playerSize?.width??this.playerSize.width,player_height:this.statContext.playerSize?.height??this.playerSize.height,muted:u,sound_volume:Math.round(f*100),buffer_time:this.calcBufferTime(s),mode:ce(m,this.statContext.isPreviewPlayerView),visibility:le(m),subtitles_enabled:T?!!T:this.currentSubtitle?.enabled,auto_subtitles:v.find(({id:_})=>_===T)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:E?.language,playback_rate:S,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(b)}),o(e.events.willStart$,()=>{this.logPlay()}),o(e.events.playing$,()=>{let s=e.info.currentBuffer$.getValue(),r={buffer_time:this.calcBufferTime(s)};this.logPlaying(r),this.wasPaused&&this.logResume()}),o(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),o(e.events.willStop$,()=>{this.logStop()}),o(Ct(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let c=s=>{switch(s){case U.NETWORK:return"network";case U.VIDEO_PIPELINE:return"video_pipeline";case U.EXTERNAL_API:return"external_api";case U.PARSER:return"parser";case U.DOM:return"dom";default:return"wtf"}},h=s=>U.FATAL===s?"critical":"informative";o(e.events.fetcherRecoverableError$,({id:s,category:r,data:d,message:u,httpCode:f,UVBackendErrorCode:m})=>{let v={error_severity:h(r),error_category:c(r),player_error_code:s,player_error_trace:d,http_error_code:f,uv_backend_error_code_subcode:m,error_message:u};this.logError(v),h(r)==="critical"&&this.logCannotPlay()}),o(e.events.managedError$,({id:s,category:r,data:d,message:u})=>{let f={error_severity:h(r),error_category:c(r),player_error_code:s,player_error_trace:d,error_message:u};this.logError(f)}),o(e.events.fatalError$,({id:s,category:r,data:d,message:u})=>{let f={error_severity:"critical",error_category:c(r),player_error_code:s,player_error_trace:d,error_message:u};this.logError(f),this.logCannotPlay()}),o(ue({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(k(({connectionReused:s})=>s!==void 0),k(({connectionMetrics:s})=>s!==void 0),Ri((s,r)=>s.connectionType===r.connectionType)),({connectionMetrics:s})=>{let r=e.info.currentFormat$.getValue(),d=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),f=e.info.rttEstimation$.getValue(),m={playback_url:N(r,d,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:f?Math.round(f):void 0,network_type:this.statContext.networkType??s?.networkType,dns_resolve_time:s?.dnsResolveTime,tcp_handshake_time:s?.tcpHandshakeTime,tls_handshake_time:s?.tlsHandshakeTime};this.logConnectionEstablished(m)}),o(Et(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),s=>{this.logDownloadBytes(s)}),o(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),o(e.events.willSeek$,()=>{let s={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(s)}),o(e.events.seeked$,()=>{let s={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(s),this.seekAction$.next("unknown")}),o(e.info.isStalled$,s=>{let r=e.info.currentBuffer$.getValue(),d=this.calcBufferTime(r);s&&d&&d>0&&this.logBufferStarvation({buffer_time:d})}),o(e.info.currentBuffer$.pipe(k(s=>!!this.calcBufferTime(s)),Di()),s=>{let r=this.calcBufferTime(s);if(this.statContext.preload){let d={buffer_time:r};this.logPreloadEnded(d)}this.logReady({buffer_time:r})});let l;o(ue({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(k(({videoStream:s,audioStream:r})=>s!==void 0&&r!==void 0),k(({quality:s})=>s!==void 0)),({videoStream:s,audioStream:r,quality:d})=>{if(l!==d){let u=e.info.isAutoQualityEnabled$.getValue(),f=s?.codec,m=r?.codec,v={user_quality:u?"auto":x(d),playback_quality:x(l),download_quality:x(d),codec_info:f&&m?`${f},${m}`:void 0};l=d,this.logQualityChanged(v)}});let p,g;return o(e.info.surface$,s=>{let r=ce(s,this.statContext.isPreviewPlayerView);r&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:r}),g=le(s),p!==g&&this.isStarted&&(p=le(s),this.logVisibilityChanged({visibility:g}))}),o(ue({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:r})=>{if(this.isStarted){let d={muted:s,sound_volume:Math.round(r*100)};this.logSoundChanged(d)}}),o(e.info.currentFormat$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={content_type:G(s),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(r)}),o(e.info.currentAudioStream$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={audio_track_lang:s.language,codec_info:s.codec};this.logAudioTrackSwitched(r)}),o(e.info.currentVideoStream$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={hdr:s.hdr,codec_info:s.codec};this.logVideoTrackSwitched(r)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscribe:i,subscription:t}=Rt();i(e.actionSeek$,this.seekAction$),i(e.playerSize$,({width:n,height:c})=>{n&&c&&(this.playerSize={width:n,height:c},this.isStarted&&this.logViewPortChanged({player_width:n,player_height:c}))}),i(e.isLoaderVisible$,n=>{n&&this.isStarted&&this.logShowLoader()}),i(e.actionSubtitlesSwitched$,n=>{if(this.currentSubtitle={...n},this.isStarted){let c={subtitles_enabled:n.enabled,subtitles_track_lang:n.lang,auto_subtitles:n.auto};this.logSubtitlesSwitched(c)}});let{surface$:o}=ee(this.uiEvents,i,this.player);return i(o,n=>{this.isStarted&&this.logModeChanged({mode:ce(n)})}),i(e.actionQuality$,n=>{let c=g=>Object.values($e).includes(g),h=this.player?.info.currentVideoStream$.getValue()?.codec,l=this.player?.info.currentAudioStream$.getValue()?.codec,p={user_quality:c(n)?"auto":x(n),playback_quality:x(this.player?.info.currentQuality$.getValue()),download_quality:x(this.player?.info.currentQuality$.getValue()),codec_info:h&&l?`${h},${l}`:void 0};this.logQualityChangeRequested(p)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:i,subscribe:t}=Rt();return t(e.init$,o=>{let n={slot:o};this.logAdvConfiguration(n)}),t(e.slotRequested$,()=>{this.logAdvRequest()}),t(e.started$,o=>{let n={adv_section:o};this.logAdvBreakStarted(n)}),t(e.ended$,o=>{let n={adv_section:o};this.logAdvBreakEnded(n)}),t(e.error$,o=>{let n={error_message:o};this.logAdvError(n)}),this.resubscribeBeforeunload(),this.subscription.add(i),i}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),D.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}createRequiredParams(e){let i=this.vsid$.getValue();ki(i);let t=this.eventNumber++,o=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,n={vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${P}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||$.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:o,current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let c of this.config.disabledParams)delete n[c];return n}createRequiredFatParams(){let e={stats_version:"2.1.1",browser:this.statContext.browser??$.browser.current,browser_version:this.statContext.browserVersion??String($.browser.currentVersion),os:this.statContext.os??$.device.os.name,os_version:this.statContext.osVersion??$.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||$.device.isMobile?"mobile":"desktop"),device_manufacturer:this.statContext.deviceManufacturer??$.device.details.vendor,device_model:this.statContext.deviceModel??$.device.details.model,navigation:this.statContext.navigation};for(let i of this.config.disabledParams)delete e[i];return e}log(e,i,t=!1){if(this.config.disabledEvents.includes(e))return;let o=this.createRequiredParams(e),n={};t&&(n=this.createRequiredFatParams()),this.logger.log({...o,...n,...i})}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)}logAdvConfiguration(e){this.log("adv_configuration",e)}logAdvRequest(){this.log("adv_request")}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=$i(Ni(),"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};var Oi={};import{PlaybackState as Mt,Subscription as Bi}from"@vkontakte/videoplayer-core/evergreen";import{Logger as Fi}from"@vkontakte/videoplayer-shared/evergreen";var pe=class{constructor(){this.startTime=null;this.stopTime=null;this.accumulatedTime=0}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime!==null?(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null):this.startTime=this.now())}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}};var Nt=()=>window.Image?new Image:document.createElement("img");var qe=class{constructor(e){this.position=0;this.started=!1;this.heartbeatPixels=[];this.heartbeatLastTimeSent={};this.idleCallbackIds=[];this.stopwatch=new pe;this.subscription=new Bi;this.params=e;let i=new Fi;this.log=i.createComponentLog("MediascopePixel")}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(i=>this.onPlaybackState(i))).add(e.info.position$.subscribe(i=>this.onPosition(i))).add(e.info.atLiveEdge$.subscribe(i=>this.isActiveLive=i)),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=>window.cancelIdleCallback(e)),this.send("stop")}onPlaybackState(e){e===Mt.PLAYING?this.started?this.play():this.start():e===Mt.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,i=this.heartbeatPixels[0]?.delay;if(i!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},i*1e3)}catch(t){this.log({message:t.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[i,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[i]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[i]=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,i){return e?.filter(t=>t.event===i.event&&i.keys.every(o=>!!t[o]))}getFrameTimestamp(){let e;if(this.isActiveLive){let i=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-i}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(i=>!/={@[a-zA-Z_]+}/.test(i)).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(requestIdleCallback(()=>Nt().src=this.prepareUrl(e)))}catch(i){this.log({message:i.message})}}send(e){let i=this.preparePixels(e);for(let{url:t}of i)this.call(t)}sendHeartbeat(e){this.call(e)}};export{H as ApiEnv,be as ConnectionType,me as ContentType,Ke as InteractiveInterfaceClick,qe as MediascopePixel,Oi as MediascopePixelTypes,Ce as OneStat,ge as Quality,ve as SeekAction,Dt as ThinOneStat,P as VERSION};
6
+ var e=Object.defineProperty,t=e=>e;function n(e,n){this[e]=t.bind(null,n)}var r=(t,r)=>{for(var i in r)e(t,i,{get:r[i],enumerable:!0,configurable:!0,set:n.bind(r,i)})},i;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(i||={});var a;(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`})(a||={});var o;(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`})(o||={});var s;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(s||={});var c;(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`})(c||={});var l;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(l||={});var u={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`},d={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`},f={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},p={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`};import{fillWithDefault as m}from"@vkontakte/videoplayer-shared/evergreen";var h=`CIOPGQJGDIHBABABA`,g={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:``},_={apiEnv:`vk_alias`,apiKey:h,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:!1},v=e=>m(e,_);function y(){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 b,combine as x,fromEvent as S,isNonNullable as C,isNullable as w,merge as ee,now as T,observableFrom as te,once as ne,safeStorage as re,Subject as ie,Subscription as E,ValueSubject as D}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as ae,detectEmbed as oe}from"@vkontakte/videoplayer-shared/evergreen";var se=()=>Math.floor(Math.random()*2**32).toString(36).padStart(13,`0`),ce=()=>Math.floor(Math.random()*2**64).toString(36).padStart(13,`0`);class O{static vsid;static getVSID(){return O.vsid}static generateVSID(e){return O.vsid=e?ce():se(),O.vsid}}var le=e=>{let{operation:t,custom:n}=e,r=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=d[e]??e,r=t;return t&&(e===`mode`?r=p[t]??t:e===`quality`&&(r=f[t]??t)),[n,r]}));return{...e,operation:u[t]??t,custom:r}},k=`1.0.100-dev.319d6ebf.0`;import{ValueSubject as ue,getExponentialDelay as de,ErrorCategory as A}from"@vkontakte/videoplayer-shared/evergreen";var fe=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class pe{params;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new ue(!1);backoffTimeoutId;constructor(e){this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}async logRequest(e){let t=`log.externalLog`,n=this.createLogParams(e),r=this.sessionKey??await this._authorizeWithBackoff();if(!r)return;let i=async(e,a=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(t,n,r)}catch(n){if(!n||!(`error_code`in n)){this.params.error$.next({id:`logRequestUnknown`,category:A.NETWORK,message:`Unknown ${t} error`,thrown:n});return}let r=n?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),a>0?i(e,a-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),a>0?i(e,a-1):void 0;default:this.params.error$.next({id:`LogRequest#${r}`,category:A.EXTERNAL_API,message:`${t} error`,data:n});return}}};return i(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0}),this.refreshAuthTokenPromise}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${k}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=window.navigator;n=fe.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(le):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=de(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(()=>{this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:A.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})).finally(()=>this.backoffTimeoutId=0)},e)})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e={session_data:{version:2,device_id:this.params.deviceId,client_version:k.split(`-`)[0],client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(`auth.anonymLogin`,e).then(e=>((!e||!e.session_key)&&this.params.error$.next({id:`AuthorizeFailed`,category:A.EXTERNAL_API,message:`No session key`,data:e}),this.sessionKey=e?.session_key??void 0,this.sessionKey)).catch(async e=>{this.sessionKey=void 0;let t=e?.error_code;switch(t){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}t?this.params.error$.next({id:`Authorize#${t}`,category:A.EXTERNAL_API,message:`authorize error`,data:e}):this.params.error$.next({id:`AuthorizeUnknown`,category:A.NETWORK,message:`authorize error`,thrown:e})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}import{ErrorCategory as j,now as me}from"@vkontakte/videoplayer-shared/evergreen";class he{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??g[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==`auto`||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),t=(await(await fetch(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return t}catch(e){return this.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:j.NETWORK,message:`Unhandled resolve api base url error`,thrown:e}),g.vk_alias}finally{this.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:j.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}async sendRequest(e,t,n){let r=me(),i=i=>{if(i instanceof TypeError&&[`Failed to fetch`,`NetworkError when attempting to fetch resource.`].includes(i.message)){this.params.error$.next({id:`Network`,category:j.NETWORK,message:`Request failed`,thrown:i});return}this.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:j.NETWORK,message:`Unhandled request error`,thrown:i,data:{method:e,params:t,sessionKey:n,time:me()-r}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let a={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:this._prepareQueryParams({method:e,queryParams:t,sessionKey:n})};return this.params.config.useKeepalive&&(a.keepalive=!0),fetch(`${this.apiBaseUrl}/fb.do`,a).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),a=me()-r;if(isFinite(n)&&this.timeSynchronisation?.addServerTime(n,a),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,i)},i)}_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),Object.entries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}import{ErrorCategory as ge,now as _e,safeStorage as M,debounceFn as ve}from"@vkontakte/videoplayer-shared/evergreen";var N=`onestat_events`,ye=e=>t=>t.timestamp+e>=_e();class be{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;loggerDebugLog;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`),this.firstFlush=ve(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let t=M.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=ve(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{let{operation:t}=e;return[`action_play`,`watch_coverage_record`,`watch_coverage_live`].includes(t)};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:ge.WTF,message:e?String(e):`Unknown logger error`,thrown:e})}}readFromStorage(){let e=M.get(N);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let t=this.readFromStorage(),n=(t[this.userSalt]??[]).filter(ye(this.params.config.storageExpiration));M.set(N,JSON.stringify({...t,[this.userSalt]:[...n,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(ye(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],M.set(N,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of Object.entries(e)){let r=n.filter(ye(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`})}M.set(N,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 xe,Surface as P,VideoFormat as F,VideoQuality as I}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as Se}from"@vkontakte/videoplayer-shared/evergreen";var Ce=e=>e&&{[I.INVARIANT]:`unknown`,[I.Q_144P]:`mobile`,[I.Q_240P]:`lowest`,[I.Q_360P]:`low`,[I.Q_480P]:`medium`,[I.Q_576P]:`unknown`,[I.Q_720P]:`high`,[I.Q_1080P]:`fullhd`,[I.Q_1440P]:`quadhd`,[I.Q_2160P]:`ultrahd`,[I.Q_4320P]:`unknown`}[e],we=e=>e&&{[xe.HTTP1]:`http1`,[xe.HTTP2]:`http2`,[xe.QUIC]:`http3`}[e],Te=e=>{if(e!==void 0)switch(e){case F.MPEG:return`mp4`;case F.DASH:case F.DASH_LIVE:case F.DASH_STREAMS:return`dash`;case F.DASH_SEP:return`dash_sep`;case F.DASH_ONDEMAND:return`ondemand_dash`;case F.DASH_WEBM:case F.DASH_LIVE_WEBM:return`webm`;case F.DASH_WEBM_AV1:return`av1`;case F.DASH_LIVE_CMAF:return`ondemand_dash_live`;case F.HLS:case F.HLS_LIVE:return`hls`;case F.HLS_FMP4:return`hls_fmp4`;case F.HLS_ONDEMAND:return`ondemand_hls`;case F.HLS_LIVE_CMAF:return`ondemand_hls_live`;case F.WEB_RTC_LIVE:return`webrtc`;default:return Se(e)}},Ee=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case P.NONE:case P.INLINE:return;case P.FULLSCREEN:return`fullscreen`;case P.SECOND_SCREEN:return`chromecast`;case P.PIP:return`pip`;case P.INVISIBLE:return`invisible`;default:return Se(e)}},De=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class Oe{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}import{PlaybackState as ke}from"@vkontakte/videoplayer-core/evergreen";import{filter as Ae,filterChanged as je,fromEvent as Me,isNullable as Ne,map as Pe,merge as Fe,Observable as Ie,Subject as Le,Subscription as Re,ValueSubject as ze}from"@vkontakte/videoplayer-shared/evergreen";var Be=(e,t)=>new Ie(n=>{let r=new Re,i=Fe(Me(window,`beforeunload`),e.events.willDestruct$),a=new ze(void 0),o;r.add(e.info.isLive$.pipe(je()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(Pe(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c}=e.events,l=e.events.willSeek$.pipe(Ae(()=>e.info.playbackState$.getValue()===ke.PLAYING)),u=e.events.seeked$.pipe(Ae(()=>e.info.playbackState$.getValue()===ke.PLAYING)),d=!1,f=new Le;r.add(l.subscribe(()=>{d||f.next(),d=!0})),r.add(u.subscribe(()=>d=!1));let p=new Le,m=new Le,h=Fe(s,u,p),g=Fe(c,f,i,e.events.looped$,m),_,v=()=>_=a.getValue(),y=()=>{let e=a.getValue();Ne(_)||_===e||Ne(e)||(n.next({from:_,to:e}),_=void 0)},b=()=>{m.next(),p.next()};if(r.add(h.subscribe(v)),r.add(g.subscribe(y)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(h.subscribe(()=>{n(),e=window.setTimeout(b,t.forceInterval)})),r.add(g.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(h.subscribe(()=>e=window.setTimeout(b,t.forceInterval))),r.add(g.subscribe(()=>window.clearTimeout(e)))}return r});import{Surface as L}from"@vkontakte/videoplayer-core/evergreen";import{debounce as Ve,filterChanged as He,Subject as Ue}from"@vkontakte/videoplayer-shared/evergreen";var We=(e,t,n)=>{let r=new Ue,i=r.pipe(Ve(0),He()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?L.PIP:o?L.FULLSCREEN:s?L.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?L.FULLSCREEN:a?L.PIP:s?L.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case L.SECOND_SCREEN:case L.NONE:case L.INLINE:!o&&!a&&(e===L.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},Ge=`_one-stat_deviceId`,R=()=>{let e=new E;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Ke{api;logger;config;subscription=new E;beforeunloadSubscription;timeSynchronisation;debugLogger=new ae;oneStatDebugLog=this.debugLogger.createComponentLog(`onestat`);loopCounter=0;disabled=!1;experimental;get vsid$(){return new D(O.getVSID())}isid$=new D(void 0);zenUid$=new D(void 0);statContext;isEmbed;embedParent;uiEvents;player;seekAction$=new D(`unknown`);deviceId;constructor(e,t){this.statContext=e,this.config=v(t.config??{}),C(t.apiEnv)&&(this.config.apiEnv=t.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Oe);let n=new ie;this.experimental={error$:n};let r=re.get(Ge);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=y(),re.set(Ge,this.deviceId)),this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??ce()),this.zenUid$.next(t.zenUid);let i=new he({config:this.config,error$:n,timeSynchronisation:this.timeSynchronisation});this.api=new pe({config:this.config,apiTransport:i,refreshAuthToken:t.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:n,vktvVersion:t.vktvVersion}),this.logger=new be({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:n,userSalt:t.userSalt});let{isEmbed:a,topOrigin:o}=oe();this.isEmbed=a,this.embedParent=o?new URL(o).hostname:void 0,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let t=new E,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(Be(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),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=T():(C(r)&&this.logEmptyBuffer({duration:T()-r}),r=void 0)});let i=!1;t.add(e.events.fatalError$.pipe(ne()).subscribe(()=>i=!0)),n(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let e=C(r)?T()-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=T(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>o=T()),n(e.info.currentBuffer$,e=>{!s&&e&&e.end-e.start>0&&C(a)&&(this.logPlayerReady({duration:T()-a}),s=!0)}),n(e.events.firstFrame$,()=>{C(a)&&!s&&(this.logPlayerReady({duration:T()-a}),s=!0),C(o)&&this.logFirstFrame({time:T()-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(x({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=Ce(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:Te(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:we(e)}),this.updateContext({connectionType:we(e)})}),n(e.info.httpConnectionReused$,e=>{w(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:Ee(e,this.statContext.isPreviewPlayerView)})}),n(x({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}=R();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}=We(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:Ee(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}=R();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}=R();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`}),O.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(ee(S(e,`change`),te([`init`])).subscribe(()=>this.updateContext({network:De(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=S(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(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let n=this.createLogItem(e,t);this.logger.log(n)}createLogItem({operation:e,param:t,time:n},r={}){let i=this.timeSynchronisation?.now()??T(),a=this.vsid$.getValue();b(a);let o=this.isid$.getValue(),s=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,l,u;if(this.isEmbed||this.statContext.place===`embed`){l=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>this.config.embedUrlParams.includes(e));u=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;l=e&&URL.canParse(e)?new URL(e).hostname:e,u=location.href.substring(0,1024)}let d={vsid:a,isid:o,vid:this.statContext.movieId,uid:this.zenUid$.getValue(),ct:this.statContext.contentType,place:this.isEmbed?`embed`:this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?`auto`:this.statContext.autoplay===!1?``:void 0,param:t,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:s,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:l,direct_url:u,rate:this.statContext.rate===1||w(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,...r};for(let e of this.config.disabledCustomFields)delete d[e];return{operation:e,type:1,time:n,network:this.statContext.network,timestamp:i,custom:d}}}var qe={};r(qe,{VERSION:()=>k,ThinOneStat:()=>an,ActionSeekType:()=>lt});import{assertNonNullable as Je,detectEmbed as Ye,fromEvent as Xe,Logger as Ze,merge as Qe,combine as z,filter as B,filterChanged as $e,once as et,skip as tt,safeStorage as nt,getWindow as rt,Subject as it,Subscription as at,ValueSubject as ot,ErrorCategory as V}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as H}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as st}from"@vkontakte/videoplayer-shared/evergreen";var ct;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(ct||={});var lt;(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`})(lt||={});var ut=`CIOPGQJGDIHBABABA`,dt={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:``},ft={apiKey:ut,apiEnv:`okcdn`,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*60*1e3,watchCoverageHeartbeatInterval:3e4,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNDefaultTargetDuration:1e3,downloadBytesMaxTime:3e4},pt=e=>st(e,ft);import{getExponentialDelay as mt,ErrorCategory as U,ValueSubject as ht}from"@vkontakte/videoplayer-shared/evergreen";class gt{authorized$;params;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors;backoffTimeoutId;constructor(e){this.params=e,this.authorized$=new ht(!1),this.consequentAuthErrors=0}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this.authorizeWithBackoff()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}async logRequest(e){let t=`log.logUvStat`,n=this.createLogParams(e),r={},i=this.sessionKey??await this.authorizeWithBackoff();if(!i)return;let a=async(e,o=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(t,n,i,r)}catch(n){if(!n||!(`error_code`in n)){this.params.error$.next({id:`logRequestUnknown`,category:U.NETWORK,message:`Unknown ${t} error`,thrown:n});return}let r=n?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),o>0?a(e,o-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),o>0?a(e,o-1):void 0;default:this.params.error$.next({id:`LogRequest#${r}`,category:U.EXTERNAL_API,message:`${t} error`,data:n});return}}};return a(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0}),this.refreshAuthTokenPromise}createLogParams(e){return{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${k}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=mt(this.consequentAuthErrors);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(async()=>{try{t(await this.doAuthorize())}catch(e){this.params.error$.next({id:`AuthorizeBackoff`,category:U.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})}finally{this.backoffTimeoutId=0}},e)})}doAuthorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e={session_data:{version:2,device_id:this.params.deviceId,client_version:k.split(`-`)[0],client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(`auth.anonymLogin`,e).then(e=>((!e||!e.session_key)&&this.params.error$.next({id:`AuthorizeFailed`,category:U.EXTERNAL_API,message:`No session key`,data:e}),this.sessionKey=e?.session_key??void 0,this.sessionKey)).catch(async e=>{this.sessionKey=void 0;let t=e?.error_code;switch(t){case 401:return this.authToken=await this.refreshAuthToken(),this.authorizeWithBackoff()}t?this.params.error$.next({id:`Authorize#${t}`,category:U.EXTERNAL_API,message:`authorize error`,data:e}):this.params.error$.next({id:`AuthorizeUnknown`,category:U.NETWORK,message:`authorize error`,thrown:e})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}import{now as _t,ErrorCategory as W}from"@vkontakte/videoplayer-shared/evergreen";class vt{params;apiKey;apiBaseUrl;apiEnv;isApiBaseUrlFetched;timeSynchronisation;constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??dt[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}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:W.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}async sendRequest(e,t,n,r){let i=_t(),a=r=>{if(r instanceof TypeError&&[`Failed to fetch`,`NetworkError when attempting to fetch resource.`].includes(r.message)){this.params.error$.next({id:`Network`,category:W.NETWORK,message:`Request failed`,thrown:r});return}this.params.error$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:W.NETWORK,message:`Unhandled request error`,thrown:r,data:{method:e,params:t,sessionKey:n,time:_t()-i}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`,...r},body:this.prepareQueryParams({method:e,queryParams:t,sessionKey:n})}).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),r=_t()-i;if(isFinite(n)&&this.timeSynchronisation?.addServerTime(n,r),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)}async resolveApiBaseUrl(){if(this.apiEnv!==`auto`||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),t=(await(await fetch(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return t}catch(e){return this.params.error$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:W.NETWORK,message:`Unhandled resolve api base url error`,thrown:e}),dt.vk_alias}finally{this.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),Object.entries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}import{ErrorCategory as yt,now as bt,safeStorage as G,debounceFn as xt}from"@vkontakte/videoplayer-shared/evergreen";var K=`thinonestat_events`,St=e=>t=>t.client_time+e>=bt();class Ct{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;loggerDebugLog;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`),this.firstFlush=xt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let t=G.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=xt(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{let{event_name:t}=e;return[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`].includes(t)};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:yt.WTF,message:String(e)||`Unknown logger error`,thrown:e})}}readFromStorage(){let e=G.get(K);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let t=this.readFromStorage(),n=(t[this.userSalt]??[]).filter(St(this.params.config.storageExpiration));G.set(K,JSON.stringify({...t,[this.userSalt]:[...n,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(St(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],G.set(K,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of Object.entries(e)){let r=n.filter(St(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`})}G.set(K,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid===e.vsid?this.debouncedFlush():this.firstFlush(),this.lastVsid=e.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()}}function wt(){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 Tt{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}import{PlaybackState as Et}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Dt,Subscription as Ot,ValueSubject as kt,Subject as At,fromEvent as jt,isNullable as Mt,merge as q,filter as Nt,filterChanged as Pt,getWindow as Ft}from"@vkontakte/videoplayer-shared/evergreen";var It=(e,t,n)=>new Dt(r=>{let i=new Ot,a=new kt(void 0),o;i.add(e.info.isLive$.pipe(Pt()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(Pt()).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(Nt(()=>e.info.playbackState$.getValue()===Et.PLAYING)),f=e.events.seeked$.pipe(Nt(()=>e.info.playbackState$.getValue()===Et.PLAYING)),p=!1,m=new At;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=q(jt(Ft(),`beforeunload`),e.events.willDestruct$),g,_=()=>g=a.getValue(),v=()=>{let e=a.getValue();Mt(g)||Mt(e)||g===e||(r.next({from:g,to:e}),g=void 0)},y=new At,b=new At,x=q(s,f,y),S=q(c,m,h,l,u,b),C=t.started$&&t.ended$?q(x,t.ended$):x,w=t.started$&&t.ended$?q(S,t.started$):S;if(i.add(C.subscribe(_)).add(w.subscribe(v)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{b.next(),y.next()};i.add(C.subscribe(()=>{let r=Ft().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(w.subscribe(()=>{e.forEach(e=>{Ft().clearTimeout(e)}),e=[]}))}return i});import{Subscription as Lt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Rt,merge as zt}from"@vkontakte/videoplayer-shared/evergreen";var Bt=(e,t)=>new Rt(n=>{let r=new Lt;return r.add(zt(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 Vt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Ht,filter as Ut,getWindow as Wt}from"@vkontakte/videoplayer-shared/evergreen";var Gt=(e,{maxTimeWindow:t})=>new Ht(n=>{let r=new Vt,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(Wt().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=Wt().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(Ut(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 Kt,Subscription as qt,merge as Jt}from"@vkontakte/videoplayer-shared/evergreen";var Yt=e=>new Kt(t=>{let n=new qt,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(Jt(p,m).subscribe(l)).add(Jt(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),e}),n});import{assertNever as Xt}from"@vkontakte/videoplayer-shared/evergreen";import{HttpConnectionType as Zt,Surface as J,VideoFormat as Y,VideoQuality as X}from"@vkontakte/videoplayer-core/evergreen";var Qt=e=>e&&{[Zt.HTTP1]:`http1`,[Zt.HTTP2]:`http2`,[Zt.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 Xt(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 Xt(e)}},$t=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}},en=(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`}},tn=e=>{switch(e){case void 0:return;case J.INVISIBLE:return`background`;default:return`foreground`}},nn=`_thin-one-stat_deviceId`,rn=()=>{let e=new at;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class an{api;logger;config;subscription;beforeunloadSubscription;timeSynchronisation;statContext;deviceId;targetDuration;debugLogger=new Ze;thinOneStatDebugLog=this.debugLogger.createComponentLog(`ThinOneStat`);eventNumber=1;isStarted;wasPaused;isLive;position;cdnHostname;isEmbed;embedHostname;connectionType;connectionReused;player;playerSize={width:0,height:0};currentSubtitle;uiEvents;seekAction$=new ot(`unknown`);get vsid$(){return new ot(O.getVSID())}isid$=new ot(void 0);getTotalViewTime=()=>0;constructor(e,t){this.statContext=e,this.config=pt(t.config??{}),this.subscription=new at,this.config.synchronizeTime&&(this.timeSynchronisation=new Tt);let n=new it,r=nt.get(nn);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=wt(),nt.set(nn,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??ce());let i=new vt({error$:n,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new gt({config:this.config,apiTransport:i,error$:n,deviceId:this.deviceId,refreshAuthToken:t.refreshAuthToken}),this.logger=new Ct({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:n,userSalt:t.userSalt});let{isEmbed:a,topOrigin:o}=Ye();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,t){let n=new at,r=(e,t)=>n.add(e.subscribe(t));r(Yt(e),e=>{this.getTotalViewTime=e}),r(e.info.isLive$,e=>this.isLive=e);let i;r(z({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(B(({hostname:e})=>e!==void 0),B(({connectionType:e})=>e!==void 0),B(({connectionReused:e})=>e!==void 0)),({hostname:t,connectionType:n,connectionReused:r})=>{if(i!==void 0&&i!==t){let i={cdn_host:t,connection_type:Qt(n),connection_reused:r,content_type:Z(e.info.currentFormat$.getValue())};this.logFailover(i)}this.cdnHostname=i=t}),r(e.info.httpConnectionType$,e=>{this.connectionType=Qt(e)}),r(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),r(It(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),t=>{let n={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:Z(e.info.currentFormat$.getValue()),playback_quality:Q(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(n);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...n,live:!!t})}}),r(Bt(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),r(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)}}),r(e.events.manifestRequested$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(t)}),r(e.events.firstBytesManifest$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(t)}),r(e.events.manifestReceived$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(t)}),r(e.events.firstBytesRequested$,()=>{let t={playback_url:$(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(t)}),r(e.events.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)}),r(Qe(e.events.willStart$,e.events.looped$),t=>{t&&this.resetViewSession();let n={isid:this.isid$.getValue(),stream_profile:$t(Z(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*H.display.pixelRatio,web_layout:this.statContext.isMobile||H.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)}),r(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:en(o,this.statContext.isPreviewPlayerView),visibility:tn(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)}),r(e.events.willStart$,()=>{this.logPlay()}),r(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.wasPaused&&this.logResume()}),r(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),r(e.events.willStop$,()=>{this.logStop()}),r(Qe(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let a=e=>{switch(e){case V.NETWORK:return`network`;case V.VIDEO_PIPELINE:return`video_pipeline`;case V.EXTERNAL_API:return`external_api`;case V.PARSER:return`parser`;case V.DOM:return`dom`;default:return`wtf`}},o=e=>V.FATAL===e?`critical`:`informative`;r(e.events.fetcherRecoverableError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:s})=>{let c={error_severity:o(t),error_category:a(t),player_error_code:e,player_error_trace:n,http_error_code:i,uv_backend_error_code_subcode:s,error_message:r};this.logError(c),o(t)===`critical`&&this.logCannotPlay()}),r(e.events.managedError$,({id:e,category:t,data:n,message:r})=>{let i={error_severity:o(t),error_category:a(t),player_error_code:e,player_error_trace:n,error_message:r};this.logError(i)}),r(e.events.fatalError$,({id:e,category:t,data:n,message:r})=>{let i={error_severity:`critical`,error_category:a(t),player_error_code:e,player_error_trace:n,error_message:r};this.logError(i),this.logCannotPlay()}),r(z({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(B(({connectionReused:e})=>e!==void 0),B(({connectionMetrics:e})=>e!==void 0),$e((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(),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.statContext.networkType??t?.networkType,dns_resolve_time:t?.dnsResolveTime,tcp_handshake_time:t?.tcpHandshakeTime,tls_handshake_time:t?.tlsHandshakeTime};this.logConnectionEstablished(o)}),r(Gt(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.logDownloadBytes(e)}),r(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),r(e.events.willSeek$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),r(e.events.seeked$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),r(e.info.isStalled$,t=>{let n=e.info.currentBuffer$.getValue(),r=this.calcBufferTime(n);t&&r&&r>0&&this.logBufferStarvation({buffer_time:r})}),r(e.info.currentBuffer$.pipe(B(e=>!!this.calcBufferTime(e)),et()),e=>{let t=this.calcBufferTime(e);if(this.statContext.preload){let e={buffer_time:t};this.logPreloadEnded(e)}this.logReady({buffer_time:t})});let s;r(z({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(B(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),B(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(s!==r){let i=e.info.isAutoQualityEnabled$.getValue(),a=t?.codec,o=n?.codec,c={user_quality:i?`auto`:Q(r),playback_quality:Q(s),download_quality:Q(r),codec_info:a&&o?`${a},${o}`:void 0};s=r,this.logQualityChanged(c)}});let c,l;return r(e.info.surface$,e=>{let t=en(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),l=tn(e),c!==l&&this.isStarted&&(c=tn(e),this.logVisibilityChanged({visibility:l}))}),r(z({muted:e.info.muted$,volume:e.info.volume$}),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),r(e.info.currentFormat$.pipe(B(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)}),r(e.info.currentAudioStream$.pipe(B(e=>e!==void 0),tt(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),r(e.info.currentVideoStream$.pipe(B(e=>e!==void 0),tt(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToUi(e){this.uiEvents=e;let{subscribe:t,subscription:n}=rn();t(e.actionSeek$,this.seekAction$),t(e.playerSize$,({width:e,height:t})=>{e&&t&&(this.playerSize={width:e,height:t},this.isStarted&&this.logViewPortChanged({player_width:e,player_height:t}))}),t(e.isLoaderVisible$,e=>{e&&this.isStarted&&this.logShowLoader()}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle={...e},this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:r}=We(this.uiEvents,t,this.player);return t(r,e=>{this.isStarted&&this.logModeChanged({mode:en(e)})}),t(e.actionQuality$,e=>{let t=e=>Object.values(ct).includes(e),n=this.player?.info.currentVideoStream$.getValue()?.codec,r=this.player?.info.currentAudioStream$.getValue()?.codec,i={user_quality:t(e)?`auto`:Q(e),playback_quality:Q(this.player?.info.currentQuality$.getValue()),download_quality:Q(this.player?.info.currentQuality$.getValue()),codec_info:n&&r?`${n},${r}`:void 0};this.logQualityChangeRequested(i)}),this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToAds(e){let{subscription:t,subscribe:n}=rn();return n(e.init$,e=>{let t={slot:e};this.logAdvConfiguration(t)}),n(e.slotRequested$,()=>{this.logAdvRequest()}),n(e.started$,e=>{let t={adv_section:e};this.logAdvBreakStarted(t)}),n(e.ended$,e=>{let t={adv_section:e};this.logAdvBreakEnded(t)}),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`}),O.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}createRequiredParams(e){let t=this.vsid$.getValue();Je(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:${k}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||H.device.isMobile?`mobile`:`desktop`}`,product:this.statContext.product,event_number:n,playback_position: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.1`,browser:this.statContext.browser??H.browser.current,browser_version:this.statContext.browserVersion??String(H.browser.currentVersion),os:this.statContext.os??H.device.os.name,os_version:this.statContext.osVersion??H.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||H.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??H.device.details.vendor,device_model:this.statContext.deviceModel??H.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,n=!1){if(this.config.disabledEvents.includes(e))return;let r=this.createRequiredParams(e),i={};n&&(i=this.createRequiredFatParams()),this.logger.log({...r,...i,...t})}logWatchCoverage(e){this.log(`watch_coverage`,e,!0)}logWatchCoverageLive(e){this.log(`watch_coverage_live`,e,!0)}logWatchedN(e){this.log(`watched_n`,e,!0)}logStartSession(e){this.log(`start_session`,e,!0)}logPreloadStarted(e){this.log(`preload_started`,e)}logPreloadEnded(e){this.log(`preload_ended`,e)}logPreloadError(){this.log(`preload_error`)}logPlaybackStarted(e){this.log(`playback_started`,e,!0)}logPlay(){this.log(`play`)}logManifestRequest(e){this.log(`manifest_request`,e)}logFirstByteManifest(e){this.log(`first_byte_manifest`,e)}logFirstMediaRequest(e){this.log(`first_media_request`,e)}logFirstByteMedia(e){this.log(`first_byte_media`,e)}logManifestReceived(e){this.log(`manifest_received`,e)}logConnectionEstablished(e){this.log(`connection_established`,e)}logFirstVideoFrameDecoded(){this.log(`first_video_frame_decoded`)}logReady(e){this.log(`ready`,e)}logPlaying(e){this.log(`playing`,e)}logPause(){this.log(`pause`)}logResume(){this.log(`resume`)}logSeeking(e){this.log(`seeking`,e)}logSeeked(e){this.log(`seeked`,e)}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)}logAdvConfiguration(e){this.log(`adv_configuration`,e)}logAdvRequest(){this.log(`adv_request`)}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=Xe(rt(),`beforeunload`).subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}}import{PlaybackState as on,Subscription as sn}from"@vkontakte/videoplayer-core/evergreen";import{Logger as cn}from"@vkontakte/videoplayer-shared/evergreen";class ln{startTime=null;stopTime=null;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 un=()=>window.Image?new Image:document.createElement(`img`);class dn{params;position=0;started=!1;isActiveLive;heartbeatPixels=[];heartbeatLastTimeSent={};heartbeatInterval;heartbeatFirstTimeoutId;idleCallbackIds=[];log;stopwatch=new ln;subscription=new sn;constructor(e){this.params=e,this.log=new cn().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=>window.cancelIdleCallback(e)),this.send(`stop`)}onPlaybackState(e){e===on.PLAYING?this.started?this.play():this.start():e===on.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(requestIdleCallback(()=>un().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{k as VERSION,qe as ThinOneStat,c as SeekAction,a as Quality,Ke as OneStat,dn as MediascopePixel,l as InteractiveInterfaceClick,o as ContentType,s as ConnectionType,i as ApiEnv};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-statistics",
3
- "version": "1.0.100-dev.04f0bb5f.0",
3
+ "version": "1.0.100-dev.319d6ebf.0",
4
4
  "author": "vk.com",
5
5
  "description": "Statistics library for vk.com videoplayer",
6
6
  "homepage": "https://vk.com",
@@ -54,7 +54,7 @@
54
54
  "**/*.d.ts"
55
55
  ],
56
56
  "dependencies": {
57
- "@vkontakte/videoplayer-core": "2.0.154-dev.04f0bb5f.0",
58
- "@vkontakte/videoplayer-shared": "1.0.83-dev.04f0bb5f.0"
57
+ "@vkontakte/videoplayer-core": "2.0.154-dev.319d6ebf.0",
58
+ "@vkontakte/videoplayer-shared": "1.0.83-dev.319d6ebf.0"
59
59
  }
60
60
  }
@@ -1,7 +1,7 @@
1
1
  export declare const generateVSID: () => string;
2
2
  export declare const generateISID: () => string;
3
3
  export declare class ShareVSID {
4
- private static vsid;
5
- static getVSID(): string;
6
- static generateVSID(isVsid64: boolean): string;
4
+ private static vsid;
5
+ static getVSID(): string;
6
+ static generateVSID(isVsid64: boolean): string;
7
7
  }
package/types/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- export * from './oneStat';
2
- export * as ThinOneStat from './thinOneStat';
3
- export { VERSION } from './env';
4
- export * as MediascopePixelTypes from './mediascopePixel/types';
5
- export { MediascopePixel, IMediascopePixel } from './mediascopePixel/MediascopePixel';
1
+ export * from "./oneStat";
2
+ export * as ThinOneStat from "./thinOneStat";
3
+ export { VERSION } from "./env";
4
+ export type * as MediascopePixelTypes from "./mediascopePixel/types";
5
+ export { MediascopePixel } from "./mediascopePixel/MediascopePixel";
6
+ export type { IMediascopePixel } from "./mediascopePixel/MediascopePixel";
@@ -1,40 +1,40 @@
1
- import type { IPlayer } from '@vkontakte/videoplayer-core';
2
- import type { MediascopeParams } from './types';
1
+ import type { IPlayer } from "@vkontakte/videoplayer-core";
2
+ import type { MediascopeParams } from "./types";
3
3
  export interface IMediascopePixel {
4
- attachTo(player: IPlayer): void;
5
- destroy(): void;
4
+ attachTo(player: IPlayer): void;
5
+ destroy(): void;
6
6
  }
7
7
  export declare class MediascopePixel implements IMediascopePixel {
8
- private params;
9
- private position;
10
- private started;
11
- private isActiveLive?;
12
- private heartbeatPixels;
13
- private heartbeatLastTimeSent;
14
- private heartbeatInterval?;
15
- private heartbeatFirstTimeoutId?;
16
- private idleCallbackIds;
17
- private log;
18
- private stopwatch;
19
- private subscription;
20
- constructor(params: MediascopeParams);
21
- attachTo(player: IPlayer): void;
22
- destroy(): void;
23
- private onPlaybackState;
24
- private start;
25
- private play;
26
- private pause;
27
- private onPosition;
28
- private onWillSeek;
29
- private onSeeked;
30
- private onEnded;
31
- private validatePixels;
32
- private getFrameTimestamp;
33
- private getUTC;
34
- private prepareUrl;
35
- private preparePixels;
36
- private prepareHeartbeatPixels;
37
- private call;
38
- private send;
39
- private sendHeartbeat;
8
+ private params;
9
+ private position;
10
+ private started;
11
+ private isActiveLive?;
12
+ private heartbeatPixels;
13
+ private heartbeatLastTimeSent;
14
+ private heartbeatInterval?;
15
+ private heartbeatFirstTimeoutId?;
16
+ private idleCallbackIds;
17
+ private log;
18
+ private stopwatch;
19
+ private subscription;
20
+ constructor(params: MediascopeParams);
21
+ attachTo(player: IPlayer): void;
22
+ destroy(): void;
23
+ private onPlaybackState;
24
+ private start;
25
+ private play;
26
+ private pause;
27
+ private onPosition;
28
+ private onWillSeek;
29
+ private onSeeked;
30
+ private onEnded;
31
+ private validatePixels;
32
+ private getFrameTimestamp;
33
+ private getUTC;
34
+ private prepareUrl;
35
+ private preparePixels;
36
+ private prepareHeartbeatPixels;
37
+ private call;
38
+ private send;
39
+ private sendHeartbeat;
40
40
  }
@@ -1,12 +1,12 @@
1
1
  export declare class Stopwatch {
2
- private startTime;
3
- private stopTime;
4
- private accumulatedTime;
5
- get time(): number;
6
- get timeMs(): number;
7
- get isRunning(): boolean;
8
- start(): void;
9
- stop(): void;
10
- reset(): void;
11
- private now;
2
+ private startTime;
3
+ private stopTime;
4
+ private accumulatedTime;
5
+ get time(): number;
6
+ get timeMs(): number;
7
+ get isRunning(): boolean;
8
+ start(): void;
9
+ stop(): void;
10
+ reset(): void;
11
+ private now;
12
12
  }
@@ -1,9 +1,9 @@
1
1
  export interface Pixel {
2
- event: 'start' | 'stop' | 'pause' | 'resume' | 'heartbeat';
3
- url: string;
4
- interval?: number;
5
- delay?: number;
2
+ event: "start" | "stop" | "pause" | "resume" | "heartbeat";
3
+ url: string;
4
+ interval?: number;
5
+ delay?: number;
6
6
  }
7
7
  export interface MediascopeParams {
8
- pixels: Pixel[];
8
+ pixels: Pixel[];
9
9
  }
@@ -1,40 +1,41 @@
1
- import { IConfig } from './config';
2
- import { ILogItem } from './types';
3
- import { IApiTransport } from './ApiTransport';
4
- import { ISubject, IError, ValueSubject, IValueObservable } from '@vkontakte/videoplayer-shared';
1
+ import type { IConfig } from "./config";
2
+ import type { ILogItem } from "./types";
3
+ import type { IApiTransport } from "./ApiTransport";
4
+ import type { ISubject, IError, IValueObservable } from "@vkontakte/videoplayer-shared";
5
+ import { ValueSubject } from "@vkontakte/videoplayer-shared";
5
6
  export interface IApi {
6
- authorize(authToken?: string): Promise<string | undefined>;
7
- logRequest(items: ILogItem[]): Promise<void>;
8
- logBeacon(items: ILogItem[]): void;
9
- authorized$: IValueObservable<boolean>;
10
- destroy(): void;
7
+ authorize(authToken?: string): Promise<string | undefined>;
8
+ logRequest(items: ILogItem[]): Promise<void>;
9
+ logBeacon(items: ILogItem[]): void;
10
+ authorized$: IValueObservable<boolean>;
11
+ destroy(): void;
11
12
  }
12
13
  export interface IApiParams {
13
- config: IConfig;
14
- apiTransport: IApiTransport;
15
- refreshAuthToken?: () => Promise<string | undefined>;
16
- mobile: boolean;
17
- deviceId: string;
18
- error$: ISubject<IError>;
19
- /** переданная версия приложения smart_tv */
20
- vktvVersion?: string;
14
+ config: IConfig;
15
+ apiTransport: IApiTransport;
16
+ refreshAuthToken?: () => Promise<string | undefined>;
17
+ mobile: boolean;
18
+ deviceId: string;
19
+ error$: ISubject<IError>;
20
+ /** переданная версия приложения smart_tv */
21
+ vktvVersion?: string;
21
22
  }
22
23
  export default class Api implements IApi {
23
- private params;
24
- private authToken;
25
- private sessionKey;
26
- private authorizePromise?;
27
- private refreshAuthTokenPromise?;
28
- private consequentAuthErrors;
29
- authorized$: ValueSubject<boolean>;
30
- private backoffTimeoutId;
31
- constructor(params: IApiParams);
32
- authorize(authToken?: string): Promise<string | undefined>;
33
- logBeacon(items: ILogItem[]): void;
34
- logRequest(items: ILogItem[]): Promise<void>;
35
- destroy(): void;
36
- private refreshAuthToken;
37
- private createLogParams;
38
- private _authorizeWithBackoff;
39
- private _authorize;
24
+ private params;
25
+ private authToken;
26
+ private sessionKey;
27
+ private authorizePromise?;
28
+ private refreshAuthTokenPromise?;
29
+ private consequentAuthErrors;
30
+ authorized$: ValueSubject<boolean>;
31
+ private backoffTimeoutId;
32
+ constructor(params: IApiParams);
33
+ authorize(authToken?: string): Promise<string | undefined>;
34
+ logBeacon(items: ILogItem[]): void;
35
+ logRequest(items: ILogItem[]): Promise<void>;
36
+ destroy(): void;
37
+ private refreshAuthToken;
38
+ private createLogParams;
39
+ private _authorizeWithBackoff;
40
+ private _authorize;
40
41
  }
@@ -1,25 +1,25 @@
1
- import { IConfig } from './config';
2
- import { IError, ISubject } from '@vkontakte/videoplayer-shared';
3
- import type { TimeSynchronisation } from './utils/timeSynchronisation';
1
+ import type { IConfig } from "./config";
2
+ import type { IError, ISubject } from "@vkontakte/videoplayer-shared";
3
+ import type { TimeSynchronisation } from "./utils/timeSynchronisation";
4
4
  export interface IApiTransportParams {
5
- config: IConfig;
6
- error$: ISubject<IError>;
7
- timeSynchronisation?: TimeSynchronisation;
5
+ config: IConfig;
6
+ error$: ISubject<IError>;
7
+ timeSynchronisation?: TimeSynchronisation;
8
8
  }
9
9
  export interface IApiTransport {
10
- sendBeacon(method: string, params: Record<string, unknown>, sessionKey?: string): boolean;
11
- sendRequest<T = unknown>(method: string, params: Record<string, unknown>, sessionKey?: string): Promise<T>;
10
+ sendBeacon(method: string, params: Record<string, unknown>, sessionKey?: string): boolean;
11
+ sendRequest<T = unknown>(method: string, params: Record<string, unknown>, sessionKey?: string): Promise<T>;
12
12
  }
13
13
  export default class ApiTransport implements IApiTransport {
14
- private apiKey;
15
- private apiBaseUrl;
16
- private apiEnv;
17
- private timeSynchronisation?;
18
- private isApiBaseUrlFetched;
19
- private params;
20
- constructor(params: IApiTransportParams);
21
- private resolveApiBaseUrl;
22
- sendBeacon(method: string, params: Record<string, unknown>, sessionKey?: string): boolean;
23
- sendRequest<T = unknown>(method: string, params: Record<string, unknown>, sessionKey?: string): Promise<T>;
24
- private _prepareQueryParams;
14
+ private apiKey;
15
+ private apiBaseUrl;
16
+ private apiEnv;
17
+ private timeSynchronisation?;
18
+ private isApiBaseUrlFetched;
19
+ private params;
20
+ constructor(params: IApiTransportParams);
21
+ private resolveApiBaseUrl;
22
+ sendBeacon(method: string, params: Record<string, unknown>, sessionKey?: string): boolean;
23
+ sendRequest<T = unknown>(method: string, params: Record<string, unknown>, sessionKey?: string): Promise<T>;
24
+ private _prepareQueryParams;
25
25
  }