@vkontakte/videoplayer-statistics 1.0.82-dev.505e7dcd.0 → 1.0.82-dev.5160770c.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/evergreen.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.82-dev.505e7dcd.0
3
- * Tue, 08 Jul 2025 08:11:01 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.82-dev.5160770c.0
3
+ * Tue, 08 Jul 2025 17:41:10 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-82/doc/
5
5
  */
6
- var Pt=Object.defineProperty;var Et=(s,e)=>{for(var i in e)Pt(s,i,{get:e[i],enumerable:!0})};var R=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.OKCDN="okcdn",n.AUTO="auto",n))(R||{}),oe=(u=>(u.Q144P="mobile",u.Q240P="lowest",u.Q360P="low",u.Q480P="medium",u.Q720P="high",u.Q1080P="fullhd",u.Q1440P="quadhd",u.Q2160P="ultrahd",u.UNKNOWN="unknown",u))(oe||{}),re=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(re||{});var se=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(se||{});var ne=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(ne||{}),we=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(we||{}),Te={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"},ke={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"},xe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Le={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as At}from"@vkontakte/videoplayer-shared/evergreen";var Ce="CIOPGQJGDIHBABABA",ae={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 wt={apiEnv:"vk_alias",apiKey:Ce,requestRetryCount: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}},$e=s=>At(s,wt);function de(){let s="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]=s[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Bt,combine as qe,fromEvent as ze,isNonNullable as D,isNullable as Qe,merge as Ft,now as k,observableFrom as Ut,once as Ht,safeStorage as je,Subject as Wt,Subscription as me,ValueSubject as z,createURL as Ge}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as Kt,detectEmbed as qt}from"@vkontakte/videoplayer-shared/evergreen";var De=s=>{let{operation:e,custom:i}=s,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let n=ke[o]??o,d=r;return r&&(o==="mode"?d=Le[r]??r:o==="quality"&&(d=xe[r]??r)),[n,d]}));return{...s,operation:Te[e]??e,custom:t}};var _="1.0.82-dev.505e7dcd.0";import{ValueSubject as Tt,getExponentialDelay as kt,ErrorCategory as C}from"@vkontakte/videoplayer-shared/evergreen";var xt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,V=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Tt(!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 r=async(n,d=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:C.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let u=l?.error_code;switch(u){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(n,d-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(n,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${u}`,category:C.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return r(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:${_}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:r}=window.navigator;t=xt.test(r)}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(De):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=kt(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:C.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:_.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:C.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:C.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:C.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 U,now as ce}from"@vkontakte/videoplayer-shared/evergreen";var M=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=ae[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:U.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),ae.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}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:U.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=ce(),r=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:U.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:U.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:i,sessionKey:t,time:ce()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(n=>{let d=Number(n.headers.get("content-length"))===0,l=new Date(n.headers.get("date")??"").getTime(),u=ce()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,u),!d)return n.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_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 Lt,now as Ct,safeStorage as B,debounceFn as Ne}from"@vkontakte/videoplayer-shared/evergreen";var H="onestat_events",ue=s=>e=>e.timestamp+s>=Ct(),W=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=Ne(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=B.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Ne(()=>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:Lt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=B.get(H);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(ue(this.params.config.storageExpiration));B.set(H,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(ue(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],B.set(H,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(ue(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`})}B.set(H,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 le,Surface as $,VideoFormat as v,VideoQuality as P}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as Oe}from"@vkontakte/videoplayer-shared/evergreen";var Re=s=>s&&{[P.INVARIANT]:"unknown",[P.Q_144P]:"mobile",[P.Q_240P]:"lowest",[P.Q_360P]:"low",[P.Q_480P]:"medium",[P.Q_576P]:"unknown",[P.Q_720P]:"high",[P.Q_1080P]:"fullhd",[P.Q_1440P]:"quadhd",[P.Q_2160P]:"ultrahd",[P.Q_4320P]:"unknown"}[s],he=s=>s&&{[le.HTTP1]:"http1",[le.HTTP2]:"http2",[le.QUIC]:"http3"}[s],Ve=s=>{if(s!==void 0)switch(s){case v.MPEG:return"mp4";case v.DASH:case v.DASH_LIVE:case v.DASH_STREAMS:return"dash";case v.DASH_SEP:return"dash_sep";case v.DASH_ONDEMAND:return"ondemand_dash";case v.DASH_WEBM:case v.DASH_LIVE_WEBM:return"webm";case v.DASH_WEBM_AV1:return"av1";case v.DASH_LIVE_CMAF:return"ondemand_dash_live";case v.HLS:case v.HLS_LIVE:return"hls";case v.HLS_ONDEMAND:return"ondemand_hls";case v.HLS_LIVE_CMAF:return"ondemand_hls_live";case v.WEB_RTC_LIVE:return"webrtc";default:return Oe(s)}},K=s=>{if(s!==void 0)switch(s){case $.NONE:case $.INLINE:return;case $.FULLSCREEN:return"fullscreen";case $.SECOND_SCREEN:return"chromecast";case $.PIP:return"pip";case $.INVISIBLE:return"invisible";default:return Oe(s)}},Me=s=>{switch(s){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var q=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)}};var Be=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),Fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as Ue}from"@vkontakte/videoplayer-core/evergreen";import{filter as He,filterChanged as Dt,fromEvent as Nt,isNullable as We,map as Ot,merge as pe,Observable as Rt,Subject as fe,Subscription as Vt,ValueSubject as Mt}from"@vkontakte/videoplayer-shared/evergreen";var Ke=(s,e)=>new Rt(i=>{let t=new Vt,o=pe(Nt(window,"beforeunload"),s.events.willDestruct$),r=new Mt(void 0),n;t.add(s.info.isLive$.pipe(Dt()).subscribe(g=>{n&&(n.unsubscribe(),r.next(void 0)),g?n=s.info.liveTime$.pipe(Ot(y=>y&&y/1e3)).subscribe(r):n=s.info.position$.subscribe(r),t.add(n)}));let{playing$:d,paused$:l}=s.events,u=s.events.willSeek$.pipe(He(()=>s.info.playbackState$.getValue()===Ue.PLAYING)),h=s.events.seeked$.pipe(He(()=>s.info.playbackState$.getValue()===Ue.PLAYING)),p=!1,a=new fe;t.add(u.subscribe(()=>{p||a.next(),p=!0})),t.add(h.subscribe(()=>p=!1));let c=new fe,m=new fe,f=pe(d,h,c),I=pe(l,a,o,s.events.looped$,m),S,A=()=>S=r.getValue(),w=()=>{let g=r.getValue();We(S)||S===g||We(g)||(i.next({from:S,to:g}),S=void 0)},T=()=>{m.next(),c.next()};if(t.add(f.subscribe(A)),t.add(I.subscribe(w)),e.forceInterval&&isFinite(e.forceInterval)){let g=0;t.add(f.subscribe(()=>g=window.setTimeout(T,e.forceInterval))),t.add(I.subscribe(()=>window.clearTimeout(g)))}return t});var zt="_one-stat_",Ye=`${zt}deviceId`,ge=()=>{let s=new me;return{subscription:s,subscribe:(e,i)=>{e&&s.add(e.subscribe(i))}}},be=class{constructor(e,i){this.subscription=new me;this.debugLogger=new Kt;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new z(void 0);this.isid$=new z(void 0);this.zenUid$=new z(void 0);this.seekAction$=new z("unknown");this.statContext=e,this.config=$e(i.config??{}),D(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new q);let t=new Wt;this.experimental={error$:t};let o=je.get(Ye);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=de(),je.set(Ye,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??Fe()),this.zenUid$.next(i.zenUid);let r=new M({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new V({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new W({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,topOrigin:d}=qt();this.isEmbed=n,this.embedParent=d?new URL(d).hostname:void 0,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new me,t=(a,c)=>i.add(a.subscribe(c));t(e.events.willStart$,()=>{let a=e.info.position$.getValue();this.logActionPlay({position:a}),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$,()=>{this.logSeek({action:this.seekAction$.getValue(),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(Ke(e,{forceInterval:this.config.watchCoverageInterval}),a=>{let c=e.info.isLive$.getValue(),m=e.info.atLiveEdge$.getValue(),f={start:parseFloat(a.from.toFixed(3)),end:parseFloat(a.to.toFixed(3))};if(m){let I=e.info.liveLatency$.getValue()??0,S=e.info.currentBuffer$.getValue()?.end??0,A=e.info.liveBufferTime$.getValue()??0,w=Math.round((I-(S-A))*1e3),T=Math.round(I*1e3);w&&T&&(f.latency=w,f.bufferLatency=T)}c?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,a=>{a?o=k():(D(o)&&this.logEmptyBuffer({duration:k()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ht()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let c=D(o)?k()-o:void 0;this.logCloseAtEmptyBuffer({duration:c??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:a})=>{this.logError({fatal:!1,errorType:a})}),t(e.events.fatalError$,({id:a})=>{this.logError({fatal:!0,errorType:a})});let n,d,l=!1;t(e.events.firstBytes$,a=>{n=k(),this.logFirstBytes({time:a})}),t(e.events.willStart$,()=>d=k()),t(e.info.currentBuffer$,a=>{!l&&a&&a.end-a.start>0&&D(n)&&(this.logPlayerReady({duration:k()-n}),l=!0)}),t(e.events.firstFrame$,()=>{D(n)&&!l&&(this.logPlayerReady({duration:k()-n}),l=!0),D(d)&&this.logFirstFrame({time:k()-d})});let u;t(e.info.currentVideoStream$,a=>{a&&(u&&a.id!==u&&this.logTrackSwitch(a),u=a.id)});let h;t(e.info.currentAudioStream$,a=>{a&&(h&&a.id!==h&&this.logTrackSwitch(a),h=a.id)}),t(e.info.atLiveEdge$,a=>this.updateContext({liveEdge:a})),t(qe({muted:e.info.muted$,volume:e.info.volume$}),({muted:a,volume:c})=>this.updateContext({audible:!a&&c>0})),t(e.info.currentQuality$,a=>{let c=Re(a);this.updateContext({quality:c}),c&&this.logQuality(c)}),t(e.info.isAutoQualityEnabled$,a=>this.updateContext({autoQuality:a})),t(e.info.currentFormat$,a=>this.updateContext({contentType:Ve(a)})),t(e.info.currentPlaybackRate$,a=>this.updateContext({rate:a})),t(e.info.is3DVideo$,a=>this.updateContext({is3d:a}));let p;return t(e.info.hostname$,a=>{let c=p!==void 0&&p!==a;this.updateContext({cdnHostname:a,failover:c}),c&&this.logFailover(a),p=a}),t(e.info.throughputEstimation$,a=>this.updateContext({downloadSpeed:a})),t(e.info.httpConnectionType$,a=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:he(a)}),this.updateContext({connectionType:he(a)})}),t(e.info.httpConnectionReused$,a=>{Qe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:a}),this.updateContext({connectionReused:a})}),t(e.info.surface$,a=>this.updateContext({mode:K(a)})),t(qe({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:a,available:c})=>{let m=c.find(({id:I})=>I===a),f=m&&(m.isAuto?`${m.language}_auto`:m.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}=ge();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":K(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":K(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o.split(".")[0]})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=ge();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}=ge();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"}),this.vsid$.next(Be())}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(Ft(ze(e,"change"),Ut(["init"])).subscribe(()=>this.updateContext({network:Me(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=ze(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 r=this.timeSynchronisation?.now()??k(),n=this.vsid$.getValue();Bt(n);let d=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,h,p;if(this.isEmbed||this.statContext.place==="embed"){h=this.embedParent;let c=[...new URLSearchParams(location.search).entries()].filter(([m,f])=>this.config.embedUrlParams.includes(m));p=new URLSearchParams(c).toString()}else this.statContext.place==="direct"&&(this.statContext.refDomain?h=Ge(this.statContext.refDomain)?.hostname??this.statContext.refDomain:document.referrer&&(h=Ge(document.referrer)?.hostname??document.referrer),p=location.href.substring(0,1024));let a={vsid:n,isid:d,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:u===!0?1:u===!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:h,direct_url:p,rate:this.statContext.rate===1||Qe(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 c of this.config.disabledCustomFields)delete a[c];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:a}}};var St={};Et(St,{SeekType:()=>Q,ThinOneStat:()=>te,VERSION:()=>_});import{assertNonNullable as ai,detectEmbed as di,fromEvent as ci,Logger as ui,merge as mt,safeStorage as bt,Subject as li,Subscription as Ae,ValueSubject as ee}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as L,PlaybackState as vt}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as Qt}from"@vkontakte/videoplayer-shared/evergreen";var Q=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(Q||{});var Je="CIOPGQJGDIHBABABA",ve={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 jt={apiKey:Je,apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:15,synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1},Ze=s=>Qt(s,jt);import{getExponentialDelay as Gt,ErrorCategory as N,ValueSubject as Yt}from"@vkontakte/videoplayer-shared/evergreen";var j=class{constructor(e){this.params=e,this.authorized$=new Yt(!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={},r=this.sessionKey??await this.authorizeWithBackoff();if(!r)return;let n=async(d,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,r,o)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:N.NETWORK,message:`Unknown ${i} error`,thrown:u});return}let h=u?.error_code;switch(h){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),l>0?n(d,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),l>0?n(d,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:N.EXTERNAL_API,message:`${i} error`,data:u});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){return{collector:"ok.mobile.apps.video",uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${_}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=Gt(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:N.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:_.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:N.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:N.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:N.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 Ie,ErrorCategory as G}from"@vkontakte/videoplayer-shared/evergreen";var Y=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=ve[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}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:G.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let r=Ie(),n=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:G.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:G.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:Ie()-r}})};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(d=>{let l=Number(d.headers.get("content-length"))===0,u=new Date(d.headers.get("date")??"").getTime(),h=Ie()-r;if(isFinite(u)&&this.timeSynchronisation?.addServerTime(u,h),!l)return d.json().then(p=>Object.prototype.hasOwnProperty.call(p,"error_msg")?Promise.reject(p):p,n)},n)}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:G.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),ve.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 Xt,now as Jt,safeStorage as F,debounceFn as et}from"@vkontakte/videoplayer-shared/evergreen";var X="thinonestat_events",Se=s=>e=>e.client_time+s>=Jt(),J=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=et(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=F.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:Xt.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=F.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(Se(this.params.config.storageExpiration));F.set(X,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(Se(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],F.set(X,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(Se(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`})}F.set(X,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 ye(){let s="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]=s[o===19?t&3|8:t]);return e.join("")}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 tt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Zt,Subscription as ei,ValueSubject as ti,Subject as _e,fromEvent as ii,isNullable as it,merge as Pe,filter as ot,filterChanged as rt}from"@vkontakte/videoplayer-shared/evergreen";var st=(s,e)=>new Zt(i=>{let t=new ei,o=new ti(void 0),r;t.add(s.info.isLive$.pipe(rt()).subscribe(y=>{r&&(r.unsubscribe(),o.next(void 0)),y?r=s.info.liveTime$.pipe(rt()).subscribe(o):r=s.info.position$.subscribe(o),t.add(r)}));let{playing$:n,paused$:d,ended$:l,looped$:u}=s.events,h=s.events.willSeek$.pipe(ot(()=>s.info.playbackState$.getValue()===tt.PLAYING)),p=s.events.seeked$.pipe(ot(()=>s.info.playbackState$.getValue()===tt.PLAYING)),a=!1,c=new _e;t.add(h.subscribe(()=>{a||c.next(),a=!0})).add(p.subscribe(()=>a=!1));let m=Pe(ii(window,"beforeunload"),s.events.willDestruct$),f,I=()=>f=o.getValue(),S=()=>{let y=o.getValue();it(f)||it(y)||f===y||(i.next({from:f,to:y}),f=void 0)},A=new _e,w=new _e,T=Pe(n,c,A),g=Pe(d,p,m,l,u,w);if(t.add(T.subscribe(I)).add(g.subscribe(S)),e.heartbeatInterval&&isFinite(e.heartbeatInterval)){let y=[],yt=e.heartbeatInterval*1e3,_t=()=>{w.next(),A.next()};t.add(T.subscribe(()=>{let ie=window.setTimeout(_t,yt);y.push(ie)})).add(g.subscribe(()=>{y.forEach(ie=>{window.clearTimeout(ie)}),y=[]}))}return t});import{Subscription as oi}from"@vkontakte/videoplayer-core/evergreen";import{Observable as ri}from"@vkontakte/videoplayer-shared/evergreen";var nt=(s,e)=>new ri(i=>{let t=new oi,o=1e4,r=0;return t.add(s.info.position$.subscribe(()=>{let n=e.getTotalViewTime()*1e3;n>r&&n%o===0&&(r=n,i.next({target_duration:o,current_tvt:n}))})),t});import{Observable as si,Subscription as ni,merge as at}from"@vkontakte/videoplayer-shared/evergreen";var dt=s=>new si(e=>{let i=new ni,t=0,o=1,r=0,n=!1,d=!1,l=()=>{if(!n)return;let g=Date.now();r+=(g-t)*o,t=g},u=()=>{(!n||d)&&(t=Date.now(),n=!0,d=!1)},h=()=>{n&&(l(),n=!1)},p=()=>{n&&(l(),n=!1,d=!0)},a=g=>{n&&l(),o=g,t=Date.now()},{started$:c,playing$:m,paused$:f,willSeek$:I,ended$:S,willDestruct$:A}=s.events,{currentPlaybackRate$:w}=s.info;i.add(I.subscribe(p)).add(at(c,m).subscribe(u)).add(at(f,S,A).subscribe(h)).add(w.subscribe(a));let T=()=>{let g=r;return n&&(g+=(Date.now()-t)*o),Math.floor(g/1e3)};return e.next(T),i});import{assertNever as ct}from"@vkontakte/videoplayer-shared/evergreen";import{Surface as O,VideoFormat as b,VideoQuality as E}from"@vkontakte/videoplayer-core/evergreen";var Ee=s=>{if(s!==void 0)switch(s){case b.MPEG:return"MP4";case b.DASH:case b.DASH_LIVE:return"DASH";case b.DASH_SEP:return"DASH_SEP";case b.DASH_ONDEMAND:return"ONDEMAND_DASH";case b.HLS_ONDEMAND:return"ONDEMAND_HLS";case b.HLS:case b.HLS_LIVE:return"HLS";case b.DASH_WEBM:case b.DASH_LIVE_WEBM:return"WEBM";case b.DASH_LIVE_CMAF:return"ONDEMAND_DASH_LIVE";case b.HLS_LIVE_CMAF:return"ONDEMAND_HLS_LIVE";case b.WEB_RTC_LIVE:return"WEBRTC";case b.DASH_WEBM_AV1:return"AV1";case b.DASH_STREAMS:return"MULTI_DASH";default:return ct(s)}},x=s=>{if(s!==void 0)switch(s){case E.Q_144P:return"144p";case E.Q_240P:return"240p";case E.Q_360P:return"360p";case E.Q_480P:return"480p";case E.Q_720P:return"720p";case E.Q_1080P:return"1080p";case E.Q_1440P:return"1440p";case E.Q_2160P:return"2160p";case E.INVARIANT:case E.Q_576P:case E.Q_4320P:return"UNKNOWN";default:return ct(s)}},ut=s=>{if(s!==void 0)switch(s){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"WEBRTC":return"live";default:return}},lt=(s,e,i)=>{if(s&&e)switch(s){case b.MPEG:return i&&e[s]&&e[s][i];default:return e[s]?.url}},ht=s=>{if(s!==void 0)switch(s){case O.NONE:return;case O.INLINE:return"inline";case O.FULLSCREEN:return"fullscreen";case O.SECOND_SCREEN:return"chromecast";case O.PIP:return"pip_external"}},pt=s=>{if(s!==void 0)return s===O.INVISIBLE?"background":"foreground"};var ft=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),gt=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var hi="_thin-one-stat_",It=`${hi}deviceId`,pi=()=>{let s=new Ae;return{subscription:s,subscribe:(e,i)=>{e&&s.add(e.subscribe(i))}}},te=class{constructor(e,i){this.debugLogger=new ui;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.seekAction$=new ee("unknown");this.playerSize$=new ee({width:0,height:0});this.vsid$=new ee(void 0);this.isid$=new ee(void 0);this.statContext=e,this.config=Ze(i.config??{}),this.subscription=new Ae,this.config.synchronizeTime&&(this.timeSynchronisation=new Z);let t=new li,o=bt.get(It);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=ye(),bt.set(It,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??gt());let r=new Y({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new j({config:this.config,apiTransport:r,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new J({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,topOrigin:d}=di();this.isEmbed=n,this.embedHostname=d?new URL(d).hostname:void 0}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new Ae,t=(r,n)=>i.add(r.subscribe(n));t(dt(e),r=>{this.getTotalViewTime=r}),t(e.info.isLive$,r=>this.isLive=r),t(e.info.position$,r=>this.position=r);let o;return t(e.info.hostname$,r=>{o!==void 0&&o!==r&&this.logFailover({cdn_host:r}),this.cdnHostname=o=r}),t(st(e,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),r=>{let n=Math.round(r.from*1e3),d=Math.round(r.to*1e3),l={watch_interval:`${n}-${d}`,in_history:!!this.statContext.inHistory,content_type:Ee(e.info.currentFormat$.getValue()),playback_quality:x(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(l);else{let h=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...l,live:!!h})}}),t(nt(e,{getTotalViewTime:this.getTotalViewTime}),r=>{this.logWatchedN(r)}),t(mt(e.events.willStart$,e.events.looped$),r=>{r&&this.resetViewSession();let n={isid:this.isid$.getValue(),stream_profile:ut(Ee(e.info.currentFormat$.getValue())),dpi:L.display.pixelRatio,web_layout:L.device.isMobile?"mobile":"desktop",iframe_host:this.isEmbed?this.embedHostname??void 0:null,from_downloads:!0,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.logStartSession(n)}),t(e.events.willReady$,()=>{if(this.statContext.preload){let r=e.info.currentFormat$.getValue(),n=e.info.availableSources$.getValue(),d=e.info.currentBuffer$.getValue(),l=e.info.currentQuality$.getValue(),u={target_buffer_time:d?d.end-d.start:void 0,playback_url:lt(r,n,l),playback_quality:x(l)};this.logPreloadStarted(u)}}),t(e.events.ready$,()=>{if(this.statContext.preload){let r=e.info.currentBuffer$.getValue(),n={buffer_time:r?r.end-r.start:void 0};this.logPreloadEnded(n)}}),t(e.events.playing$,()=>{this.logPlay()}),t(e.info.playbackState$,r=>{if(r===vt.PLAYING){let n=e.info.currentBuffer$.getValue(),d={buffer_time:n?n.end-n.start:void 0};if(this.logPlaying(d),this.isStarted)this.logResume();else{this.isStarted=!0;let l=e.info.currentQuality$.getValue(),u=e.info.isAutoQualityEnabled$.getValue(),h=e.info.muted$.getValue(),p=e.info.volume$.getValue(),a=e.info.surface$.getValue(),c=e.info.availableTextTracks$.getValue(),m=e.info.currentTextTrack$.getValue(),f=e.info.currentAudioStream$.getValue(),I=e.info.currentPlaybackRate$.getValue(),S={playback_quality:x(l),user_quality:u?"auto":x(l),player_width:this.playerSize$.getValue().width,player_height:this.playerSize$.getValue().height,muted:h,sound_volume:p,buffer_time:n?Math.round(n.end-n.start):void 0,mode:ht(a),visibility:pt(a),subtitles_enabled:!!m,auto_subtitles:!!c.find(({id:A})=>A===m)?.isAuto,audio_track_lang:f?.language,playback_rate:I,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(S)}}else r===vt.PAUSED&&this.logPause()}),t(e.events.willSeek$,({to:r})=>{let n={target_position:r,seek_type:this.seekAction$.getValue()};this.logSeeking(n)}),t(e.events.seeked$,()=>{let n={target_position:e.info.position$.getValue(),seek_type:this.seekAction$.getValue()};this.logSeeked(n),this.seekAction$.next("unknown")}),t(mt(e.info.isBuffering$,e.info.isStalled$),r=>{r&&this.logShowLoader()}),t(e.info.currentQuality$,r=>{if(r){let n=e.info.isAutoQualityEnabled$.getValue(),d=e.info.currentVideoStream$.getValue()?.codec,l=e.info.currentAudioStream$.getValue()?.codec,u={user_quality:n?"auto":x(r),playback_quality:x(r),download_quality:x(r),codec_info:d&&l?`${d},${l}`:void 0,manual_switch:!n};this.logQualityChanged(u)}}),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){let{subscribe:i,subscription:t}=pi();return i(e.actionSeek$,this.seekAction$),i(e.playerSize$,this.playerSize$),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ft()),this.eventNumber=0}destroy(){this.api.destroy()}createRequiredParams(e){let i=this.vsid$.getValue();ai(i);let t=this.eventNumber++;return{vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:`@vkontakte/videoplayer-statistics:${_}`,platform:`web:${L.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:this.isLive?void 0:Math.round(this.position),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname}}createRequiredFatParams(){return{stats_version:_,browser:L.browser.current,browser_version:String(L.browser.currentVersion),os:L.device.current,os_version:"",device_type:L.device.isMobile?"mobile":"desktop",navigation:this.statContext.navigation}}log(e,i,t=!1){let o=this.createRequiredParams(e),r={};t&&(r=this.createRequiredFatParams()),this.logger.log({...o,...r,...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)}logPlaybackStarted(e){this.log("playback_started",e,!0)}logPlay(){this.log("play")}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)}logShowLoader(){this.log("show_loader")}logQualityChanged(e){this.log("quality_changed",e)}logFailover(e){this.log("failover",e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=ci(window,"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};export{R as ApiEnv,se as ConnectionType,re as ContentType,we as InteractiveInterfaceClick,be as OneStat,oe as Quality,ne as SeekAction,St as ThinOneStat,_ as VERSION};
6
+ var Pt=Object.defineProperty;var Et=(s,e)=>{for(var i in e)Pt(s,i,{get:e[i],enumerable:!0})};var R=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.OKCDN="okcdn",n.AUTO="auto",n))(R||{}),oe=(u=>(u.Q144P="mobile",u.Q240P="lowest",u.Q360P="low",u.Q480P="medium",u.Q720P="high",u.Q1080P="fullhd",u.Q1440P="quadhd",u.Q2160P="ultrahd",u.UNKNOWN="unknown",u))(oe||{}),re=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(re||{});var se=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(se||{});var ne=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(ne||{}),we=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(we||{}),Te={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"},ke={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"},xe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Le={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as At}from"@vkontakte/videoplayer-shared/evergreen";var Ce="CIOPGQJGDIHBABABA",ae={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 wt={apiEnv:"vk_alias",apiKey:Ce,requestRetryCount: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}},$e=s=>At(s,wt);function de(){let s="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]=s[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Bt,combine as qe,fromEvent as ze,isNonNullable as D,isNullable as Qe,merge as Ft,now as k,observableFrom as Ut,once as Ht,safeStorage as je,Subject as Wt,Subscription as me,ValueSubject as z,createURL as Ge}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as Kt,detectEmbed as qt}from"@vkontakte/videoplayer-shared/evergreen";var De=s=>{let{operation:e,custom:i}=s,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let n=ke[o]??o,d=r;return r&&(o==="mode"?d=Le[r]??r:o==="quality"&&(d=xe[r]??r)),[n,d]}));return{...s,operation:Te[e]??e,custom:t}};var _="1.0.82-dev.5160770c.0";import{ValueSubject as Tt,getExponentialDelay as kt,ErrorCategory as C}from"@vkontakte/videoplayer-shared/evergreen";var xt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,V=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Tt(!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 r=async(n,d=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:C.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let u=l?.error_code;switch(u){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(n,d-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(n,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${u}`,category:C.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return r(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:${_}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:r}=window.navigator;t=xt.test(r)}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(De):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=kt(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:C.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:_.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:C.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:C.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:C.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 U,now as ce}from"@vkontakte/videoplayer-shared/evergreen";var M=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=ae[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:U.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),ae.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}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:U.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=ce(),r=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:U.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:U.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:i,sessionKey:t,time:ce()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(n=>{let d=Number(n.headers.get("content-length"))===0,l=new Date(n.headers.get("date")??"").getTime(),u=ce()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,u),!d)return n.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_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 Lt,now as Ct,safeStorage as B,debounceFn as Ne}from"@vkontakte/videoplayer-shared/evergreen";var H="onestat_events",ue=s=>e=>e.timestamp+s>=Ct(),W=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=Ne(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=B.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Ne(()=>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:Lt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=B.get(H);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(ue(this.params.config.storageExpiration));B.set(H,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(ue(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],B.set(H,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(ue(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`})}B.set(H,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 le,Surface as $,VideoFormat as v,VideoQuality as P}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as Oe}from"@vkontakte/videoplayer-shared/evergreen";var Re=s=>s&&{[P.INVARIANT]:"unknown",[P.Q_144P]:"mobile",[P.Q_240P]:"lowest",[P.Q_360P]:"low",[P.Q_480P]:"medium",[P.Q_576P]:"unknown",[P.Q_720P]:"high",[P.Q_1080P]:"fullhd",[P.Q_1440P]:"quadhd",[P.Q_2160P]:"ultrahd",[P.Q_4320P]:"unknown"}[s],he=s=>s&&{[le.HTTP1]:"http1",[le.HTTP2]:"http2",[le.QUIC]:"http3"}[s],Ve=s=>{if(s!==void 0)switch(s){case v.MPEG:return"mp4";case v.DASH:case v.DASH_LIVE:case v.DASH_STREAMS:return"dash";case v.DASH_SEP:return"dash_sep";case v.DASH_ONDEMAND:return"ondemand_dash";case v.DASH_WEBM:case v.DASH_LIVE_WEBM:return"webm";case v.DASH_WEBM_AV1:return"av1";case v.DASH_LIVE_CMAF:return"ondemand_dash_live";case v.HLS:case v.HLS_LIVE:return"hls";case v.HLS_ONDEMAND:return"ondemand_hls";case v.HLS_LIVE_CMAF:return"ondemand_hls_live";case v.WEB_RTC_LIVE:return"webrtc";default:return Oe(s)}},K=s=>{if(s!==void 0)switch(s){case $.NONE:case $.INLINE:return;case $.FULLSCREEN:return"fullscreen";case $.SECOND_SCREEN:return"chromecast";case $.PIP:return"pip";case $.INVISIBLE:return"invisible";default:return Oe(s)}},Me=s=>{switch(s){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var q=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)}};var Be=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),Fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as Ue}from"@vkontakte/videoplayer-core/evergreen";import{filter as He,filterChanged as Dt,fromEvent as Nt,isNullable as We,map as Ot,merge as pe,Observable as Rt,Subject as fe,Subscription as Vt,ValueSubject as Mt}from"@vkontakte/videoplayer-shared/evergreen";var Ke=(s,e)=>new Rt(i=>{let t=new Vt,o=pe(Nt(window,"beforeunload"),s.events.willDestruct$),r=new Mt(void 0),n;t.add(s.info.isLive$.pipe(Dt()).subscribe(g=>{n&&(n.unsubscribe(),r.next(void 0)),g?n=s.info.liveTime$.pipe(Ot(y=>y&&y/1e3)).subscribe(r):n=s.info.position$.subscribe(r),t.add(n)}));let{playing$:d,paused$:l}=s.events,u=s.events.willSeek$.pipe(He(()=>s.info.playbackState$.getValue()===Ue.PLAYING)),h=s.events.seeked$.pipe(He(()=>s.info.playbackState$.getValue()===Ue.PLAYING)),p=!1,a=new fe;t.add(u.subscribe(()=>{p||a.next(),p=!0})),t.add(h.subscribe(()=>p=!1));let c=new fe,m=new fe,f=pe(d,h,c),I=pe(l,a,o,s.events.looped$,m),S,A=()=>S=r.getValue(),w=()=>{let g=r.getValue();We(S)||S===g||We(g)||(i.next({from:S,to:g}),S=void 0)},T=()=>{m.next(),c.next()};if(t.add(f.subscribe(A)),t.add(I.subscribe(w)),e.forceInterval&&isFinite(e.forceInterval)){let g=0;t.add(f.subscribe(()=>g=window.setTimeout(T,e.forceInterval))),t.add(I.subscribe(()=>window.clearTimeout(g)))}return t});var zt="_one-stat_",Ye=`${zt}deviceId`,ge=()=>{let s=new me;return{subscription:s,subscribe:(e,i)=>{e&&s.add(e.subscribe(i))}}},be=class{constructor(e,i){this.subscription=new me;this.debugLogger=new Kt;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new z(void 0);this.isid$=new z(void 0);this.zenUid$=new z(void 0);this.seekAction$=new z("unknown");this.statContext=e,this.config=$e(i.config??{}),D(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new q);let t=new Wt;this.experimental={error$:t};let o=je.get(Ye);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=de(),je.set(Ye,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??Fe()),this.zenUid$.next(i.zenUid);let r=new M({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new V({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new W({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,topOrigin:d}=qt();this.isEmbed=n,this.embedParent=d?new URL(d).hostname:void 0,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new me,t=(a,c)=>i.add(a.subscribe(c));t(e.events.willStart$,()=>{let a=e.info.position$.getValue();this.logActionPlay({position:a}),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$,()=>{this.logSeek({action:this.seekAction$.getValue(),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(Ke(e,{forceInterval:this.config.watchCoverageInterval}),a=>{let c=e.info.isLive$.getValue(),m=e.info.atLiveEdge$.getValue(),f={start:parseFloat(a.from.toFixed(3)),end:parseFloat(a.to.toFixed(3))};if(m){let I=e.info.liveLatency$.getValue()??0,S=e.info.currentBuffer$.getValue()?.end??0,A=e.info.liveBufferTime$.getValue()??0,w=Math.round((I-(S-A))*1e3),T=Math.round(I*1e3);w&&T&&(f.latency=w,f.bufferLatency=T)}c?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,a=>{a?o=k():(D(o)&&this.logEmptyBuffer({duration:k()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ht()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let c=D(o)?k()-o:void 0;this.logCloseAtEmptyBuffer({duration:c??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:a})=>{this.logError({fatal:!1,errorType:a})}),t(e.events.fatalError$,({id:a})=>{this.logError({fatal:!0,errorType:a})});let n,d,l=!1;t(e.events.firstBytes$,a=>{n=k(),this.logFirstBytes({time:a})}),t(e.events.willStart$,()=>d=k()),t(e.info.currentBuffer$,a=>{!l&&a&&a.end-a.start>0&&D(n)&&(this.logPlayerReady({duration:k()-n}),l=!0)}),t(e.events.firstFrame$,()=>{D(n)&&!l&&(this.logPlayerReady({duration:k()-n}),l=!0),D(d)&&this.logFirstFrame({time:k()-d})});let u;t(e.info.currentVideoStream$,a=>{a&&(u&&a.id!==u&&this.logTrackSwitch(a),u=a.id)});let h;t(e.info.currentAudioStream$,a=>{a&&(h&&a.id!==h&&this.logTrackSwitch(a),h=a.id)}),t(e.info.atLiveEdge$,a=>this.updateContext({liveEdge:a})),t(qe({muted:e.info.muted$,volume:e.info.volume$}),({muted:a,volume:c})=>this.updateContext({audible:!a&&c>0})),t(e.info.currentQuality$,a=>{let c=Re(a);this.updateContext({quality:c}),c&&this.logQuality(c)}),t(e.info.isAutoQualityEnabled$,a=>this.updateContext({autoQuality:a})),t(e.info.currentFormat$,a=>this.updateContext({contentType:Ve(a)})),t(e.info.currentPlaybackRate$,a=>this.updateContext({rate:a})),t(e.info.is3DVideo$,a=>this.updateContext({is3d:a}));let p;return t(e.info.hostname$,a=>{let c=p!==void 0&&p!==a;this.updateContext({cdnHostname:a,failover:c}),c&&this.logFailover(a),p=a}),t(e.info.throughputEstimation$,a=>this.updateContext({downloadSpeed:a})),t(e.info.httpConnectionType$,a=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:he(a)}),this.updateContext({connectionType:he(a)})}),t(e.info.httpConnectionReused$,a=>{Qe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:a}),this.updateContext({connectionReused:a})}),t(e.info.surface$,a=>this.updateContext({mode:K(a)})),t(qe({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:a,available:c})=>{let m=c.find(({id:I})=>I===a),f=m&&(m.isAuto?`${m.language}_auto`:m.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}=ge();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":K(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":K(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o.split(".")[0]})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=ge();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}=ge();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"}),this.vsid$.next(Be())}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(Ft(ze(e,"change"),Ut(["init"])).subscribe(()=>this.updateContext({network:Me(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=ze(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 r=this.timeSynchronisation?.now()??k(),n=this.vsid$.getValue();Bt(n);let d=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,h,p;if(this.isEmbed||this.statContext.place==="embed"){h=this.embedParent;let c=[...new URLSearchParams(location.search).entries()].filter(([m,f])=>this.config.embedUrlParams.includes(m));p=new URLSearchParams(c).toString()}else this.statContext.place==="direct"&&(this.statContext.refDomain?h=Ge(this.statContext.refDomain)?.hostname??this.statContext.refDomain:document.referrer&&(h=Ge(document.referrer)?.hostname??document.referrer),p=location.href.substring(0,1024));let a={vsid:n,isid:d,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:u===!0?1:u===!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:h,direct_url:p,rate:this.statContext.rate===1||Qe(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 c of this.config.disabledCustomFields)delete a[c];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:a}}};var St={};Et(St,{SeekType:()=>Q,ThinOneStat:()=>te,VERSION:()=>_});import{assertNonNullable as ai,detectEmbed as di,fromEvent as ci,Logger as ui,merge as mt,safeStorage as bt,Subject as li,Subscription as Ae,ValueSubject as ee}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as L,PlaybackState as vt}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as Qt}from"@vkontakte/videoplayer-shared/evergreen";var Q=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(Q||{});var Je="CIOPGQJGDIHBABABA",ve={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 jt={apiKey:Je,apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:15,synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1},Ze=s=>Qt(s,jt);import{getExponentialDelay as Gt,ErrorCategory as N,ValueSubject as Yt}from"@vkontakte/videoplayer-shared/evergreen";var j=class{constructor(e){this.params=e,this.authorized$=new Yt(!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={},r=this.sessionKey??await this.authorizeWithBackoff();if(!r)return;let n=async(d,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,r,o)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:N.NETWORK,message:`Unknown ${i} error`,thrown:u});return}let h=u?.error_code;switch(h){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),l>0?n(d,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),l>0?n(d,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:N.EXTERNAL_API,message:`${i} error`,data:u});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){return{collector:"ok.mobile.apps.video",uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${_}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=Gt(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:N.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:_.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:N.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:N.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:N.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 Ie,ErrorCategory as G}from"@vkontakte/videoplayer-shared/evergreen";var Y=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=ve[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}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:G.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let r=Ie(),n=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:G.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:G.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:Ie()-r}})};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(d=>{let l=Number(d.headers.get("content-length"))===0,u=new Date(d.headers.get("date")??"").getTime(),h=Ie()-r;if(isFinite(u)&&this.timeSynchronisation?.addServerTime(u,h),!l)return d.json().then(p=>Object.prototype.hasOwnProperty.call(p,"error_msg")?Promise.reject(p):p,n)},n)}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:G.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),ve.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 Xt,now as Jt,safeStorage as F,debounceFn as et}from"@vkontakte/videoplayer-shared/evergreen";var X="thinonestat_events",Se=s=>e=>e.client_time+s>=Jt(),J=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=et(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=F.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:Xt.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=F.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(Se(this.params.config.storageExpiration));F.set(X,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(Se(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],F.set(X,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(Se(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`})}F.set(X,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 ye(){let s="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]=s[o===19?t&3|8:t]);return e.join("")}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 tt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Zt,Subscription as ei,ValueSubject as ti,Subject as _e,fromEvent as ii,isNullable as it,merge as Pe,filter as ot,filterChanged as rt}from"@vkontakte/videoplayer-shared/evergreen";var st=(s,e)=>new Zt(i=>{let t=new ei,o=new ti(void 0),r;t.add(s.info.isLive$.pipe(rt()).subscribe(y=>{r&&(r.unsubscribe(),o.next(void 0)),y?r=s.info.liveTime$.pipe(rt()).subscribe(o):r=s.info.position$.subscribe(o),t.add(r)}));let{playing$:n,paused$:d,ended$:l,looped$:u}=s.events,h=s.events.willSeek$.pipe(ot(()=>s.info.playbackState$.getValue()===tt.PLAYING)),p=s.events.seeked$.pipe(ot(()=>s.info.playbackState$.getValue()===tt.PLAYING)),a=!1,c=new _e;t.add(h.subscribe(()=>{a||c.next(),a=!0})).add(p.subscribe(()=>a=!1));let m=Pe(ii(window,"beforeunload"),s.events.willDestruct$),f,I=()=>f=o.getValue(),S=()=>{let y=o.getValue();it(f)||it(y)||f===y||(i.next({from:f,to:y}),f=void 0)},A=new _e,w=new _e,T=Pe(n,c,A),g=Pe(d,p,m,l,u,w);if(t.add(T.subscribe(I)).add(g.subscribe(S)),e.heartbeatInterval&&isFinite(e.heartbeatInterval)){let y=[],yt=e.heartbeatInterval*1e3,_t=()=>{w.next(),A.next()};t.add(T.subscribe(()=>{let ie=window.setTimeout(_t,yt);y.push(ie)})).add(g.subscribe(()=>{y.forEach(ie=>{window.clearTimeout(ie)}),y=[]}))}return t});import{Subscription as oi}from"@vkontakte/videoplayer-core/evergreen";import{Observable as ri}from"@vkontakte/videoplayer-shared/evergreen";var nt=(s,e)=>new ri(i=>{let t=new oi,o=1e4,r=0;return t.add(s.info.position$.subscribe(()=>{let n=e.getTotalViewTime()*1e3;n>r&&n%o===0&&(r=n,i.next({target_duration:o,current_tvt:n}))})),t});import{Observable as si,Subscription as ni,merge as at}from"@vkontakte/videoplayer-shared/evergreen";var dt=s=>new si(e=>{let i=new ni,t=0,o=1,r=0,n=!1,d=!1,l=()=>{if(!n)return;let g=Date.now();r+=(g-t)*o,t=g},u=()=>{(!n||d)&&(t=Date.now(),n=!0,d=!1)},h=()=>{n&&(l(),n=!1)},p=()=>{n&&(l(),n=!1,d=!0)},a=g=>{n&&l(),o=g,t=Date.now()},{started$:c,playing$:m,paused$:f,willSeek$:I,ended$:S,willDestruct$:A}=s.events,{currentPlaybackRate$:w}=s.info;i.add(I.subscribe(p)).add(at(c,m).subscribe(u)).add(at(f,S,A).subscribe(h)).add(w.subscribe(a));let T=()=>{let g=r;return n&&(g+=(Date.now()-t)*o),Math.floor(g/1e3)};return e.next(T),i});import{assertNever as ct}from"@vkontakte/videoplayer-shared/evergreen";import{Surface as O,VideoFormat as b,VideoQuality as E}from"@vkontakte/videoplayer-core/evergreen";var Ee=s=>{if(s!==void 0)switch(s){case b.MPEG:return"MP4";case b.DASH:case b.DASH_LIVE:return"DASH";case b.DASH_SEP:return"DASH_SEP";case b.DASH_ONDEMAND:return"ONDEMAND_DASH";case b.HLS_ONDEMAND:return"ONDEMAND_HLS";case b.HLS:case b.HLS_LIVE:return"HLS";case b.DASH_WEBM:case b.DASH_LIVE_WEBM:return"WEBM";case b.DASH_LIVE_CMAF:return"ONDEMAND_DASH_LIVE";case b.HLS_LIVE_CMAF:return"ONDEMAND_HLS_LIVE";case b.WEB_RTC_LIVE:return"WEBRTC";case b.DASH_WEBM_AV1:return"AV1";case b.DASH_STREAMS:return"MULTI_DASH";default:return ct(s)}},x=s=>{if(s!==void 0)switch(s){case E.Q_144P:return"144p";case E.Q_240P:return"240p";case E.Q_360P:return"360p";case E.Q_480P:return"480p";case E.Q_720P:return"720p";case E.Q_1080P:return"1080p";case E.Q_1440P:return"1440p";case E.Q_2160P:return"2160p";case E.INVARIANT:case E.Q_576P:case E.Q_4320P:return"UNKNOWN";default:return ct(s)}},ut=s=>{if(s!==void 0)switch(s){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"WEBRTC":return"live";default:return}},lt=(s,e,i)=>{if(s&&e)switch(s){case b.MPEG:return i&&e[s]&&e[s][i];default:return e[s]?.url}},ht=s=>{if(s!==void 0)switch(s){case O.NONE:return;case O.INLINE:return"inline";case O.FULLSCREEN:return"fullscreen";case O.SECOND_SCREEN:return"chromecast";case O.PIP:return"pip_external"}},pt=s=>{if(s!==void 0)return s===O.INVISIBLE?"background":"foreground"};var ft=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),gt=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var hi="_thin-one-stat_",It=`${hi}deviceId`,pi=()=>{let s=new Ae;return{subscription:s,subscribe:(e,i)=>{e&&s.add(e.subscribe(i))}}},te=class{constructor(e,i){this.debugLogger=new ui;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.seekAction$=new ee("unknown");this.playerSize$=new ee({width:0,height:0});this.vsid$=new ee(void 0);this.isid$=new ee(void 0);this.statContext=e,this.config=Ze(i.config??{}),this.subscription=new Ae,this.config.synchronizeTime&&(this.timeSynchronisation=new Z);let t=new li,o=bt.get(It);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=ye(),bt.set(It,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??gt());let r=new Y({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new j({config:this.config,apiTransport:r,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new J({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,topOrigin:d}=di();this.isEmbed=n,this.embedHostname=d?new URL(d).hostname:void 0}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new Ae,t=(r,n)=>i.add(r.subscribe(n));t(dt(e),r=>{this.getTotalViewTime=r}),t(e.info.isLive$,r=>this.isLive=r),t(e.info.position$,r=>this.position=r);let o;return t(e.info.hostname$,r=>{o!==void 0&&o!==r&&this.logFailover({cdn_host:r}),this.cdnHostname=o=r}),t(st(e,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),r=>{let n=Math.round(r.from*1e3),d=Math.round(r.to*1e3),l={watch_interval:`${n}-${d}`,in_history:!!this.statContext.inHistory,content_type:Ee(e.info.currentFormat$.getValue()),playback_quality:x(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(l);else{let h=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...l,live:!!h})}}),t(nt(e,{getTotalViewTime:this.getTotalViewTime}),r=>{this.logWatchedN(r)}),t(mt(e.events.willStart$,e.events.looped$),r=>{r&&this.resetViewSession();let n={isid:this.isid$.getValue(),stream_profile:ut(Ee(e.info.currentFormat$.getValue())),dpi:L.display.pixelRatio,web_layout:L.device.isMobile?"mobile":"desktop",iframe_host:this.isEmbed?this.embedHostname??void 0:null,from_downloads:!0,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.logStartSession(n)}),t(e.events.willReady$,()=>{if(this.statContext.preload){let r=e.info.currentFormat$.getValue(),n=e.info.availableSources$.getValue(),d=e.info.currentBuffer$.getValue(),l=e.info.currentQuality$.getValue(),u={target_buffer_time:d?d.end-d.start:void 0,playback_url:lt(r,n,l),playback_quality:x(l)};this.logPreloadStarted(u)}}),t(e.events.ready$,()=>{if(this.statContext.preload){let r=e.info.currentBuffer$.getValue(),n={buffer_time:r?r.end-r.start:void 0};this.logPreloadEnded(n)}}),t(e.events.playing$,()=>{this.logPlay()}),t(e.info.playbackState$,r=>{if(r===vt.PLAYING){let n=e.info.currentBuffer$.getValue(),d={buffer_time:n?n.end-n.start:void 0};if(this.logPlaying(d),this.isStarted)this.logResume();else{this.isStarted=!0;let l=e.info.currentQuality$.getValue(),u=e.info.isAutoQualityEnabled$.getValue(),h=e.info.muted$.getValue(),p=e.info.volume$.getValue(),a=e.info.surface$.getValue(),c=e.info.availableTextTracks$.getValue(),m=e.info.currentTextTrack$.getValue(),f=e.info.currentAudioStream$.getValue(),I=e.info.currentPlaybackRate$.getValue(),S={playback_quality:x(l),user_quality:u?"auto":x(l),player_width:this.playerSize$.getValue().width,player_height:this.playerSize$.getValue().height,muted:h,sound_volume:p,buffer_time:n?Math.round(n.end-n.start):void 0,mode:ht(a),visibility:pt(a),subtitles_enabled:!!m,auto_subtitles:!!c.find(({id:A})=>A===m)?.isAuto,audio_track_lang:f?.language,playback_rate:I,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(S)}}else r===vt.PAUSED&&this.logPause()}),t(e.events.willSeek$,({to:r})=>{let n={target_position:r,seek_type:this.seekAction$.getValue()};this.logSeeking(n)}),t(e.events.seeked$,()=>{let n={target_position:e.info.position$.getValue(),seek_type:this.seekAction$.getValue()};this.logSeeked(n),this.seekAction$.next("unknown")}),t(mt(e.info.isBuffering$,e.info.isStalled$),r=>{r&&this.logShowLoader()}),t(e.info.currentQuality$,r=>{if(r){let n=e.info.isAutoQualityEnabled$.getValue(),d=e.info.currentVideoStream$.getValue()?.codec,l=e.info.currentAudioStream$.getValue()?.codec,u={user_quality:n?"auto":x(r),playback_quality:x(r),download_quality:x(r),codec_info:d&&l?`${d},${l}`:void 0,manual_switch:!n};this.logQualityChanged(u)}}),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){let{subscribe:i,subscription:t}=pi();return i(e.actionSeek$,this.seekAction$),i(e.playerSize$,this.playerSize$),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ft()),this.eventNumber=0}destroy(){this.api.destroy()}createRequiredParams(e){let i=this.vsid$.getValue();ai(i);let t=this.eventNumber++;return{vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:`@vkontakte/videoplayer-statistics:${_}`,platform:`web:${L.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:this.isLive?void 0:Math.round(this.position),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname}}createRequiredFatParams(){return{stats_version:_,browser:L.browser.current,browser_version:String(L.browser.currentVersion),os:L.device.current,os_version:"",device_type:L.device.isMobile?"mobile":"desktop",navigation:this.statContext.navigation}}log(e,i,t=!1){let o=this.createRequiredParams(e),r={};t&&(r=this.createRequiredFatParams()),this.logger.log({...o,...r,...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)}logPlaybackStarted(e){this.log("playback_started",e,!0)}logPlay(){this.log("play")}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)}logShowLoader(){this.log("show_loader")}logQualityChanged(e){this.log("quality_changed",e)}logFailover(e){this.log("failover",e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=ci(window,"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};export{R as ApiEnv,se as ConnectionType,re as ContentType,we as InteractiveInterfaceClick,be as OneStat,oe as Quality,ne as SeekAction,St as ThinOneStat,_ as VERSION};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-statistics",
3
- "version": "1.0.82-dev.505e7dcd.0",
3
+ "version": "1.0.82-dev.5160770c.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.136-dev.2d84cdb2.0",
58
- "@vkontakte/videoplayer-shared": "1.0.64-dev.6c7e23ee.0"
57
+ "@vkontakte/videoplayer-core": "2.0.136-dev.b4f06324.0",
58
+ "@vkontakte/videoplayer-shared": "1.0.64-dev.12fe6571.0"
59
59
  }
60
60
  }