@vkontakte/videoplayer-statistics 1.0.51-dev.9505da81.0 → 1.0.51-dev.bbd1265d.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.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- "use strict";var k=Object.defineProperty,Ie=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyDescriptors,Pe=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var ee=(r,e,i)=>e in r?k(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,P=(r,e)=>{for(var i in e||(e={}))te.call(e,i)&&ee(r,i,e[i]);if(Z)for(var i of Z(e))Ee.call(e,i)&&ee(r,i,e[i]);return r},$=(r,e)=>Ie(r,ye(e));var _e=(r,e)=>{for(var i in e)k(r,i,{get:e[i],enumerable:!0})},Ae=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!te.call(r,o)&&o!==i&&k(r,o,{get:()=>e[o],enumerable:!(t=Se(e,o))||t.enumerable});return r};var xe=r=>Ae(k({},"__esModule",{value:!0}),r);var I=(r,e,i)=>new Promise((t,o)=>{var n=l=>{try{h(i.next(l))}catch(p){o(p)}},a=l=>{try{h(i.throw(l))}catch(p){o(p)}},h=l=>l.done?t(l.value):Promise.resolve(l.value).then(n,a);h((i=i.apply(r,e)).next())});var Le={};_e(Le,{ApiEnv:()=>x,ConnectionType:()=>N,ContentType:()=>O,InteractiveInterfaceClick:()=>K,OneStat:()=>U,Quality:()=>R,SeekAction:()=>D,VERSION:()=>C});module.exports=xe(Le);var x=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(x||{}),R=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(R||{}),O=(g=>(g.MP4="mp4",g.DASH="dash",g.DASH_SEP="dash_sep",g.ONDEMAND_DASH="ondemand_dash",g.HLS="hls",g.ONDEMAND_HLS="ondemand_hls",g.WEBM="webm",g.AV1="av1",g.ONDEMAND_DASH_LIVE="ondemand_dash_live",g.ONDEMAND_HLS_LIVE="ondemand_hls_live",g.WEBRTC="webrtc",g.UNKNOWN="unknown",g.RTMP="rtmp",g))(O||{});var N=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(N||{});var D=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))(D||{}),K=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(K||{}),ie={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"},oe={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"},se={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},re={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ne=require("@vkontakte/videoplayer-shared"),Ce={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ae=r=>(0,ne.fillWithDefault)(r,Ce);function q(){let r="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]=r[o===19?t&3|8:t]);return e.join("")}var d=require("@vkontakte/videoplayer-shared"),W=require("@vkontakte/videoplayer-shared");var de=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var p,s,u;let h=(p=oe[n])!=null?p:n,l=a;return a&&(n==="mode"?l=(s=re[a])!=null?s:a:n==="quality"&&(l=(u=se[a])!=null?u:a)),[h,l]}));return $(P({},r),{operation:(o=ie[e])!=null?o:e,custom:t})};var C="1.0.51-dev.9505da81.0",ue="CIOPGQJGDIHBABABA",z={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var v=require("@vkontakte/videoplayer-shared");var T=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new v.ValueSubject(!1);this.params=e}authorize(e){return I(this,null,function*(){return this.authToken=e!=null?e:yield 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)}logRequest(e){return I(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(p,...s)=>I(this,[p,...s],function*(h,l=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:v.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:u});return}let m=u==null?void 0:u.error_code;switch(m){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${m}`,category:v.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:u});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return I(this,null,function*(){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",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${C}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(de):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,v.getExponentialDelay)(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:v.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return I(this,null,function*(){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.uuid,client_version:C.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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:v.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>I(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:v.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:v.ErrorCategory.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})}};var S=require("@vkontakte/videoplayer-shared");var w=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=z[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){return I(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),z.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return I(this,null,function*(){let o=(0,S.now)(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:S.ErrorCategory.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:(0,S.now)()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var s,u;let h=Number(a.headers.get("content-length"))===0,l=new Date((s=a.headers.get("date"))!=null?s:"").getTime(),p=(0,S.now)()-o;if(isFinite(l)&&((u=this.timeSynchronisation)==null||u.addServerTime(l,p)),!h)return a.json().then(m=>Object.prototype.hasOwnProperty.call(m,"error_msg")?Promise.reject(m):m,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var b=require("@vkontakte/videoplayer-shared");var B="onestat_events",Q=r=>e=>e.timestamp+r>=(0,b.now)(),F=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=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=b.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:b.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=b.safeStorage.get(B);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(Q(this.params.config.storageExpiration));b.safeStorage.set(B,JSON.stringify($(P({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(Q(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],b.safeStorage.set(B,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(Q(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}b.safeStorage.set(B,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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()}};var c=require("@vkontakte/videoplayer-core"),j=require("@vkontakte/videoplayer-shared");var ce=r=>r&&{[c.VideoQuality.INVARIANT]:"unknown",[c.VideoQuality.Q_144P]:"mobile",[c.VideoQuality.Q_240P]:"lowest",[c.VideoQuality.Q_360P]:"low",[c.VideoQuality.Q_480P]:"medium",[c.VideoQuality.Q_720P]:"high",[c.VideoQuality.Q_1080P]:"fullhd",[c.VideoQuality.Q_1440P]:"quadhd",[c.VideoQuality.Q_2160P]:"ultrahd",[c.VideoQuality.Q_4320P]:"unknown"}[r],G=r=>r&&{[c.HttpConnectionType.HTTP1]:"http1",[c.HttpConnectionType.HTTP2]:"http2",[c.HttpConnectionType.QUIC]:"http3"}[r],le=r=>{if(r!==void 0)switch(r){case c.VideoFormat.MPEG:return"mp4";case c.VideoFormat.DASH_LIVE:return"dash";case c.VideoFormat.DASH_SEP:return"dash_sep";case c.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case c.VideoFormat.DASH_WEBM:case c.VideoFormat.DASH_LIVE_WEBM:return"webm";case c.VideoFormat.DASH_WEBM_AV1:return"av1";case c.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case c.VideoFormat.HLS:case c.VideoFormat.HLS_LIVE:return"hls";case c.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case c.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case c.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,j.assertNever)(r)}},M=r=>{if(r!==void 0)switch(r){case c.Surface.NONE:case c.Surface.INLINE:return;case c.Surface.FULLSCREEN:return"fullscreen";case c.Surface.SECOND_SCREEN:return"chromecast";case c.Surface.PIP:return"pip";case c.Surface.INVISIBLE:return"invisible";default:return(0,j.assertNever)(r)}},pe=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var V=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Y=require("@vkontakte/videoplayer-core"),f=require("@vkontakte/videoplayer-shared"),ge=(r,e)=>new f.Observable(i=>{let t=new f.Subscription,o=(0,f.merge)((0,f.fromEvent)(window,"beforeunload"),r.events.willDestruct$),n=new f.ValueSubject(void 0),a;t.add(r.info.isLive$.pipe((0,f.filterChanged)()).subscribe(y=>{a&&(a.unsubscribe(),n.next(void 0)),y?a=r.info.liveTime$.pipe((0,f.map)(H=>H&&H/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:h,paused$:l}=r.events,p=r.events.willSeek$.pipe((0,f.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),s=r.events.seeked$.pipe((0,f.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),u=!1,m=new f.Subject;t.add(p.subscribe(()=>{u||m.next(),u=!0})),t.add(s.subscribe(()=>u=!1));let g=new f.Subject,E=new f.Subject,_=(0,f.merge)(h,s,g),L=(0,f.merge)(l,m,o,r.events.looped$,E),A,me=()=>A=n.getValue(),be=()=>{let y=n.getValue();(0,f.isNullable)(A)||A===y||(0,f.isNullable)(y)||(i.next({from:A,to:y}),A=void 0)},ve=()=>{E.next(),g.next()};if(t.add(_.subscribe(me)),t.add(L.subscribe(be)),e.forceInterval&&isFinite(e.forceInterval)){let y=0;t.add(_.subscribe(()=>y=window.setTimeout(ve,e.forceInterval))),t.add(L.subscribe(()=>window.clearTimeout(y)))}return t});var we="_one-stat_",X=`${we}uuid`,J=()=>{let r=new d.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},U=class{constructor(e,i){this.subscription=new d.Subscription;this.debugLogger=new W.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new d.ValueSubject(void 0);this.isid$=new d.ValueSubject(void 0);this.seekAction$=new d.ValueSubject("unknown");var l,p,s;this.statContext=e,this.config=ae((l=i.config)!=null?l:{}),(0,d.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new V);let t=new d.Subject;this.experimental={error$:t};let o=d.safeStorage.get(X);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),d.safeStorage.set(X,this.uuid)):this.uuid=o:(this.uuid=q(),d.safeStorage.set(X,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((p=i.isid)!=null?p:fe());let n=new w({apiKey:ue,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new T({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new F({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:h}=(0,W.detectEmbed)();this.isEmbed=a,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext=P(P({},this.statContext),e)}attachTo(e){let i=new d.Subscription,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ge(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),m={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;t(e.info.isStalled$,s=>{s?o=(0,d.now)():((0,d.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,d.now)()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe((0,d.once)()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=(0,d.isNonNullable)(o)?(0,d.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,h,l=!1;t(e.events.firstBytes$,s=>{a=(0,d.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,d.now)()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&(0,d.isNonNullable)(a)&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0)}),t(e.events.firstFrame$,()=>{(0,d.isNonNullable)(a)&&!l&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0),(0,d.isNonNullable)(h)&&this.logFirstFrame({time:(0,d.now)()-h})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,d.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let p;return t(e.info.hostname$,s=>{let u=p!==void 0&&p!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),p=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:G(s)}),this.updateContext({connectionType:G(s)})}),t(e.info.httpConnectionReused$,s=>{(0,d.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:M(s)})),t((0,d.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let m=u.find(({id:E})=>E===s),g=m&&(m.isAuto?`${m.language}_auto`:m.language);this.updateContext({subtitles:g})}),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}=J();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":M((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":M((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=J();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=J();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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((0,d.merge)((0,d.fromEvent)(e,"change"),(0,d.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,d.fromEvent)(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var g,E;let n=(E=(g=this.timeSynchronisation)==null?void 0:g.now())!=null?E:(0,d.now)(),a=this.vsid$.getValue();(0,d.assertNonNullable)(a);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,s,u;if(this.isEmbed){s=this.embedParent;let _=[...new URLSearchParams(location.search).entries()].filter(([L,A])=>this.config.embedUrlParams.includes(L));u=new URLSearchParams(_).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),u=location.href.substring(0,1024));let m=P({vsid:a,isid:h,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:u,rate:this.statContext.rate===1||(0,d.isNullable)(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 _ of this.config.disabledCustomFields)delete m[_];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:m}}};
6
+ "use strict";var k=Object.defineProperty,Ie=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyDescriptors,Pe=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var ee=(r,e,i)=>e in r?k(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,P=(r,e)=>{for(var i in e||(e={}))te.call(e,i)&&ee(r,i,e[i]);if(Z)for(var i of Z(e))Ee.call(e,i)&&ee(r,i,e[i]);return r},$=(r,e)=>Ie(r,ye(e));var _e=(r,e)=>{for(var i in e)k(r,i,{get:e[i],enumerable:!0})},Ae=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!te.call(r,o)&&o!==i&&k(r,o,{get:()=>e[o],enumerable:!(t=Se(e,o))||t.enumerable});return r};var xe=r=>Ae(k({},"__esModule",{value:!0}),r);var I=(r,e,i)=>new Promise((t,o)=>{var n=l=>{try{h(i.next(l))}catch(p){o(p)}},a=l=>{try{h(i.throw(l))}catch(p){o(p)}},h=l=>l.done?t(l.value):Promise.resolve(l.value).then(n,a);h((i=i.apply(r,e)).next())});var Le={};_e(Le,{ApiEnv:()=>x,ConnectionType:()=>N,ContentType:()=>O,InteractiveInterfaceClick:()=>K,OneStat:()=>U,Quality:()=>R,SeekAction:()=>D,VERSION:()=>C});module.exports=xe(Le);var x=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(x||{}),R=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(R||{}),O=(f=>(f.MP4="mp4",f.DASH="dash",f.DASH_SEP="dash_sep",f.ONDEMAND_DASH="ondemand_dash",f.HLS="hls",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))(O||{});var N=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(N||{});var D=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))(D||{}),K=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(K||{}),ie={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"},oe={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"},se={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},re={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ne=require("@vkontakte/videoplayer-shared"),Ce={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ae=r=>(0,ne.fillWithDefault)(r,Ce);function q(){let r="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]=r[o===19?t&3|8:t]);return e.join("")}var d=require("@vkontakte/videoplayer-shared"),W=require("@vkontakte/videoplayer-shared");var de=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var p,s,u;let h=(p=oe[n])!=null?p:n,l=a;return a&&(n==="mode"?l=(s=re[a])!=null?s:a:n==="quality"&&(l=(u=se[a])!=null?u:a)),[h,l]}));return $(P({},r),{operation:(o=ie[e])!=null?o:e,custom:t})};var C="1.0.51-dev.bbd1265d.0",ue="CIOPGQJGDIHBABABA",z={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var v=require("@vkontakte/videoplayer-shared");var T=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new v.ValueSubject(!1);this.params=e}authorize(e){return I(this,null,function*(){return this.authToken=e!=null?e:yield 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)}logRequest(e){return I(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(p,...s)=>I(this,[p,...s],function*(h,l=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:v.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:u});return}let m=u==null?void 0:u.error_code;switch(m){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${m}`,category:v.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:u});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return I(this,null,function*(){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",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${C}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(de):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,v.getExponentialDelay)(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:v.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return I(this,null,function*(){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.uuid,client_version:C.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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:v.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>I(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:v.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:v.ErrorCategory.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})}};var S=require("@vkontakte/videoplayer-shared");var w=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=z[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){return I(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),z.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return I(this,null,function*(){let o=(0,S.now)(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:S.ErrorCategory.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:(0,S.now)()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var s,u;let h=Number(a.headers.get("content-length"))===0,l=new Date((s=a.headers.get("date"))!=null?s:"").getTime(),p=(0,S.now)()-o;if(isFinite(l)&&((u=this.timeSynchronisation)==null||u.addServerTime(l,p)),!h)return a.json().then(m=>Object.prototype.hasOwnProperty.call(m,"error_msg")?Promise.reject(m):m,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var b=require("@vkontakte/videoplayer-shared");var B="onestat_events",Q=r=>e=>e.timestamp+r>=(0,b.now)(),F=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=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=b.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:b.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=b.safeStorage.get(B);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(Q(this.params.config.storageExpiration));b.safeStorage.set(B,JSON.stringify($(P({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(Q(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],b.safeStorage.set(B,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(Q(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}b.safeStorage.set(B,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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()}};var c=require("@vkontakte/videoplayer-core"),j=require("@vkontakte/videoplayer-shared");var ce=r=>r&&{[c.VideoQuality.INVARIANT]:"unknown",[c.VideoQuality.Q_144P]:"mobile",[c.VideoQuality.Q_240P]:"lowest",[c.VideoQuality.Q_360P]:"low",[c.VideoQuality.Q_480P]:"medium",[c.VideoQuality.Q_720P]:"high",[c.VideoQuality.Q_1080P]:"fullhd",[c.VideoQuality.Q_1440P]:"quadhd",[c.VideoQuality.Q_2160P]:"ultrahd",[c.VideoQuality.Q_4320P]:"unknown"}[r],G=r=>r&&{[c.HttpConnectionType.HTTP1]:"http1",[c.HttpConnectionType.HTTP2]:"http2",[c.HttpConnectionType.QUIC]:"http3"}[r],le=r=>{if(r!==void 0)switch(r){case c.VideoFormat.MPEG:return"mp4";case c.VideoFormat.DASH_LIVE:return"dash";case c.VideoFormat.DASH_SEP:return"dash_sep";case c.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case c.VideoFormat.DASH_WEBM:case c.VideoFormat.DASH_LIVE_WEBM:return"webm";case c.VideoFormat.DASH_WEBM_AV1:return"av1";case c.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case c.VideoFormat.HLS:case c.VideoFormat.HLS_LIVE:return"hls";case c.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case c.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case c.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,j.assertNever)(r)}},M=r=>{if(r!==void 0)switch(r){case c.Surface.NONE:case c.Surface.INLINE:return;case c.Surface.FULLSCREEN:return"fullscreen";case c.Surface.SECOND_SCREEN:return"chromecast";case c.Surface.PIP:return"pip";case c.Surface.INVISIBLE:return"invisible";default:return(0,j.assertNever)(r)}},pe=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var V=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),ge=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Y=require("@vkontakte/videoplayer-core"),g=require("@vkontakte/videoplayer-shared"),fe=(r,e)=>new g.Observable(i=>{let t=new g.Subscription,o=(0,g.merge)((0,g.fromEvent)(window,"beforeunload"),r.events.willDestruct$),n=new g.ValueSubject(void 0),a;t.add(r.info.isLive$.pipe((0,g.filterChanged)()).subscribe(y=>{a&&(a.unsubscribe(),n.next(void 0)),y?a=r.info.liveTime$.pipe((0,g.map)(H=>H&&H/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:h,paused$:l}=r.events,p=r.events.willSeek$.pipe((0,g.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),s=r.events.seeked$.pipe((0,g.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),u=!1,m=new g.Subject;t.add(p.subscribe(()=>{u||m.next(),u=!0})),t.add(s.subscribe(()=>u=!1));let f=new g.Subject,E=new g.Subject,_=(0,g.merge)(h,s,f),L=(0,g.merge)(l,m,o,r.events.looped$,E),A,me=()=>A=n.getValue(),be=()=>{let y=n.getValue();(0,g.isNullable)(A)||A===y||(0,g.isNullable)(y)||(i.next({from:A,to:y}),A=void 0)},ve=()=>{E.next(),f.next()};if(t.add(_.subscribe(me)),t.add(L.subscribe(be)),e.forceInterval&&isFinite(e.forceInterval)){let y=0;t.add(_.subscribe(()=>y=window.setTimeout(ve,e.forceInterval))),t.add(L.subscribe(()=>window.clearTimeout(y)))}return t});var we="_one-stat_",X=`${we}uuid`,J=()=>{let r=new d.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},U=class{constructor(e,i){this.subscription=new d.Subscription;this.debugLogger=new W.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new d.ValueSubject(void 0);this.isid$=new d.ValueSubject(void 0);this.seekAction$=new d.ValueSubject("unknown");var l,p,s;this.statContext=e,this.config=ae((l=i.config)!=null?l:{}),(0,d.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new V);let t=new d.Subject;this.experimental={error$:t};let o=d.safeStorage.get(X);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),d.safeStorage.set(X,this.uuid)):this.uuid=o:(this.uuid=q(),d.safeStorage.set(X,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((p=i.isid)!=null?p:ge());let n=new w({apiKey:ue,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new T({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new F({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:h}=(0,W.detectEmbed)();this.isEmbed=a,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext=P(P({},this.statContext),e)}attachTo(e){let i=new d.Subscription,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(fe(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),m={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;t(e.info.isStalled$,s=>{s?o=(0,d.now)():((0,d.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,d.now)()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe((0,d.once)()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=(0,d.isNonNullable)(o)?(0,d.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,h,l=!1;t(e.events.firstBytes$,s=>{a=(0,d.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,d.now)()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&(0,d.isNonNullable)(a)&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0)}),t(e.events.firstFrame$,()=>{(0,d.isNonNullable)(a)&&!l&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0),(0,d.isNonNullable)(h)&&this.logFirstFrame({time:(0,d.now)()-h})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,d.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let p;return t(e.info.hostname$,s=>{let u=p!==void 0&&p!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),p=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:G(s)}),this.updateContext({connectionType:G(s)})}),t(e.info.httpConnectionReused$,s=>{(0,d.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:M(s)})),t((0,d.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let m=u.find(({id:E})=>E===s),f=m&&(m.isAuto?`${m.language}_auto`:m.language);this.updateContext({subtitles:f})}),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}=J();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":M((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":M((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=J();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=J();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}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}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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((0,d.merge)((0,d.fromEvent)(e,"change"),(0,d.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,d.fromEvent)(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var f,E;let n=(E=(f=this.timeSynchronisation)==null?void 0:f.now())!=null?E:(0,d.now)(),a=this.vsid$.getValue();(0,d.assertNonNullable)(a);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,s,u;if(this.isEmbed){s=this.embedParent;let _=[...new URLSearchParams(location.search).entries()].filter(([L,A])=>this.config.embedUrlParams.includes(L));u=new URLSearchParams(_).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),u=location.href.substring(0,1024));let m=P({vsid:a,isid:h,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:u,rate:this.statContext.rate===1||(0,d.isNullable)(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 _ of this.config.disabledCustomFields)delete m[_];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:m}}};
package/es2015.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- var Le=Object.defineProperty,ke=Object.defineProperties;var $e=Object.getOwnPropertyDescriptors;var oe=Object.getOwnPropertySymbols;var Re=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var se=(r,e,i)=>e in r?Le(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,I=(r,e)=>{for(var i in e||(e={}))Re.call(e,i)&&se(r,i,e[i]);if(oe)for(var i of oe(e))Oe.call(e,i)&&se(r,i,e[i]);return r},k=(r,e)=>ke(r,$e(e));var g=(r,e,i)=>new Promise((t,o)=>{var n=u=>{try{l(i.next(u))}catch(c){o(c)}},a=u=>{try{l(i.throw(u))}catch(c){o(c)}},l=u=>u.done?t(u.value):Promise.resolve(u.value).then(n,a);l((i=i.apply(r,e)).next())});var x=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(x||{}),M=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(M||{}),V=(p=>(p.MP4="mp4",p.DASH="dash",p.DASH_SEP="dash_sep",p.ONDEMAND_DASH="ondemand_dash",p.HLS="hls",p.ONDEMAND_HLS="ondemand_hls",p.WEBM="webm",p.AV1="av1",p.ONDEMAND_DASH_LIVE="ondemand_dash_live",p.ONDEMAND_HLS_LIVE="ondemand_hls_live",p.WEBRTC="webrtc",p.UNKNOWN="unknown",p.RTMP="rtmp",p))(V||{});var U=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(U||{});var W=(l=>(l.SLIDER="slider",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(W||{}),re=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(re||{}),ne={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"},ae={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"},de={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},ue={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ne}from"@vkontakte/videoplayer-shared";var De={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ce=r=>Ne(r,De);function H(){let r="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]=r[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as je,combine as _e,fromEvent as Ae,isNonNullable as A,isNullable as xe,merge as Ge,now as b,observableFrom as Ye,once as Xe,safeStorage as X,Subject as Je,Subscription as te,ValueSubject as J}from"@vkontakte/videoplayer-shared";import{Logger as Ze,detectEmbed as et}from"@vkontakte/videoplayer-shared";var le=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var c,s,d;let l=(c=ae[n])!=null?c:n,u=a;return a&&(n==="mode"?u=(s=ue[a])!=null?s:a:n==="quality"&&(u=(d=de[a])!=null?d:a)),[l,u]}));return k(I({},r),{operation:(o=ne[e])!=null?o:e,custom:t})};var $="1.0.51-dev.9505da81.0",pe="CIOPGQJGDIHBABABA",K={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Be,getExponentialDelay as Fe,ErrorCategory as E}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Be(!1);this.params=e}authorize(e){return g(this,null,function*(){return this.authToken=e!=null?e:yield 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)}logRequest(e){return g(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(c,...s)=>g(this,[c,...s],function*(l,u=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:E.NETWORK,message:`Unknown ${i} error`,thrown:d});return}let h=d==null?void 0:d.error_code;switch(h){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:E.EXTERNAL_API,message:`${i} error`,data:d});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return g(this,null,function*(){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",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${$}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(le):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Fe(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:E.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return g(this,null,function*(){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.uuid,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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:E.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>g(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:E.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:E.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 R,now as q}from"@vkontakte/videoplayer-shared";var T=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=K[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){return g(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:R.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),K.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:R.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return g(this,null,function*(){let o=q(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:R.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:R.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:q()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var s,d;let l=Number(a.headers.get("content-length"))===0,u=new Date((s=a.headers.get("date"))!=null?s:"").getTime(),c=q()-o;if(isFinite(u)&&((d=this.timeSynchronisation)==null||d.addServerTime(u,c)),!l)return a.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Me,now as Ve,safeStorage as w,debounceFn as he}from"@vkontakte/videoplayer-shared";var O="onestat_events",z=r=>e=>e.timestamp+r>=Ve(),N=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=he(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=w.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=he(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:Me.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=w.get(O);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(z(this.params.config.storageExpiration));w.set(O,JSON.stringify(k(I({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(z(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],w.set(O,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(z(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(O,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 Q,Surface as _,VideoFormat as f,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as fe}from"@vkontakte/videoplayer-shared";var ge=r=>r&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[r],j=r=>r&&{[Q.HTTP1]:"http1",[Q.HTTP2]:"http2",[Q.QUIC]:"http3"}[r],me=r=>{if(r!==void 0)switch(r){case f.MPEG:return"mp4";case f.DASH_LIVE:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return fe(r)}},D=r=>{if(r!==void 0)switch(r){case _.NONE:case _.INLINE:return;case _.FULLSCREEN:return"fullscreen";case _.SECOND_SCREEN:return"chromecast";case _.PIP:return"pip";case _.INVISIBLE:return"invisible";default:return fe(r)}},be=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var B=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 ve=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),Ie=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as Se}from"@vkontakte/videoplayer-core";import{filter as ye,filterChanged as We,fromEvent as He,isNullable as Pe,map as Ke,merge as G,Observable as qe,Subject as Y,Subscription as ze,ValueSubject as Qe}from"@vkontakte/videoplayer-shared";var Ee=(r,e)=>new qe(i=>{let t=new ze,o=G(He(window,"beforeunload"),r.events.willDestruct$),n=new Qe(void 0),a;t.add(r.info.isLive$.pipe(We()).subscribe(v=>{a&&(a.unsubscribe(),n.next(void 0)),v?a=r.info.liveTime$.pipe(Ke(F=>F&&F/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:l,paused$:u}=r.events,c=r.events.willSeek$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),s=r.events.seeked$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),d=!1,h=new Y;t.add(c.subscribe(()=>{d||h.next(),d=!0})),t.add(s.subscribe(()=>d=!1));let p=new Y,S=new Y,y=G(l,s,p),L=G(u,h,o,r.events.looped$,S),P,Ce=()=>P=n.getValue(),Te=()=>{let v=n.getValue();Pe(P)||P===v||Pe(v)||(i.next({from:P,to:v}),P=void 0)},we=()=>{S.next(),p.next()};if(t.add(y.subscribe(Ce)),t.add(L.subscribe(Te)),e.forceInterval&&isFinite(e.forceInterval)){let v=0;t.add(y.subscribe(()=>v=window.setTimeout(we,e.forceInterval))),t.add(L.subscribe(()=>window.clearTimeout(v)))}return t});var tt="_one-stat_",Z=`${tt}uuid`,ee=()=>{let r=new te;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},ie=class{constructor(e,i){this.subscription=new te;this.debugLogger=new Ze;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new J(void 0);this.isid$=new J(void 0);this.seekAction$=new J("unknown");var u,c,s;this.statContext=e,this.config=ce((u=i.config)!=null?u:{}),A(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new B);let t=new Je;this.experimental={error$:t};let o=X.get(Z);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),X.set(Z,this.uuid)):this.uuid=o:(this.uuid=H(),X.set(Z,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:Ie());let n=new T({apiKey:pe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new C({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new N({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:l}=et();this.isEmbed=a,this.embedParent=l,this.subscribe()}updateContext(e){this.statContext=I(I({},this.statContext),e)}attachTo(e){let i=new te,t=(s,d)=>i.add(s.subscribe(d));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(Ee(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let d=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};d?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=b():(A(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(Xe()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=A(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:d!=null?d:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,l,u=!1;t(e.events.firstBytes$,s=>{a=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>l=b()),t(e.info.currentBuffer$,s=>{!u&&s&&s.end-s.start>0&&A(a)&&(this.logPlayerReady({duration:b()-a}),u=!0)}),t(e.events.firstFrame$,()=>{A(a)&&!u&&(this.logPlayerReady({duration:b()-a}),u=!0),A(l)&&this.logFirstFrame({time:b()-l})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(_e({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:d})=>this.updateContext({audible:!s&&d>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ge(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:me(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let c;return t(e.info.hostname$,s=>{let d=c!==void 0&&c!==s;this.updateContext({cdnHostname:s,failover:d}),d&&this.logFailover(s),c=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:j(s)}),this.updateContext({connectionType:j(s)})}),t(e.info.httpConnectionReused$,s=>{xe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:D(s)})),t(_e({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:d})=>{let h=d.find(({id:S})=>S===s),p=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:p})}),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}=ee();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=ee();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=ee();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ve())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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(Ge(Ae(e,"change"),Ye(["init"])).subscribe(()=>this.updateContext({network:be(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=Ae(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var p,S;let n=(S=(p=this.timeSynchronisation)==null?void 0:p.now())!=null?S:b(),a=this.vsid$.getValue();je(a);let l=this.isid$.getValue(),u=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,s,d;if(this.isEmbed){s=this.embedParent;let y=[...new URLSearchParams(location.search).entries()].filter(([L,P])=>this.config.embedUrlParams.includes(L));d=new URLSearchParams(y).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),d=location.href.substring(0,1024));let h=I({vsid:a,isid:l,vid:this.statContext.movieId,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:u,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:d,rate:this.statContext.rate===1||xe(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 y of this.config.disabledCustomFields)delete h[y];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:h}}};export{x as ApiEnv,U as ConnectionType,V as ContentType,re as InteractiveInterfaceClick,ie as OneStat,M as Quality,W as SeekAction,$ as VERSION};
6
+ var Le=Object.defineProperty,ke=Object.defineProperties;var $e=Object.getOwnPropertyDescriptors;var oe=Object.getOwnPropertySymbols;var Re=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var se=(r,e,i)=>e in r?Le(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,I=(r,e)=>{for(var i in e||(e={}))Re.call(e,i)&&se(r,i,e[i]);if(oe)for(var i of oe(e))Oe.call(e,i)&&se(r,i,e[i]);return r},k=(r,e)=>ke(r,$e(e));var f=(r,e,i)=>new Promise((t,o)=>{var n=u=>{try{l(i.next(u))}catch(c){o(c)}},a=u=>{try{l(i.throw(u))}catch(c){o(c)}},l=u=>u.done?t(u.value):Promise.resolve(u.value).then(n,a);l((i=i.apply(r,e)).next())});var x=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(x||{}),M=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(M||{}),V=(p=>(p.MP4="mp4",p.DASH="dash",p.DASH_SEP="dash_sep",p.ONDEMAND_DASH="ondemand_dash",p.HLS="hls",p.ONDEMAND_HLS="ondemand_hls",p.WEBM="webm",p.AV1="av1",p.ONDEMAND_DASH_LIVE="ondemand_dash_live",p.ONDEMAND_HLS_LIVE="ondemand_hls_live",p.WEBRTC="webrtc",p.UNKNOWN="unknown",p.RTMP="rtmp",p))(V||{});var U=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(U||{});var W=(l=>(l.SLIDER="slider",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(W||{}),re=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(re||{}),ne={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"},ae={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"},de={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},ue={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ne}from"@vkontakte/videoplayer-shared";var De={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ce=r=>Ne(r,De);function H(){let r="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]=r[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as je,combine as _e,fromEvent as Ae,isNonNullable as A,isNullable as xe,merge as Ge,now as b,observableFrom as Ye,once as Xe,safeStorage as X,Subject as Je,Subscription as te,ValueSubject as J}from"@vkontakte/videoplayer-shared";import{Logger as Ze,detectEmbed as et}from"@vkontakte/videoplayer-shared";var le=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var c,s,d;let l=(c=ae[n])!=null?c:n,u=a;return a&&(n==="mode"?u=(s=ue[a])!=null?s:a:n==="quality"&&(u=(d=de[a])!=null?d:a)),[l,u]}));return k(I({},r),{operation:(o=ne[e])!=null?o:e,custom:t})};var $="1.0.51-dev.bbd1265d.0",pe="CIOPGQJGDIHBABABA",K={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Be,getExponentialDelay as Fe,ErrorCategory as E}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Be(!1);this.params=e}authorize(e){return f(this,null,function*(){return this.authToken=e!=null?e:yield 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)}logRequest(e){return f(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(c,...s)=>f(this,[c,...s],function*(l,u=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:E.NETWORK,message:`Unknown ${i} error`,thrown:d});return}let h=d==null?void 0:d.error_code;switch(h){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:E.EXTERNAL_API,message:`${i} error`,data:d});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return f(this,null,function*(){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",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${$}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(le):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Fe(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:E.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return f(this,null,function*(){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.uuid,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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:E.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>f(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:E.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:E.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 R,now as q}from"@vkontakte/videoplayer-shared";var T=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=K[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){return f(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:R.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),K.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:R.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return f(this,null,function*(){let o=q(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:R.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:R.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:q()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var s,d;let l=Number(a.headers.get("content-length"))===0,u=new Date((s=a.headers.get("date"))!=null?s:"").getTime(),c=q()-o;if(isFinite(u)&&((d=this.timeSynchronisation)==null||d.addServerTime(u,c)),!l)return a.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Me,now as Ve,safeStorage as w,debounceFn as he}from"@vkontakte/videoplayer-shared";var O="onestat_events",z=r=>e=>e.timestamp+r>=Ve(),N=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=he(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=w.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=he(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:Me.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=w.get(O);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(z(this.params.config.storageExpiration));w.set(O,JSON.stringify(k(I({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(z(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],w.set(O,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(z(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(O,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 Q,Surface as _,VideoFormat as g,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ge}from"@vkontakte/videoplayer-shared";var fe=r=>r&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[r],j=r=>r&&{[Q.HTTP1]:"http1",[Q.HTTP2]:"http2",[Q.QUIC]:"http3"}[r],me=r=>{if(r!==void 0)switch(r){case g.MPEG:return"mp4";case g.DASH_LIVE:return"dash";case g.DASH_SEP:return"dash_sep";case g.DASH_ONDEMAND:return"ondemand_dash";case g.DASH_WEBM:case g.DASH_LIVE_WEBM:return"webm";case g.DASH_WEBM_AV1:return"av1";case g.DASH_LIVE_CMAF:return"ondemand_dash_live";case g.HLS:case g.HLS_LIVE:return"hls";case g.HLS_ONDEMAND:return"ondemand_hls";case g.HLS_LIVE_CMAF:return"ondemand_hls_live";case g.WEB_RTC_LIVE:return"webrtc";default:return ge(r)}},D=r=>{if(r!==void 0)switch(r){case _.NONE:case _.INLINE:return;case _.FULLSCREEN:return"fullscreen";case _.SECOND_SCREEN:return"chromecast";case _.PIP:return"pip";case _.INVISIBLE:return"invisible";default:return ge(r)}},be=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var B=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 ve=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),Ie=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as Se}from"@vkontakte/videoplayer-core";import{filter as ye,filterChanged as We,fromEvent as He,isNullable as Pe,map as Ke,merge as G,Observable as qe,Subject as Y,Subscription as ze,ValueSubject as Qe}from"@vkontakte/videoplayer-shared";var Ee=(r,e)=>new qe(i=>{let t=new ze,o=G(He(window,"beforeunload"),r.events.willDestruct$),n=new Qe(void 0),a;t.add(r.info.isLive$.pipe(We()).subscribe(v=>{a&&(a.unsubscribe(),n.next(void 0)),v?a=r.info.liveTime$.pipe(Ke(F=>F&&F/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:l,paused$:u}=r.events,c=r.events.willSeek$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),s=r.events.seeked$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),d=!1,h=new Y;t.add(c.subscribe(()=>{d||h.next(),d=!0})),t.add(s.subscribe(()=>d=!1));let p=new Y,S=new Y,y=G(l,s,p),L=G(u,h,o,r.events.looped$,S),P,Ce=()=>P=n.getValue(),Te=()=>{let v=n.getValue();Pe(P)||P===v||Pe(v)||(i.next({from:P,to:v}),P=void 0)},we=()=>{S.next(),p.next()};if(t.add(y.subscribe(Ce)),t.add(L.subscribe(Te)),e.forceInterval&&isFinite(e.forceInterval)){let v=0;t.add(y.subscribe(()=>v=window.setTimeout(we,e.forceInterval))),t.add(L.subscribe(()=>window.clearTimeout(v)))}return t});var tt="_one-stat_",Z=`${tt}uuid`,ee=()=>{let r=new te;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},ie=class{constructor(e,i){this.subscription=new te;this.debugLogger=new Ze;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new J(void 0);this.isid$=new J(void 0);this.seekAction$=new J("unknown");var u,c,s;this.statContext=e,this.config=ce((u=i.config)!=null?u:{}),A(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new B);let t=new Je;this.experimental={error$:t};let o=X.get(Z);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),X.set(Z,this.uuid)):this.uuid=o:(this.uuid=H(),X.set(Z,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:Ie());let n=new T({apiKey:pe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new C({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new N({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:l}=et();this.isEmbed=a,this.embedParent=l,this.subscribe()}updateContext(e){this.statContext=I(I({},this.statContext),e)}attachTo(e){let i=new te,t=(s,d)=>i.add(s.subscribe(d));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(Ee(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let d=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};d?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=b():(A(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(Xe()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=A(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:d!=null?d:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,l,u=!1;t(e.events.firstBytes$,s=>{a=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>l=b()),t(e.info.currentBuffer$,s=>{!u&&s&&s.end-s.start>0&&A(a)&&(this.logPlayerReady({duration:b()-a}),u=!0)}),t(e.events.firstFrame$,()=>{A(a)&&!u&&(this.logPlayerReady({duration:b()-a}),u=!0),A(l)&&this.logFirstFrame({time:b()-l})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(_e({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:d})=>this.updateContext({audible:!s&&d>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:fe(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:me(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let c;return t(e.info.hostname$,s=>{let d=c!==void 0&&c!==s;this.updateContext({cdnHostname:s,failover:d}),d&&this.logFailover(s),c=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:j(s)}),this.updateContext({connectionType:j(s)})}),t(e.info.httpConnectionReused$,s=>{xe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:D(s)})),t(_e({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:d})=>{let h=d.find(({id:S})=>S===s),p=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:p})}),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}=ee();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=ee();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=ee();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ve())}getDeviceId(){return this.uuid}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}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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(Ge(Ae(e,"change"),Ye(["init"])).subscribe(()=>this.updateContext({network:be(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=Ae(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var p,S;let n=(S=(p=this.timeSynchronisation)==null?void 0:p.now())!=null?S:b(),a=this.vsid$.getValue();je(a);let l=this.isid$.getValue(),u=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,s,d;if(this.isEmbed){s=this.embedParent;let y=[...new URLSearchParams(location.search).entries()].filter(([L,P])=>this.config.embedUrlParams.includes(L));d=new URLSearchParams(y).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),d=location.href.substring(0,1024));let h=I({vsid:a,isid:l,vid:this.statContext.movieId,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:u,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:d,rate:this.statContext.rate===1||xe(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 y of this.config.disabledCustomFields)delete h[y];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:h}}};export{x as ApiEnv,U as ConnectionType,V as ContentType,re as InteractiveInterfaceClick,ie as OneStat,M as Quality,W as SeekAction,$ as VERSION};
package/es2018.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(n,e)=>{for(var i in e)V(n,i,{get:e[i],enumerable:!0})},be=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fe(e))!ge.call(n,o)&&o!==i&&V(n,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return n};var ve=n=>be(V({},"__esModule",{value:!0}),n);var Pe={};me(Pe,{ApiEnv:()=>_,ConnectionType:()=>k,ContentType:()=>L,InteractiveInterfaceClick:()=>U,OneStat:()=>B,Quality:()=>w,SeekAction:()=>$,VERSION:()=>A});module.exports=ve(Pe);var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),w=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(w||{}),L=(g=>(g.MP4="mp4",g.DASH="dash",g.DASH_SEP="dash_sep",g.ONDEMAND_DASH="ondemand_dash",g.HLS="hls",g.ONDEMAND_HLS="ondemand_hls",g.WEBM="webm",g.AV1="av1",g.ONDEMAND_DASH_LIVE="ondemand_dash_live",g.ONDEMAND_HLS_LIVE="ondemand_hls_live",g.WEBRTC="webrtc",g.UNKNOWN="unknown",g.RTMP="rtmp",g))(L||{});var k=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(k||{});var $=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))($||{}),U=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(U||{}),Y={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"},X={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"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=n=>(0,ee.fillWithDefault)(n,Ie);function W(){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 a=require("@vkontakte/videoplayer-shared"),F=require("@vkontakte/videoplayer-shared");var ie=n=>{var o;let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([r,d])=>{var c,s,l;let h=(c=X[r])!=null?c:r,f=d;return d&&(r==="mode"?f=(s=Z[d])!=null?s:d:r==="quality"&&(f=(l=J[d])!=null?l:d)),[h,f]}));return{...n,operation:(o=Y[e])!=null?o:e,custom:t}};var A="1.0.51-dev.9505da81.0",oe="CIOPGQJGDIHBABABA",H={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var v=require("@vkontakte/videoplayer-shared");var x=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new v.ValueSubject(!1);this.params=e}async authorize(e){return this.authToken=e!=null?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)}async logRequest(e){var d;let i="log.externalLog",t=this.createLogParams(e),o=(d=this.sessionKey)!=null?d:await this._authorizeWithBackoff();if(!o)return;let r=async(h,f=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:v.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:c});return}let s=c==null?void 0:c.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),f>0?r(h,f-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),f>0?r(h,f-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:v.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${A}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,v.getExponentialDelay)(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:v.ErrorCategory.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.uuid,client_version:A.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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:v.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:v.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:v.ErrorCategory.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}};var I=require("@vkontakte/videoplayer-shared");var C=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=H[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:I.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),H.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:I.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,I.now)(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:I.ErrorCategory.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:I.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:(0,I.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{var s,l;let h=Number(d.headers.get("content-length"))===0,f=new Date((s=d.headers.get("date"))!=null?s:"").getTime(),c=(0,I.now)()-o;if(isFinite(f)&&((l=this.timeSynchronisation)==null||l.addServerTime(f,c)),!h)return d.json().then(m=>Object.prototype.hasOwnProperty.call(m,"error_msg")?Promise.reject(m):m,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var b=require("@vkontakte/videoplayer-shared"),R="onestat_events",K=n=>e=>e.timestamp+n>=(0,b.now)(),O=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=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=b.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:b.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=b.safeStorage.get(R);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(K(this.params.config.storageExpiration));b.safeStorage.set(R,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(K(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],b.safeStorage.set(R,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(K(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}b.safeStorage.set(R,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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()}};var u=require("@vkontakte/videoplayer-core"),q=require("@vkontakte/videoplayer-shared");var se=n=>n&&{[u.VideoQuality.INVARIANT]:"unknown",[u.VideoQuality.Q_144P]:"mobile",[u.VideoQuality.Q_240P]:"lowest",[u.VideoQuality.Q_360P]:"low",[u.VideoQuality.Q_480P]:"medium",[u.VideoQuality.Q_720P]:"high",[u.VideoQuality.Q_1080P]:"fullhd",[u.VideoQuality.Q_1440P]:"quadhd",[u.VideoQuality.Q_2160P]:"ultrahd",[u.VideoQuality.Q_4320P]:"unknown"}[n],z=n=>n&&{[u.HttpConnectionType.HTTP1]:"http1",[u.HttpConnectionType.HTTP2]:"http2",[u.HttpConnectionType.QUIC]:"http3"}[n],re=n=>{if(n!==void 0)switch(n){case u.VideoFormat.MPEG:return"mp4";case u.VideoFormat.DASH_LIVE:return"dash";case u.VideoFormat.DASH_SEP:return"dash_sep";case u.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case u.VideoFormat.DASH_WEBM:case u.VideoFormat.DASH_LIVE_WEBM:return"webm";case u.VideoFormat.DASH_WEBM_AV1:return"av1";case u.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case u.VideoFormat.HLS:case u.VideoFormat.HLS_LIVE:return"hls";case u.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case u.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case u.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,q.assertNever)(n)}},N=n=>{if(n!==void 0)switch(n){case u.Surface.NONE:case u.Surface.INLINE:return;case u.Surface.FULLSCREEN:return"fullscreen";case u.Surface.SECOND_SCREEN:return"chromecast";case u.Surface.PIP:return"pip";case u.Surface.INVISIBLE:return"invisible";default:return(0,q.assertNever)(n)}},ne=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var D=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Q=require("@vkontakte/videoplayer-core"),p=require("@vkontakte/videoplayer-shared"),ue=(n,e)=>new p.Observable(i=>{let t=new p.Subscription,o=(0,p.merge)((0,p.fromEvent)(window,"beforeunload"),n.events.willDestruct$),r=new p.ValueSubject(void 0),d;t.add(n.info.isLive$.pipe((0,p.filterChanged)()).subscribe(S=>{d&&(d.unsubscribe(),r.next(void 0)),S?d=n.info.liveTime$.pipe((0,p.map)(M=>M&&M/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:h,paused$:f}=n.events,c=n.events.willSeek$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),s=n.events.seeked$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),l=!1,m=new p.Subject;t.add(c.subscribe(()=>{l||m.next(),l=!0})),t.add(s.subscribe(()=>l=!1));let g=new p.Subject,y=new p.Subject,P=(0,p.merge)(h,s,g),T=(0,p.merge)(f,m,o,n.events.looped$,y),E,ce=()=>E=r.getValue(),le=()=>{let S=r.getValue();(0,p.isNullable)(E)||E===S||(0,p.isNullable)(S)||(i.next({from:E,to:S}),E=void 0)},pe=()=>{y.next(),g.next()};if(t.add(P.subscribe(ce)),t.add(T.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let S=0;t.add(P.subscribe(()=>S=window.setTimeout(pe,e.forceInterval))),t.add(T.subscribe(()=>window.clearTimeout(S)))}return t});var ye="_one-stat_",j=`${ye}uuid`,G=()=>{let n=new a.Subscription;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},B=class{constructor(e,i){this.subscription=new a.Subscription;this.debugLogger=new F.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new a.ValueSubject(void 0);this.isid$=new a.ValueSubject(void 0);this.seekAction$=new a.ValueSubject("unknown");var f,c,s;this.statContext=e,this.config=te((f=i.config)!=null?f:{}),(0,a.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new D);let t=new a.Subject;this.experimental={error$:t};let o=a.safeStorage.get(j);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),a.safeStorage.set(j,this.uuid)):this.uuid=o:(this.uuid=W(),a.safeStorage.set(j,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:de());let r=new C({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new x({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new O({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:h}=(0,F.detectEmbed)();this.isEmbed=d,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new a.Subscription,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),m={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;t(e.info.isStalled$,s=>{s?o=(0,a.now)():((0,a.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,a.now)()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe((0,a.once)()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=(0,a.isNonNullable)(o)?(0,a.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:l!=null?l:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,h,f=!1;t(e.events.firstBytes$,s=>{d=(0,a.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,a.now)()),t(e.info.currentBuffer$,s=>{!f&&s&&s.end-s.start>0&&(0,a.isNonNullable)(d)&&(this.logPlayerReady({duration:(0,a.now)()-d}),f=!0)}),t(e.events.firstFrame$,()=>{(0,a.isNonNullable)(d)&&!f&&(this.logPlayerReady({duration:(0,a.now)()-d}),f=!0),(0,a.isNonNullable)(h)&&this.logFirstFrame({time:(0,a.now)()-h})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,a.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let c;return t(e.info.hostname$,s=>{let l=c!==void 0&&c!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),c=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(s)}),this.updateContext({connectionType:z(s)})}),t(e.info.httpConnectionReused$,s=>{(0,a.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:N(s)})),t((0,a.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let m=l.find(({id:y})=>y===s),g=m&&(m.isAuto?`${m.language}_auto`:m.language);this.updateContext({subtitles:g})}),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}=G();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var d;let r=o?"pip":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var d;let r=o?"fullscreen":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=G();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=G();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var r,d;let i=(d=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?d:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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((0,a.merge)((0,a.fromEvent)(e,"change"),(0,a.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,a.fromEvent)(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var g,y;let r=(y=(g=this.timeSynchronisation)==null?void 0:g.now())!=null?y:(0,a.now)(),d=this.vsid$.getValue();(0,a.assertNonNullable)(d);let h=this.isid$.getValue(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,s,l;if(this.isEmbed){s=this.embedParent;let P=[...new URLSearchParams(location.search).entries()].filter(([T,E])=>this.config.embedUrlParams.includes(T));l=new URLSearchParams(P).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),l=location.href.substring(0,1024));let m={vsid:d,isid:h,vid:this.statContext.movieId,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:f,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:l,rate:this.statContext.rate===1||(0,a.isNullable)(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 m[P];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:m}}};
6
+ "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var me=(n,e)=>{for(var i in e)V(n,i,{get:e[i],enumerable:!0})},be=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ge(e))!fe.call(n,o)&&o!==i&&V(n,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return n};var ve=n=>be(V({},"__esModule",{value:!0}),n);var Pe={};me(Pe,{ApiEnv:()=>_,ConnectionType:()=>k,ContentType:()=>L,InteractiveInterfaceClick:()=>U,OneStat:()=>B,Quality:()=>w,SeekAction:()=>$,VERSION:()=>A});module.exports=ve(Pe);var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),w=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(w||{}),L=(f=>(f.MP4="mp4",f.DASH="dash",f.DASH_SEP="dash_sep",f.ONDEMAND_DASH="ondemand_dash",f.HLS="hls",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))(L||{});var k=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(k||{});var $=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))($||{}),U=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(U||{}),Y={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"},X={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"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=n=>(0,ee.fillWithDefault)(n,Ie);function W(){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 a=require("@vkontakte/videoplayer-shared"),F=require("@vkontakte/videoplayer-shared");var ie=n=>{var o;let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([r,d])=>{var c,s,l;let h=(c=X[r])!=null?c:r,g=d;return d&&(r==="mode"?g=(s=Z[d])!=null?s:d:r==="quality"&&(g=(l=J[d])!=null?l:d)),[h,g]}));return{...n,operation:(o=Y[e])!=null?o:e,custom:t}};var A="1.0.51-dev.bbd1265d.0",oe="CIOPGQJGDIHBABABA",H={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var v=require("@vkontakte/videoplayer-shared");var x=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new v.ValueSubject(!1);this.params=e}async authorize(e){return this.authToken=e!=null?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)}async logRequest(e){var d;let i="log.externalLog",t=this.createLogParams(e),o=(d=this.sessionKey)!=null?d:await this._authorizeWithBackoff();if(!o)return;let r=async(h,g=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:v.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:c});return}let s=c==null?void 0:c.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),g>0?r(h,g-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),g>0?r(h,g-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:v.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${A}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,v.getExponentialDelay)(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:v.ErrorCategory.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.uuid,client_version:A.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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:v.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:v.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:v.ErrorCategory.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}};var I=require("@vkontakte/videoplayer-shared");var C=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=H[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:I.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),H.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:I.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,I.now)(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:I.ErrorCategory.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:I.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:(0,I.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{var s,l;let h=Number(d.headers.get("content-length"))===0,g=new Date((s=d.headers.get("date"))!=null?s:"").getTime(),c=(0,I.now)()-o;if(isFinite(g)&&((l=this.timeSynchronisation)==null||l.addServerTime(g,c)),!h)return d.json().then(m=>Object.prototype.hasOwnProperty.call(m,"error_msg")?Promise.reject(m):m,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var b=require("@vkontakte/videoplayer-shared"),R="onestat_events",K=n=>e=>e.timestamp+n>=(0,b.now)(),O=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=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=b.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:b.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=b.safeStorage.get(R);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(K(this.params.config.storageExpiration));b.safeStorage.set(R,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(K(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],b.safeStorage.set(R,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(K(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}b.safeStorage.set(R,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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()}};var u=require("@vkontakte/videoplayer-core"),q=require("@vkontakte/videoplayer-shared");var se=n=>n&&{[u.VideoQuality.INVARIANT]:"unknown",[u.VideoQuality.Q_144P]:"mobile",[u.VideoQuality.Q_240P]:"lowest",[u.VideoQuality.Q_360P]:"low",[u.VideoQuality.Q_480P]:"medium",[u.VideoQuality.Q_720P]:"high",[u.VideoQuality.Q_1080P]:"fullhd",[u.VideoQuality.Q_1440P]:"quadhd",[u.VideoQuality.Q_2160P]:"ultrahd",[u.VideoQuality.Q_4320P]:"unknown"}[n],z=n=>n&&{[u.HttpConnectionType.HTTP1]:"http1",[u.HttpConnectionType.HTTP2]:"http2",[u.HttpConnectionType.QUIC]:"http3"}[n],re=n=>{if(n!==void 0)switch(n){case u.VideoFormat.MPEG:return"mp4";case u.VideoFormat.DASH_LIVE:return"dash";case u.VideoFormat.DASH_SEP:return"dash_sep";case u.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case u.VideoFormat.DASH_WEBM:case u.VideoFormat.DASH_LIVE_WEBM:return"webm";case u.VideoFormat.DASH_WEBM_AV1:return"av1";case u.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case u.VideoFormat.HLS:case u.VideoFormat.HLS_LIVE:return"hls";case u.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case u.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case u.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,q.assertNever)(n)}},N=n=>{if(n!==void 0)switch(n){case u.Surface.NONE:case u.Surface.INLINE:return;case u.Surface.FULLSCREEN:return"fullscreen";case u.Surface.SECOND_SCREEN:return"chromecast";case u.Surface.PIP:return"pip";case u.Surface.INVISIBLE:return"invisible";default:return(0,q.assertNever)(n)}},ne=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var D=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Q=require("@vkontakte/videoplayer-core"),p=require("@vkontakte/videoplayer-shared"),ue=(n,e)=>new p.Observable(i=>{let t=new p.Subscription,o=(0,p.merge)((0,p.fromEvent)(window,"beforeunload"),n.events.willDestruct$),r=new p.ValueSubject(void 0),d;t.add(n.info.isLive$.pipe((0,p.filterChanged)()).subscribe(S=>{d&&(d.unsubscribe(),r.next(void 0)),S?d=n.info.liveTime$.pipe((0,p.map)(M=>M&&M/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:h,paused$:g}=n.events,c=n.events.willSeek$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),s=n.events.seeked$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),l=!1,m=new p.Subject;t.add(c.subscribe(()=>{l||m.next(),l=!0})),t.add(s.subscribe(()=>l=!1));let f=new p.Subject,y=new p.Subject,P=(0,p.merge)(h,s,f),T=(0,p.merge)(g,m,o,n.events.looped$,y),E,ce=()=>E=r.getValue(),le=()=>{let S=r.getValue();(0,p.isNullable)(E)||E===S||(0,p.isNullable)(S)||(i.next({from:E,to:S}),E=void 0)},pe=()=>{y.next(),f.next()};if(t.add(P.subscribe(ce)),t.add(T.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let S=0;t.add(P.subscribe(()=>S=window.setTimeout(pe,e.forceInterval))),t.add(T.subscribe(()=>window.clearTimeout(S)))}return t});var ye="_one-stat_",j=`${ye}uuid`,G=()=>{let n=new a.Subscription;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},B=class{constructor(e,i){this.subscription=new a.Subscription;this.debugLogger=new F.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new a.ValueSubject(void 0);this.isid$=new a.ValueSubject(void 0);this.seekAction$=new a.ValueSubject("unknown");var g,c,s;this.statContext=e,this.config=te((g=i.config)!=null?g:{}),(0,a.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new D);let t=new a.Subject;this.experimental={error$:t};let o=a.safeStorage.get(j);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),a.safeStorage.set(j,this.uuid)):this.uuid=o:(this.uuid=W(),a.safeStorage.set(j,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:de());let r=new C({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new x({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new O({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:h}=(0,F.detectEmbed)();this.isEmbed=d,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new a.Subscription,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),m={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;t(e.info.isStalled$,s=>{s?o=(0,a.now)():((0,a.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,a.now)()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe((0,a.once)()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=(0,a.isNonNullable)(o)?(0,a.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:l!=null?l:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,h,g=!1;t(e.events.firstBytes$,s=>{d=(0,a.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,a.now)()),t(e.info.currentBuffer$,s=>{!g&&s&&s.end-s.start>0&&(0,a.isNonNullable)(d)&&(this.logPlayerReady({duration:(0,a.now)()-d}),g=!0)}),t(e.events.firstFrame$,()=>{(0,a.isNonNullable)(d)&&!g&&(this.logPlayerReady({duration:(0,a.now)()-d}),g=!0),(0,a.isNonNullable)(h)&&this.logFirstFrame({time:(0,a.now)()-h})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,a.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let c;return t(e.info.hostname$,s=>{let l=c!==void 0&&c!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),c=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(s)}),this.updateContext({connectionType:z(s)})}),t(e.info.httpConnectionReused$,s=>{(0,a.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:N(s)})),t((0,a.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let m=l.find(({id:y})=>y===s),f=m&&(m.isAuto?`${m.language}_auto`:m.language);this.updateContext({subtitles:f})}),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}=G();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var d;let r=o?"pip":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var d;let r=o?"fullscreen":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=G();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=G();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}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}`})}logWatchCoverageLive(e){var r,d;let i=(d=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?d:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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((0,a.merge)((0,a.fromEvent)(e,"change"),(0,a.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,a.fromEvent)(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var f,y;let r=(y=(f=this.timeSynchronisation)==null?void 0:f.now())!=null?y:(0,a.now)(),d=this.vsid$.getValue();(0,a.assertNonNullable)(d);let h=this.isid$.getValue(),g=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,s,l;if(this.isEmbed){s=this.embedParent;let P=[...new URLSearchParams(location.search).entries()].filter(([T,E])=>this.config.embedUrlParams.includes(T));l=new URLSearchParams(P).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),l=location.href.substring(0,1024));let m={vsid:d,isid:h,vid:this.statContext.movieId,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:g,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:l,rate:this.statContext.rate===1||(0,a.isNullable)(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 m[P];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:m}}};
package/es2018.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),D=(d=>(d.Q144P="mobile",d.Q240P="lowest",d.Q360P="low",d.Q480P="medium",d.Q720P="high",d.Q1080P="fullhd",d.Q1440P="quadhd",d.Q2160P="ultrahd",d.UNKNOWN="unknown",d))(D||{}),B=(p=>(p.MP4="mp4",p.DASH="dash",p.DASH_SEP="dash_sep",p.ONDEMAND_DASH="ondemand_dash",p.HLS="hls",p.ONDEMAND_HLS="ondemand_hls",p.WEBM="webm",p.AV1="av1",p.ONDEMAND_DASH_LIVE="ondemand_dash_live",p.ONDEMAND_HLS_LIVE="ondemand_hls_live",p.WEBRTC="webrtc",p.UNKNOWN="unknown",p.RTMP="rtmp",p))(B||{});var F=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(F||{});var M=(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))(M||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={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"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ae}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=a=>Ae(a,xe);function V(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Fe,combine as Ie,fromEvent as Se,isNonNullable as E,isNullable as ye,merge as Me,now as m,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=a=>{var o;let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([r,n])=>{var d,s,u;let c=(d=ie[r])!=null?d:r,l=n;return n&&(r==="mode"?l=(s=se[n])!=null?s:n:r==="quality"&&(l=(u=oe[n])!=null?u:n)),[c,l]}));return{...a,operation:(o=te[e])!=null?o:e,custom:t}};var w="1.0.51-dev.9505da81.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as y}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!1);this.params=e}async authorize(e){return this.authToken=e!=null?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)}async logRequest(e){var n;let i="log.externalLog",t=this.createLogParams(e),o=(n=this.sessionKey)!=null?n:await this._authorizeWithBackoff();if(!o)return;let r=async(c,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:y.NETWORK,message:`Unknown ${i} error`,thrown:d});return}let s=d==null?void 0:d.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:y.EXTERNAL_API,message:`${i} error`,data:d});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(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:y.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.uuid,client_version:w.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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:y.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:y.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:y.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 L,now as W}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:L.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:L.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:L.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:L.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(n=>{var s,u;let c=Number(n.headers.get("content-length"))===0,l=new Date((s=n.headers.get("date"))!=null?s:"").getTime(),d=W()-o;if(isFinite(l)&&((u=this.timeSynchronisation)==null||u.addServerTime(l,d)),!c)return n.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as Le,safeStorage as C,debounceFn as de}from"@vkontakte/videoplayer-shared";var k="onestat_events",H=a=>e=>e.timestamp+a>=Le(),$=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=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=C.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:we.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=C.get(k);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(H(this.params.config.storageExpiration));C.set(k,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],C.set(k,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(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`})}C.set(k,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 K,Surface as P,VideoFormat as f,VideoQuality as g}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=a=>a&&{[g.INVARIANT]:"unknown",[g.Q_144P]:"mobile",[g.Q_240P]:"lowest",[g.Q_360P]:"low",[g.Q_480P]:"medium",[g.Q_720P]:"high",[g.Q_1080P]:"fullhd",[g.Q_1440P]:"quadhd",[g.Q_2160P]:"ultrahd",[g.Q_4320P]:"unknown"}[a],q=a=>a&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[a],le=a=>{if(a!==void 0)switch(a){case f.MPEG:return"mp4";case f.DASH_LIVE:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return ue(a)}},R=a=>{if(a!==void 0)switch(a){case P.NONE:case P.INLINE:return;case P.FULLSCREEN:return"fullscreen";case P.SECOND_SCREEN:return"chromecast";case P.PIP:return"pip";case P.INVISIBLE:return"invisible";default:return ue(a)}},pe=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Be}from"@vkontakte/videoplayer-shared";var ve=(a,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),a.events.willDestruct$),r=new Be(void 0),n;t.add(a.info.isLive$.pipe($e()).subscribe(b=>{n&&(n.unsubscribe(),r.next(void 0)),b?n=a.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):n=a.info.position$.subscribe(r),t.add(n)}));let{playing$:c,paused$:l}=a.events,d=a.events.willSeek$.pipe(me(()=>a.info.playbackState$.getValue()===ge.PLAYING)),s=a.events.seeked$.pipe(me(()=>a.info.playbackState$.getValue()===ge.PLAYING)),u=!1,h=new Q;t.add(d.subscribe(()=>{u||h.next(),u=!0})),t.add(s.subscribe(()=>u=!1));let p=new Q,v=new Q,I=z(c,s,p),T=z(l,h,o,a.events.looped$,v),S,Pe=()=>S=r.getValue(),Ee=()=>{let b=r.getValue();be(S)||S===b||be(b)||(i.next({from:S,to:b}),S=void 0)},_e=()=>{v.next(),p.next()};if(t.add(I.subscribe(Pe)),t.add(T.subscribe(Ee)),e.forceInterval&&isFinite(e.forceInterval)){let b=0;t.add(I.subscribe(()=>b=window.setTimeout(_e,e.forceInterval))),t.add(T.subscribe(()=>window.clearTimeout(b)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let a=new J;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");var l,d,s;this.statContext=e,this.config=re((l=i.config)!=null?l:{}),E(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((d=i.isid)!=null?d:fe());let r=new x({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new A({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,host:c}=Ke();this.isEmbed=n,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=m():(E(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=E(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let n,c,l=!1;t(e.events.firstBytes$,s=>{n=m(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>c=m()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&E(n)&&(this.logPlayerReady({duration:m()-n}),l=!0)}),t(e.events.firstFrame$,()=>{E(n)&&!l&&(this.logPlayerReady({duration:m()-n}),l=!0),E(c)&&this.logFirstFrame({time:m()-c})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let d;return t(e.info.hostname$,s=>{let u=d!==void 0&&d!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),d=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let h=u.find(({id:v})=>v===s),p=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:p})}),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}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var n;let r=o?"pip":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var n;let r=o?"fullscreen":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var r,n;let i=(n=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?n:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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(Me(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=Se(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var p,v;let r=(v=(p=this.timeSynchronisation)==null?void 0:p.now())!=null?v:m(),n=this.vsid$.getValue();Fe(n);let c=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,d=this.statContext.firstConnectionReused,s,u;if(this.isEmbed){s=this.embedParent;let I=[...new URLSearchParams(location.search).entries()].filter(([T,S])=>this.config.embedUrlParams.includes(T));u=new URLSearchParams(I).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),u=location.href.substring(0,1024));let h={vsid:n,isid:c,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:d===!0?1:d===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:u,rate:this.statContext.rate===1||ye(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 I of this.config.disabledCustomFields)delete h[I];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:h}}};export{_ as ApiEnv,F as ConnectionType,B as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,M as SeekAction,w as VERSION};
6
+ var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),D=(d=>(d.Q144P="mobile",d.Q240P="lowest",d.Q360P="low",d.Q480P="medium",d.Q720P="high",d.Q1080P="fullhd",d.Q1440P="quadhd",d.Q2160P="ultrahd",d.UNKNOWN="unknown",d))(D||{}),B=(p=>(p.MP4="mp4",p.DASH="dash",p.DASH_SEP="dash_sep",p.ONDEMAND_DASH="ondemand_dash",p.HLS="hls",p.ONDEMAND_HLS="ondemand_hls",p.WEBM="webm",p.AV1="av1",p.ONDEMAND_DASH_LIVE="ondemand_dash_live",p.ONDEMAND_HLS_LIVE="ondemand_hls_live",p.WEBRTC="webrtc",p.UNKNOWN="unknown",p.RTMP="rtmp",p))(B||{});var F=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(F||{});var M=(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))(M||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={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"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ae}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=a=>Ae(a,xe);function V(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Fe,combine as Ie,fromEvent as Se,isNonNullable as E,isNullable as ye,merge as Me,now as m,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=a=>{var o;let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([r,n])=>{var d,s,u;let c=(d=ie[r])!=null?d:r,l=n;return n&&(r==="mode"?l=(s=se[n])!=null?s:n:r==="quality"&&(l=(u=oe[n])!=null?u:n)),[c,l]}));return{...a,operation:(o=te[e])!=null?o:e,custom:t}};var w="1.0.51-dev.bbd1265d.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as y}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!1);this.params=e}async authorize(e){return this.authToken=e!=null?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)}async logRequest(e){var n;let i="log.externalLog",t=this.createLogParams(e),o=(n=this.sessionKey)!=null?n:await this._authorizeWithBackoff();if(!o)return;let r=async(c,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:y.NETWORK,message:`Unknown ${i} error`,thrown:d});return}let s=d==null?void 0:d.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:y.EXTERNAL_API,message:`${i} error`,data:d});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(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:y.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.uuid,client_version:w.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=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:y.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:y.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:y.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 L,now as W}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:L.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:L.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:L.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:L.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(n=>{var s,u;let c=Number(n.headers.get("content-length"))===0,l=new Date((s=n.headers.get("date"))!=null?s:"").getTime(),d=W()-o;if(isFinite(l)&&((u=this.timeSynchronisation)==null||u.addServerTime(l,d)),!c)return n.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as Le,safeStorage as C,debounceFn as de}from"@vkontakte/videoplayer-shared";var k="onestat_events",H=a=>e=>e.timestamp+a>=Le(),$=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=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=C.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:we.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=C.get(k);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(H(this.params.config.storageExpiration));C.set(k,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],C.set(k,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(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`})}C.set(k,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 K,Surface as P,VideoFormat as g,VideoQuality as f}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=a=>a&&{[f.INVARIANT]:"unknown",[f.Q_144P]:"mobile",[f.Q_240P]:"lowest",[f.Q_360P]:"low",[f.Q_480P]:"medium",[f.Q_720P]:"high",[f.Q_1080P]:"fullhd",[f.Q_1440P]:"quadhd",[f.Q_2160P]:"ultrahd",[f.Q_4320P]:"unknown"}[a],q=a=>a&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[a],le=a=>{if(a!==void 0)switch(a){case g.MPEG:return"mp4";case g.DASH_LIVE:return"dash";case g.DASH_SEP:return"dash_sep";case g.DASH_ONDEMAND:return"ondemand_dash";case g.DASH_WEBM:case g.DASH_LIVE_WEBM:return"webm";case g.DASH_WEBM_AV1:return"av1";case g.DASH_LIVE_CMAF:return"ondemand_dash_live";case g.HLS:case g.HLS_LIVE:return"hls";case g.HLS_ONDEMAND:return"ondemand_hls";case g.HLS_LIVE_CMAF:return"ondemand_hls_live";case g.WEB_RTC_LIVE:return"webrtc";default:return ue(a)}},R=a=>{if(a!==void 0)switch(a){case P.NONE:case P.INLINE:return;case P.FULLSCREEN:return"fullscreen";case P.SECOND_SCREEN:return"chromecast";case P.PIP:return"pip";case P.INVISIBLE:return"invisible";default:return ue(a)}},pe=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i: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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),ge=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as fe}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Be}from"@vkontakte/videoplayer-shared";var ve=(a,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),a.events.willDestruct$),r=new Be(void 0),n;t.add(a.info.isLive$.pipe($e()).subscribe(b=>{n&&(n.unsubscribe(),r.next(void 0)),b?n=a.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):n=a.info.position$.subscribe(r),t.add(n)}));let{playing$:c,paused$:l}=a.events,d=a.events.willSeek$.pipe(me(()=>a.info.playbackState$.getValue()===fe.PLAYING)),s=a.events.seeked$.pipe(me(()=>a.info.playbackState$.getValue()===fe.PLAYING)),u=!1,h=new Q;t.add(d.subscribe(()=>{u||h.next(),u=!0})),t.add(s.subscribe(()=>u=!1));let p=new Q,v=new Q,I=z(c,s,p),T=z(l,h,o,a.events.looped$,v),S,Pe=()=>S=r.getValue(),Ee=()=>{let b=r.getValue();be(S)||S===b||be(b)||(i.next({from:S,to:b}),S=void 0)},_e=()=>{v.next(),p.next()};if(t.add(I.subscribe(Pe)),t.add(T.subscribe(Ee)),e.forceInterval&&isFinite(e.forceInterval)){let b=0;t.add(I.subscribe(()=>b=window.setTimeout(_e,e.forceInterval))),t.add(T.subscribe(()=>window.clearTimeout(b)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let a=new J;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");var l,d,s;this.statContext=e,this.config=re((l=i.config)!=null?l:{}),E(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((d=i.isid)!=null?d:ge());let r=new x({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new A({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(s=this.statContext.mobile)!=null?s:!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,host:c}=Ke();this.isEmbed=n,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=m():(E(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=E(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let n,c,l=!1;t(e.events.firstBytes$,s=>{n=m(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>c=m()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&E(n)&&(this.logPlayerReady({duration:m()-n}),l=!0)}),t(e.events.firstFrame$,()=>{E(n)&&!l&&(this.logPlayerReady({duration:m()-n}),l=!0),E(c)&&this.logFirstFrame({time:m()-c})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let d;return t(e.info.hostname$,s=>{let u=d!==void 0&&d!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),d=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let h=u.find(({id:v})=>v===s),p=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:p})}),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}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var n;let r=o?"pip":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var n;let r=o?"fullscreen":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}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}`})}logWatchCoverageLive(e){var r,n;let i=(n=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?n:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}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(Me(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=Se(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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={}){var p,v;let r=(v=(p=this.timeSynchronisation)==null?void 0:p.now())!=null?v:m(),n=this.vsid$.getValue();Fe(n);let c=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,d=this.statContext.firstConnectionReused,s,u;if(this.isEmbed){s=this.embedParent;let I=[...new URLSearchParams(location.search).entries()].filter(([T,S])=>this.config.embedUrlParams.includes(T));u=new URLSearchParams(I).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),u=location.href.substring(0,1024));let h={vsid:n,isid:c,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:d===!0?1:d===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:u,rate:this.statContext.rate===1||ye(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 I of this.config.disabledCustomFields)delete h[I];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:h}}};export{_ as ApiEnv,F as ConnectionType,B as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,M as SeekAction,w as VERSION};
package/esnext.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- "use strict";var M=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(r,e)=>{for(var i in e)M(r,i,{get:e[i],enumerable:!0})},be=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fe(e))!ge.call(r,o)&&o!==i&&M(r,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return r};var ve=r=>be(M({},"__esModule",{value:!0}),r);var Pe={};me(Pe,{ApiEnv:()=>P,ConnectionType:()=>w,ContentType:()=>T,InteractiveInterfaceClick:()=>V,OneStat:()=>N,Quality:()=>C,SeekAction:()=>k,VERSION:()=>_});module.exports=ve(Pe);var P=(a=>(a.PROD="prod",a.VK_ALIAS="vk_alias",a.VIDEOTEST="videotest",a.TEST="test",a.AUTO="auto",a))(P||{}),C=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(C||{}),T=(h=>(h.MP4="mp4",h.DASH="dash",h.DASH_SEP="dash_sep",h.ONDEMAND_DASH="ondemand_dash",h.HLS="hls",h.ONDEMAND_HLS="ondemand_hls",h.WEBM="webm",h.AV1="av1",h.ONDEMAND_DASH_LIVE="ondemand_dash_live",h.ONDEMAND_HLS_LIVE="ondemand_hls_live",h.WEBRTC="webrtc",h.UNKNOWN="unknown",h.RTMP="rtmp",h))(T||{});var w=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(w||{});var k=(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))(k||{}),V=(a=>(a.GRAPH_SHOW="iGraphShow",a.GRAPH_HIDE="iGraphHide",a.NEXT_AREA="iNextChapterArea",a.NEXT_BUTTON="iNextChapterBtn",a.WATCH_AGAIN="iWatchAgainBtn",a))(V||{}),Y={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"},X={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"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=r=>(0,ee.fillWithDefault)(r,Ie);function U(){let r="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]=r[o===19?t&3|8:t]);return e.join("")}var n=require("@vkontakte/videoplayer-shared"),D=require("@vkontakte/videoplayer-shared");var ie=r=>{let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([o,a])=>{let u=X[o]??o,c=a;return a&&(o==="mode"?c=Z[a]??a:o==="quality"&&(c=J[a]??a)),[u,c]}));return{...r,operation:Y[e]??e,custom:t}};var _="1.0.51-dev.9505da81.0",oe="CIOPGQJGDIHBABABA",W={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var v=require("@vkontakte/videoplayer-shared");var A=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new v.ValueSubject(!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)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let a=async(u,c=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(g){if(!g||!("error_code"in g)){this.params.error$.next({id:"logRequestUnknown",category:v.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:g});return}let p=g?.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),c>0?a(u,c-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),c>0?a(u,c-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:v.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:g});return}}}};return a(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",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${_}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,v.getExponentialDelay)(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:v.ErrorCategory.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.uuid,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:v.ErrorCategory.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:v.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:v.ErrorCategory.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}};var I=require("@vkontakte/videoplayer-shared");var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=W[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:I.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),W.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}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:I.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,I.now)(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:I.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:I.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:i,sessionKey:t,time:(0,I.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(u=>{let c=Number(u.headers.get("content-length"))===0,g=new Date(u.headers.get("date")??"").getTime(),p=(0,I.now)()-o;if(isFinite(g)&&this.timeSynchronisation?.addServerTime(g,p),!c)return u.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,a)},a)}_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}};var b=require("@vkontakte/videoplayer-shared"),L="onestat_events",H=r=>e=>e.timestamp+r>=(0,b.now)(),$=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=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=b.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,b.debounceFn)(()=>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:b.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=b.safeStorage.get(L);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(H(this.params.config.storageExpiration));b.safeStorage.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],b.safeStorage.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}b.safeStorage.set(L,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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()}};var d=require("@vkontakte/videoplayer-core"),K=require("@vkontakte/videoplayer-shared");var se=r=>r&&{[d.VideoQuality.INVARIANT]:"unknown",[d.VideoQuality.Q_144P]:"mobile",[d.VideoQuality.Q_240P]:"lowest",[d.VideoQuality.Q_360P]:"low",[d.VideoQuality.Q_480P]:"medium",[d.VideoQuality.Q_720P]:"high",[d.VideoQuality.Q_1080P]:"fullhd",[d.VideoQuality.Q_1440P]:"quadhd",[d.VideoQuality.Q_2160P]:"ultrahd",[d.VideoQuality.Q_4320P]:"unknown"}[r],q=r=>r&&{[d.HttpConnectionType.HTTP1]:"http1",[d.HttpConnectionType.HTTP2]:"http2",[d.HttpConnectionType.QUIC]:"http3"}[r],re=r=>{if(r!==void 0)switch(r){case d.VideoFormat.MPEG:return"mp4";case d.VideoFormat.DASH_LIVE:return"dash";case d.VideoFormat.DASH_SEP:return"dash_sep";case d.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case d.VideoFormat.DASH_WEBM:case d.VideoFormat.DASH_LIVE_WEBM:return"webm";case d.VideoFormat.DASH_WEBM_AV1:return"av1";case d.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case d.VideoFormat.HLS:case d.VideoFormat.HLS_LIVE:return"hls";case d.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case d.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case d.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,K.assertNever)(r)}},R=r=>{if(r!==void 0)switch(r){case d.Surface.NONE:case d.Surface.INLINE:return;case d.Surface.FULLSCREEN:return"fullscreen";case d.Surface.SECOND_SCREEN:return"chromecast";case d.Surface.PIP:return"pip";case d.Surface.INVISIBLE:return"invisible";default:return(0,K.assertNever)(r)}},ne=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=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 ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var z=require("@vkontakte/videoplayer-core"),l=require("@vkontakte/videoplayer-shared"),ue=(r,e)=>new l.Observable(i=>{let t=new l.Subscription,o=(0,l.merge)((0,l.fromEvent)(window,"beforeunload"),r.events.willDestruct$),a=new l.ValueSubject(void 0),u;t.add(r.info.isLive$.pipe((0,l.filterChanged)()).subscribe(S=>{u&&(u.unsubscribe(),a.next(void 0)),S?u=r.info.liveTime$.pipe((0,l.map)(F=>F&&F/1e3)).subscribe(a):u=r.info.position$.subscribe(a),t.add(u)}));let{playing$:c,paused$:g}=r.events,p=r.events.willSeek$.pipe((0,l.filter)(()=>r.info.playbackState$.getValue()===z.PlaybackState.PLAYING)),s=r.events.seeked$.pipe((0,l.filter)(()=>r.info.playbackState$.getValue()===z.PlaybackState.PLAYING)),f=!1,m=new l.Subject;t.add(p.subscribe(()=>{f||m.next(),f=!0})),t.add(s.subscribe(()=>f=!1));let h=new l.Subject,y=new l.Subject,B=(0,l.merge)(c,s,h),G=(0,l.merge)(g,m,o,r.events.looped$,y),E,ce=()=>E=a.getValue(),le=()=>{let S=a.getValue();(0,l.isNullable)(E)||E===S||(0,l.isNullable)(S)||(i.next({from:E,to:S}),E=void 0)},pe=()=>{y.next(),h.next()};if(t.add(B.subscribe(ce)),t.add(G.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let S=0;t.add(B.subscribe(()=>S=window.setTimeout(pe,e.forceInterval))),t.add(G.subscribe(()=>window.clearTimeout(S)))}return t});var ye="_one-stat_",Q=`${ye}uuid`,j=()=>{let r=new n.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},N=class{constructor(e,i){this.subscription=new n.Subscription;this.debugLogger=new D.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new n.ValueSubject(void 0);this.isid$=new n.ValueSubject(void 0);this.seekAction$=new n.ValueSubject("unknown");this.statContext=e,this.config=te(i.config??{}),(0,n.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new n.Subject;this.experimental={error$:t};let o=n.safeStorage.get(Q);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),n.safeStorage.set(Q,this.uuid)):this.uuid=o:(this.uuid=U(),n.safeStorage.set(Q,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??de());let a=new x({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new A({config:this.config,apiTransport:a,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:u,host:c}=(0,D.detectEmbed)();this.isEmbed=u,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new n.Subscription,t=(s,f)=>i.add(s.subscribe(f));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let f=e.info.isLive$.getValue(),m={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};f?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;t(e.info.isStalled$,s=>{s?o=(0,n.now)():((0,n.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,n.now)()-o}),o=void 0)});let a=!1;i.add(e.events.fatalError$.pipe((0,n.once)()).subscribe(()=>a=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let f=(0,n.isNonNullable)(o)?(0,n.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:f??0}),o=void 0}else a||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let u,c,g=!1;t(e.events.firstBytes$,s=>{u=(0,n.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>c=(0,n.now)()),t(e.info.currentBuffer$,s=>{!g&&s&&s.end-s.start>0&&(0,n.isNonNullable)(u)&&(this.logPlayerReady({duration:(0,n.now)()-u}),g=!0)}),t(e.events.firstFrame$,()=>{(0,n.isNonNullable)(u)&&!g&&(this.logPlayerReady({duration:(0,n.now)()-u}),g=!0),(0,n.isNonNullable)(c)&&this.logFirstFrame({time:(0,n.now)()-c})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,n.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:f})=>this.updateContext({audible:!s&&f>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let p;return t(e.info.hostname$,s=>{let f=p!==void 0&&p!==s;this.updateContext({cdnHostname:s,failover:f}),f&&this.logFailover(s),p=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{(0,n.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t((0,n.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:f})=>{let m=f.find(({id:y})=>y===s),h=m&&(m.isAuto?`${m.language}_auto`:m.language);this.updateContext({subtitles:h})}),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}=j();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let a=o?"pip":R(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.inFullscreen$,o=>{let a=o?"fullscreen":R(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=j();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=j();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}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}`})}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((0,n.merge)((0,n.fromEvent)(e,"change"),(0,n.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(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=(0,n.fromEvent)(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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 a=this.timeSynchronisation?.now()??(0,n.now)(),u=this.vsid$.getValue();(0,n.assertNonNullable)(u);let c=this.isid$.getValue(),g=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,s,f;if(this.isEmbed){s=this.embedParent;let h=[...new URLSearchParams(location.search).entries()].filter(([y,B])=>this.config.embedUrlParams.includes(y));f=new URLSearchParams(h).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),f=location.href.substring(0,1024));let m={vsid:u,isid:c,vid:this.statContext.movieId,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:g,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:f,rate:this.statContext.rate===1||(0,n.isNullable)(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 h of this.config.disabledCustomFields)delete m[h];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:a,custom:m}}};
6
+ "use strict";var M=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var me=(r,e)=>{for(var i in e)M(r,i,{get:e[i],enumerable:!0})},be=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ge(e))!fe.call(r,o)&&o!==i&&M(r,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return r};var ve=r=>be(M({},"__esModule",{value:!0}),r);var Pe={};me(Pe,{ApiEnv:()=>P,ConnectionType:()=>w,ContentType:()=>T,InteractiveInterfaceClick:()=>V,OneStat:()=>N,Quality:()=>C,SeekAction:()=>k,VERSION:()=>_});module.exports=ve(Pe);var P=(a=>(a.PROD="prod",a.VK_ALIAS="vk_alias",a.VIDEOTEST="videotest",a.TEST="test",a.AUTO="auto",a))(P||{}),C=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(C||{}),T=(h=>(h.MP4="mp4",h.DASH="dash",h.DASH_SEP="dash_sep",h.ONDEMAND_DASH="ondemand_dash",h.HLS="hls",h.ONDEMAND_HLS="ondemand_hls",h.WEBM="webm",h.AV1="av1",h.ONDEMAND_DASH_LIVE="ondemand_dash_live",h.ONDEMAND_HLS_LIVE="ondemand_hls_live",h.WEBRTC="webrtc",h.UNKNOWN="unknown",h.RTMP="rtmp",h))(T||{});var w=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(w||{});var k=(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))(k||{}),V=(a=>(a.GRAPH_SHOW="iGraphShow",a.GRAPH_HIDE="iGraphHide",a.NEXT_AREA="iNextChapterArea",a.NEXT_BUTTON="iNextChapterBtn",a.WATCH_AGAIN="iWatchAgainBtn",a))(V||{}),Y={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"},X={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"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=r=>(0,ee.fillWithDefault)(r,Ie);function U(){let r="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]=r[o===19?t&3|8:t]);return e.join("")}var n=require("@vkontakte/videoplayer-shared"),D=require("@vkontakte/videoplayer-shared");var ie=r=>{let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([o,a])=>{let u=X[o]??o,c=a;return a&&(o==="mode"?c=Z[a]??a:o==="quality"&&(c=J[a]??a)),[u,c]}));return{...r,operation:Y[e]??e,custom:t}};var _="1.0.51-dev.bbd1265d.0",oe="CIOPGQJGDIHBABABA",W={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var v=require("@vkontakte/videoplayer-shared");var A=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new v.ValueSubject(!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)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let a=async(u,c=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(f){if(!f||!("error_code"in f)){this.params.error$.next({id:"logRequestUnknown",category:v.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:f});return}let p=f?.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),c>0?a(u,c-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),c>0?a(u,c-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:v.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:f});return}}}};return a(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",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${_}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,v.getExponentialDelay)(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:v.ErrorCategory.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.uuid,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:v.ErrorCategory.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:v.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:v.ErrorCategory.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}};var I=require("@vkontakte/videoplayer-shared");var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=W[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:I.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),W.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}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:I.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,I.now)(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:I.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:I.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:i,sessionKey:t,time:(0,I.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(u=>{let c=Number(u.headers.get("content-length"))===0,f=new Date(u.headers.get("date")??"").getTime(),p=(0,I.now)()-o;if(isFinite(f)&&this.timeSynchronisation?.addServerTime(f,p),!c)return u.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,a)},a)}_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}};var b=require("@vkontakte/videoplayer-shared"),L="onestat_events",H=r=>e=>e.timestamp+r>=(0,b.now)(),$=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=(0,b.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=b.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,b.debounceFn)(()=>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:b.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=b.safeStorage.get(L);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(H(this.params.config.storageExpiration));b.safeStorage.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],b.safeStorage.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}b.safeStorage.set(L,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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()}};var d=require("@vkontakte/videoplayer-core"),K=require("@vkontakte/videoplayer-shared");var se=r=>r&&{[d.VideoQuality.INVARIANT]:"unknown",[d.VideoQuality.Q_144P]:"mobile",[d.VideoQuality.Q_240P]:"lowest",[d.VideoQuality.Q_360P]:"low",[d.VideoQuality.Q_480P]:"medium",[d.VideoQuality.Q_720P]:"high",[d.VideoQuality.Q_1080P]:"fullhd",[d.VideoQuality.Q_1440P]:"quadhd",[d.VideoQuality.Q_2160P]:"ultrahd",[d.VideoQuality.Q_4320P]:"unknown"}[r],q=r=>r&&{[d.HttpConnectionType.HTTP1]:"http1",[d.HttpConnectionType.HTTP2]:"http2",[d.HttpConnectionType.QUIC]:"http3"}[r],re=r=>{if(r!==void 0)switch(r){case d.VideoFormat.MPEG:return"mp4";case d.VideoFormat.DASH_LIVE:return"dash";case d.VideoFormat.DASH_SEP:return"dash_sep";case d.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case d.VideoFormat.DASH_WEBM:case d.VideoFormat.DASH_LIVE_WEBM:return"webm";case d.VideoFormat.DASH_WEBM_AV1:return"av1";case d.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case d.VideoFormat.HLS:case d.VideoFormat.HLS_LIVE:return"hls";case d.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case d.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case d.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,K.assertNever)(r)}},R=r=>{if(r!==void 0)switch(r){case d.Surface.NONE:case d.Surface.INLINE:return;case d.Surface.FULLSCREEN:return"fullscreen";case d.Surface.SECOND_SCREEN:return"chromecast";case d.Surface.PIP:return"pip";case d.Surface.INVISIBLE:return"invisible";default:return(0,K.assertNever)(r)}},ne=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=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 ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var z=require("@vkontakte/videoplayer-core"),l=require("@vkontakte/videoplayer-shared"),ue=(r,e)=>new l.Observable(i=>{let t=new l.Subscription,o=(0,l.merge)((0,l.fromEvent)(window,"beforeunload"),r.events.willDestruct$),a=new l.ValueSubject(void 0),u;t.add(r.info.isLive$.pipe((0,l.filterChanged)()).subscribe(S=>{u&&(u.unsubscribe(),a.next(void 0)),S?u=r.info.liveTime$.pipe((0,l.map)(F=>F&&F/1e3)).subscribe(a):u=r.info.position$.subscribe(a),t.add(u)}));let{playing$:c,paused$:f}=r.events,p=r.events.willSeek$.pipe((0,l.filter)(()=>r.info.playbackState$.getValue()===z.PlaybackState.PLAYING)),s=r.events.seeked$.pipe((0,l.filter)(()=>r.info.playbackState$.getValue()===z.PlaybackState.PLAYING)),g=!1,m=new l.Subject;t.add(p.subscribe(()=>{g||m.next(),g=!0})),t.add(s.subscribe(()=>g=!1));let h=new l.Subject,y=new l.Subject,B=(0,l.merge)(c,s,h),G=(0,l.merge)(f,m,o,r.events.looped$,y),E,ce=()=>E=a.getValue(),le=()=>{let S=a.getValue();(0,l.isNullable)(E)||E===S||(0,l.isNullable)(S)||(i.next({from:E,to:S}),E=void 0)},pe=()=>{y.next(),h.next()};if(t.add(B.subscribe(ce)),t.add(G.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let S=0;t.add(B.subscribe(()=>S=window.setTimeout(pe,e.forceInterval))),t.add(G.subscribe(()=>window.clearTimeout(S)))}return t});var ye="_one-stat_",Q=`${ye}uuid`,j=()=>{let r=new n.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},N=class{constructor(e,i){this.subscription=new n.Subscription;this.debugLogger=new D.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new n.ValueSubject(void 0);this.isid$=new n.ValueSubject(void 0);this.seekAction$=new n.ValueSubject("unknown");this.statContext=e,this.config=te(i.config??{}),(0,n.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new n.Subject;this.experimental={error$:t};let o=n.safeStorage.get(Q);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),n.safeStorage.set(Q,this.uuid)):this.uuid=o:(this.uuid=U(),n.safeStorage.set(Q,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??de());let a=new x({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new A({config:this.config,apiTransport:a,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:u,host:c}=(0,D.detectEmbed)();this.isEmbed=u,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new n.Subscription,t=(s,g)=>i.add(s.subscribe(g));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let g=e.info.isLive$.getValue(),m={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};g?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;t(e.info.isStalled$,s=>{s?o=(0,n.now)():((0,n.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,n.now)()-o}),o=void 0)});let a=!1;i.add(e.events.fatalError$.pipe((0,n.once)()).subscribe(()=>a=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let g=(0,n.isNonNullable)(o)?(0,n.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:g??0}),o=void 0}else a||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let u,c,f=!1;t(e.events.firstBytes$,s=>{u=(0,n.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>c=(0,n.now)()),t(e.info.currentBuffer$,s=>{!f&&s&&s.end-s.start>0&&(0,n.isNonNullable)(u)&&(this.logPlayerReady({duration:(0,n.now)()-u}),f=!0)}),t(e.events.firstFrame$,()=>{(0,n.isNonNullable)(u)&&!f&&(this.logPlayerReady({duration:(0,n.now)()-u}),f=!0),(0,n.isNonNullable)(c)&&this.logFirstFrame({time:(0,n.now)()-c})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,n.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:g})=>this.updateContext({audible:!s&&g>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let p;return t(e.info.hostname$,s=>{let g=p!==void 0&&p!==s;this.updateContext({cdnHostname:s,failover:g}),g&&this.logFailover(s),p=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{(0,n.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t((0,n.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:g})=>{let m=g.find(({id:y})=>y===s),h=m&&(m.isAuto?`${m.language}_auto`:m.language);this.updateContext({subtitles:h})}),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}=j();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let a=o?"pip":R(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.inFullscreen$,o=>{let a=o?"fullscreen":R(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=j();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=j();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}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}`})}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}`})}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((0,n.merge)((0,n.fromEvent)(e,"change"),(0,n.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(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=(0,n.fromEvent)(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}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 a=this.timeSynchronisation?.now()??(0,n.now)(),u=this.vsid$.getValue();(0,n.assertNonNullable)(u);let c=this.isid$.getValue(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,s,g;if(this.isEmbed){s=this.embedParent;let h=[...new URLSearchParams(location.search).entries()].filter(([y,B])=>this.config.embedUrlParams.includes(y));g=new URLSearchParams(h).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let m={vsid:u,isid:c,vid:this.statContext.movieId,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:f,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:g,rate:this.statContext.rate===1||(0,n.isNullable)(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 h of this.config.disabledCustomFields)delete m[h];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:a,custom:m}}};
package/esnext.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),N=(u=>(u.Q144P="mobile",u.Q240P="lowest",u.Q360P="low",u.Q480P="medium",u.Q720P="high",u.Q1080P="fullhd",u.Q1440P="quadhd",u.Q2160P="ultrahd",u.UNKNOWN="unknown",u))(N||{}),D=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(D||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={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"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ae}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>Ae(n,xe);function M(){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 Fe,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Me,now as m,observableFrom as Ve,once as Ue,safeStorage as Q,Subject as We,Subscription as X,ValueSubject as j}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let a=ie[o]??o,d=r;return r&&(o==="mode"?d=se[r]??r:o==="quality"&&(d=oe[r]??r)),[a,d]}));return{...n,operation:te[e]??e,custom:t}};var C="1.0.51-dev.9505da81.0",ae="CIOPGQJGDIHBABABA",V={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!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)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(a,d=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let u=p?.error_code;switch(u){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${u}`,category:I.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${C}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(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:I.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.uuid,client_version:C.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:I.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:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.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 T,now as U}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=V[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:T.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),V.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:T.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=U(),r=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:T.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:T.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:U()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{let d=Number(a.headers.get("content-length"))===0,p=new Date(a.headers.get("date")??"").getTime(),u=U()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,u),!d)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as x,debounceFn as de}from"@vkontakte/videoplayer-shared";var w="onestat_events",W=n=>e=>e.timestamp+n>=ke(),k=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=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=x.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>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:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=x.get(w);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(W(this.params.config.storageExpiration));x.set(w,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(W(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],x.set(w,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(W(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`})}x.set(w,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 H,Surface as S,VideoFormat as f,VideoQuality as g}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[g.INVARIANT]:"unknown",[g.Q_144P]:"mobile",[g.Q_240P]:"lowest",[g.Q_360P]:"low",[g.Q_480P]:"medium",[g.Q_720P]:"high",[g.Q_1080P]:"fullhd",[g.Q_1440P]:"quadhd",[g.Q_2160P]:"ultrahd",[g.Q_4320P]:"unknown"}[n],K=n=>n&&{[H.HTTP1]:"http1",[H.HTTP2]:"http2",[H.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case f.MPEG:return"mp4";case f.DASH_LIVE:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},L=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var $=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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as q,Observable as Ne,Subject as z,Subscription as De,ValueSubject as Be}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=q(Re(window,"beforeunload"),n.events.willDestruct$),r=new Be(void 0),a;t.add(n.info.isLive$.pipe($e()).subscribe(b=>{a&&(a.unsubscribe(),r.next(void 0)),b?a=n.info.liveTime$.pipe(Oe(O=>O&&O/1e3)).subscribe(r):a=n.info.position$.subscribe(r),t.add(a)}));let{playing$:d,paused$:p}=n.events,u=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),s=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),l=!1,h=new z;t.add(u.subscribe(()=>{l||h.next(),l=!0})),t.add(s.subscribe(()=>l=!1));let c=new z,v=new z,R=q(d,s,c),Z=q(p,h,o,n.events.looped$,v),P,Pe=()=>P=r.getValue(),Ee=()=>{let b=r.getValue();be(P)||P===b||be(b)||(i.next({from:P,to:b}),P=void 0)},_e=()=>{v.next(),c.next()};if(t.add(R.subscribe(Pe)),t.add(Z.subscribe(Ee)),e.forceInterval&&isFinite(e.forceInterval)){let b=0;t.add(R.subscribe(()=>b=window.setTimeout(_e,e.forceInterval))),t.add(Z.subscribe(()=>window.clearTimeout(b)))}return t});var qe="_one-stat_",G=`${qe}uuid`,Y=()=>{let n=new X;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},J=class{constructor(e,i){this.subscription=new X;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new j(void 0);this.isid$=new j(void 0);this.seekAction$=new j("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new $);let t=new We;this.experimental={error$:t};let o=Q.get(G);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),Q.set(G,this.uuid)):this.uuid=o:(this.uuid=M(),Q.set(G,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??fe());let r=new A({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new k({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:d}=Ke();this.isEmbed=a,this.embedParent=d,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new X,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=m():(y(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=y(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:l??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,d,p=!1;t(e.events.firstBytes$,s=>{a=m(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>d=m()),t(e.info.currentBuffer$,s=>{!p&&s&&s.end-s.start>0&&y(a)&&(this.logPlayerReady({duration:m()-a}),p=!0)}),t(e.events.firstFrame$,()=>{y(a)&&!p&&(this.logPlayerReady({duration:m()-a}),p=!0),y(d)&&this.logFirstFrame({time:m()-d})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let u;return t(e.info.hostname$,s=>{let l=u!==void 0&&u!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),u=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:K(s)}),this.updateContext({connectionType:K(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:L(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let h=l.find(({id:v})=>v===s),c=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:c})}),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}=Y();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=Y();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=Y();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}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}`})}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(Me(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(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=Se(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??m(),a=this.vsid$.getValue();Fe(a);let d=this.isid$.getValue(),p=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,s,l;if(this.isEmbed){s=this.embedParent;let c=[...new URLSearchParams(location.search).entries()].filter(([v,R])=>this.config.embedUrlParams.includes(v));l=new URLSearchParams(c).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),l=location.href.substring(0,1024));let h={vsid:a,isid:d,vid:this.statContext.movieId,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:p,connection_reused:u===!0?1:u===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:l,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let c of this.config.disabledCustomFields)delete h[c];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:h}}};export{E as ApiEnv,B as ConnectionType,D as ContentType,ee as InteractiveInterfaceClick,J as OneStat,N as Quality,F as SeekAction,C as VERSION};
6
+ var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),N=(u=>(u.Q144P="mobile",u.Q240P="lowest",u.Q360P="low",u.Q480P="medium",u.Q720P="high",u.Q1080P="fullhd",u.Q1440P="quadhd",u.Q2160P="ultrahd",u.UNKNOWN="unknown",u))(N||{}),D=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(D||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={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"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ae}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>Ae(n,xe);function M(){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 Fe,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Me,now as m,observableFrom as Ve,once as Ue,safeStorage as Q,Subject as We,Subscription as X,ValueSubject as j}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let a=ie[o]??o,d=r;return r&&(o==="mode"?d=se[r]??r:o==="quality"&&(d=oe[r]??r)),[a,d]}));return{...n,operation:te[e]??e,custom:t}};var C="1.0.51-dev.bbd1265d.0",ae="CIOPGQJGDIHBABABA",V={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!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)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(a,d=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let u=p?.error_code;switch(u){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${u}`,category:I.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${C}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(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:I.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.uuid,client_version:C.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:I.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:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.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 T,now as U}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=V[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:T.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),V.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:T.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=U(),r=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:T.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:T.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:U()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{let d=Number(a.headers.get("content-length"))===0,p=new Date(a.headers.get("date")??"").getTime(),u=U()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,u),!d)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as x,debounceFn as de}from"@vkontakte/videoplayer-shared";var w="onestat_events",W=n=>e=>e.timestamp+n>=ke(),k=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=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=x.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>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:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=x.get(w);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(W(this.params.config.storageExpiration));x.set(w,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(W(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],x.set(w,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(W(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`})}x.set(w,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 H,Surface as S,VideoFormat as g,VideoQuality as f}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[f.INVARIANT]:"unknown",[f.Q_144P]:"mobile",[f.Q_240P]:"lowest",[f.Q_360P]:"low",[f.Q_480P]:"medium",[f.Q_720P]:"high",[f.Q_1080P]:"fullhd",[f.Q_1440P]:"quadhd",[f.Q_2160P]:"ultrahd",[f.Q_4320P]:"unknown"}[n],K=n=>n&&{[H.HTTP1]:"http1",[H.HTTP2]:"http2",[H.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case g.MPEG:return"mp4";case g.DASH_LIVE:return"dash";case g.DASH_SEP:return"dash_sep";case g.DASH_ONDEMAND:return"ondemand_dash";case g.DASH_WEBM:case g.DASH_LIVE_WEBM:return"webm";case g.DASH_WEBM_AV1:return"av1";case g.DASH_LIVE_CMAF:return"ondemand_dash_live";case g.HLS:case g.HLS_LIVE:return"hls";case g.HLS_ONDEMAND:return"ondemand_hls";case g.HLS_LIVE_CMAF:return"ondemand_hls_live";case g.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},L=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var $=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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),ge=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as fe}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as q,Observable as Ne,Subject as z,Subscription as De,ValueSubject as Be}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=q(Re(window,"beforeunload"),n.events.willDestruct$),r=new Be(void 0),a;t.add(n.info.isLive$.pipe($e()).subscribe(b=>{a&&(a.unsubscribe(),r.next(void 0)),b?a=n.info.liveTime$.pipe(Oe(O=>O&&O/1e3)).subscribe(r):a=n.info.position$.subscribe(r),t.add(a)}));let{playing$:d,paused$:p}=n.events,u=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===fe.PLAYING)),s=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===fe.PLAYING)),l=!1,h=new z;t.add(u.subscribe(()=>{l||h.next(),l=!0})),t.add(s.subscribe(()=>l=!1));let c=new z,v=new z,R=q(d,s,c),Z=q(p,h,o,n.events.looped$,v),P,Pe=()=>P=r.getValue(),Ee=()=>{let b=r.getValue();be(P)||P===b||be(b)||(i.next({from:P,to:b}),P=void 0)},_e=()=>{v.next(),c.next()};if(t.add(R.subscribe(Pe)),t.add(Z.subscribe(Ee)),e.forceInterval&&isFinite(e.forceInterval)){let b=0;t.add(R.subscribe(()=>b=window.setTimeout(_e,e.forceInterval))),t.add(Z.subscribe(()=>window.clearTimeout(b)))}return t});var qe="_one-stat_",G=`${qe}uuid`,Y=()=>{let n=new X;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},J=class{constructor(e,i){this.subscription=new X;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new j(void 0);this.isid$=new j(void 0);this.seekAction$=new j("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new $);let t=new We;this.experimental={error$:t};let o=Q.get(G);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),Q.set(G,this.uuid)):this.uuid=o:(this.uuid=M(),Q.set(G,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??ge());let r=new A({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new k({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:d}=Ke();this.isEmbed=a,this.embedParent=d,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new X,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=m():(y(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=y(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:l??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,d,p=!1;t(e.events.firstBytes$,s=>{a=m(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>d=m()),t(e.info.currentBuffer$,s=>{!p&&s&&s.end-s.start>0&&y(a)&&(this.logPlayerReady({duration:m()-a}),p=!0)}),t(e.events.firstFrame$,()=>{y(a)&&!p&&(this.logPlayerReady({duration:m()-a}),p=!0),y(d)&&this.logFirstFrame({time:m()-d})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let u;return t(e.info.hostname$,s=>{let l=u!==void 0&&u!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),u=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:K(s)}),this.updateContext({connectionType:K(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:L(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let h=l.find(({id:v})=>v===s),c=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:c})}),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}=Y();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=Y();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=Y();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}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}`})}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}`})}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(Me(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(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=Se(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??m(),a=this.vsid$.getValue();Fe(a);let d=this.isid$.getValue(),p=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,s,l;if(this.isEmbed){s=this.embedParent;let c=[...new URLSearchParams(location.search).entries()].filter(([v,R])=>this.config.embedUrlParams.includes(v));l=new URLSearchParams(c).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),l=location.href.substring(0,1024));let h={vsid:a,isid:d,vid:this.statContext.movieId,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:p,connection_reused:u===!0?1:u===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:l,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let c of this.config.disabledCustomFields)delete h[c];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:h}}};export{E as ApiEnv,B as ConnectionType,D as ContentType,ee as InteractiveInterfaceClick,J as OneStat,N as Quality,F as SeekAction,C as VERSION};
package/evergreen.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.51-dev.9505da81.0
3
- * Tue, 09 Jul 2024 13:42:45 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.51-dev.bbd1265d.0
3
+ * Mon, 15 Jul 2024 10:34:33 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-51/doc/
5
5
  */
6
- var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),N=(u=>(u.Q144P="mobile",u.Q240P="lowest",u.Q360P="low",u.Q480P="medium",u.Q720P="high",u.Q1080P="fullhd",u.Q1440P="quadhd",u.Q2160P="ultrahd",u.UNKNOWN="unknown",u))(N||{}),D=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(D||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={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"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ae}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>Ae(n,xe);function M(){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 Fe,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Me,now as m,observableFrom as Ve,once as Ue,safeStorage as Q,Subject as We,Subscription as X,ValueSubject as j}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let a=ie[o]??o,d=r;return r&&(o==="mode"?d=se[r]??r:o==="quality"&&(d=oe[r]??r)),[a,d]}));return{...n,operation:te[e]??e,custom:t}};var C="1.0.51-dev.9505da81.0",ae="CIOPGQJGDIHBABABA",V={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!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)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(a,d=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let u=p?.error_code;switch(u){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${u}`,category:I.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${C}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(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:I.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.uuid,client_version:C.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:I.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:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.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 T,now as U}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=V[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:T.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),V.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:T.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=U(),r=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:T.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:T.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:U()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{let d=Number(a.headers.get("content-length"))===0,p=new Date(a.headers.get("date")??"").getTime(),u=U()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,u),!d)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as x,debounceFn as de}from"@vkontakte/videoplayer-shared";var w="onestat_events",W=n=>e=>e.timestamp+n>=ke(),k=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=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=x.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>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:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=x.get(w);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(W(this.params.config.storageExpiration));x.set(w,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(W(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],x.set(w,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(W(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`})}x.set(w,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 H,Surface as S,VideoFormat as f,VideoQuality as g}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[g.INVARIANT]:"unknown",[g.Q_144P]:"mobile",[g.Q_240P]:"lowest",[g.Q_360P]:"low",[g.Q_480P]:"medium",[g.Q_720P]:"high",[g.Q_1080P]:"fullhd",[g.Q_1440P]:"quadhd",[g.Q_2160P]:"ultrahd",[g.Q_4320P]:"unknown"}[n],K=n=>n&&{[H.HTTP1]:"http1",[H.HTTP2]:"http2",[H.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case f.MPEG:return"mp4";case f.DASH_LIVE:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},L=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var $=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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as q,Observable as Ne,Subject as z,Subscription as De,ValueSubject as Be}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=q(Re(window,"beforeunload"),n.events.willDestruct$),r=new Be(void 0),a;t.add(n.info.isLive$.pipe($e()).subscribe(b=>{a&&(a.unsubscribe(),r.next(void 0)),b?a=n.info.liveTime$.pipe(Oe(O=>O&&O/1e3)).subscribe(r):a=n.info.position$.subscribe(r),t.add(a)}));let{playing$:d,paused$:p}=n.events,u=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),s=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),l=!1,h=new z;t.add(u.subscribe(()=>{l||h.next(),l=!0})),t.add(s.subscribe(()=>l=!1));let c=new z,v=new z,R=q(d,s,c),Z=q(p,h,o,n.events.looped$,v),P,Pe=()=>P=r.getValue(),Ee=()=>{let b=r.getValue();be(P)||P===b||be(b)||(i.next({from:P,to:b}),P=void 0)},_e=()=>{v.next(),c.next()};if(t.add(R.subscribe(Pe)),t.add(Z.subscribe(Ee)),e.forceInterval&&isFinite(e.forceInterval)){let b=0;t.add(R.subscribe(()=>b=window.setTimeout(_e,e.forceInterval))),t.add(Z.subscribe(()=>window.clearTimeout(b)))}return t});var qe="_one-stat_",G=`${qe}uuid`,Y=()=>{let n=new X;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},J=class{constructor(e,i){this.subscription=new X;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new j(void 0);this.isid$=new j(void 0);this.seekAction$=new j("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new $);let t=new We;this.experimental={error$:t};let o=Q.get(G);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),Q.set(G,this.uuid)):this.uuid=o:(this.uuid=M(),Q.set(G,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??fe());let r=new A({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new k({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:d}=Ke();this.isEmbed=a,this.embedParent=d,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new X,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=m():(y(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=y(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:l??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,d,p=!1;t(e.events.firstBytes$,s=>{a=m(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>d=m()),t(e.info.currentBuffer$,s=>{!p&&s&&s.end-s.start>0&&y(a)&&(this.logPlayerReady({duration:m()-a}),p=!0)}),t(e.events.firstFrame$,()=>{y(a)&&!p&&(this.logPlayerReady({duration:m()-a}),p=!0),y(d)&&this.logFirstFrame({time:m()-d})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let u;return t(e.info.hostname$,s=>{let l=u!==void 0&&u!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),u=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:K(s)}),this.updateContext({connectionType:K(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:L(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let h=l.find(({id:v})=>v===s),c=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:c})}),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}=Y();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=Y();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=Y();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}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}`})}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(Me(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(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=Se(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??m(),a=this.vsid$.getValue();Fe(a);let d=this.isid$.getValue(),p=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,s,l;if(this.isEmbed){s=this.embedParent;let c=[...new URLSearchParams(location.search).entries()].filter(([v,R])=>this.config.embedUrlParams.includes(v));l=new URLSearchParams(c).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),l=location.href.substring(0,1024));let h={vsid:a,isid:d,vid:this.statContext.movieId,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:p,connection_reused:u===!0?1:u===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:l,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let c of this.config.disabledCustomFields)delete h[c];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:h}}};export{E as ApiEnv,B as ConnectionType,D as ContentType,ee as InteractiveInterfaceClick,J as OneStat,N as Quality,F as SeekAction,C as VERSION};
6
+ var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),N=(u=>(u.Q144P="mobile",u.Q240P="lowest",u.Q360P="low",u.Q480P="medium",u.Q720P="high",u.Q1080P="fullhd",u.Q1440P="quadhd",u.Q2160P="ultrahd",u.UNKNOWN="unknown",u))(N||{}),D=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(D||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(d=>(d.SLIDER="slider",d.DOUBLE_TAP="double_tap",d.TIME_CODE="time_code",d.EPISODE="episode",d.REWIND="rewind",d.LIVE="live",d.UNKNOWN="unknown",d))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={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"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ae}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>Ae(n,xe);function M(){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 Fe,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Me,now as m,observableFrom as Ve,once as Ue,safeStorage as Q,Subject as We,Subscription as X,ValueSubject as j}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let a=ie[o]??o,d=r;return r&&(o==="mode"?d=se[r]??r:o==="quality"&&(d=oe[r]??r)),[a,d]}));return{...n,operation:te[e]??e,custom:t}};var C="1.0.51-dev.bbd1265d.0",ae="CIOPGQJGDIHBABABA",V={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!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)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(a,d=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let u=p?.error_code;switch(u){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?r(a,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${u}`,category:I.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return r(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${C}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(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:I.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.uuid,client_version:C.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:I.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:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.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 T,now as U}from"@vkontakte/videoplayer-shared";var A=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=V[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:T.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),V.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:T.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=U(),r=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:T.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:T.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:U()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{let d=Number(a.headers.get("content-length"))===0,p=new Date(a.headers.get("date")??"").getTime(),u=U()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,u),!d)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as x,debounceFn as de}from"@vkontakte/videoplayer-shared";var w="onestat_events",W=n=>e=>e.timestamp+n>=ke(),k=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=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=x.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>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:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=x.get(w);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(W(this.params.config.storageExpiration));x.set(w,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(W(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],x.set(w,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(W(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`})}x.set(w,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(e=!1){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),this.api.logRequest(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 H,Surface as S,VideoFormat as g,VideoQuality as f}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[f.INVARIANT]:"unknown",[f.Q_144P]:"mobile",[f.Q_240P]:"lowest",[f.Q_360P]:"low",[f.Q_480P]:"medium",[f.Q_720P]:"high",[f.Q_1080P]:"fullhd",[f.Q_1440P]:"quadhd",[f.Q_2160P]:"ultrahd",[f.Q_4320P]:"unknown"}[n],K=n=>n&&{[H.HTTP1]:"http1",[H.HTTP2]:"http2",[H.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case g.MPEG:return"mp4";case g.DASH_LIVE:return"dash";case g.DASH_SEP:return"dash_sep";case g.DASH_ONDEMAND:return"ondemand_dash";case g.DASH_WEBM:case g.DASH_LIVE_WEBM:return"webm";case g.DASH_WEBM_AV1:return"av1";case g.DASH_LIVE_CMAF:return"ondemand_dash_live";case g.HLS:case g.HLS_LIVE:return"hls";case g.HLS_ONDEMAND:return"ondemand_hls";case g.HLS_LIVE_CMAF:return"ondemand_hls_live";case g.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},L=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var $=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 he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),ge=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as fe}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as q,Observable as Ne,Subject as z,Subscription as De,ValueSubject as Be}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=q(Re(window,"beforeunload"),n.events.willDestruct$),r=new Be(void 0),a;t.add(n.info.isLive$.pipe($e()).subscribe(b=>{a&&(a.unsubscribe(),r.next(void 0)),b?a=n.info.liveTime$.pipe(Oe(O=>O&&O/1e3)).subscribe(r):a=n.info.position$.subscribe(r),t.add(a)}));let{playing$:d,paused$:p}=n.events,u=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===fe.PLAYING)),s=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===fe.PLAYING)),l=!1,h=new z;t.add(u.subscribe(()=>{l||h.next(),l=!0})),t.add(s.subscribe(()=>l=!1));let c=new z,v=new z,R=q(d,s,c),Z=q(p,h,o,n.events.looped$,v),P,Pe=()=>P=r.getValue(),Ee=()=>{let b=r.getValue();be(P)||P===b||be(b)||(i.next({from:P,to:b}),P=void 0)},_e=()=>{v.next(),c.next()};if(t.add(R.subscribe(Pe)),t.add(Z.subscribe(Ee)),e.forceInterval&&isFinite(e.forceInterval)){let b=0;t.add(R.subscribe(()=>b=window.setTimeout(_e,e.forceInterval))),t.add(Z.subscribe(()=>window.clearTimeout(b)))}return t});var qe="_one-stat_",G=`${qe}uuid`,Y=()=>{let n=new X;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},J=class{constructor(e,i){this.subscription=new X;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new j(void 0);this.isid$=new j(void 0);this.seekAction$=new j("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new $);let t=new We;this.experimental={error$:t};let o=Q.get(G);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),Q.set(G,this.uuid)):this.uuid=o:(this.uuid=M(),Q.set(G,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??ge());let r=new A({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new k({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:d}=Ke();this.isEmbed=a,this.embedParent=d,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new X,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),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(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),h={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(h):this.logWatchCoverageRecord(h)});let o;t(e.info.isStalled$,s=>{s?o=m():(y(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=y(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:l??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,d,p=!1;t(e.events.firstBytes$,s=>{a=m(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>d=m()),t(e.info.currentBuffer$,s=>{!p&&s&&s.end-s.start>0&&y(a)&&(this.logPlayerReady({duration:m()-a}),p=!0)}),t(e.events.firstFrame$,()=>{y(a)&&!p&&(this.logPlayerReady({duration:m()-a}),p=!0),y(d)&&this.logFirstFrame({time:m()-d})}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let u;return t(e.info.hostname$,s=>{let l=u!==void 0&&u!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),u=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:K(s)}),this.updateContext({connectionType:K(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:L(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let h=l.find(({id:v})=>v===s),c=h&&(h.isAuto?`${h.language}_auto`:h.language);this.updateContext({subtitles:c})}),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}=Y();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":L(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=Y();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()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=Y();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}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}`})}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}`})}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(Me(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(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=Se(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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"})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??m(),a=this.vsid$.getValue();Fe(a);let d=this.isid$.getValue(),p=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,s,l;if(this.isEmbed){s=this.embedParent;let c=[...new URLSearchParams(location.search).entries()].filter(([v,R])=>this.config.embedUrlParams.includes(v));l=new URLSearchParams(c).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(s=new URL(this.statContext.refDomain||document.referrer).hostname),l=location.href.substring(0,1024));let h={vsid:a,isid:d,vid:this.statContext.movieId,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:p,connection_reused:u===!0?1:u===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:s,direct_url:l,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let c of this.config.disabledCustomFields)delete h[c];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:h}}};export{E as ApiEnv,B as ConnectionType,D as ContentType,ee as InteractiveInterfaceClick,J as OneStat,N as Quality,F as SeekAction,C as VERSION};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-statistics",
3
- "version": "1.0.51-dev.9505da81.0",
3
+ "version": "1.0.51-dev.bbd1265d.0",
4
4
  "author": "vk.com",
5
5
  "description": "Statistics library for vk.com videoplayer",
6
6
  "homepage": "https://vk.com",
@@ -49,9 +49,9 @@
49
49
  "**/*.d.ts"
50
50
  ],
51
51
  "dependencies": {
52
- "@vkontakte/videoplayer-shared": "1.0.37-dev.d644b4e8.0"
52
+ "@vkontakte/videoplayer-shared": "1.0.37-dev.d458b64b.0"
53
53
  },
54
54
  "peerDependencies": {
55
- "@vkontakte/videoplayer-core": "2.0.105-dev.9e273154.0"
55
+ "@vkontakte/videoplayer-core": "2.0.105-dev.15db9323.0"
56
56
  }
57
57
  }
@@ -289,6 +289,7 @@ export declare class OneStat implements IOneStat {
289
289
  logReady(payload: IReadyPayload): void;
290
290
  logStarted(...args: Parameters<typeof this.logActionPlay>): void;
291
291
  logPlay(): void;
292
+ logPlaying(): void;
292
293
  logPause(payload: IPausePayload): void;
293
294
  logSeek(payload: ISeekPayload): void;
294
295
  logFirstBytes(payload: IFirstBytesPayload): void;
package/types/values.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ILogCustomData } from './types';
2
2
  export type Operation = 'action_play' | 'action_play_interactive' | 'first_bytes' | 'player_ready' | 'first_frame' | 'seek' | 'watch_coverage_record' | 'watch_coverage_live' | 'empty_buffer' | 'action_stop' | 'close_at_empty_buffer' | 'content_error' | 'player_interface_click' | 'next_movie' | 'track_switch' | // Пока не поддержана
3
- 'failover' | 'play_toggle' | 'pause' | 'adv';
3
+ 'failover' | 'play_toggle' | 'pause' | 'adv' | 'playing';
4
4
  export declare enum ApiEnv {
5
5
  PROD = "prod",
6
6
  VK_ALIAS = "vk_alias",