@vkontakte/videoplayer-statistics 1.0.96-dev.4e3741f9.0 → 1.0.96-dev.c564bb3a.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs +3 -3
- package/es2015.esm.js +3 -3
- package/es2018.cjs +3 -3
- package/es2018.esm.js +3 -3
- package/es2024.cjs +3 -3
- package/es2024.esm.js +3 -3
- package/esnext.cjs +3 -3
- package/esnext.esm.js +3 -3
- package/evergreen.esm.js +3 -3
- package/package.json +3 -3
package/evergreen.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.96-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.96-dev.c564bb3a.0
|
|
3
|
+
* Wed, 14 Jan 2026 08:57:48 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-96/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Nt=Object.defineProperty;var Mt=(n,e)=>{for(var i in e)Nt(n,i,{get:e[i],enumerable:!0})};var U=(d=>(d.PROD="prod",d.VK_ALIAS="vk_alias",d.VIDEOTEST="videotest",d.TEST="test",d.OKCDN="okcdn",d.AUTO="auto",d))(U||{}),pe=(r=>(r.Q144P="mobile",r.Q240P="lowest",r.Q360P="low",r.Q480P="medium",r.Q720P="high",r.Q1080P="fullhd",r.Q1440P="quadhd",r.Q2160P="ultrahd",r.UNKNOWN="unknown",r))(pe||{}),fe=(f=>(f.MP4="mp4",f.DASH="dash",f.DASH_SEP="dash_sep",f.ONDEMAND_DASH="ondemand_dash",f.HLS="hls",f.HLS_FMP4="hls_fmp4",f.ONDEMAND_HLS="ondemand_hls",f.WEBM="webm",f.AV1="av1",f.ONDEMAND_DASH_LIVE="ondemand_dash_live",f.ONDEMAND_HLS_LIVE="ondemand_hls_live",f.WEBRTC="webrtc",f.UNKNOWN="unknown",f.RTMP="rtmp",f))(fe||{});var ge=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(ge||{});var me=(c=>(c.SLIDER="slider",c.DOUBLE_TAP="double_tap",c.TIME_CODE="time_code",c.EPISODE="episode",c.REWIND="rewind",c.LIVE="live",c.UNKNOWN="unknown",c))(me||{}),qe=(s=>(s.GRAPH_SHOW="iGraphShow",s.GRAPH_HIDE="iGraphHide",s.NEXT_AREA="iNextChapterArea",s.NEXT_BUTTON="iNextChapterBtn",s.WATCH_AGAIN="iWatchAgainBtn",s))(qe||{}),Qe={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"},We={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"},Ke={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},ze={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv",minimal:"minimal"};import{fillWithDefault as Vt}from"@vkontakte/videoplayer-shared/evergreen";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 Ot={apiEnv:"vk_alias",apiKey:je,apiBaseUrl:null,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},useKeepalive:!1,watchCoverageTimeoutFix:!1},Ge=n=>Vt(n,Ot);function be(){let n="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]=n[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as ei,combine as at,fromEvent as dt,isNonNullable as V,isNullable as ct,merge as ti,now as $,observableFrom as ii,once as oi,safeStorage as lt,Subject as ri,Subscription as we,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as si,detectEmbed as ni}from"@vkontakte/videoplayer-shared/evergreen";var Ft=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),R=class n{static getVSID(){return n.vsid}static generateVSID(){return n.vsid=Ft(),n.vsid}};var Ye=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,s])=>{let d=We[o]??o,c=s;return s&&(o==="mode"?c=ze[s]??s:o==="quality"&&(c=Ke[s]??s)),[d,c]}));return{...n,operation:Qe[e]??e,custom:t}};var _="1.0.96-dev.4e3741f9.0";import{ValueSubject as Bt,getExponentialDelay as Ut,ErrorCategory as N}from"@vkontakte/videoplayer-shared/evergreen";var Ht=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,H=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Bt(!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 s=async(d,c=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:N.NETWORK,message:`Unknown ${i} error`,thrown:h});return}let r=h?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),c>0?s(d,c-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),c>0?s(d,c-1):void 0;default:{this.params.error$.next({id:`LogRequest#${r}`,category:N.EXTERNAL_API,message:`${i} error`,data:h});return}}}};return s(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:s}=window.navigator;t=Ht.test(s)}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(Ye):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ut(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:N.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: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{ErrorCategory as z,now as Ie}from"@vkontakte/videoplayer-shared/evergreen";var q=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??ve[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:z.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),ve.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}),s=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,s)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:z.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=Ie(),s=c=>{if(c instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(c.message)){this.params.error$.next({id:"Network",category:z.NETWORK,message:"Request failed",thrown:c});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:z.NETWORK,message:"Unhandled request error",thrown:c,data:{method:e,params:i,sessionKey:t,time:Ie()-o}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let d={method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})};return this.params.config.useKeepalive&&(d.keepalive=!0),fetch(`${this.apiBaseUrl}/fb.do`,d).then(c=>{let h=Number(c.headers.get("content-length"))===0,r=new Date(c.headers.get("date")??"").getTime(),l=Ie()-o;if(isFinite(r)&&this.timeSynchronisation?.addServerTime(r,l),!h)return c.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,s)},s)}_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 qt,now as Qt,safeStorage as Q,debounceFn as Xe}from"@vkontakte/videoplayer-shared/evergreen";var j="onestat_events",ye=n=>e=>e.timestamp+n>=Qt(),G=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=Xe(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=Q.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Xe(()=>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:qt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=Q.get(j);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(ye(this.params.config.storageExpiration));Q.set(j,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(ye(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],Q.set(j,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(ye(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`})}Q.set(j,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 Se,Surface as M,VideoFormat as I,VideoQuality as T}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as Je}from"@vkontakte/videoplayer-shared/evergreen";var Ze=n=>n&&{[T.INVARIANT]:"unknown",[T.Q_144P]:"mobile",[T.Q_240P]:"lowest",[T.Q_360P]:"low",[T.Q_480P]:"medium",[T.Q_576P]:"unknown",[T.Q_720P]:"high",[T.Q_1080P]:"fullhd",[T.Q_1440P]:"quadhd",[T.Q_2160P]:"ultrahd",[T.Q_4320P]:"unknown"}[n],_e=n=>n&&{[Se.HTTP1]:"http1",[Se.HTTP2]:"http2",[Se.QUIC]:"http3"}[n],et=n=>{if(n!==void 0)switch(n){case I.MPEG:return"mp4";case I.DASH:case I.DASH_LIVE:case I.DASH_STREAMS:return"dash";case I.DASH_SEP:return"dash_sep";case I.DASH_ONDEMAND:return"ondemand_dash";case I.DASH_WEBM:case I.DASH_LIVE_WEBM:return"webm";case I.DASH_WEBM_AV1:return"av1";case I.DASH_LIVE_CMAF:return"ondemand_dash_live";case I.HLS:case I.HLS_LIVE:return"hls";case I.HLS_FMP4:return"hls_fmp4";case I.HLS_ONDEMAND:return"ondemand_hls";case I.HLS_LIVE_CMAF:return"ondemand_hls_live";case I.WEB_RTC_LIVE:return"webrtc";default:return Je(n)}},Pe=(n,e)=>{if(e)return"minimal";switch(n){case void 0:case M.NONE:case M.INLINE:return;case M.FULLSCREEN:return"fullscreen";case M.SECOND_SCREEN:return"chromecast";case M.PIP:return"pip";case M.INVISIBLE:return"invisible";default:return Je(n)}},tt=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var Y=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 it=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ot}from"@vkontakte/videoplayer-core/evergreen";import{filter as rt,filterChanged as Wt,fromEvent as Kt,isNullable as st,map as zt,merge as Te,Observable as jt,Subject as Ee,Subscription as Gt,ValueSubject as Yt}from"@vkontakte/videoplayer-shared/evergreen";var nt=(n,e)=>new jt(i=>{let t=new Gt,o=Te(Kt(window,"beforeunload"),n.events.willDestruct$),s=new Yt(void 0),d;t.add(n.info.isLive$.pipe(Wt()).subscribe(g=>{d&&(d.unsubscribe(),s.next(void 0)),g?d=n.info.liveTime$.pipe(zt(w=>w&&w/1e3)).subscribe(s):d=n.info.position$.subscribe(s),t.add(d)}));let{playing$:c,paused$:h}=n.events,r=n.events.willSeek$.pipe(rt(()=>n.info.playbackState$.getValue()===ot.PLAYING)),l=n.events.seeked$.pipe(rt(()=>n.info.playbackState$.getValue()===ot.PLAYING)),u=!1,a=new Ee;t.add(r.subscribe(()=>{u||a.next(),u=!0})),t.add(l.subscribe(()=>u=!1));let p=new Ee,f=new Ee,v=Te(c,l,p),m=Te(h,a,o,n.events.looped$,f),y,C=()=>y=s.getValue(),P=()=>{let g=s.getValue();st(y)||y===g||st(g)||(i.next({from:y,to:g}),y=void 0)},S=()=>{f.next(),p.next()};if(t.add(v.subscribe(C)),t.add(m.subscribe(P)),e.forceInterval&&isFinite(e.forceInterval))if(e.watchCoverageTimeoutFix){let g,w=()=>{g!==void 0&&(window.clearTimeout(g),g=void 0)};t.add(v.subscribe(()=>{w(),g=window.setTimeout(S,e.forceInterval)})),t.add(m.subscribe(()=>w())),t.add(()=>w())}else{let g=0;t.add(v.subscribe(()=>g=window.setTimeout(S,e.forceInterval))),t.add(m.subscribe(()=>window.clearTimeout(g)))}return t});import{Surface as x}from"@vkontakte/videoplayer-core/evergreen";import{debounce as Xt,filterChanged as Jt,Subject as Zt}from"@vkontakte/videoplayer-shared/evergreen";var X=(n,e,i)=>{let t=new Zt,o=t.pipe(Xt(0),Jt()),s=!1,d=!1,c=!1;return e(n.inPiP$,h=>{s=h,t.next(h?x.PIP:d?x.FULLSCREEN:c?x.INLINE:void 0)}),e(n.inFullscreen$,h=>{d=h,t.next(h?x.FULLSCREEN:s?x.PIP:c?x.INLINE:void 0)}),i&&e(i.info.surface$,h=>{switch(h){case x.SECOND_SCREEN:case x.NONE:case x.INLINE:{!d&&!s&&(h===x.INLINE&&(c=!0),t.next(h));break}}}),{surface$:o}};var ai="_one-stat_",ut=`${ai}deviceId`,Ae=()=>{let n=new we;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},xe=class{constructor(e,i){this.subscription=new we;this.debugLogger=new si;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.isid$=new J(void 0);this.zenUid$=new J(void 0);this.seekAction$=new J("unknown");this.statContext=e,this.config=Ge(i.config??{}),V(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Y);let t=new ri;this.experimental={error$:t};let o=lt.get(ut);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=be(),lt.set(ut,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??it()),this.zenUid$.next(i.zenUid);let s=new q({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new H({config:this.config,apiTransport:s,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new G({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,topOrigin:c}=ni();this.isEmbed=d,this.embedParent=c?new URL(c).hostname:void 0,this.subscribe()}get vsid$(){return new J(R.getVSID())}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new we,t=(a,p)=>i.add(a.subscribe(p));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(nt(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),a=>{let p=e.info.isLive$.getValue(),f=e.info.atLiveEdge$.getValue(),v={start:parseFloat(a.from.toFixed(3)),end:parseFloat(a.to.toFixed(3))};if(f){let m=e.info.liveLatency$.getValue()??0,y=e.info.currentBuffer$.getValue()?.end??0,C=e.info.liveBufferTime$.getValue()??0,P=Math.round((m-(y-C))*1e3),S=Math.round(m*1e3);P&&S&&(v.latency=P,v.bufferLatency=S)}p?this.logWatchCoverageLive(v):this.logWatchCoverageRecord(v)});let o;t(e.info.isStalled$,a=>{a?o=$():(V(o)&&this.logEmptyBuffer({duration:$()-o}),o=void 0)});let s=!1;i.add(e.events.fatalError$.pipe(oi()).subscribe(()=>s=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let p=V(o)?$()-o:void 0;this.logCloseAtEmptyBuffer({duration:p??0}),o=void 0}else s||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 d,c,h=!1;t(e.events.firstBytes$,a=>{d=$(),this.logFirstBytes({time:a})}),t(e.events.willStart$,()=>c=$()),t(e.info.currentBuffer$,a=>{!h&&a&&a.end-a.start>0&&V(d)&&(this.logPlayerReady({duration:$()-d}),h=!0)}),t(e.events.firstFrame$,()=>{V(d)&&!h&&(this.logPlayerReady({duration:$()-d}),h=!0),V(c)&&this.logFirstFrame({time:$()-c})});let r;t(e.info.currentVideoStream$,a=>{a&&(r&&a.id!==r&&this.logTrackSwitch(a),r=a.id)});let l;t(e.info.currentAudioStream$,a=>{a&&(l&&a.id!==l&&this.logTrackSwitch(a),l=a.id)}),t(e.info.atLiveEdge$,a=>this.updateContext({liveEdge:a})),t(at({muted:e.info.muted$,volume:e.info.volume$}),({muted:a,volume:p})=>this.updateContext({audible:!a&&p>0})),t(e.info.currentQuality$,a=>{let p=Ze(a);this.updateContext({quality:p}),p&&this.logQuality(p)}),t(e.info.isAutoQualityEnabled$,a=>this.updateContext({autoQuality:a})),t(e.info.currentFormat$,a=>this.updateContext({contentType:et(a)})),t(e.info.currentPlaybackRate$,a=>this.updateContext({rate:a})),t(e.info.is3DVideo$,a=>this.updateContext({is3d:a}));let u;return t(e.info.hostname$,a=>{let p=u!==void 0&&u!==a;this.updateContext({cdnHostname:a,failover:p}),p&&this.logFailover(a),u=a}),t(e.info.throughputEstimation$,a=>this.updateContext({downloadSpeed:a})),t(e.info.httpConnectionType$,a=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:_e(a)}),this.updateContext({connectionType:_e(a)})}),t(e.info.httpConnectionReused$,a=>{ct(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:a}),this.updateContext({connectionReused:a})}),t(e.info.surface$,a=>{this.uiEvents||this.updateContext({mode:Pe(a,this.statContext.isPreviewPlayerView)})}),t(at({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:a,available:p})=>{let f=p.find(({id:m})=>m===a),v=f&&(f.isAuto?`${f.language}_auto`:f.language);this.updateContext({subtitles:v?.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}=Ae();if(!this.player)return i;t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$);let{surface$:o}=X(this.uiEvents,t,this.player);return t(o,s=>{this.updateContext({mode:Pe(s,this.statContext.isPreviewPlayerView)})}),t(e.actionSetSubtitle$,s=>this.updateContext({subtitles:s?.split(".")[0]})),t(e.nextMovie$,s=>this.logNextMovie(s)),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToAds(e){let{subscription:i,subscribe:t}=Ae();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}=Ae();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"}),R.generateVSID()}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(ti(dt(e,"change"),ii(["init"])).subscribe(()=>this.updateContext({network:tt(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=dt(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 s=this.timeSynchronisation?.now()??$(),d=this.vsid$.getValue();ei(d);let c=this.isid$.getValue(),h=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,r=this.statContext.firstConnectionReused,l,u;if(this.isEmbed||this.statContext.place==="embed"){l=this.embedParent;let p=[...new URLSearchParams(location.search).entries()].filter(([f,v])=>this.config.embedUrlParams.includes(f));u=new URLSearchParams(p).toString()}else if(this.statContext.place==="direct"){let p=this.statContext.refDomain||document.referrer;p&&URL.canParse(p)?l=new URL(p).hostname:l=p,u=location.href.substring(0,1024)}let a={vsid:d,isid:c,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:h,connection_reused:r===!0?1:r===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:l,direct_url:u,rate:this.statContext.rate===1||ct(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 p of this.config.disabledCustomFields)delete a[p];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:s,custom:a}}};var Ct={};Mt(Ct,{ActionSeekType:()=>Z,ThinOneStat:()=>le,VERSION:()=>_});import{assertNonNullable as _i,detectEmbed as Pi,fromEvent as Ti,Logger as Ei,merge as Ve,combine as ce,filter as B,filterChanged as Ai,safeStorage as wt,Subject as wi,Subscription as Fe,ValueSubject as Oe}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as k}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as di}from"@vkontakte/videoplayer-shared/evergreen";var ke=(t=>(t.AUTO="auto",t.AUTO_POOR="auto_poor",t.AUTO_RICH="auto_rich",t))(ke||{});var Z=(c=>(c.SLIDER="slider",c.DOUBLE_TAP="double_tap",c.TIME_CODE="time_code",c.EPISODE="episode",c.REWIND="rewind",c.LIVE="live",c.UNKNOWN="unknown",c))(Z||{});var pt="CIOPGQJGDIHBABABA",Ce={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 ci={apiKey:pt,apiEnv:"okcdn",apiBaseUrl:null,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:30,synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNFirstTvtLog:1e3,watchedNDefaultTargetDuration:1e4},ft=n=>di(n,ci);import{getExponentialDelay as li,ErrorCategory as O,ValueSubject as ui}from"@vkontakte/videoplayer-shared/evergreen";var ee=class{constructor(e){this.params=e,this.authorized$=new ui(!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={},s=this.sessionKey??await this.authorizeWithBackoff();if(!s)return;let d=async(c,h=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,s,o)}catch(r){if(!r||!("error_code"in r)){this.params.error$.next({id:"logRequestUnknown",category:O.NETWORK,message:`Unknown ${i} error`,thrown:r});return}let l=r?.error_code;switch(l){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),h>0?d(c,h-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),h>0?d(c,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${l}`,category:O.EXTERNAL_API,message:`${i} error`,data:r});return}}}};return d(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=li(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:O.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:O.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:O.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:O.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 Le,ErrorCategory as te}from"@vkontakte/videoplayer-shared/evergreen";var ie=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ce[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}),s=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,s)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:te.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let s=Le(),d=c=>{if(c instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(c.message)){this.params.error$.next({id:"Network",category:te.NETWORK,message:"Request failed",thrown:c});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:te.NETWORK,message:"Unhandled request error",thrown:c,data:{method:e,params:i,sessionKey:t,time:Le()-s}})};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(c=>{let h=Number(c.headers.get("content-length"))===0,r=new Date(c.headers.get("date")??"").getTime(),l=Le()-s;if(isFinite(r)&&this.timeSynchronisation?.addServerTime(r,l),!h)return c.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,d)},d)}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:te.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Ce.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 hi,now as pi,safeStorage as W,debounceFn as gt}from"@vkontakte/videoplayer-shared/evergreen";var oe="thinonestat_events",$e=n=>e=>e.client_time+n>=pi(),re=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=gt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=W.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=gt(()=>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:hi.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=W.get(oe);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter($e(this.params.config.storageExpiration));W.set(oe,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter($e(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],W.set(oe,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter($e(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}W.set(oe,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 Re(){let n="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]=n[o===19?t&3|8:t]);return e.join("")}var se=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 mt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as fi,Subscription as gi,ValueSubject as mi,Subject as De,fromEvent as vi,isNullable as vt,merge as K,filter as bt,filterChanged as It}from"@vkontakte/videoplayer-shared/evergreen";var yt=(n,e,i)=>new fi(t=>{let o=new gi,s=new mi(void 0),d;o.add(n.info.isLive$.pipe(It()).subscribe(L=>{d&&(d.unsubscribe(),s.next(void 0)),L?d=n.info.liveTime$.pipe(It()).subscribe(s):d=n.info.position$.subscribe(s),o.add(d)}));let{playing$:c,paused$:h,ended$:r,looped$:l}=n.events,u=n.events.willSeek$.pipe(bt(()=>n.info.playbackState$.getValue()===mt.PLAYING)),a=n.events.seeked$.pipe(bt(()=>n.info.playbackState$.getValue()===mt.PLAYING)),p=!1,f=new De;o.add(u.subscribe(()=>{p||f.next(),p=!0})).add(a.subscribe(()=>p=!1));let v=K(vi(window,"beforeunload"),n.events.willDestruct$),m,y=()=>m=s.getValue(),C=()=>{let L=s.getValue();vt(m)||vt(L)||m===L||(t.next({from:m,to:L}),m=void 0)},P=new De,S=new De,g=K(c,f,P),w=K(h,a,v,r,l,S),Ue=e.started$&&e.ended$?K(g,e.ended$):g,He=e.started$&&e.ended$?K(w,e.started$):w;if(o.add(Ue.subscribe(y)).add(He.subscribe(C)),i.heartbeatInterval&&isFinite(i.heartbeatInterval)){let L=[],Rt=i.heartbeatInterval*1e3,Dt=()=>{S.next(),P.next()};o.add(Ue.subscribe(()=>{let he=window.setTimeout(Dt,Rt);L.push(he)})).add(He.subscribe(()=>{L.forEach(he=>{window.clearTimeout(he)}),L=[]}))}return o});import{Subscription as bi}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Ii}from"@vkontakte/videoplayer-shared/evergreen";var St=(n,e)=>new Ii(i=>{let t=new bi,o=0;return t.add(n.info.position$.subscribe(()=>{let s=e.getTotalViewTime()*1e3;s>o&&(s===e.firstTvtLog||s%e.targetDuration===0)&&(o=s,i.next({target_duration:e.targetDuration,current_tvt:s}))})),t});import{Observable as yi,Subscription as Si,merge as _t}from"@vkontakte/videoplayer-shared/evergreen";var Pt=n=>new yi(e=>{let i=new Si,t=0,o=1,s=0,d=!1,c=!1,h=()=>{if(!d)return;let g=Date.now();s+=(g-t)*o,t=g},r=()=>{(!d||c)&&(t=Date.now(),d=!0,c=!1)},l=()=>{d&&(h(),d=!1)},u=()=>{d&&(h(),d=!1,c=!0)},a=g=>{d&&h(),o=g,t=Date.now()},{started$:p,playing$:f,paused$:v,willSeek$:m,ended$:y,willDestruct$:C}=n.events,{currentPlaybackRate$:P}=n.info;i.add(m.subscribe(u)).add(_t(p,f).subscribe(r)).add(_t(v,y,C).subscribe(l)).add(P.subscribe(a));let S=()=>{let g=s;return d&&(g+=(Date.now()-t)*o),g};return e.next(S),i});import{assertNever as Tt}from"@vkontakte/videoplayer-shared/evergreen";import{HttpConnectionType as Ne,Surface as F,VideoFormat as b,VideoQuality as E}from"@vkontakte/videoplayer-core/evergreen";var Me=n=>n&&{[Ne.HTTP1]:"http1",[Ne.HTTP2]:"http2",[Ne.QUIC]:"http3"}[n],ne=n=>{if(n!==void 0)switch(n){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.HLS_FMP4:return"HLS_FMP4";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 Tt(n)}},A=n=>{if(n!==void 0)switch(n){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 Tt(n)}},Et=n=>{if(n!==void 0)switch(n){case"MP4":case"ONDEMAND_DASH":case"ONDEMAND_DASH_LIVE":case"ONDEMAND_HLS":case"ONDEMAND_HLS_LIVE":case"MULTI_DASH":case"WEBM":case"AV1":return"vod";case"DASH":case"HLS":case"HLS_FMP4":case"WEBRTC":return"live";default:return}},D=(n,e,i)=>{if(n&&e)switch(n){case b.MPEG:return i&&e[n]&&e[n][i];default:return e[n]?.url}},ae=(n,e=!1)=>{if(e)return"minimal";switch(n){case void 0:case F.NONE:return;case F.INLINE:return"inline";case F.FULLSCREEN:return"fullscreen";case F.SECOND_SCREEN:return"chromecast";case F.PIP:return"pip_external"}},de=n=>{switch(n){case void 0:return;case F.INVISIBLE:return"background";default:return"foreground"}};var At=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var xi="_thin-one-stat_",xt=`${xi}deviceId`,kt=()=>{let n=new Fe;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},le=class{constructor(e,i){this.debugLogger=new Ei;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.playerSize={width:0,height:0};this.seekAction$=new Oe("unknown");this.isid$=new Oe(void 0);this.statContext=e,this.config=ft(i.config??{}),this.subscription=new Fe,this.config.synchronizeTime&&(this.timeSynchronisation=new se);let t=new wi,o=wt.get(xt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=Re(),wt.set(xt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??At());let s=new ie({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new ee({config:this.config,apiTransport:s,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new re({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,topOrigin:c}=Pi();this.isEmbed=d,this.embedHostname=c?new URL(c).hostname:void 0}get vsid$(){return new Oe(R.getVSID())}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,i){let t=new Fe,o=(r,l)=>t.add(r.subscribe(l));o(Pt(e),r=>{this.getTotalViewTime=r}),o(e.info.isLive$,r=>this.isLive=r);let s;o(ce({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(B(({hostname:r})=>r!==void 0),B(({connectionType:r})=>r!==void 0),B(({connectionReused:r})=>r!==void 0)),({hostname:r,connectionType:l,connectionReused:u})=>{if(s!==void 0&&s!==r){let p={cdn_host:r,connection_type:Me(l),connection_reused:u,content_type:ne(e.info.currentFormat$.getValue())};this.logFailover(p)}this.cdnHostname=s=r}),o(e.info.httpConnectionType$,r=>{this.connectionType=Me(r)}),o(e.info.httpConnectionReused$,r=>{this.connectionReused=r}),o(yt(e,i,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),r=>{let l=Math.round(r.from*1e3),u=Math.round(r.to*1e3),a={watch_interval:`${l}-${u}`,in_history:!!this.statContext.inHistory,content_type:ne(e.info.currentFormat$.getValue()),playback_quality:A(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(a);else{let f=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...a,live:!!f})}}),o(St(e,{targetDuration:this.targetDuration,firstTvtLog:this.config.watchedNFirstTvtLog,getTotalViewTime:this.getTotalViewTime}),r=>{this.logWatchedN(r)}),o(e.events.willReady$,()=>{if(this.statContext.preload){let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentBuffer$.getValue(),a=e.info.currentQuality$.getValue(),p={target_buffer_time:this.calcBufferTime(u),playback_url:D(r,l,a),playback_quality:A(a)};this.logPreloadStarted(p)}}),o(e.events.ready$,()=>{let r=e.info.currentBuffer$.getValue();if(this.statContext.preload){let l={buffer_time:this.calcBufferTime(r)};this.logPreloadEnded(l)}this.logReady({buffer_time:this.calcBufferTime(r)})}),o(e.events.manifestRequested$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(a)}),o(e.events.firstBytesManifest$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(a)}),o(e.events.manifestReceived$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(a)}),o(e.events.firstBytesRequested$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(a)}),o(e.events.firstBytesReceived$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(a)}),o(Ve(e.events.willStart$,e.events.looped$),r=>{r&&this.resetViewSession();let u={isid:this.isid$.getValue(),stream_profile:Et(ne(e.info.currentFormat$.getValue())),dpi:96*k.display.pixelRatio,web_layout:this.statContext.isMobile||k.device.isMobile?"mobile":"desktop",preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(u.iframe_host=this.embedHostname??"unknown"),this.logStartSession(u)}),o(e.events.started$,()=>{this.isStarted=!0;let r=e.info.currentBuffer$.getValue(),l=e.info.currentQuality$.getValue(),u=e.info.isAutoQualityEnabled$.getValue(),a=e.info.muted$.getValue(),p=e.info.volume$.getValue(),f=e.info.surface$.getValue(),v=e.info.availableTextTracks$.getValue(),m=e.info.currentTextTrack$.getValue(),y=e.info.currentAudioStream$.getValue(),C=e.info.currentPlaybackRate$.getValue(),P={playback_quality:A(l),user_quality:u?"auto":A(l),player_width:this.playerSize.width,player_height:this.playerSize.height,muted:a,sound_volume:Math.round(p*100),buffer_time:this.calcBufferTime(r),mode:ae(f,this.statContext.isPreviewPlayerView),visibility:de(f),subtitles_enabled:m?!!m:this.currentSubtitle?.enabled,auto_subtitles:v.find(({id:S})=>S===m)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:y?.language,playback_rate:C,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(P)}),o(Ve(e.events.willStart$,e.events.willResume$),()=>{this.logPlay()}),o(e.events.playing$,()=>{let r=e.info.currentBuffer$.getValue(),l={buffer_time:this.calcBufferTime(r)};this.logPlaying(l),this.wasPaused&&this.logResume()}),o(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),o(e.events.willStop$,()=>{this.logStop()}),o(Ve(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()}),o(ce({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(B(({connectionReused:r})=>r!==void 0),Ai((r,l)=>r.connectionType===l.connectionType)),()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a=e.info.rttEstimation$.getValue(),p={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:a?Math.round(a):void 0};this.logConnectionEstablished(p)}),o(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),o(e.events.willSeek$,()=>{let r={seek_type:this.seekAction$.getValue()};this.logSeeking(r)}),o(e.events.seeked$,()=>{let r={seek_type:this.seekAction$.getValue()};this.logSeeked(r),this.seekAction$.next("unknown")}),o(e.info.isStalled$,r=>{let l=e.info.currentBuffer$.getValue(),u=this.calcBufferTime(l);r&&u&&u>0&&this.logBufferStarvation({buffer_time:u})});let d;o(ce({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(B(({videoStream:r,audioStream:l})=>r!==void 0&&l!==void 0),B(({quality:r})=>r!==void 0)),({videoStream:r,audioStream:l,quality:u})=>{if(d!==u){let a=e.info.isAutoQualityEnabled$.getValue(),p=r?.codec,f=l?.codec,v={user_quality:a?"auto":A(u),playback_quality:A(u),download_quality:A(u),codec_info:p&&f?`${p},${f}`:void 0};d=u,this.logQualityChanged(v)}});let c,h;return o(e.info.surface$,r=>{let l=ae(r,this.statContext.isPreviewPlayerView);l&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:l}),h=de(r),c!==h&&this.isStarted&&(c=de(r),this.logVisibilityChanged({visibility:h}))}),o(ce({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:l})=>{if(this.isStarted){let u={muted:r,sound_volume:Math.round(l*100)};this.logSoundChanged(u)}}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscribe:i,subscription:t}=kt();i(e.actionSeek$,this.seekAction$),i(e.playerSize$,({width:s,height:d})=>{s&&d&&(this.playerSize={width:s,height:d},this.logViewPortChanged({player_width:s,player_height:d}))}),i(e.isLoaderVisible$,s=>{s&&this.isStarted&&this.logShowLoader()}),i(e.actionSubtitlesSwitched$,s=>{if(this.currentSubtitle={...s},this.isStarted){let d={subtitles_enabled:s.enabled,subtitles_track_lang:s.lang,auto_subtitles:s.auto};this.logSubtitlesSwitched(d)}});let{surface$:o}=X(this.uiEvents,i,this.player);return i(o,s=>{this.isStarted&&this.logModeChanged({mode:ae(s)})}),i(e.actionQuality$,s=>{let d=l=>Object.values(ke).includes(l),c=this.player?.info.currentVideoStream$.getValue()?.codec,h=this.player?.info.currentAudioStream$.getValue()?.codec,r={user_quality:d(s)?"auto":A(s),playback_quality:A(this.player?.info.currentQuality$.getValue()),download_quality:A(this.player?.info.currentQuality$.getValue()),codec_info:c&&h?`${c},${h}`:void 0};this.logQualityChangeRequested(r)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:i,subscribe:t}=kt();return t(e.init$,o=>{let s={slot:o};this.logAdvConfiguration(s)}),t(e.slotRequested$,()=>{this.logAdvRequest()}),t(e.started$,o=>{let s={adv_section:o};this.logAdvBreakStarted(s)}),t(e.ended$,o=>{let s={adv_section:o};this.logAdvBreakEnded(s)}),t(e.error$,o=>{let s={error_message:o};this.logAdvError(s)}),this.resubscribeBeforeunload(),this.subscription.add(i),i}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),R.generateVSID(),this.eventNumber=0}destroy(){this.api.destroy()}calcBufferTime(e){return e?Math.round((e.end??0)-(e.start??0))*1e3:void 0}createRequiredParams(e){let i=this.vsid$.getValue();_i(i);let t=this.eventNumber++,o=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3;return{vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${_}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||k.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:o,current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname}}createRequiredFatParams(){return{stats_version:"2.1.1",browser:this.statContext.browser??k.browser.current,browser_version:this.statContext.browserVersion??String(k.browser.currentVersion),os:this.statContext.os??k.device.os.name,os_version:this.statContext.osVersion??k.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||k.device.isMobile?"mobile":"desktop"),device_manufacturer:this.statContext.deviceManufacturer??k.device.details.vendor,device_model:this.statContext.deviceModel??k.device.details.model,navigation:this.statContext.navigation}}log(e,i,t=!1){let o=this.createRequiredParams(e),s={};t&&(s=this.createRequiredFatParams()),this.logger.log({...o,...s,...i})}logWatchCoverage(e){this.log("watch_coverage",e,!0)}logWatchCoverageLive(e){this.log("watch_coverage_live",e,!0)}logWatchedN(e){this.log("watched_n",e,!0)}logStartSession(e){this.log("start_session",e,!0)}logPreloadStarted(e){this.log("preload_started",e)}logPreloadEnded(e){this.log("preload_ended",e)}logPreloadError(){this.log("preload_error")}logPlaybackStarted(e){this.log("playback_started",e,!0)}logPlay(){this.log("play")}logManifestRequest(e){this.log("manifest_request",e)}logFirstByteManifest(e){this.log("first_byte_manifest",e)}logFirstMediaRequest(e){this.log("first_media_request",e)}logFirstByteMedia(e){this.log("first_byte_media",e)}logManifestReceived(e){this.log("manifest_received",e)}logConnectionEstablished(e){this.log("connection_established",e)}logFirstVideoFrameDecoded(){this.log("first_video_frame_decoded")}logReady(e){this.log("ready",e)}logPlaying(e){this.log("playing",e)}logPause(){this.log("pause")}logResume(){this.log("resume")}logSeeking(e){this.log("seeking",e)}logSeeked(e){this.log("seeked",e)}logStop(){this.log("stop")}logBufferStarvation(e){this.log("buffer_starvation",e)}logShowLoader(){this.log("show_loader")}logQualityChangeRequested(e){this.log("quality_change_requested",e)}logQualityChanged(e){this.log("quality_changed",e)}logCdnHostChanged(e){this.log("cdn_host_changed",e)}logViewPortChanged(e){this.log("view_port_changed",e)}logModeChanged(e){this.log("mode_changed",e)}logVisibilityChanged(e){this.log("visibility_changed",e)}logSubtitlesSwitched(e){this.log("subtitles_switched",e)}logSoundChanged(e){this.log("sound_changed",e)}logFailover(e){this.log("failover",e)}logAdvConfiguration(e){this.log("adv_configuration",e)}logAdvRequest(){this.log("adv_request")}logAdvBreakStarted(e){this.log("adv_break_started",e)}logAdvBreakEnded(e){this.log("adv_break_ended",e)}logAdvError(e){this.log("adv_error",e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Ti(window,"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};var ki={};import{PlaybackState as $t,Subscription as Ci}from"@vkontakte/videoplayer-core/evergreen";import{Logger as Li}from"@vkontakte/videoplayer-shared/evergreen";var ue=class{constructor(){this.startTime=null;this.stopTime=null;this.accumulatedTime=0}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime!==null?(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null):this.startTime=this.now())}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}};var Lt=()=>window.Image?new Image:document.createElement("img");var Be=class{constructor(e){this.position=0;this.started=!1;this.heartbeatPixels=[];this.heartbeatLastTimeSent={};this.idleCallbackIds=[];this.stopwatch=new ue;this.subscription=new Ci;this.params=e;let i=new Li;this.log=i.createComponentLog("MediascopePixel")}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(i=>this.onPlaybackState(i))).add(e.info.position$.subscribe(i=>this.onPosition(i))).add(e.info.atLiveEdge$.subscribe(i=>this.isActiveLive=i)),this.subscription.add(e.events.willSeek$.subscribe(()=>this.onWillSeek())).add(e.events.seeked$.subscribe(()=>this.onSeeked())).add(e.events.ended$.subscribe(()=>this.onEnded()))}destroy(){this.stopwatch.reset(),this.subscription.unsubscribe(),window.clearTimeout(this.heartbeatFirstTimeoutId),this.idleCallbackIds.forEach(e=>window.cancelIdleCallback(e)),this.send("stop")}onPlaybackState(e){e===$t.PLAYING?this.started?this.play():this.start():e===$t.PAUSED&&this.pause()}start(){this.started=!0,this.stopwatch.start(),this.send("start"),this.heartbeatPixels=this.prepareHeartbeatPixels(),this.heartbeatInterval=this.heartbeatPixels[0]?.interval;let e=this.heartbeatPixels[0]?.url,i=this.heartbeatPixels[0]?.delay;if(i!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},i*1e3)}catch(t){this.log({message:t.message})}}play(){this.stopwatch.start(),this.send("resume")}pause(){this.stopwatch.stop(),this.send("pause")}onPosition(e){if(this.position=e,this.heartbeatInterval&&this.stopwatch.time!==0&&this.stopwatch.time%this.heartbeatInterval===0)for(let[i,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[i]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[i]=this.stopwatch.time,this.sendHeartbeat(t))}onWillSeek(){this.started&&this.send("stop")}onSeeked(){this.started&&this.send("start")}onEnded(){this.stopwatch.stop(),this.send("stop")}validatePixels(e,i){return e?.filter(t=>t.event===i.event&&i.keys.every(o=>!!t[o]))}getFrameTimestamp(){let e;if(this.isActiveLive){let i=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-i}else e=this.position||0;return Math.floor(e)}getUTC(){return Math.floor(Date.now()/1e3)}prepareUrl(e){return e.replace("{@fts_fake_sec}",String(this.getFrameTimestamp())).replace("{@utc_sec}",String(this.getUTC())).split("&").filter(i=>!/={@[a-zA-Z_]+}/.test(i)).join("&")}preparePixels(e){return this.validatePixels(this.params.pixels,{event:e,keys:["url"]})}prepareHeartbeatPixels(){return this.validatePixels(this.params.pixels,{event:"heartbeat",keys:["url","interval"]})}call(e){try{this.idleCallbackIds.push(requestIdleCallback(()=>Lt().src=this.prepareUrl(e)))}catch(i){this.log({message:i.message})}}send(e){let i=this.preparePixels(e);for(let{url:t}of i)this.call(t)}sendHeartbeat(e){this.call(e)}};export{U as ApiEnv,ge as ConnectionType,fe as ContentType,qe as InteractiveInterfaceClick,Be as MediascopePixel,ki as MediascopePixelTypes,xe as OneStat,pe as Quality,me as SeekAction,Ct as ThinOneStat,_ as VERSION};
|
|
6
|
+
var Nt=Object.defineProperty;var Mt=(n,e)=>{for(var i in e)Nt(n,i,{get:e[i],enumerable:!0})};var U=(d=>(d.PROD="prod",d.VK_ALIAS="vk_alias",d.VIDEOTEST="videotest",d.TEST="test",d.OKCDN="okcdn",d.AUTO="auto",d))(U||{}),pe=(r=>(r.Q144P="mobile",r.Q240P="lowest",r.Q360P="low",r.Q480P="medium",r.Q720P="high",r.Q1080P="fullhd",r.Q1440P="quadhd",r.Q2160P="ultrahd",r.UNKNOWN="unknown",r))(pe||{}),fe=(f=>(f.MP4="mp4",f.DASH="dash",f.DASH_SEP="dash_sep",f.ONDEMAND_DASH="ondemand_dash",f.HLS="hls",f.HLS_FMP4="hls_fmp4",f.ONDEMAND_HLS="ondemand_hls",f.WEBM="webm",f.AV1="av1",f.ONDEMAND_DASH_LIVE="ondemand_dash_live",f.ONDEMAND_HLS_LIVE="ondemand_hls_live",f.WEBRTC="webrtc",f.UNKNOWN="unknown",f.RTMP="rtmp",f))(fe||{});var ge=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(ge||{});var me=(c=>(c.SLIDER="slider",c.DOUBLE_TAP="double_tap",c.TIME_CODE="time_code",c.EPISODE="episode",c.REWIND="rewind",c.LIVE="live",c.UNKNOWN="unknown",c))(me||{}),qe=(s=>(s.GRAPH_SHOW="iGraphShow",s.GRAPH_HIDE="iGraphHide",s.NEXT_AREA="iNextChapterArea",s.NEXT_BUTTON="iNextChapterBtn",s.WATCH_AGAIN="iWatchAgainBtn",s))(qe||{}),Qe={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"},We={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"},Ke={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},ze={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv",minimal:"minimal"};import{fillWithDefault as Vt}from"@vkontakte/videoplayer-shared/evergreen";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 Ot={apiEnv:"vk_alias",apiKey:je,apiBaseUrl:null,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},useKeepalive:!1,watchCoverageTimeoutFix:!1},Ge=n=>Vt(n,Ot);function be(){let n="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]=n[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as ei,combine as at,fromEvent as dt,isNonNullable as V,isNullable as ct,merge as ti,now as $,observableFrom as ii,once as oi,safeStorage as lt,Subject as ri,Subscription as we,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as si,detectEmbed as ni}from"@vkontakte/videoplayer-shared/evergreen";var Ft=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),R=class n{static getVSID(){return n.vsid}static generateVSID(){return n.vsid=Ft(),n.vsid}};var Ye=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,s])=>{let d=We[o]??o,c=s;return s&&(o==="mode"?c=ze[s]??s:o==="quality"&&(c=Ke[s]??s)),[d,c]}));return{...n,operation:Qe[e]??e,custom:t}};var _="1.0.96-dev.c564bb3a.0";import{ValueSubject as Bt,getExponentialDelay as Ut,ErrorCategory as N}from"@vkontakte/videoplayer-shared/evergreen";var Ht=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,H=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Bt(!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 s=async(d,c=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:N.NETWORK,message:`Unknown ${i} error`,thrown:h});return}let r=h?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),c>0?s(d,c-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),c>0?s(d,c-1):void 0;default:{this.params.error$.next({id:`LogRequest#${r}`,category:N.EXTERNAL_API,message:`${i} error`,data:h});return}}}};return s(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:s}=window.navigator;t=Ht.test(s)}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(Ye):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ut(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:N.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: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{ErrorCategory as z,now as Ie}from"@vkontakte/videoplayer-shared/evergreen";var q=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??ve[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:z.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),ve.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}),s=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,s)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:z.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=Ie(),s=c=>{if(c instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(c.message)){this.params.error$.next({id:"Network",category:z.NETWORK,message:"Request failed",thrown:c});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:z.NETWORK,message:"Unhandled request error",thrown:c,data:{method:e,params:i,sessionKey:t,time:Ie()-o}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let d={method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})};return this.params.config.useKeepalive&&(d.keepalive=!0),fetch(`${this.apiBaseUrl}/fb.do`,d).then(c=>{let h=Number(c.headers.get("content-length"))===0,r=new Date(c.headers.get("date")??"").getTime(),l=Ie()-o;if(isFinite(r)&&this.timeSynchronisation?.addServerTime(r,l),!h)return c.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,s)},s)}_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 qt,now as Qt,safeStorage as Q,debounceFn as Xe}from"@vkontakte/videoplayer-shared/evergreen";var j="onestat_events",ye=n=>e=>e.timestamp+n>=Qt(),G=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=Xe(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=Q.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Xe(()=>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:qt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=Q.get(j);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(ye(this.params.config.storageExpiration));Q.set(j,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(ye(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],Q.set(j,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(ye(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`})}Q.set(j,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 Se,Surface as M,VideoFormat as I,VideoQuality as T}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as Je}from"@vkontakte/videoplayer-shared/evergreen";var Ze=n=>n&&{[T.INVARIANT]:"unknown",[T.Q_144P]:"mobile",[T.Q_240P]:"lowest",[T.Q_360P]:"low",[T.Q_480P]:"medium",[T.Q_576P]:"unknown",[T.Q_720P]:"high",[T.Q_1080P]:"fullhd",[T.Q_1440P]:"quadhd",[T.Q_2160P]:"ultrahd",[T.Q_4320P]:"unknown"}[n],_e=n=>n&&{[Se.HTTP1]:"http1",[Se.HTTP2]:"http2",[Se.QUIC]:"http3"}[n],et=n=>{if(n!==void 0)switch(n){case I.MPEG:return"mp4";case I.DASH:case I.DASH_LIVE:case I.DASH_STREAMS:return"dash";case I.DASH_SEP:return"dash_sep";case I.DASH_ONDEMAND:return"ondemand_dash";case I.DASH_WEBM:case I.DASH_LIVE_WEBM:return"webm";case I.DASH_WEBM_AV1:return"av1";case I.DASH_LIVE_CMAF:return"ondemand_dash_live";case I.HLS:case I.HLS_LIVE:return"hls";case I.HLS_FMP4:return"hls_fmp4";case I.HLS_ONDEMAND:return"ondemand_hls";case I.HLS_LIVE_CMAF:return"ondemand_hls_live";case I.WEB_RTC_LIVE:return"webrtc";default:return Je(n)}},Pe=(n,e)=>{if(e)return"minimal";switch(n){case void 0:case M.NONE:case M.INLINE:return;case M.FULLSCREEN:return"fullscreen";case M.SECOND_SCREEN:return"chromecast";case M.PIP:return"pip";case M.INVISIBLE:return"invisible";default:return Je(n)}},tt=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var Y=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 it=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ot}from"@vkontakte/videoplayer-core/evergreen";import{filter as rt,filterChanged as Wt,fromEvent as Kt,isNullable as st,map as zt,merge as Te,Observable as jt,Subject as Ee,Subscription as Gt,ValueSubject as Yt}from"@vkontakte/videoplayer-shared/evergreen";var nt=(n,e)=>new jt(i=>{let t=new Gt,o=Te(Kt(window,"beforeunload"),n.events.willDestruct$),s=new Yt(void 0),d;t.add(n.info.isLive$.pipe(Wt()).subscribe(g=>{d&&(d.unsubscribe(),s.next(void 0)),g?d=n.info.liveTime$.pipe(zt(w=>w&&w/1e3)).subscribe(s):d=n.info.position$.subscribe(s),t.add(d)}));let{playing$:c,paused$:h}=n.events,r=n.events.willSeek$.pipe(rt(()=>n.info.playbackState$.getValue()===ot.PLAYING)),l=n.events.seeked$.pipe(rt(()=>n.info.playbackState$.getValue()===ot.PLAYING)),u=!1,a=new Ee;t.add(r.subscribe(()=>{u||a.next(),u=!0})),t.add(l.subscribe(()=>u=!1));let p=new Ee,f=new Ee,v=Te(c,l,p),m=Te(h,a,o,n.events.looped$,f),y,C=()=>y=s.getValue(),P=()=>{let g=s.getValue();st(y)||y===g||st(g)||(i.next({from:y,to:g}),y=void 0)},S=()=>{f.next(),p.next()};if(t.add(v.subscribe(C)),t.add(m.subscribe(P)),e.forceInterval&&isFinite(e.forceInterval))if(e.watchCoverageTimeoutFix){let g,w=()=>{g!==void 0&&(window.clearTimeout(g),g=void 0)};t.add(v.subscribe(()=>{w(),g=window.setTimeout(S,e.forceInterval)})),t.add(m.subscribe(()=>w())),t.add(()=>w())}else{let g=0;t.add(v.subscribe(()=>g=window.setTimeout(S,e.forceInterval))),t.add(m.subscribe(()=>window.clearTimeout(g)))}return t});import{Surface as x}from"@vkontakte/videoplayer-core/evergreen";import{debounce as Xt,filterChanged as Jt,Subject as Zt}from"@vkontakte/videoplayer-shared/evergreen";var X=(n,e,i)=>{let t=new Zt,o=t.pipe(Xt(0),Jt()),s=!1,d=!1,c=!1;return e(n.inPiP$,h=>{s=h,t.next(h?x.PIP:d?x.FULLSCREEN:c?x.INLINE:void 0)}),e(n.inFullscreen$,h=>{d=h,t.next(h?x.FULLSCREEN:s?x.PIP:c?x.INLINE:void 0)}),i&&e(i.info.surface$,h=>{switch(h){case x.SECOND_SCREEN:case x.NONE:case x.INLINE:{!d&&!s&&(h===x.INLINE&&(c=!0),t.next(h));break}}}),{surface$:o}};var ai="_one-stat_",ut=`${ai}deviceId`,Ae=()=>{let n=new we;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},xe=class{constructor(e,i){this.subscription=new we;this.debugLogger=new si;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.isid$=new J(void 0);this.zenUid$=new J(void 0);this.seekAction$=new J("unknown");this.statContext=e,this.config=Ge(i.config??{}),V(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Y);let t=new ri;this.experimental={error$:t};let o=lt.get(ut);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=be(),lt.set(ut,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??it()),this.zenUid$.next(i.zenUid);let s=new q({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new H({config:this.config,apiTransport:s,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new G({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,topOrigin:c}=ni();this.isEmbed=d,this.embedParent=c?new URL(c).hostname:void 0,this.subscribe()}get vsid$(){return new J(R.getVSID())}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new we,t=(a,p)=>i.add(a.subscribe(p));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(nt(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),a=>{let p=e.info.isLive$.getValue(),f=e.info.atLiveEdge$.getValue(),v={start:parseFloat(a.from.toFixed(3)),end:parseFloat(a.to.toFixed(3))};if(f){let m=e.info.liveLatency$.getValue()??0,y=e.info.currentBuffer$.getValue()?.end??0,C=e.info.liveBufferTime$.getValue()??0,P=Math.round((m-(y-C))*1e3),S=Math.round(m*1e3);P&&S&&(v.latency=P,v.bufferLatency=S)}p?this.logWatchCoverageLive(v):this.logWatchCoverageRecord(v)});let o;t(e.info.isStalled$,a=>{a?o=$():(V(o)&&this.logEmptyBuffer({duration:$()-o}),o=void 0)});let s=!1;i.add(e.events.fatalError$.pipe(oi()).subscribe(()=>s=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let p=V(o)?$()-o:void 0;this.logCloseAtEmptyBuffer({duration:p??0}),o=void 0}else s||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 d,c,h=!1;t(e.events.firstBytes$,a=>{d=$(),this.logFirstBytes({time:a})}),t(e.events.willStart$,()=>c=$()),t(e.info.currentBuffer$,a=>{!h&&a&&a.end-a.start>0&&V(d)&&(this.logPlayerReady({duration:$()-d}),h=!0)}),t(e.events.firstFrame$,()=>{V(d)&&!h&&(this.logPlayerReady({duration:$()-d}),h=!0),V(c)&&this.logFirstFrame({time:$()-c})});let r;t(e.info.currentVideoStream$,a=>{a&&(r&&a.id!==r&&this.logTrackSwitch(a),r=a.id)});let l;t(e.info.currentAudioStream$,a=>{a&&(l&&a.id!==l&&this.logTrackSwitch(a),l=a.id)}),t(e.info.atLiveEdge$,a=>this.updateContext({liveEdge:a})),t(at({muted:e.info.muted$,volume:e.info.volume$}),({muted:a,volume:p})=>this.updateContext({audible:!a&&p>0})),t(e.info.currentQuality$,a=>{let p=Ze(a);this.updateContext({quality:p}),p&&this.logQuality(p)}),t(e.info.isAutoQualityEnabled$,a=>this.updateContext({autoQuality:a})),t(e.info.currentFormat$,a=>this.updateContext({contentType:et(a)})),t(e.info.currentPlaybackRate$,a=>this.updateContext({rate:a})),t(e.info.is3DVideo$,a=>this.updateContext({is3d:a}));let u;return t(e.info.hostname$,a=>{let p=u!==void 0&&u!==a;this.updateContext({cdnHostname:a,failover:p}),p&&this.logFailover(a),u=a}),t(e.info.throughputEstimation$,a=>this.updateContext({downloadSpeed:a})),t(e.info.httpConnectionType$,a=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:_e(a)}),this.updateContext({connectionType:_e(a)})}),t(e.info.httpConnectionReused$,a=>{ct(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:a}),this.updateContext({connectionReused:a})}),t(e.info.surface$,a=>{this.uiEvents||this.updateContext({mode:Pe(a,this.statContext.isPreviewPlayerView)})}),t(at({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:a,available:p})=>{let f=p.find(({id:m})=>m===a),v=f&&(f.isAuto?`${f.language}_auto`:f.language);this.updateContext({subtitles:v?.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}=Ae();if(!this.player)return i;t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$);let{surface$:o}=X(this.uiEvents,t,this.player);return t(o,s=>{this.updateContext({mode:Pe(s,this.statContext.isPreviewPlayerView)})}),t(e.actionSetSubtitle$,s=>this.updateContext({subtitles:s?.split(".")[0]})),t(e.nextMovie$,s=>this.logNextMovie(s)),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToAds(e){let{subscription:i,subscribe:t}=Ae();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}=Ae();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"}),R.generateVSID()}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(ti(dt(e,"change"),ii(["init"])).subscribe(()=>this.updateContext({network:tt(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=dt(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 s=this.timeSynchronisation?.now()??$(),d=this.vsid$.getValue();ei(d);let c=this.isid$.getValue(),h=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,r=this.statContext.firstConnectionReused,l,u;if(this.isEmbed||this.statContext.place==="embed"){l=this.embedParent;let p=[...new URLSearchParams(location.search).entries()].filter(([f,v])=>this.config.embedUrlParams.includes(f));u=new URLSearchParams(p).toString()}else if(this.statContext.place==="direct"){let p=this.statContext.refDomain||document.referrer;p&&URL.canParse(p)?l=new URL(p).hostname:l=p,u=location.href.substring(0,1024)}let a={vsid:d,isid:c,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:h,connection_reused:r===!0?1:r===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:l,direct_url:u,rate:this.statContext.rate===1||ct(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 p of this.config.disabledCustomFields)delete a[p];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:s,custom:a}}};var Ct={};Mt(Ct,{ActionSeekType:()=>Z,ThinOneStat:()=>le,VERSION:()=>_});import{assertNonNullable as _i,detectEmbed as Pi,fromEvent as Ti,Logger as Ei,merge as Ve,combine as ce,filter as B,filterChanged as Ai,safeStorage as wt,Subject as wi,Subscription as Fe,ValueSubject as Oe}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as k}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as di}from"@vkontakte/videoplayer-shared/evergreen";var ke=(t=>(t.AUTO="auto",t.AUTO_POOR="auto_poor",t.AUTO_RICH="auto_rich",t))(ke||{});var Z=(c=>(c.SLIDER="slider",c.DOUBLE_TAP="double_tap",c.TIME_CODE="time_code",c.EPISODE="episode",c.REWIND="rewind",c.LIVE="live",c.UNKNOWN="unknown",c))(Z||{});var pt="CIOPGQJGDIHBABABA",Ce={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 ci={apiKey:pt,apiEnv:"okcdn",apiBaseUrl:null,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:30,synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNFirstTvtLog:1e3,watchedNDefaultTargetDuration:1e4},ft=n=>di(n,ci);import{getExponentialDelay as li,ErrorCategory as O,ValueSubject as ui}from"@vkontakte/videoplayer-shared/evergreen";var ee=class{constructor(e){this.params=e,this.authorized$=new ui(!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={},s=this.sessionKey??await this.authorizeWithBackoff();if(!s)return;let d=async(c,h=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,s,o)}catch(r){if(!r||!("error_code"in r)){this.params.error$.next({id:"logRequestUnknown",category:O.NETWORK,message:`Unknown ${i} error`,thrown:r});return}let l=r?.error_code;switch(l){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),h>0?d(c,h-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),h>0?d(c,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${l}`,category:O.EXTERNAL_API,message:`${i} error`,data:r});return}}}};return d(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=li(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:O.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:O.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:O.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:O.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 Le,ErrorCategory as te}from"@vkontakte/videoplayer-shared/evergreen";var ie=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ce[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}),s=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,s)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:te.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let s=Le(),d=c=>{if(c instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(c.message)){this.params.error$.next({id:"Network",category:te.NETWORK,message:"Request failed",thrown:c});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:te.NETWORK,message:"Unhandled request error",thrown:c,data:{method:e,params:i,sessionKey:t,time:Le()-s}})};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(c=>{let h=Number(c.headers.get("content-length"))===0,r=new Date(c.headers.get("date")??"").getTime(),l=Le()-s;if(isFinite(r)&&this.timeSynchronisation?.addServerTime(r,l),!h)return c.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,d)},d)}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:te.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Ce.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 hi,now as pi,safeStorage as W,debounceFn as gt}from"@vkontakte/videoplayer-shared/evergreen";var oe="thinonestat_events",$e=n=>e=>e.client_time+n>=pi(),re=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=gt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=W.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=gt(()=>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:hi.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=W.get(oe);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter($e(this.params.config.storageExpiration));W.set(oe,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter($e(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],W.set(oe,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter($e(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}W.set(oe,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 Re(){let n="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]=n[o===19?t&3|8:t]);return e.join("")}var se=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 mt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as fi,Subscription as gi,ValueSubject as mi,Subject as De,fromEvent as vi,isNullable as vt,merge as K,filter as bt,filterChanged as It}from"@vkontakte/videoplayer-shared/evergreen";var yt=(n,e,i)=>new fi(t=>{let o=new gi,s=new mi(void 0),d;o.add(n.info.isLive$.pipe(It()).subscribe(L=>{d&&(d.unsubscribe(),s.next(void 0)),L?d=n.info.liveTime$.pipe(It()).subscribe(s):d=n.info.position$.subscribe(s),o.add(d)}));let{playing$:c,paused$:h,ended$:r,looped$:l}=n.events,u=n.events.willSeek$.pipe(bt(()=>n.info.playbackState$.getValue()===mt.PLAYING)),a=n.events.seeked$.pipe(bt(()=>n.info.playbackState$.getValue()===mt.PLAYING)),p=!1,f=new De;o.add(u.subscribe(()=>{p||f.next(),p=!0})).add(a.subscribe(()=>p=!1));let v=K(vi(window,"beforeunload"),n.events.willDestruct$),m,y=()=>m=s.getValue(),C=()=>{let L=s.getValue();vt(m)||vt(L)||m===L||(t.next({from:m,to:L}),m=void 0)},P=new De,S=new De,g=K(c,f,P),w=K(h,a,v,r,l,S),Ue=e.started$&&e.ended$?K(g,e.ended$):g,He=e.started$&&e.ended$?K(w,e.started$):w;if(o.add(Ue.subscribe(y)).add(He.subscribe(C)),i.heartbeatInterval&&isFinite(i.heartbeatInterval)){let L=[],Rt=i.heartbeatInterval*1e3,Dt=()=>{S.next(),P.next()};o.add(Ue.subscribe(()=>{let he=window.setTimeout(Dt,Rt);L.push(he)})).add(He.subscribe(()=>{L.forEach(he=>{window.clearTimeout(he)}),L=[]}))}return o});import{Subscription as bi}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Ii}from"@vkontakte/videoplayer-shared/evergreen";var St=(n,e)=>new Ii(i=>{let t=new bi,o=0;return t.add(n.info.position$.subscribe(()=>{let s=e.getTotalViewTime()*1e3;s>o&&(s===e.firstTvtLog||s%e.targetDuration===0)&&(o=s,i.next({target_duration:e.targetDuration,current_tvt:s}))})),t});import{Observable as yi,Subscription as Si,merge as _t}from"@vkontakte/videoplayer-shared/evergreen";var Pt=n=>new yi(e=>{let i=new Si,t=0,o=1,s=0,d=!1,c=!1,h=()=>{if(!d)return;let g=Date.now();s+=(g-t)*o,t=g},r=()=>{(!d||c)&&(t=Date.now(),d=!0,c=!1)},l=()=>{d&&(h(),d=!1)},u=()=>{d&&(h(),d=!1,c=!0)},a=g=>{d&&h(),o=g,t=Date.now()},{started$:p,playing$:f,paused$:v,willSeek$:m,ended$:y,willDestruct$:C}=n.events,{currentPlaybackRate$:P}=n.info;i.add(m.subscribe(u)).add(_t(p,f).subscribe(r)).add(_t(v,y,C).subscribe(l)).add(P.subscribe(a));let S=()=>{let g=s;return d&&(g+=(Date.now()-t)*o),g};return e.next(S),i});import{assertNever as Tt}from"@vkontakte/videoplayer-shared/evergreen";import{HttpConnectionType as Ne,Surface as F,VideoFormat as b,VideoQuality as E}from"@vkontakte/videoplayer-core/evergreen";var Me=n=>n&&{[Ne.HTTP1]:"http1",[Ne.HTTP2]:"http2",[Ne.QUIC]:"http3"}[n],ne=n=>{if(n!==void 0)switch(n){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.HLS_FMP4:return"HLS_FMP4";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 Tt(n)}},A=n=>{if(n!==void 0)switch(n){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 Tt(n)}},Et=n=>{if(n!==void 0)switch(n){case"MP4":case"ONDEMAND_DASH":case"ONDEMAND_DASH_LIVE":case"ONDEMAND_HLS":case"ONDEMAND_HLS_LIVE":case"MULTI_DASH":case"WEBM":case"AV1":return"vod";case"DASH":case"HLS":case"HLS_FMP4":case"WEBRTC":return"live";default:return}},D=(n,e,i)=>{if(n&&e)switch(n){case b.MPEG:return i&&e[n]&&e[n][i];default:return e[n]?.url}},ae=(n,e=!1)=>{if(e)return"minimal";switch(n){case void 0:case F.NONE:return;case F.INLINE:return"inline";case F.FULLSCREEN:return"fullscreen";case F.SECOND_SCREEN:return"chromecast";case F.PIP:return"pip_external"}},de=n=>{switch(n){case void 0:return;case F.INVISIBLE:return"background";default:return"foreground"}};var At=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var xi="_thin-one-stat_",xt=`${xi}deviceId`,kt=()=>{let n=new Fe;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},le=class{constructor(e,i){this.debugLogger=new Ei;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.playerSize={width:0,height:0};this.seekAction$=new Oe("unknown");this.isid$=new Oe(void 0);this.statContext=e,this.config=ft(i.config??{}),this.subscription=new Fe,this.config.synchronizeTime&&(this.timeSynchronisation=new se);let t=new wi,o=wt.get(xt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=Re(),wt.set(xt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??At());let s=new ie({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new ee({config:this.config,apiTransport:s,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new re({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,topOrigin:c}=Pi();this.isEmbed=d,this.embedHostname=c?new URL(c).hostname:void 0}get vsid$(){return new Oe(R.getVSID())}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,i){let t=new Fe,o=(r,l)=>t.add(r.subscribe(l));o(Pt(e),r=>{this.getTotalViewTime=r}),o(e.info.isLive$,r=>this.isLive=r);let s;o(ce({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(B(({hostname:r})=>r!==void 0),B(({connectionType:r})=>r!==void 0),B(({connectionReused:r})=>r!==void 0)),({hostname:r,connectionType:l,connectionReused:u})=>{if(s!==void 0&&s!==r){let p={cdn_host:r,connection_type:Me(l),connection_reused:u,content_type:ne(e.info.currentFormat$.getValue())};this.logFailover(p)}this.cdnHostname=s=r}),o(e.info.httpConnectionType$,r=>{this.connectionType=Me(r)}),o(e.info.httpConnectionReused$,r=>{this.connectionReused=r}),o(yt(e,i,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),r=>{let l=Math.round(r.from*1e3),u=Math.round(r.to*1e3),a={watch_interval:`${l}-${u}`,in_history:!!this.statContext.inHistory,content_type:ne(e.info.currentFormat$.getValue()),playback_quality:A(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(a);else{let f=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...a,live:!!f})}}),o(St(e,{targetDuration:this.targetDuration,firstTvtLog:this.config.watchedNFirstTvtLog,getTotalViewTime:this.getTotalViewTime}),r=>{this.logWatchedN(r)}),o(e.events.willReady$,()=>{if(this.statContext.preload){let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentBuffer$.getValue(),a=e.info.currentQuality$.getValue(),p={target_buffer_time:this.calcBufferTime(u),playback_url:D(r,l,a),playback_quality:A(a)};this.logPreloadStarted(p)}}),o(e.events.ready$,()=>{let r=e.info.currentBuffer$.getValue();if(this.statContext.preload){let l={buffer_time:this.calcBufferTime(r)};this.logPreloadEnded(l)}this.logReady({buffer_time:this.calcBufferTime(r)})}),o(e.events.manifestRequested$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(a)}),o(e.events.firstBytesManifest$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(a)}),o(e.events.manifestReceived$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(a)}),o(e.events.firstBytesRequested$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(a)}),o(e.events.firstBytesReceived$,()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(a)}),o(Ve(e.events.willStart$,e.events.looped$),r=>{r&&this.resetViewSession();let u={isid:this.isid$.getValue(),stream_profile:Et(ne(e.info.currentFormat$.getValue())),dpi:96*k.display.pixelRatio,web_layout:this.statContext.isMobile||k.device.isMobile?"mobile":"desktop",preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(u.iframe_host=this.embedHostname??"unknown"),this.logStartSession(u)}),o(e.events.started$,()=>{this.isStarted=!0;let r=e.info.currentBuffer$.getValue(),l=e.info.currentQuality$.getValue(),u=e.info.isAutoQualityEnabled$.getValue(),a=e.info.muted$.getValue(),p=e.info.volume$.getValue(),f=e.info.surface$.getValue(),v=e.info.availableTextTracks$.getValue(),m=e.info.currentTextTrack$.getValue(),y=e.info.currentAudioStream$.getValue(),C=e.info.currentPlaybackRate$.getValue(),P={playback_quality:A(l),user_quality:u?"auto":A(l),player_width:this.playerSize.width,player_height:this.playerSize.height,muted:a,sound_volume:Math.round(p*100),buffer_time:this.calcBufferTime(r),mode:ae(f,this.statContext.isPreviewPlayerView),visibility:de(f),subtitles_enabled:m?!!m:this.currentSubtitle?.enabled,auto_subtitles:v.find(({id:S})=>S===m)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:y?.language,playback_rate:C,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(P)}),o(Ve(e.events.willStart$,e.events.willResume$),()=>{this.logPlay()}),o(e.events.playing$,()=>{let r=e.info.currentBuffer$.getValue(),l={buffer_time:this.calcBufferTime(r)};this.logPlaying(l),this.wasPaused&&this.logResume()}),o(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),o(e.events.willStop$,()=>{this.logStop()}),o(Ve(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()}),o(ce({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(B(({connectionReused:r})=>r!==void 0),Ai((r,l)=>r.connectionType===l.connectionType)),()=>{let r=e.info.currentFormat$.getValue(),l=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),a=e.info.rttEstimation$.getValue(),p={playback_url:D(r,l,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:a?Math.round(a):void 0};this.logConnectionEstablished(p)}),o(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),o(e.events.willSeek$,()=>{let r={seek_type:this.seekAction$.getValue()};this.logSeeking(r)}),o(e.events.seeked$,()=>{let r={seek_type:this.seekAction$.getValue()};this.logSeeked(r),this.seekAction$.next("unknown")}),o(e.info.isStalled$,r=>{let l=e.info.currentBuffer$.getValue(),u=this.calcBufferTime(l);r&&u&&u>0&&this.logBufferStarvation({buffer_time:u})});let d;o(ce({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(B(({videoStream:r,audioStream:l})=>r!==void 0&&l!==void 0),B(({quality:r})=>r!==void 0)),({videoStream:r,audioStream:l,quality:u})=>{if(d!==u){let a=e.info.isAutoQualityEnabled$.getValue(),p=r?.codec,f=l?.codec,v={user_quality:a?"auto":A(u),playback_quality:A(u),download_quality:A(u),codec_info:p&&f?`${p},${f}`:void 0};d=u,this.logQualityChanged(v)}});let c,h;return o(e.info.surface$,r=>{let l=ae(r,this.statContext.isPreviewPlayerView);l&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:l}),h=de(r),c!==h&&this.isStarted&&(c=de(r),this.logVisibilityChanged({visibility:h}))}),o(ce({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:l})=>{if(this.isStarted){let u={muted:r,sound_volume:Math.round(l*100)};this.logSoundChanged(u)}}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscribe:i,subscription:t}=kt();i(e.actionSeek$,this.seekAction$),i(e.playerSize$,({width:s,height:d})=>{s&&d&&(this.playerSize={width:s,height:d},this.logViewPortChanged({player_width:s,player_height:d}))}),i(e.isLoaderVisible$,s=>{s&&this.isStarted&&this.logShowLoader()}),i(e.actionSubtitlesSwitched$,s=>{if(this.currentSubtitle={...s},this.isStarted){let d={subtitles_enabled:s.enabled,subtitles_track_lang:s.lang,auto_subtitles:s.auto};this.logSubtitlesSwitched(d)}});let{surface$:o}=X(this.uiEvents,i,this.player);return i(o,s=>{this.isStarted&&this.logModeChanged({mode:ae(s)})}),i(e.actionQuality$,s=>{let d=l=>Object.values(ke).includes(l),c=this.player?.info.currentVideoStream$.getValue()?.codec,h=this.player?.info.currentAudioStream$.getValue()?.codec,r={user_quality:d(s)?"auto":A(s),playback_quality:A(this.player?.info.currentQuality$.getValue()),download_quality:A(this.player?.info.currentQuality$.getValue()),codec_info:c&&h?`${c},${h}`:void 0};this.logQualityChangeRequested(r)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:i,subscribe:t}=kt();return t(e.init$,o=>{let s={slot:o};this.logAdvConfiguration(s)}),t(e.slotRequested$,()=>{this.logAdvRequest()}),t(e.started$,o=>{let s={adv_section:o};this.logAdvBreakStarted(s)}),t(e.ended$,o=>{let s={adv_section:o};this.logAdvBreakEnded(s)}),t(e.error$,o=>{let s={error_message:o};this.logAdvError(s)}),this.resubscribeBeforeunload(),this.subscription.add(i),i}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),R.generateVSID(),this.eventNumber=0}destroy(){this.api.destroy()}calcBufferTime(e){return e?Math.round((e.end??0)-(e.start??0))*1e3:void 0}createRequiredParams(e){let i=this.vsid$.getValue();_i(i);let t=this.eventNumber++,o=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3;return{vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${_}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||k.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:o,current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname}}createRequiredFatParams(){return{stats_version:"2.1.1",browser:this.statContext.browser??k.browser.current,browser_version:this.statContext.browserVersion??String(k.browser.currentVersion),os:this.statContext.os??k.device.os.name,os_version:this.statContext.osVersion??k.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||k.device.isMobile?"mobile":"desktop"),device_manufacturer:this.statContext.deviceManufacturer??k.device.details.vendor,device_model:this.statContext.deviceModel??k.device.details.model,navigation:this.statContext.navigation}}log(e,i,t=!1){let o=this.createRequiredParams(e),s={};t&&(s=this.createRequiredFatParams()),this.logger.log({...o,...s,...i})}logWatchCoverage(e){this.log("watch_coverage",e,!0)}logWatchCoverageLive(e){this.log("watch_coverage_live",e,!0)}logWatchedN(e){this.log("watched_n",e,!0)}logStartSession(e){this.log("start_session",e,!0)}logPreloadStarted(e){this.log("preload_started",e)}logPreloadEnded(e){this.log("preload_ended",e)}logPreloadError(){this.log("preload_error")}logPlaybackStarted(e){this.log("playback_started",e,!0)}logPlay(){this.log("play")}logManifestRequest(e){this.log("manifest_request",e)}logFirstByteManifest(e){this.log("first_byte_manifest",e)}logFirstMediaRequest(e){this.log("first_media_request",e)}logFirstByteMedia(e){this.log("first_byte_media",e)}logManifestReceived(e){this.log("manifest_received",e)}logConnectionEstablished(e){this.log("connection_established",e)}logFirstVideoFrameDecoded(){this.log("first_video_frame_decoded")}logReady(e){this.log("ready",e)}logPlaying(e){this.log("playing",e)}logPause(){this.log("pause")}logResume(){this.log("resume")}logSeeking(e){this.log("seeking",e)}logSeeked(e){this.log("seeked",e)}logStop(){this.log("stop")}logBufferStarvation(e){this.log("buffer_starvation",e)}logShowLoader(){this.log("show_loader")}logQualityChangeRequested(e){this.log("quality_change_requested",e)}logQualityChanged(e){this.log("quality_changed",e)}logCdnHostChanged(e){this.log("cdn_host_changed",e)}logViewPortChanged(e){this.log("view_port_changed",e)}logModeChanged(e){this.log("mode_changed",e)}logVisibilityChanged(e){this.log("visibility_changed",e)}logSubtitlesSwitched(e){this.log("subtitles_switched",e)}logSoundChanged(e){this.log("sound_changed",e)}logFailover(e){this.log("failover",e)}logAdvConfiguration(e){this.log("adv_configuration",e)}logAdvRequest(){this.log("adv_request")}logAdvBreakStarted(e){this.log("adv_break_started",e)}logAdvBreakEnded(e){this.log("adv_break_ended",e)}logAdvError(e){this.log("adv_error",e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Ti(window,"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};var ki={};import{PlaybackState as $t,Subscription as Ci}from"@vkontakte/videoplayer-core/evergreen";import{Logger as Li}from"@vkontakte/videoplayer-shared/evergreen";var ue=class{constructor(){this.startTime=null;this.stopTime=null;this.accumulatedTime=0}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime!==null?(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null):this.startTime=this.now())}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}};var Lt=()=>window.Image?new Image:document.createElement("img");var Be=class{constructor(e){this.position=0;this.started=!1;this.heartbeatPixels=[];this.heartbeatLastTimeSent={};this.idleCallbackIds=[];this.stopwatch=new ue;this.subscription=new Ci;this.params=e;let i=new Li;this.log=i.createComponentLog("MediascopePixel")}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(i=>this.onPlaybackState(i))).add(e.info.position$.subscribe(i=>this.onPosition(i))).add(e.info.atLiveEdge$.subscribe(i=>this.isActiveLive=i)),this.subscription.add(e.events.willSeek$.subscribe(()=>this.onWillSeek())).add(e.events.seeked$.subscribe(()=>this.onSeeked())).add(e.events.ended$.subscribe(()=>this.onEnded()))}destroy(){this.stopwatch.reset(),this.subscription.unsubscribe(),window.clearTimeout(this.heartbeatFirstTimeoutId),this.idleCallbackIds.forEach(e=>window.cancelIdleCallback(e)),this.send("stop")}onPlaybackState(e){e===$t.PLAYING?this.started?this.play():this.start():e===$t.PAUSED&&this.pause()}start(){this.started=!0,this.stopwatch.start(),this.send("start"),this.heartbeatPixels=this.prepareHeartbeatPixels(),this.heartbeatInterval=this.heartbeatPixels[0]?.interval;let e=this.heartbeatPixels[0]?.url,i=this.heartbeatPixels[0]?.delay;if(i!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},i*1e3)}catch(t){this.log({message:t.message})}}play(){this.stopwatch.start(),this.send("resume")}pause(){this.stopwatch.stop(),this.send("pause")}onPosition(e){if(this.position=e,this.heartbeatInterval&&this.stopwatch.time!==0&&this.stopwatch.time%this.heartbeatInterval===0)for(let[i,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[i]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[i]=this.stopwatch.time,this.sendHeartbeat(t))}onWillSeek(){this.started&&this.send("stop")}onSeeked(){this.started&&this.send("start")}onEnded(){this.stopwatch.stop(),this.send("stop")}validatePixels(e,i){return e?.filter(t=>t.event===i.event&&i.keys.every(o=>!!t[o]))}getFrameTimestamp(){let e;if(this.isActiveLive){let i=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-i}else e=this.position||0;return Math.floor(e)}getUTC(){return Math.floor(Date.now()/1e3)}prepareUrl(e){return e.replace("{@fts_fake_sec}",String(this.getFrameTimestamp())).replace("{@utc_sec}",String(this.getUTC())).split("&").filter(i=>!/={@[a-zA-Z_]+}/.test(i)).join("&")}preparePixels(e){return this.validatePixels(this.params.pixels,{event:e,keys:["url"]})}prepareHeartbeatPixels(){return this.validatePixels(this.params.pixels,{event:"heartbeat",keys:["url","interval"]})}call(e){try{this.idleCallbackIds.push(requestIdleCallback(()=>Lt().src=this.prepareUrl(e)))}catch(i){this.log({message:i.message})}}send(e){let i=this.preparePixels(e);for(let{url:t}of i)this.call(t)}sendHeartbeat(e){this.call(e)}};export{U as ApiEnv,ge as ConnectionType,fe as ContentType,qe as InteractiveInterfaceClick,Be as MediascopePixel,ki as MediascopePixelTypes,xe as OneStat,pe as Quality,me as SeekAction,Ct as ThinOneStat,_ as VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vkontakte/videoplayer-statistics",
|
|
3
|
-
"version": "1.0.96-dev.
|
|
3
|
+
"version": "1.0.96-dev.c564bb3a.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.150-dev.
|
|
58
|
-
"@vkontakte/videoplayer-shared": "1.0.79-dev.
|
|
57
|
+
"@vkontakte/videoplayer-core": "2.0.150-dev.c564bb3a.0",
|
|
58
|
+
"@vkontakte/videoplayer-shared": "1.0.79-dev.c564bb3a.0"
|
|
59
59
|
}
|
|
60
60
|
}
|