@vkontakte/videoplayer-interactive 1.0.6-dev.5a11a96.0 → 1.0.6-dev.9aa76b8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/evergreen.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.6-dev.5a11a96.0
3
- * Tue, 12 Dec 2023 11:20:59 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.6-dev.9aa76b8.0
3
+ * Tue, 12 Dec 2023 10:50:05 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-6/doc/
5
5
  */
6
- import{loadVKLangPack as tt,Subscription as ce,ValueSubject as it,Observable as ye,getCurrentBrowser as nt,CurrentClientBrowser as st,once as rt}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as he}from"uuid";import{Player as at}from"@vkontakte/videoplayer-core/esnext.esm.js";const ot="1.0.6-dev.5a11a96.0";function ke(i,e=1){let t="0",n="0",s="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+s},${e})`}const O="SDK_NAME",ct="SDK_NAME-controls-container",Fe=()=>document.querySelector(`.${ct}`),V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ge={top:"flex-start",bottom:"flex-end",center:"center"},ve={start:"flex-start",end:"flex-end",center:"center"},be={start:"left",end:"right",center:"center"},Be=({target:i,props:e})=>{i.style.alignItems=ge[e?.text?.gravityVertical]??ge.center,i.style.justifyContent=ve[e?.text?.gravityHorizontal]??ve.center,i.style.textAlign=be[e?.text?.alignment]??be.start},Pe=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},$e=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=ke(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},De=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${ke(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},le=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class de{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${O}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",r=>{r.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${O}-control-container-${this.control.id}`)}}const He=i=>{if(i.type.trim().toLowerCase()==="area")return new ht(i)};class ht extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");return r.classList.add(`${O}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",$e({target:r,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),De({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),le({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${O}-${this.control.id}`)}}const Ue=i=>{if(i.type.trim().toLowerCase()==="button")return new lt(i)};class lt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");r.type="button",r.classList.add(`${O}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),$e({target:r,props:this.control.props,fallback:V}),De({target:r,props:this.control.props,fallback:V,dependsOn:n}),Be({target:r,props:this.control.props}),Pe({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${O}-${this.control.id}`)}}const dt=i=>{if(i.type.trim().toLowerCase()==="text")return new ut(i)};class ut extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${O}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),Be({target:r,props:this.control.props}),Pe({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${O}-${this.control.id}`)}}class ft{constructor(e){this.layout=e}}const pt=i=>{if(i.type.trim().toLowerCase()==="relative")return new ze(i)};class ze extends ft{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Ge{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...e,s(t)]:[...e]},[])}}const We=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new mt(i,e)};class mt extends Ge{constructor(e,t){super(e),this.rootElement=t??Fe(),this.layout=new ze(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",Ue),this.addControlFactory("text",dt),this.addControlFactory("area",He)}createView(e){const t=document.createElement("div");return t.classList.add(`${O}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const s=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(s,e)}),this.rootElement.append(t),t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${O}-${this.container.id}`)}}function Qe(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const W={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ue=i=>z(i,W.Object),re=i=>z(i,W.String),U=i=>z(i,W.Array),qe=i=>z(i,W.Number),yt=i=>z(i,W.Function),Ce=i=>qe(i)&&!isNaN(i),gt=i=>i==null,G=i=>ue(i)&&Object.keys(i).length===0,Xe=i=>U(i)&&!i.length,X=(i,e)=>re(i)&&(e?i.trim():i).length,Ze=window.navigator.userAgent.toLowerCase(),vt=/mobi/i.test(Ze);Ze.indexOf("android")>-1;const bt="video_interactive",Ct="videoint",Et=250;class wt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=t,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=St(e),this.resizeObserver=new ResizeObserver(Qe(this.onResize,Et)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!qe(e.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await tt(this.lang,bt,Ct)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function St(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const It=(i={})=>Array.from(new Set(i.sessions?.map(e=>e.visitedChapters.map(t=>t.chapterId)??[]).flat())),Ee=(i=[],e="")=>i.reduce((t,n)=>(t.find(s=>s[e]===n[e])||t.push(n),t),[]),we="chapterId";class ${constructor(e){this.id=e?.id??he(),this.startDate=e?.startDate?new Date(e.startDate).toISOString():new Date(Date.now()).toISOString(),this.updateOn=e?.updateOn?new Date(e.updateOn).toISOString():null,this.visitedChapters=e?.visitedChapters?Ee(Array.from(e.visitedChapters),we):[],this.branches=U(e?.branches)?e.branches:[]}update(e){e?.startDate&&(this.startDate=new Date(e.startDate).toISOString()),e?.updateOn&&(this.updateOn=new Date(e.updateOn).toISOString()),U(e?.visitedChapters)&&(this.visitedChapters=Ee([...this.visitedChapters,...e.visitedChapters],we)),U(e?.branches)&&(this.branches=this.branches.concat(e.branches))}getSession(){return{...this}}static createVisitedChapter(e){return[{chapterId:e}]}static createBranch(e,t,n){return[{chapterId:e,branchId:t,autoSelect:n}]}}class Z{constructor(e){this.id=e?.id??he(),this.manifestId=e?.manifestId,this.manifestVersion=e?.manifestVersion,this.manifestBuild=e?.manifestBuild,this.sessions=U(e?.sessions)?e?.sessions.map(t=>new $(t)):[],this.isCompleted=e?.isCompleted??!1}update(e){this.id=e?.id??this.id,this.manifestId=e?.manifestId??this.manifestId,this.manifestVersion=e?.manifestVersion??this.manifestVersion,this.manifestBuild=e?.manifestBuild??this.manifestBuild,this.isCompleted=e?.isCompleted??this.isCompleted}addSession(e){this.sessions.push(new $(e))}updateSession(e,t){let n;gt(e)?n=this.sessions[this.sessions.length-1]:n=this.sessions.find(s=>s.id===e),n&&n.update(t)}resetSession(){this.sessions=[]}getHistory(){return{...this,sessions:this.sessions.map(e=>e.getSession())}}}const ae="SDK_NAME-history-changed";class Tt extends EventTarget{constructor(){super(),this.history=new Z,this.sendEvent()}onChapterChange({chapterId:e,mediaId:t,autoSelect:n=!1,isLastChapter:s=!1}){this.history.isCompleted?this.history=new Z({manifestId:this.history.manifestId,manifestVersion:this.history.manifestVersion,manifestBuild:this.history.manifestBuild}):s&&this.history.update({isCompleted:!0}),this.history.sessions.length?this.history.updateSession(null,{updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,n)}):this.history.addSession({updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,!1)}),this.sendEvent()}onManifestChange(e,t){t?this.history=new Z(t):this.history=new Z({manifestId:e.id,manifestVersion:e.version,manifestBuild:e.build}),this.history.addSession({updateOn:Date.now()}),this.sendEvent()}getHistory(){if(history)return this.history.getHistory()}sendEvent(){this.dispatchEvent(new CustomEvent(ae,{bubbles:!1,detail:this.getHistory()}))}destroy(){this.history=void 0}}function xt(i,e){if(!e||!i||!e.sessions.length)return;const t=e.sessions.reverse().find(n=>n.branches.length);return t.branches[t.branches.length-1].chapterId??void 0}const ee=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Rt="3.1",Se={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},At={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},jt=i=>{const e=[];for(const t of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let g=[At];switch(a){case"await":l?g=[]:r=[];break;case"default":{const p={type:"onSuspense",action:{type:Se.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?g=[p]:r=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:Se[a],args:{}}};l?g=[p]:r=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:he(),events:g})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=Rt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Nt="3.2",Lt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Nt},media:e}}return i},Ot="3.3",Vt=(i=[])=>({edit:{chapters:i},view:{}}),Ie={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Mt=i=>{const e=[],t=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:g,type:p,...w})=>({...w,type:g??p})),events:l.events?.length?l.events:[Ie]}));e.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Ie]}),t.push({id:s,x:r,y:o})}return{...i,chapters:e,graph:Vt(t),metadata:{...i.metadata,version:Ot}}},_t=[{version:"3.0",migrate:jt},{version:"3.1",migrate:Lt},{version:"3.2",migrate:Mt}],kt=i=>_t.reduce((e,t)=>ee(e.metadata.version,t.version)?e:t.migrate(e),i),Ft=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var B;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(B||(B={}));const Te={metadata:"Object",chapters:"Array"},Bt="3.0.0",Pt="3.3.0",Ke=i=>{const e=ee(i,Bt);return e===-1?!1:e===0?!0:ee(i,Pt)!==1},$t=i=>{if(!ue(i))return!1;for(const e in Te)if(!i[e]||!z(i[e],Te[e]))return!1;return Ke(i.metadata.version)},Dt=i=>i.type===Ft.Text;class R{constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class Ye{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let s=n.length;s>0;s--)if(n[s]===t){n.splice(s,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(s=>{s(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Ht{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{yt(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Ut{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return zt(...this.loaders[e])(t)}}function zt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function te(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function oe({actions:i,errors:e,chapterId:t,...n}){if(t){const s=i.getManifest(),r=i.getChapter(s.chapters,t);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:e,result:{chapter:r,media:o,graph:a}}:{...n,errors:te(e,oe.name,"Could not find media"),actions:i}}}return{...n,errors:te(e,oe.name,"Could not find chapter"),actions:i}}const Gt=async i=>{try{let e,t;if(ue(i))e=i;else if(re(i)){t=new URL(i).href;const s=await fetch(t);if(!s.ok)return{};e=await s.json()}else return{};if(!$t(e))return{};const n=e.metadata.media;if(re(n)&&!e.media)try{let s;t?s=new URL(n,t).href:(s=new URL(n).href,t=s);const r=await fetch(s);if(!r.ok)throw new Error;e.metadata.media=await r.json()}catch{return Xt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Wt(i){const{manifest:e,manifestURL:t}=await Gt(i),n=kt(e);return n.media=Qt(n.media,t),delete n.metadata.media,n}function ne(i,e){return i.find(t=>t.id===e)}function xe(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Re(i,e){return i.videos.find(t=>t.id===e)}function Qt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=qt(n.url,e);return{...n,url:s||n.url}})}))}}function qt(i,e){try{return new URL(i,e).href}catch{return""}}function Xt(i){return ee(i,"3.2.0")>=0}class Zt extends Ut{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:te},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await Wt(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",oe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:xe,getChapter:ne,getMedia:Re,getByBranches:this.getByBranches.bind(this),addErrorMessage:te},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=ne(this.manifest.chapters,e);if(t){const n=Re(this.manifest.media,t.videoId),s=xe(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:s}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=ne(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const s=this.getByChapterId(n.chapterId);return s&&t.push(s),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const m={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Ae={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},x={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function Kt(){const i=new Map;function e({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function t(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)t(s[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function je(i,e=[]){let t={},n;const s=!e.length;for(const r of i.variants)switch(!n&&"cover"in r&&(n=r.cover),r.type){case"mp4":(s||e.includes("mp4"))&&(t={...t,MPEG:{"Invariant quality":r.url}});break;case"hls":(s||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:r.url}});break;case"dash":(s||e.includes("dash"))&&(t={...t,DASH:{type:"url",url:r.url}});break}return{sources:t,thumbUrl:n,title:i.id}}const K=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Yt=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},J={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},Jt=2;function ei(i){const e=Kt();let t,n;const s=new Ye;let r={},o=!1,a=null,c=!1,l;i&&g(i);function g(d){a=d}function p(d,y,f){if(!a)throw Error("need to set interactive controller");const b=(e.map.get(d)??{})[y];if(b){r={chapterId:f,listId:d,itemId:y,...b};const v=r.player;n=v.info.currentQuality$.subscribe(E=>{if(!(!E||!v.info.position$.getValue())){t=E;for(const N of e.map)Object.values(N[1]).forEach(({player:L})=>{v.info.isAutoQualityEnabled$.getValue()||K(L,E)})}}),b.container.remove(),o=!1,a.setPlayer(b.player),c||(a.init(),c=!0),s.emit(J.activePlayerChanged,{player:r.player,config:r.config});return}throw Error("Can't set. Not find.")}async function w(d,y,f){if(!a)throw Error("need to set interactive controller");if(G(r)||d!==r.itemId)return;if(f>=0&&!o){const b=a.getChapterBranches();o=!0;const v=new Set;for(const E of b)v.has(E.media.id)||(await A({media:E.media,chapterId:E.chapter.id,setAsActive:!1,title:E.chapter.label}),v.add(E.media.id))}}async function C({chapter:{id:d},media:y}){if(G(r))return;n?.unsubscribe();const f=r.player.info.muted$.getValue(),I=r.player.info.currentQuality$.getValue(),b=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),E=r.player.info.currentPlaybackRate$.getValue(),N=!b;let L=!1;for(const j of e.map)if(j[0]===y.id){const Q=Object.keys(j[1]);for(const k of Q)k===r.itemId?(Q.length<Jt||(L=!0),e.removePlayer(j[0],k)):(L=!0,p(j[0],k,d),N?K(r.player,I):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(f),r.player.setPlaybackRate(E))}else e.removePlayer(j[0]);L||(await A({media:y,chapterId:d,setAsActive:!0,playbackRate:E}),N?K(r.player,I):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(f))}async function A({media:d,chapterId:y,prefetch:f=!0,setAsActive:I=!0,autoplay:b=!1,preferredExt:v,title:E,playbackRate:N}){const L=Math.random().toString(),j=document.createElement("div");l.append(j);const Q=r?.player?.info.isAutoQualityEnabled$.getValue();let k;if(a?.options?.vkVideoLoader){const q=Yt(d);q.length&&(k=await a.options.vkVideoLoader(...q))}const pe={container:j,...k?.videos?.[0]||{sources:je(d,v).sources},title:E},F=new at;F.initVideo(pe);const et=j.lastChild,me=new ce;me.add(F.info.position$.subscribe(function(q){w(L,F.info.duration$.getValue(),q)})).add(F.events.canplay$.subscribe(function(){Q||K(F,t),N&&F.setPlaybackRate(N)})),et&&(j.style.display="none",j.classList.add(y));const P=e.createPlayer({listId:d.id,itemId:L,player:F,container:j,sources:je(d,v).sources,config:pe,subscription:me});return I&&p(d.id,P.itemId,y),b&&P.player.play(),f&&!b&&P.player.prepare(),s.emit(J.playerCreated,P.player),{player:P.player,config:P.config}}function _(){h(),a=null}function h(){a?.off(m.chapterChanged,C),e.removeAll(),r={},c=!1,o=!1}async function u({source:d,initialChapter:y,container:f}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=f;const{media:I,chapter:b}=await a.setChapter({chapterId:y});if(I){a.on(m.chapterChanged,C);const{player:v,config:E}=await A({media:I,chapterId:b.id,title:b.label});return s.emit(J.initiated,{container:f,media:I,chapterId:b.id}),{player:v,config:E}}else console.error("not found")}return{...e,on:s.on.bind(s),off:s.off.bind(s),init:u,setInteractiveController:g,createPlayer:A,removeAll:_,getActivePlayer:function(){return r}}}const ti=3e3,ii=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=ti)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const g of i){const p=g.startTime-o;if(p<=l&&(l<=g.endTime||g.endTime===null)){c=!0;break}l<p&&(a=a===-1?p:Math.min(a,p))}return!c&&a!==-1?a:null}}},D=ii(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),fe=i=>U(i)&&!Xe(i),Je=i=>Xe(i.branches)||i.order==="end",ni=(i,e)=>{const t=i*1e3;return fe(e.controls)&&t<(e.startTime??0)},Ne=(i,e)=>{const t=i*1e3;return fe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ie=i=>i.some(e=>e.action.type==="expect"),Le=i=>i.find(e=>e.action.type==="expect"),si=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),ri=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!Dt(r));if(fe(s)){const r=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:r});else{const a=[];let c=-1/0,l=1/0,g=[];const p=[];for(let w=0;w<e.length;w++){const C=e[w];if(p.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=r[0]&&C.range[1]>=r[1])return e[w].subjects.push(o),e;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(w),g=g.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(w),g=g.concat(C.subjects),r[1]=C.range[1])}if(p.push(o),r[0]<=l&&r[1]>=c)return[{subjects:p,range:r}];a.length&&a.reverse().forEach(w=>{e.splice(w,1)}),e.push({subjects:g.concat([o]),range:r})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),ai=(i,e)=>ie(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ie(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class oi{constructor({player:e,container:t,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a}){this.container=t,this.branches=n,this.selectBranches=s,this.subscription=new ce,this.player=e,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.globalEventEmitter=o,this.gameState=T.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo))}hide=()=>{setTimeout(()=>{this.gameState!==T.end&&(ie(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!0,isFirst:!1});else{const t=si({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})},onEvent:(n,s)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!this.isSelectedControlEvent&&(this.isSelectedContainerEvent||(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime)))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ie(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState))return;const t=this.player.info.position$.getValue();if(ni(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(Ne(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const r=this.gameState;this.gameState=T.afterInteractive,r===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=Ne(t,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(m.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function ci(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function s({timestamp:a,priority:c,initiator:l}){if(Ce(a)){const g=i[a]??null;if(g&&X(c,!0)){let p={};const w=g[c];return w&&(p={...p,...w}),p=G(p)?null:p,p&&X(l,!0)?p[l]??null:p}return g}return null}function r({timestamp:a,priority:c,initiator:l}){if(Ce(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!G(i[a][c]))return!0}else return!1;if(delete i[a][c],!G(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...g}){i[a]?.[c]?.[l]?i[a][c][l].push({...g}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...g}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...g}]}}:i[a]={[c]:{[l]:[{...g}]}}}return{map:i,remove:r,add:o,removeAll:e,get:s,getLte:t,getGte:n}}const hi=[S.expect,S.setNextBranch],li=1/0;function Oe(i){let e=i,t;const n=di(),s=new ci;let r;const o=()=>{p(),_()},a=h=>{s.add.call(void 0,h),w()},c=(h=[])=>{for(const u of h)if(u.action(),hi.includes(u.actionType))break},l=h=>{if(!n.isReady(h))return;const u=Y(s.get({timestamp:h,priority:"control"})??{}),d=Y(s.get({timestamp:h,priority:"container"})??{}),y=Y(s.get({timestamp:h,priority:"chapter"})??{});c([...u,...d,...y])},g=()=>{c([...Y(s.get({timestamp:1/0,priority:"chapter"})??{})])},p=()=>{t&&(r?.unsubscribe(),t=void 0)},w=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),r=e.events.ended$.subscribe(t))},C=h=>{p(),e=h},A=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},_=()=>{n.release(),s.removeAll()};return{setPlayer:C,add:a,remove:A,exec:l,execEndOfVideo:g,listen:w,unlisten:p,release:o,containersEventsCallState:n}}function di(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??li,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function Y(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}const ui=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=e.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},fi=250;function pi(i){let e=()=>{};const t=new ResizeObserver(a=>{r(a),e=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:g,videoContentHeight:p}=ui(c,l);c.style.setProperty("--interactive-content-width",`${g}px`),c.style.setProperty("--interactive-content-height",`${p}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Qe(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},fi);function o(){e=void 0,t.disconnect(),s()}return{resizeObserver:t,calc:()=>{e()},release:o}}class mi{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const yi=i=>Math.floor(Math.random()*i),gi=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},vi=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},bi=i=>{const e=i.length,t=yi(e);return i[t]},Ve=1,Ci=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ve;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ve,e>=t)return i[n];return i[i.length-1]},Me=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),se=(i,e=!1)=>({...i,args:e?{...i.args,...Me}:{...Me,...i.args}}),_e=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:h,controlType:u,controlId:d,containerId:y,branches:f=[],onEvent:I,isEOV:b=()=>!1})=>{const v=se(h,b()),E={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},N=i.emit.bind(i,m.interactives,{subjectId:d,subjectType:u,subjectName:"control",type:x.actionChoice,actionType:h.type,payload:{containerId:y,...v.args}});switch(v.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const L=f.find(j=>j.id===v.args.branchId);if(!L)return;I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:L.chapterId,autoSelect:!1}}):(t.add({...E,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:L.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:u,action:h}):t.add({...E,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:h})});return}case S.openURI.trim().toLowerCase():{I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?_({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:h.args.uri}}):(t.add({...E,action:_.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:u,endTime:d},branches:y=[],isEOV:f=!1,autoSelected:I=!1})=>{const b=se(h,f),v={timestamp:!b.args.shouldOpenNow||f?1/0:d,priority:"container",initiator:u,actionType:b.type},E=i.emit.bind(i,m.interactives,{subjectId:u,subjectName:"container",type:x.actionChoice,actionType:b.type,payload:b.args});switch(b.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const N=y.find(L=>L.id===b.args.branchId);if(!N)return;E(),t.add({...v,action:A.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{chapterId:N.chapterId,autoSelect:I}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{E(),t.add({...v,action:C.bind(null,{subjectId:u,subjectName:"container",action:b})});return}case S.openURI.trim().toLowerCase():{E(),t.add({...v,action:_.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:u,isEOV:d=!1}){const y=Le(h.events);if(y){const f=se(y.action,d);i.emit(m.interactives,{subjectId:h.id,subjectName:"container",type:x.actionChoice,actionType:f.type,payload:f.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:S.expect,action:p.bind(null,{subjectId:h.id,subjectName:"container"})}),s.isExpect=!0}else for(const f of h.events)a({action:f.action,container:h,branches:u,isEOV:d})}const l=({chapterId:h,action:u,branches:d=[]})=>{const y=i.emit.bind(i,m.interactives,{subjectId:h,subjectName:"chapter",type:x.actionChoice,actionType:u.type,payload:u.args});switch(u.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const f=d.find(I=>I.id===u.args.branchId);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const f=bi(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const f=Ci(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const f=vi(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const f=gi(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return y(),C.bind(null,{subjectId:h,subjectName:"chapter",action:u});case S.openURI.trim().toLowerCase():return y(),_.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{URI:u.args.uri}});default:console.error("Unexpected chapter event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function g(h){const u=Le(h.events);if(u){if(Je(h))return;i.emit(m.interactives,{subjectId:h.id,subjectName:"chapter",type:x.actionChoice,actionType:u.action.type,payload:u.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:S.expect,action:p.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const y=l({chapterId:h.id,action:d.action,branches:h.branches});y&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:y})})}const p=({subjectId:h,subjectName:u,action:d})=>{e.pause(),i.emit(m.interactives,{subjectId:h,subjectName:u,type:x.actionExecution,actionType:d?.type??S.expect})},w=({subjectId:h,subjectName:u})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(m.interactives,{subjectId:h,subjectName:u,type:x.actionExecution,actionType:"after-expect"})},C=({subjectId:h,subjectName:u,subjectType:d,action:y})=>{i.emit(m.interactives,{subjectId:h,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type})},A=({subjectId:h,subjectName:u,subjectType:d,action:y,payload:f})=>{f.behaviour="change-chapter",i.emit(m.interactives,{subjectId:h,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type,payload:f})},_=({subjectId:h,subjectName:u,subjectType:d,action:y,payload:f})=>{if(!f.URI)return;const I=window.open(f.URI,"_blank","noopener,noreferrer");I&&(I.opener=null),i.emit(m.interactives,{subjectId:h,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:p,expectEventHandler:w,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:r,state:s}};class H{constructor(e,t,n,s){this.target=e,this.type=t,this.listener=n,this.options=H.#a(e,s),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),s=Object.keys(t).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),H.#h(e)?t:t.capture||!1}}static#s=void 0;static#h(e){let t=H.#s;if(t===void 0){t=!1;try{const n={},s={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};e.addEventListener("test",r,n),e.removeEventListener("test",r,n)}catch{t=!1}H.#s=t}return t||!1}}class Ei{constructor(){this.bindingMap=new mi}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,s){if(!this.bindingMap)return;const r=new H(e,t,n,s);this.bindingMap.push(t,r)}listenOnce(e,t,n,s){const r=o=>{this.unlisten(e,t,r),n(o)};this.listen(e,t,r,s)}unlisten(e,t,n){if(!this.bindingMap)return;const s=this.bindingMap.get(t)||[];for(const r of s)r.target===e&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(t,r))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class wi{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let s=3;s<n;s+=40)if(t[s]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let s;t&&(s=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&s&&this.restore(s),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class Si{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
6
+ import{loadVKLangPack as tt,Subscription as ce,ValueSubject as it,Observable as ye,getCurrentBrowser as nt,CurrentClientBrowser as st,once as rt}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as he}from"uuid";import{Player as at}from"@vkontakte/videoplayer-core/esnext.esm.js";const ot="1.0.6-dev.9aa76b8.0";function ke(i,e=1){let t="0",n="0",s="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+s},${e})`}const O="SDK_NAME",ct="SDK_NAME-controls-container",Fe=()=>document.querySelector(`.${ct}`),V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ge={top:"flex-start",bottom:"flex-end",center:"center"},ve={start:"flex-start",end:"flex-end",center:"center"},be={start:"left",end:"right",center:"center"},Be=({target:i,props:e})=>{i.style.alignItems=ge[e?.text?.gravityVertical]??ge.center,i.style.justifyContent=ve[e?.text?.gravityHorizontal]??ve.center,i.style.textAlign=be[e?.text?.alignment]??be.start},Pe=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},$e=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=ke(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},De=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${ke(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},le=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class de{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${O}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",r=>{r.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${O}-control-container-${this.control.id}`)}}const He=i=>{if(i.type.trim().toLowerCase()==="area")return new ht(i)};class ht extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");return r.classList.add(`${O}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",$e({target:r,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),De({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),le({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${O}-${this.control.id}`)}}const Ue=i=>{if(i.type.trim().toLowerCase()==="button")return new lt(i)};class lt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");r.type="button",r.classList.add(`${O}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),$e({target:r,props:this.control.props,fallback:V}),De({target:r,props:this.control.props,fallback:V,dependsOn:n}),Be({target:r,props:this.control.props}),Pe({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${O}-${this.control.id}`)}}const dt=i=>{if(i.type.trim().toLowerCase()==="text")return new ut(i)};class ut extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${O}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),Be({target:r,props:this.control.props}),Pe({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${O}-${this.control.id}`)}}class ft{constructor(e){this.layout=e}}const pt=i=>{if(i.type.trim().toLowerCase()==="relative")return new ze(i)};class ze extends ft{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Ge{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...e,s(t)]:[...e]},[])}}const We=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new mt(i,e)};class mt extends Ge{constructor(e,t){super(e),this.rootElement=t??Fe(),this.layout=new ze(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",Ue),this.addControlFactory("text",dt),this.addControlFactory("area",He)}createView(e){const t=document.createElement("div");return t.classList.add(`${O}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const s=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(s,e)}),this.rootElement.append(t),t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${O}-${this.container.id}`)}}function Qe(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const W={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ue=i=>z(i,W.Object),re=i=>z(i,W.String),U=i=>z(i,W.Array),qe=i=>z(i,W.Number),yt=i=>z(i,W.Function),Ce=i=>qe(i)&&!isNaN(i),gt=i=>i==null,G=i=>ue(i)&&Object.keys(i).length===0,Xe=i=>U(i)&&!i.length,X=(i,e)=>re(i)&&(e?i.trim():i).length,Ze=window.navigator.userAgent.toLowerCase(),vt=/mobi/i.test(Ze);Ze.indexOf("android")>-1;const bt="video_interactive",Ct="videoint",Et=250;class wt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=t,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=St(e),this.resizeObserver=new ResizeObserver(Qe(this.onResize,Et)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!qe(e.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await tt(this.lang,bt,Ct)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function St(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const It=(i={})=>Array.from(new Set(i.sessions?.map(e=>e.visitedChapters.map(t=>t.chapterId)??[]).flat())),Ee=(i=[],e="")=>i.reduce((t,n)=>(t.find(s=>s[e]===n[e])||t.push(n),t),[]),we="chapterId";class ${constructor(e){this.id=e?.id??he(),this.startDate=e?.startDate?new Date(e.startDate).toISOString():new Date(Date.now()).toISOString(),this.updateOn=e?.updateOn?new Date(e.updateOn).toISOString():null,this.visitedChapters=e?.visitedChapters?Ee(Array.from(e.visitedChapters),we):[],this.branches=U(e?.branches)?e.branches:[]}update(e){e?.startDate&&(this.startDate=new Date(e.startDate).toISOString()),e?.updateOn&&(this.updateOn=new Date(e.updateOn).toISOString()),U(e?.visitedChapters)&&(this.visitedChapters=Ee([...this.visitedChapters,...e.visitedChapters],we)),U(e?.branches)&&(this.branches=this.branches.concat(e.branches))}getSession(){return{...this}}static createVisitedChapter(e){return[{chapterId:e}]}static createBranch(e,t,n){return[{chapterId:e,branchId:t,autoSelect:n}]}}class Z{constructor(e){this.id=e?.id??he(),this.manifestId=e?.manifestId,this.manifestVersion=e?.manifestVersion,this.manifestBuild=e?.manifestBuild,this.sessions=U(e?.sessions)?e?.sessions.map(t=>new $(t)):[],this.isCompleted=e?.isCompleted??!1}update(e){this.id=e?.id??this.id,this.manifestId=e?.manifestId??this.manifestId,this.manifestVersion=e?.manifestVersion??this.manifestVersion,this.manifestBuild=e?.manifestBuild??this.manifestBuild,this.isCompleted=e?.isCompleted??this.isCompleted}addSession(e){this.sessions.push(new $(e))}updateSession(e,t){let n;gt(e)?n=this.sessions[this.sessions.length-1]:n=this.sessions.find(s=>s.id===e),n&&n.update(t)}resetSession(){this.sessions=[]}getHistory(){return{...this,sessions:this.sessions.map(e=>e.getSession())}}}const ae="SDK_NAME-history-changed";class Tt extends EventTarget{constructor(){super(),this.history=new Z,this.sendEvent()}onChapterChange({chapterId:e,mediaId:t,autoSelect:n=!1,isLastChapter:s=!1}){this.history.isCompleted?this.history=new Z({manifestId:this.history.manifestId,manifestVersion:this.history.manifestVersion,manifestBuild:this.history.manifestBuild}):s&&this.history.update({isCompleted:!0}),this.history.sessions.length?this.history.updateSession(null,{updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,n)}):this.history.addSession({updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,!1)}),this.sendEvent()}onManifestChange(e,t){t?this.history=new Z(t):this.history=new Z({manifestId:e.id,manifestVersion:e.version,manifestBuild:e.build}),this.history.addSession({updateOn:Date.now()}),this.sendEvent()}getHistory(){if(history)return this.history.getHistory()}sendEvent(){this.dispatchEvent(new CustomEvent(ae,{bubbles:!1,detail:this.getHistory()}))}destroy(){this.history=void 0}}function xt(i,e){if(!e||!i||!e.sessions.length)return;const t=e.sessions.reverse().find(n=>n.branches.length);return t.branches[t.branches.length-1].chapterId??void 0}const ee=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Rt="3.1",Se={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},At={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},jt=i=>{const e=[];for(const t of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let g=[At];switch(a){case"await":l?g=[]:r=[];break;case"default":{const p={type:"onSuspense",action:{type:Se.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?g=[p]:r=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:Se[a],args:{}}};l?g=[p]:r=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:he(),events:g})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=Rt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Nt="3.2",Lt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Nt},media:e}}return i},Ot="3.3",Vt=(i=[])=>({edit:{chapters:i},view:{}}),Ie={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Mt=i=>{const e=[],t=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:g,type:p,...w})=>({...w,type:g??p})),events:l.events?.length?l.events:[Ie]}));e.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Ie]}),t.push({id:s,x:r,y:o})}return{...i,chapters:e,graph:Vt(t),metadata:{...i.metadata,version:Ot}}},_t=[{version:"3.0",migrate:jt},{version:"3.1",migrate:Lt},{version:"3.2",migrate:Mt}],kt=i=>_t.reduce((e,t)=>ee(e.metadata.version,t.version)?e:t.migrate(e),i),Ft=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var B;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(B||(B={}));const Te={metadata:"Object",chapters:"Array"},Bt="3.0.0",Pt="3.3.0",Ke=i=>{const e=ee(i,Bt);return e===-1?!1:e===0?!0:ee(i,Pt)!==1},$t=i=>{if(!ue(i))return!1;for(const e in Te)if(!i[e]||!z(i[e],Te[e]))return!1;return Ke(i.metadata.version)},Dt=i=>i.type===Ft.Text;class R{constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class Ye{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let s=n.length;s>0;s--)if(n[s]===t){n.splice(s,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(s=>{s(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Ht{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{yt(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Ut{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return zt(...this.loaders[e])(t)}}function zt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function te(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function oe({actions:i,errors:e,chapterId:t,...n}){if(t){const s=i.getManifest(),r=i.getChapter(s.chapters,t);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:e,result:{chapter:r,media:o,graph:a}}:{...n,errors:te(e,oe.name,"Could not find media"),actions:i}}}return{...n,errors:te(e,oe.name,"Could not find chapter"),actions:i}}const Gt=async i=>{try{let e,t;if(ue(i))e=i;else if(re(i)){t=new URL(i).href;const s=await fetch(t);if(!s.ok)return{};e=await s.json()}else return{};if(!$t(e))return{};const n=e.metadata.media;if(re(n)&&!e.media)try{let s;t?s=new URL(n,t).href:(s=new URL(n).href,t=s);const r=await fetch(s);if(!r.ok)throw new Error;e.metadata.media=await r.json()}catch{return Xt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Wt(i){const{manifest:e,manifestURL:t}=await Gt(i),n=kt(e);return n.media=Qt(n.media,t),delete n.metadata.media,n}function ne(i,e){return i.find(t=>t.id===e)}function xe(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Re(i,e){return i.videos.find(t=>t.id===e)}function Qt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=qt(n.url,e);return{...n,url:s||n.url}})}))}}function qt(i,e){try{return new URL(i,e).href}catch{return""}}function Xt(i){return ee(i,"3.2.0")>=0}class Zt extends Ut{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:te},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await Wt(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",oe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:xe,getChapter:ne,getMedia:Re,getByBranches:this.getByBranches.bind(this),addErrorMessage:te},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=ne(this.manifest.chapters,e);if(t){const n=Re(this.manifest.media,t.videoId),s=xe(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:s}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=ne(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const s=this.getByChapterId(n.chapterId);return s&&t.push(s),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const m={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Ae={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},x={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function Kt(){const i=new Map;function e({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function t(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)t(s[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function je(i,e=[]){let t={},n;const s=!e.length;for(const r of i.variants)switch(!n&&"cover"in r&&(n=r.cover),r.type){case"mp4":(s||e.includes("mp4"))&&(t={...t,MPEG:{"Invariant quality":r.url}});break;case"hls":(s||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:r.url}});break;case"dash":(s||e.includes("dash"))&&(t={...t,DASH:{type:"url",url:r.url}});break}return{sources:t,thumbUrl:n,title:i.id}}const K=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Yt=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},J={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},Jt=2;function ei(i){const e=Kt();let t,n;const s=new Ye;let r={},o=!1,a=null,c=!1,l;i&&g(i);function g(d){a=d}function p(d,y,f){if(!a)throw Error("need to set interactive controller");const b=(e.map.get(d)??{})[y];if(b){r={chapterId:f,listId:d,itemId:y,...b};const v=r.player;n=v.info.currentQuality$.subscribe(E=>{if(!(!E||!v.info.position$.getValue())){t=E;for(const N of e.map)Object.values(N[1]).forEach(({player:L})=>{v.info.isAutoQualityEnabled$.getValue()||K(L,E)})}}),b.container.remove(),o=!1,a.setPlayer(b.player),c||(a.init(),c=!0),s.emit(J.activePlayerChanged,{player:r.player,config:r.config});return}throw Error("Can't set. Not find.")}async function w(d,y,f){if(!a)throw Error("need to set interactive controller");if(G(r)||d!==r.itemId)return;if(f>=0&&!o){const b=a.getChapterBranches();o=!0;const v=new Set;for(const E of b)v.has(E.media.id)||(await A({media:E.media,chapterId:E.chapter.id,setAsActive:!1,title:E.chapter.label}),v.add(E.media.id))}}async function C({chapter:{id:d},media:y}){if(G(r))return;n?.unsubscribe();const f=r.player.info.muted$.getValue(),I=r.player.info.currentQuality$.getValue(),b=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),E=r.player.info.currentPlaybackRate$.getValue(),N=!b;let L=!1;for(const j of e.map)if(j[0]===y.id){const Q=Object.keys(j[1]);for(const k of Q)k===r.itemId?(Q.length<Jt||(L=!0),e.removePlayer(j[0],k)):(L=!0,p(j[0],k,d),N?K(r.player,I):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(f),r.player.setPlaybackRate(E))}else e.removePlayer(j[0]);L||(await A({media:y,chapterId:d,setAsActive:!0,playbackRate:E}),N?K(r.player,I):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(f))}async function A({media:d,chapterId:y,prefetch:f=!0,setAsActive:I=!0,autoplay:b=!1,preferredExt:v,title:E,playbackRate:N}){const L=Math.random().toString(),j=document.createElement("div");l.append(j);const Q=r?.player?.info.isAutoQualityEnabled$.getValue();let k;if(a?.options?.vkVideoLoader){const q=Yt(d);q.length&&(k=await a.options.vkVideoLoader(...q))}const pe={container:j,...k?.videos?.[0]||{sources:je(d,v).sources},title:E},F=new at;F.initVideo(pe);const et=j.lastChild,me=new ce;me.add(F.info.position$.subscribe(function(q){w(L,F.info.duration$.getValue(),q)})).add(F.events.canplay$.subscribe(function(){Q||K(F,t),N&&F.setPlaybackRate(N)})),et&&(j.style.display="none",j.classList.add(y));const P=e.createPlayer({listId:d.id,itemId:L,player:F,container:j,sources:je(d,v).sources,config:pe,subscription:me});return I&&p(d.id,P.itemId,y),b&&P.player.play(),f&&!b&&P.player.prepare(),s.emit(J.playerCreated,P.player),{player:P.player,config:P.config}}function _(){h(),a=null}function h(){a?.off(m.chapterChanged,C),e.removeAll(),r={},c=!1,o=!1}async function u({source:d,initialChapter:y,container:f}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=f;const{media:I,chapter:b}=await a.setChapter({chapterId:y});if(I){a.on(m.chapterChanged,C);const{player:v,config:E}=await A({media:I,chapterId:b.id,title:b.label});return s.emit(J.initiated,{container:f,media:I,chapterId:b.id}),{player:v,config:E}}else console.error("not found")}return{...e,on:s.on.bind(s),off:s.off.bind(s),init:u,setInteractiveController:g,createPlayer:A,removeAll:_,getActivePlayer:function(){return r}}}const ti=3e3,ii=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=ti)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const g of i){const p=g.startTime-o;if(p<=l&&(l<=g.endTime||g.endTime===null)){c=!0;break}l<p&&(a=a===-1?p:Math.min(a,p))}return!c&&a!==-1?a:null}}},D=ii(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),fe=i=>U(i)&&!Xe(i),Je=i=>Xe(i.branches)||i.order==="end",ni=(i,e)=>{const t=i*1e3;return fe(e.controls)&&t<(e.startTime??0)},Ne=(i,e)=>{const t=i*1e3;return fe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ie=i=>i.some(e=>e.action.type==="expect"),Le=i=>i.find(e=>e.action.type==="expect"),si=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),ri=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!Dt(r));if(fe(s)){const r=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:r});else{const a=[];let c=-1/0,l=1/0,g=[];const p=[];for(let w=0;w<e.length;w++){const C=e[w];if(p.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=r[0]&&C.range[1]>=r[1])return e[w].subjects.push(o),e;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(w),g=g.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(w),g=g.concat(C.subjects),r[1]=C.range[1])}if(p.push(o),r[0]<=l&&r[1]>=c)return[{subjects:p,range:r}];a.length&&a.reverse().forEach(w=>{e.splice(w,1)}),e.push({subjects:g.concat([o]),range:r})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),ai=(i,e)=>ie(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ie(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class oi{constructor({player:e,container:t,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a}){this.container=t,this.branches=n,this.selectBranches=s,this.subscription=new ce,this.player=e,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.globalEventEmitter=o,this.gameState=T.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo))}hide=()=>{setTimeout(()=>{this.gameState!==T.end&&(ie(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!0,isFirst:!1});else{const t=si({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})},onEvent:(n,s)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!this.isSelectedControlEvent&&(this.isSelectedContainerEvent||(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime)))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ie(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState))return;const t=this.player.info.position$.getValue();if(ni(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(Ne(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const r=this.gameState;this.gameState=T.afterInteractive,r===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=Ne(t,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(m.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function ci(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function s({timestamp:a,priority:c,initiator:l}){if(Ce(a)){const g=i[a]??null;if(g&&X(c,!0)){let p={};const w=g[c];return w&&(p={...p,...w}),p=G(p)?null:p,p&&X(l,!0)?p[l]??null:p}return g}return null}function r({timestamp:a,priority:c,initiator:l}){if(Ce(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!G(i[a][c]))return!0}else return!1;if(delete i[a][c],!G(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...g}){i[a]?.[c]?.[l]?i[a][c][l].push({...g}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...g}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...g}]}}:i[a]={[c]:{[l]:[{...g}]}}}return{map:i,remove:r,add:o,removeAll:e,get:s,getLte:t,getGte:n}}const hi=[S.expect,S.setNextBranch],li=1/0;function Oe(i){let e=i,t;const n=di(),s=new ci;let r;const o=()=>{p(),_()},a=h=>{s.add.call(void 0,h),w()},c=(h=[])=>{for(const u of h)if(u.action(),hi.includes(u.actionType))break},l=h=>{if(!n.isReady(h))return;const u=Y(s.get({timestamp:h,priority:"control"})??{}),d=Y(s.get({timestamp:h,priority:"container"})??{}),y=Y(s.get({timestamp:h,priority:"chapter"})??{});c([...u,...d,...y])},g=()=>{c([...Y(s.get({timestamp:1/0,priority:"chapter"})??{})])},p=()=>{t&&(r?.unsubscribe(),t=void 0)},w=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),r=e.events.ended$.subscribe(t))},C=h=>{p(),e=h},A=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},_=()=>{n.release(),s.removeAll()};return{setPlayer:C,add:a,remove:A,exec:l,execEndOfVideo:g,listen:w,unlisten:p,release:o,containersEventsCallState:n}}function di(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??li,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function Y(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}const ui=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=e.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},fi=250;function pi(i){let e=()=>{};const t=new ResizeObserver(a=>{r(a),e=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:g,videoContentHeight:p}=ui(c,l);c.style.setProperty("--interactive-content-width",`${g}px`),c.style.setProperty("--interactive-content-height",`${p}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Qe(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},fi);function o(){e=void 0,t.disconnect(),s()}return{resizeObserver:t,calc:()=>{e()},release:o}}class mi{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const yi=i=>Math.floor(Math.random()*i),gi=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},vi=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},bi=i=>{const e=i.length,t=yi(e);return i[t]},Ve=1,Ci=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ve;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ve,e>=t)return i[n];return i[i.length-1]},Me=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),se=(i,e=!1)=>({...i,args:e?{...i.args,...Me}:{...Me,...i.args}}),_e=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:h,controlType:u,controlId:d,containerId:y,branches:f=[],onEvent:I,isEOV:b=()=>!1})=>{const v=se(h,b()),E={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},N=i.emit.bind(i,m.interactives,{subjectId:d,subjectType:u,subjectName:"control",type:x.actionChoice,actionType:h.type,payload:{containerId:y,...v.args}});switch(v.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const L=f.find(j=>j.id===v.args.branchId);if(!L)return;I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:L.chapterId,autoSelect:!1}}):(t.add({...E,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:L.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:u,action:h}):t.add({...E,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:h})});return}case S.openURI.trim().toLowerCase():{I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?_({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:h.args.uri}}):(t.add({...E,action:_.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:u,endTime:d},branches:y=[],isEOV:f=!1,autoSelected:I=!1})=>{const b=se(h,f),v={timestamp:!b.args.shouldOpenNow||f?1/0:d,priority:"container",initiator:u,actionType:b.type},E=i.emit.bind(i,m.interactives,{subjectId:u,subjectName:"container",type:x.actionChoice,actionType:b.type,payload:b.args});switch(b.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const N=y.find(L=>L.id===b.args.branchId);if(!N)return;E(),t.add({...v,action:A.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{chapterId:N.chapterId,autoSelect:I}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{E(),t.add({...v,action:C.bind(null,{subjectId:u,subjectName:"container",action:b})});return}case S.openURI.trim().toLowerCase():{E(),t.add({...v,action:_.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:u,isEOV:d=!1}){const y=Le(h.events);if(y){const f=se(y.action,d);i.emit(m.interactives,{subjectId:h.id,subjectName:"container",type:x.actionChoice,actionType:f.type,payload:f.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:S.expect,action:p.bind(null,{subjectId:h.id,subjectName:"container"})}),s.isExpect=!0}else for(const f of h.events)a({action:f.action,container:h,branches:u,isEOV:d})}const l=({chapterId:h,action:u,branches:d=[]})=>{const y=i.emit.bind(i,m.interactives,{subjectId:h,subjectName:"chapter",type:x.actionChoice,actionType:u.type,payload:u.args});switch(u.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const f=d.find(I=>I.id===u.args.branchId);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const f=bi(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const f=Ci(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const f=vi(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const f=gi(d);return f?.chapterId?(y(),A.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return y(),C.bind(null,{subjectId:h,subjectName:"chapter",action:u});case S.openURI.trim().toLowerCase():return y(),_.bind(null,{subjectId:h,subjectName:"chapter",action:u,payload:{URI:u.args.uri}});default:console.error("Unexpected chapter event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function g(h){const u=Le(h.events);if(u){if(Je(h))return;i.emit(m.interactives,{subjectId:h.id,subjectName:"chapter",type:x.actionChoice,actionType:u.action.type,payload:u.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:S.expect,action:p.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const y=l({chapterId:h.id,action:d.action,branches:h.branches});y&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:y})})}const p=({subjectId:h,subjectName:u,action:d})=>{e.pause(),i.emit(m.interactives,{subjectId:h,subjectName:u,type:x.actionExecution,actionType:d?.type??S.expect})},w=({subjectId:h,subjectName:u})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(m.interactives,{subjectId:h,subjectName:u,type:x.actionExecution,actionType:"after-expect"})},C=({subjectId:h,subjectName:u,subjectType:d,action:y})=>{i.emit(m.interactives,{subjectId:h,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type})},A=({subjectId:h,subjectName:u,subjectType:d,action:y,payload:f})=>{f.behaviour="change-chapter",i.emit(m.interactives,{subjectId:h,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type,payload:f})},_=({subjectId:h,subjectName:u,subjectType:d,action:y,payload:f})=>{if(!f.URI)return;const I=window.open(f.URI,"_blank","noopener,noreferrer");I&&(I.opener=null),i.emit(m.interactives,{subjectId:h,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:p,expectEventHandler:w,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:r,state:s}};class H{constructor(e,t,n,s){this.target=e,this.type=t,this.listener=n,this.options=H.#a(e,s),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),s=Object.keys(t).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),H.#h(e)?t:t.capture||!1}}static#s=void 0;static#h(e){let t=H.#s;if(t===void 0){t=!1;try{const n={},s={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};e.addEventListener("test",r,n),e.removeEventListener("test",r,n)}catch{t=!1}H.#s=t}return t||!1}}class Ei{constructor(){this.bindingMap=new mi}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,s){if(!this.bindingMap)return;const r=new H(e,t,n,s);this.bindingMap.push(t,r)}listenOnce(e,t,n,s){const r=o=>{this.unlisten(e,t,r),n(o)};this.listen(e,t,r,s)}unlisten(e,t,n){if(!this.bindingMap)return;const s=this.bindingMap.get(t)||[];for(const r of s)r.target===e&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(t,r))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class wi{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let s=3;s<n;s+=40)if(t[s]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let s;t&&(s=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&s&&this.restore(s),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class Si{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.6-dev.5a11a96.0",
3
+ "version": "1.0.6-dev.9aa76b8.0",
4
4
  "author": "vk.com",
5
5
  "description": "Movika interactive SDK",
6
6
  "homepage": "https://vk.com",
@@ -41,14 +41,12 @@
41
41
  "./es2018.esm.js": "./es2018.esm.js",
42
42
  "./es2018.cjs.js": "./es2018.cjs.js",
43
43
  "./es2015.esm.js": "./es2015.esm.js",
44
- "./es2015.cjs.js": "./es2015.cjs.js",
45
- "./es2015.umd.js": "./es2015.umd.js"
44
+ "./es2015.cjs.js": "./es2015.cjs.js"
46
45
  },
47
46
  "files": [
48
47
  "*.cjs.js",
49
48
  "*.esm.js",
50
- "**/*.d.ts",
51
- "*.umd.js"
49
+ "**/*.d.ts"
52
50
  ],
53
51
  "dependencies": {
54
52
  "@interactiveplatform/movika-graph-editor": "^1.11.0",