@vkontakte/videoplayer-interactive 1.0.10-beta.2 → 1.0.10-dev.45d43b13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +6 -6
- package/es2015.esm.js +6 -6
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +6 -6
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/evergreen.esm.js +4 -4
- package/package.json +1 -1
package/esnext.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-interactive v1.0.10-
|
|
3
|
-
* Fri, 17 May 2024
|
|
2
|
+
* @vkontakte/videoplayer-interactive v1.0.10-dev.45d43b13.0
|
|
3
|
+
* Fri, 17 May 2024 12:52:31 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-10/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{loadVKLangPack as oe,ValueSubject as j,Subscription as tt,Observable as yt,getCurrentBrowser as ce,CurrentClientBrowser as le,once as he}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as de}from"uuid";import{Player as ue}from"@vkontakte/videoplayer-core/esnext.esm.js";const pe="1.0.10-beta.2";function Mt(i,t=1){let e="0",n="0",r="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+r},${t})`}const V="SDK_NAME",fe="SDK_NAME-controls-container",kt=()=>document.querySelector(`.${fe}`),me=.4,_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},gt={top:"flex-start",bottom:"flex-end",center:"center"},vt={start:"flex-start",end:"flex-end",center:"center"},bt={start:"left",end:"right",center:"center"},Bt=({target:i,props:t})=>{i.style.alignItems=gt[t?.text?.gravityVertical]??gt.center,i.style.justifyContent=vt[t?.text?.gravityHorizontal]??vt.center,i.style.textAlign=bt[t?.text?.alignment]??bt.start},Ft=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.color=t?.text?.color??e.textColor,i.style.fontSize=`calc(${n.height} * ${t?.text?.size??e.textSize})`,i.textContent=t?.text?.value??e.textContent},Dt=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Mt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ht=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Mt(t?.shape?.border?.color??e.borderColor,t?.shape?.border?.alpha??e.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${t?.shape?.roundCorners??e.roundCorners})`},ot=({target:i,layoutParams:t,fallback:e})=>{i.style.transform=`rotate(${-t.angle}rad)`},it="int",ct={AREA:`${it}_area`,TEXT:`${it}_text`,BUTTON:`${it}_bttn`};class lt{constructor(t){this.control=t}createView(t){const e=document.createElement("div");e.classList.add(`${V}-control-container-${this.control.id}`),t(e,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??_.innerSizesDependOn)==="self"?{height:e.style.height,width:e.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:e,dependsOn:n}}setEvents(t,e){t&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":t.addEventListener("click",s=>{s.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${V}-control-container-${this.control.id}`)}}const Gt=i=>{if(i.type.trim().toLowerCase()==="area")return new ye(i)};class ye extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");return s.classList.add(`${V}-${this.control.id}`),s.setAttribute("data-testid",ct.AREA),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",Dt({target:s,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Ht({target:s,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),ot({target:s,layoutParams:this.control.layoutParams,fallback:_}),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${V}-${this.control.id}`)}}const Ut=i=>{if(i.type.trim().toLowerCase()==="button")return new ge(i)};class ge extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");s.type="button",s.classList.add(`${V}-${this.control.id}`),s.setAttribute("data-testid",ct.BUTTON),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.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",ot({target:s,layoutParams:this.control.layoutParams,fallback:_}),Dt({target:s,props:this.control.props,fallback:_}),Ht({target:s,props:this.control.props,fallback:_,dependsOn:n}),Bt({target:s,props:this.control.props}),Ft({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${V}-${this.control.id}`)}}const ve=i=>{if(i.type.trim().toLowerCase()==="text")return new be(i)};class be extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("div");s.classList.add(`${V}-${this.control.id}`),s.setAttribute("data-testid",ct.TEXT),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:s,layoutParams:this.control.layoutParams,fallback:_}),Bt({target:s,props:this.control.props}),Ft({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){}enable(){}getElement(){return document.querySelector(`.${V}-${this.control.id}`)}}class Ce{constructor(t){this.layout=t}}const Ee=i=>{if(i.type.trim().toLowerCase()==="relative")return new Wt(i)};class Wt extends Ce{constructor(t){super(t)}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,e){t.style.position="absolute",t.style.width=`calc(var(--interactive-content-width) * ${e.width})`,t.style.height=`calc(var(--interactive-content-height) * ${e.height})`,t.style.left=`calc(var(--interactive-content-width) * ${e.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,t.style.top=`calc(var(--interactive-content-height) * ${e.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class zt{constructor(t){this.container=t,this.factories=new Map,this.#r()}addControlFactory(t,e){this.factories.set(t.trim().toLowerCase(),e),this.#r()}removeControlFactory(t){this.factories.delete(t.trim().toLowerCase()),this.#r()}#r(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...t,r(e)]:[...t]},[])}}const qt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new we(i,t)};class we extends zt{constructor(t,e){super(t),this.rootElement=e??kt(),this.layout=new Wt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Ut),this.addControlFactory("text",ve),this.addControlFactory("area",Gt)}createView(t){const e=document.createElement("div");return e.classList.add(`${V}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const r=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(r,t)}),this.rootElement.append(e),this.isRemoved=!1,e}hide(){const t=this.getElement();t&&(t.style.visibility="hidden")}show(){const t=this.getElement();t&&(t.style.visibility="visible")}enable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.enable()),t.style.opacity=1,this.isDisabled=!1)}disable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.disable()),t.style.opacity=me,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${V}-${this.container.id}`)}}function Qt(i,t){let e;return(...n)=>{clearTimeout(e),e=setTimeout(()=>i(...n),t)}}const z={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},G=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,ht=i=>G(i,z.Object),rt=i=>G(i,z.String),dt=i=>G(i,z.Array),Xt=i=>G(i,z.Number),Ie=i=>G(i,z.Function),Ct=i=>Xt(i)&&!isNaN(i),U=i=>ht(i)&&Object.keys(i).length===0,Yt=i=>dt(i)&&!i.length,Q=(i,t)=>rt(i)&&(t?i.trim():i).length,Kt=window.navigator.userAgent.toLowerCase(),Se=/mobi/i.test(Kt);Kt.indexOf("android")>-1;const Te="video_interactive",xe="videoint",Re=250;class Ae{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=e,this.onError=n,this.lang=r??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Le(t),this.resizeObserver=new ResizeObserver(Qt(this.onResize,Re)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=t=>{this.isReady&&(!t[0].contentRect.width||!t[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:t[0].contentRect.width,height:t[0].contentRect.height}))};getNextPoint(t=this.ngEditorSize){return[(this.lastZoomInfo.x-t.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-t.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=t=>{if(this.isReady){if(this.isHidden||this.hide(),!t?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(t.id),this.ngEditor.selectChapter(t.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=t.id,this.lastZoomInfo=void 0}};handleManifestChange=async(t,e=[])=>{if(!Xt(t.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 oe(this.lang,Te,xe)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:r}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new r(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:s,chapterId:o})=>{s==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",s=>{this.lastZoomInfo={...s}})}this.visitedChapterIds=new Set(e),t.metadata.id!==this.currentManifestId?(this.ngEditor.update(t),this.currentManifestId=t.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(t){this.visitedChapterIds=new Set([...this.visitedChapterIds,...t]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(t){this.ngEditor.updateVideosInfo(t)}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 Le(i){const t=document.createElement("div");return t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.height="100%",t.style.width="100%",t.style.display="none",i.append(t),t}const Oe=3e3,je=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Oe)=>{if(!i.length||t===null)return null;let a=-1,c=!1;const l=Math.round(t.info.position$.getValue()*1e3);for(const f of i){const p=f.startTime-o;if(p<=l&&(l<=f.endTime||f.endTime===null)){c=!0;break}l<p&&(a=a===-1?p:Math.min(a,p))}return!c&&a!==-1?a:null}}},Z=(i="",t="")=>{i=i.split("."),t=t.split(".");let e=0;for(let n=0;n<Math.max(i.length,t.length)&&!e;n++)i[n]>t[n]?e=1:i[n]<t[n]?e=-1:e=0;return e},Ne="3.1",Et={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Ve={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},_e=i=>{const t=[];for(const e of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let f=[Ve];switch(a){case"await":l?f=[]:s=[];break;case"default":{const p={type:"onSuspense",action:{type:Et.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[p]:s=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:Et[a],args:{}}};l?f=[p]:s=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:de(),events:f})}t.push({...e,containers:o,events:s,branches:r})}return i.metadata.version=Ne,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},$e="3.2",Pe=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:$e},media:t}}return i},Me="3.3",ke=(i=[])=>({edit:{chapters:i},view:{}}),wt={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Be=i=>{const t=[],e=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:f,type:p,...b})=>({...b,type:f??p})),events:l.events?.length?l.events:[wt]}));t.push({id:r,...a,containers:c,events:a.events?.length?a.events:[wt]}),e.push({id:r,x:s,y:o})}return{...i,chapters:t,graph:ke(e),metadata:{...i.metadata,version:Me}}},Fe=[{version:"3.0",migrate:_e},{version:"3.1",migrate:Pe},{version:"3.2",migrate:Be}],De=i=>Fe.reduce((t,e)=>Z(t.metadata.version,e.version)?t:e.migrate(t),i),He=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(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"})(F||(F={}));const It={metadata:"Object",chapters:"Array"},Ge="3.0.0",Ue="3.3.0",Zt=i=>{const t=Z(i,Ge);return t===-1?!1:t===0?!0:Z(i,Ue)!==1},We=i=>{if(!ht(i))return!1;for(const t in It)if(!i[t]||!G(i[t],It[t]))return!1;return Zt(i.metadata.version)},Jt=i=>i.type===He.Text;class E{constructor(t,e,...n){this.severity=t,this.category=e,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 te{listeners={};addListener(t,e){return this.listeners[t]=this.listeners[t]||[],this.listeners[t].push(e),this}on(t,e){return this.addListener(t,e)}once(t,e){this.listeners[t]=this.listeners[t]||[];const n=()=>{e(),this.off(t,n)};return this.listeners[t].push(n),this}off(t,e){return this.removeListener(t,e)}reset(){this.listeners={}}removeListener(t,e){const n=this.listeners[t];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===e){n.splice(r,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(r=>{r(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class ze{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{Ie(t)&&(this.fns.push(t),e&&this.updateFn())};removeFn=(t,e=!1)=>{this.fns=this.fns.filter(n=>n!==t),e&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(t=>t()),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 qe{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return Qe(...this.loaders[t])(e)}}function Qe(...i){return async function(e){const n=[...i];for(;n.length>0;)e=await n.shift()(e);return e}}function J(i,t,e){return i?{...i,[t]:i[t]?[e,...i[t]]:[e]}:{[t]:[e]}}function at({actions:i,errors:t,chapterId:e,...n}){if(e){const r=i.getManifest(),s=i.getChapter(r.chapters,e);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:t,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(t,at.name,"Could not find media"),actions:i}}}return{...n,errors:J(t,at.name,"Could not find chapter"),actions:i}}class St{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(t,e,n){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:n})}removeEventListener(t,e){if(!(t in this.listeners))return;const n=this.listeners[t];for(let r=0,s=n.length;r<s;r++)if(n[r].callback===e){n.splice(r,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const n=this.listeners[t.type].slice();for(let r=0,s=n.length;r<s;r++){const o=n[r];try{o.callback.call(this,t)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(t.type,o.callback)}return!t.defaultPrevented}}class ee extends St{constructor(){super(),this.listeners||St.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class Xe{constructor(){Object.defineProperty(this,"signal",{value:new ee,writable:!0,configurable:!0})}abort(t){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}let n=t;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(e)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Xe.prototype[Symbol.toStringTag]="AbortController",ee.prototype[Symbol.toStringTag]="AbortSignal");function ie(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Ye(i){typeof i=="function"&&(i={fetch:i});const{fetch:t,Request:e=t.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!ie({fetch:t,Request:e,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:t,Request:s};let s=e;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,f){let p;f&&f.signal&&(p=f.signal,delete f.signal);const b=new e(l,f);return p&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),b},s.prototype=e.prototype);const o=t;return{fetch:(c,l)=>{const f=s&&s.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(f){let p;try{p=new DOMException("Aborted","AbortError")}catch{p=new Error("Aborted"),p.name="AbortError"}if(f.aborted)return Promise.reject(p);const b=new Promise((C,L)=>{f.addEventListener("abort",()=>L(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:s}}const ut=ie({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ne=ut?Ye({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Tt=ut?ne.fetch:window.fetch;ut?ne.Request:window.Request;const Ke=async i=>{try{let t,e;if(ht(i))t=i;else if(rt(i)){e=new URL(i).href;const r=await Tt(e);if(!r.ok)return{};t=await r.json()}else return{};if(!We(t))return{};const n=t.metadata.media;if(rt(n)&&!t.media)try{let r;e?r=new URL(n,e).href:(r=new URL(n).href,e=r);const s=await Tt(r);if(!s.ok)throw new Error;t.metadata.media=await s.json()}catch{return ei(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function Ze(i){const{manifest:t,manifestURL:e}=await Ke(i),n=De(t);return n.media=Je(n.media,e),delete n.metadata.media,n}function nt(i,t){return i.find(e=>e.id===t)}function xt(i,t){return i.edit?.chapters?i.edit.chapters.find(e=>e.id===t):i.view?.chapters?i.view.chapters.find(e=>e.id===t):void 0}function Rt(i,t){return i.videos.find(e=>e.id===t)}function Je(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const r=ti(n.url,t);return{...n,url:r||n.url}})}))}}function ti(i,t){try{return new URL(i,t).href}catch{return""}}function ei(i){return Z(i,"3.2.0")>=0}const S=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pt=i=>dt(i)&&!Yt(i),et=i=>i.order==="end",ii=i=>dt(i.containers)&&!Yt(i.containers)&&et(i),ni=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e<(t.startTime??0)},At=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)},W=i=>i.some(t=>t.action.type==="expect"),Lt=i=>i.find(t=>t.action.type==="expect"),si=i=>i?.length===1,se=i=>si(i)&&Jt(i[0]),ri=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),ai=(i=[])=>i.reduce((t,e,n)=>{const r=(e?.controls??[]).filter(s=>!Jt(s));if(pt(r)){const s=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,f=[];const p=[];for(let b=0;b<t.length;b++){const C=t[b];if(p.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=s[0]&&C.range[1]>=s[1])return t[b].subjects.push(o),t;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[1]=C.range[1])}if(p.push(o),s[0]<=l&&s[1]>=c)return[{subjects:p,range:s}];a.length&&a.reverse().forEach(b=>{t.splice(b,1)}),t.push({subjects:f.concat([o]),range:s})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),oi=(i,t)=>W(i.events)?!1:t.some(({container:e})=>e.container.id!==i.id&&W(e.container.events)&&e.container.endTime===i.endTime&&!e.isRemoved);class ci extends qe{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new j(null),this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(t){this.release();const e=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:t});e.errors&&this.errorHandler(e.errors);const n=await Ze(e.result??t);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(t=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const e=await this.exec("chapterLoaders",at({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:xt,getChapter:nt,getMedia:Rt,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:t}));return e.errors&&this.errorHandler(e.errors),this.chapter=e.result.chapter,this.media=e.result.media,this.graph=e.result.graph,this}errorHandler(t){this.onError(t),console.error("Something went wrong with loaders",{errors:t})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(t=this.manifest.metadata.initChapterId){const e=nt(this.manifest.chapters,t);if(e){const n=Rt(this.manifest.media,e.videoId),r=xt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:r}}return null}getBranches(t=this.chapter.id){if(t===this.chapter.id)return this.getByBranches(this.chapter.branches);{const e=nt(this.manifest.chapters,t);return this.getByBranches(e?.branches)}}getByBranches(t=[]){return t.reduce((e,n)=>{const r=this.getByChapterId(n.chapterId);return r&&e.push(r),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter.id===this.manifest.metadata.initChapterId}isEndChapter(){return et(this.chapter)}}const li=i=>{const t=i.variants.find(e=>e.payload?.type==="vk");if(t&&"payload"in t){const[e,n]=t.payload.id.split("_");return[e,n]}return[]},y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},Ot={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function hi(){const i=new Map;function t({listId:r=Math.random().toString(),itemId:s=Math.random().toString(),...o}){const a=i.get(r),c={...o};return a?a[s]=c:i.set(r,{[s]:c}),{listId:r,itemId:s,...o}}function e(r,s){const o=i.get(r);if(o){if(s)return o[s]?.player.destroy(),o[s]?.container.remove(),o[s]?.subscription.unsubscribe(),delete o[s],Object.keys(o).length||i.delete(r),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(r),!0}else throw Error("Can't remove. Not find.")}function n(){for(const r of i)e(r[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function jt(i,t=[]){let e={},n;const r=!t.length;for(const s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:s.url}});break;case"dash":(r||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:e,thumbUrl:n,title:i.title??""}}const X=(i,t)=>{const e=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();e!==t&&n.includes(t)&&(i.setQuality(t),i.setAutoQuality(!1))},K={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},di=2;function ui(i){const t=hi();let e,n;const r=new te;let s={},o=!1,a=null,c=!1,l;i&&f(i);function f(d){a=d}function p(d,g,m){if(!a)throw Error("need to set interactive controller");const w=(t.map.get(d)??{})[g];if(w){s={chapterId:m,listId:d,itemId:g,...w};const R=s.player;n=R.info.currentQuality$.subscribe(v=>{if(!(!v||!R.info.position$.getValue())){e=v;for(const O of t.map)Object.values(O[1]).forEach(({player:N})=>{R.info.isAutoQualityEnabled$.getValue()||X(N,v)})}}),w.container.remove(),o=!1,a.setPlayer(w.player),c||(a.init(),c=!0),r.emit(K.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(m>=0&&!o){const w=a.getChapterBranches();o=!0;const R=new Set;for(const v of w)R.has(v.media.id)||(await L({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),R.add(v.media.id))}}async function C({chapter:{id:d},media:g}){if(U(s))return;n?.unsubscribe();const m=s.player.info.muted$.getValue(),x=s.player.info.currentQuality$.getValue(),w=s.player.info.isAutoQualityEnabled$.getValue(),R=s.player.info.volume$.getValue(),v=s.player.info.currentPlaybackRate$.getValue(),O=!w;let N=!1;for(const A of t.map)if(A[0]===g.id){const k=Object.keys(A[1]);for(const $ of k)$===s.itemId?(k.length<di||(N=!0),t.removePlayer(A[0],$)):(N=!0,p(A[0],$,d),O?X(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(m),s.player.setPlaybackRate(v))}else t.removePlayer(A[0]);N||(await L({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),O?X(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(m))}async function L({media:d,chapterId:g,prefetch:m=!0,setAsActive:x=!0,autoplay:w=!1,preferredExt:R,title:v,playbackRate:O}){const N=Math.random().toString(),A=document.createElement("div");l.append(A);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let $;if(a?.options?.vkVideoLoader){const q=li(d);q.length&&($=await a.options.vkVideoLoader(...q))}const ft={container:A,...$?.videos?.[0]||{sources:jt(d,R).sources},title:v},B=new ue;B.initVideo(ft);const ae=A.lastChild,mt=new tt;mt.add(B.info.position$.subscribe(function(q){b(N,B.info.duration$.getValue(),q)})).add(B.events.canplay$.subscribe(function(){k||X(B,e),O&&B.setPlaybackRate(O)})),ae&&(A.style.display="none",A.classList.add(g));const D=t.createPlayer({listId:d.id,itemId:N,player:B,container:A,sources:jt(d,R).sources,config:ft,subscription:mt});return x&&p(d.id,D.itemId,g),w&&D.player.play(),m&&!w&&D.player.prepare(),r.emit(K.playerCreated,D.player),{player:D.player,config:D.config}}function M(){u(),a=null}function u(){a?.off(y.chapterChanged,C),t.removeAll(),s={},c=!1,o=!1}async function h({container:d}){if(!a)throw Error("need to set interactive controller");u(),l=d;const{media:g,chapter:m}=a.getCurrentChapter();if(g){a.on(y.chapterChanged,C);const{player:x,config:w}=await L({media:g,chapterId:m.id,title:m.label});return r.emit(K.initiated,{container:d,media:g,chapterId:m.id}),{player:x,config:w}}else console.error("not found")}return{...t,on:r.on.bind(r),off:r.off.bind(r),init:h,setInteractiveController:f,createPlayer:L,removeAll:M,getActivePlayer:function(){return s}}}class pi{constructor({player:t,container:e,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:f}){this.container=e,this.branches=n,this.selectBranches=r,this.subscription=new tt,this.player=t,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&se(e.container.controls),this.disabledControls$=l,this.onRemove=f,this.globalEventEmitter=o,this.gameState=S.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)).add(this.disabledControls$.subscribe(t=>{t?this.container.disable?.():this.container.enable?.()}))}hide=()=>{setTimeout(()=>{this.gameState!==S.end&&(W(this.container.container.events)&&this.gameState===S.afterInteractive||this.selectBranches.state.isExpect||(this.gameState!==S.interactive&&this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===S.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const e=ri({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===S.end||this.gameState===S.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1}))},isEOV:()=>this.gameState===S.end});this.container.createView(e),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0}),this.disabledControls$.getValue()&&this.container.disable?.()}};selectContainerEvent(t=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:t?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:t}),!t&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const t=W(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!t)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=S.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[S.destroyed,S.removed].includes(this.gameState)&&!this.isPermanentText)return;const e=this.player.getExactTime();if(ni(e,this.container.container))this.gameState!==S.beforeInteractive&&(this.gameState=S.beforeInteractive,this.onBeforeStartTime());else if(At(e,this.container.container))this.gameState!==S.interactive&&(this.gameState=S.interactive,this.onStartTime());else if(this.gameState!==S.afterInteractive){const s=this.gameState;this.gameState=S.afterInteractive,s===S.interactive&&this.onEndTime()}else this.gameState!==S.destroyed&&!this.isPermanentText&&this.removeView();const n=At(e,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=S.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=S.removed,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=S.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}}function fi(){const i={};function t(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function e(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 r({timestamp:a,priority:c,initiator:l}){if(Ct(a)){const f=i[a]??null;if(f&&Q(c,!0)){let p={};const b=f[c];return b&&(p={...p,...b}),p=U(p)?null:p,p&&Q(l,!0)?p[l]??null:p}return f}return null}function s({timestamp:a,priority:c,initiator:l}){if(Ct(a))if(i[a]){if(Q(c,!0))if(i[a][c]){if(Q(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!U(i[a][c]))return!0}else return!1;if(delete i[a][c],!U(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...f}){i[a]?.[c]?.[l]?i[a][c][l].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...f}]}}:i[a]={[c]:{[l]:[{...f}]}}}return{map:i,remove:s,add:o,removeAll:t,get:r,getLte:e,getGte:n}}const mi=[I.expect,I.setNextBranch],yi=1/0;function Nt(i){let t=i,e;const n=gi(),r=new fi;let s;const o=()=>{b(),u()},a=h=>{r.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),mi.includes(d.actionType))break},l=(h=1/0)=>{const d=Y(r.get({timestamp:h,priority:"control"})??{}),g=Y(r.get({timestamp:h,priority:"container"})??{}),m=Y(r.get({timestamp:h,priority:"chapter"})??{});return[...d,...g,...m]},f=h=>{n.isReady(h)&&c(l(h))},p=()=>{c([...Y(r.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{e&&(s?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{f(1/0)}),s=t.events.ended$.subscribe(e))},L=h=>{b(),t=h},M=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},u=()=>{n.release(),r.removeAll()};return{setPlayer:L,add:a,remove:M,exec:f,execEndOfVideo:p,listen:C,unlisten:b,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function gi(){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??yi,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(t=>t.actionType===I.expect?-1:1)}const vi=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=t.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=r/s;let c,l;return a>o?(l=s,c=s*o):a<o?(l=r/o,c=r):(l=s,c=r),{videoContentWidth:l,videoContentHeight:c}},bi=250;function Ci(i){let t=()=>{};const e=new ResizeObserver(a=>{s(a),t=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:p}=vi(c,l);c.style.setProperty("--interactive-content-width",`${f}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 r(){const{parentElement:a}=i();a.removeAttribute("style")}const s=Qt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},bi);function o(){t=void 0,e.disconnect(),r()}return{resizeObserver:e,calc:()=>{t()},release:o}}class Ei{constructor(){this.map={}}push(t,e){t in this.map?this.map[t].push(e):this.map[t]=[e]}get(t){const e=this.map[t];return e?e.slice():null}getAll(){const t=[];for(const e in this.map)t.push(...this.map[e]);return t}remove(t,e){t in this.map&&(this.map[t]=this.map[t].filter(n=>n!==e),this.map[t].length===0&&delete this.map[t])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const wi=i=>Math.floor(Math.random()*i),Ii=i=>{let t=i.length,e=1/0,n=null;for(;t--;)i[t].weight<e&&(e=i[t].weight,n=i[t]);return n},Si=i=>{let t=i.length,e=-1/0,n=null;for(;t--;)i[t].weight>e&&(e=i[t].weight,n=i[t]);return n},Ti=i=>{const t=i.length,e=wi(t);return i[e]},Vt=1,xi=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??Vt;const e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??Vt,t>=e)return i[n];return i[i.length-1]},_t=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),st=(i,t=!1)=>({...i,args:t?{...i.args,..._t}:{..._t,...i.args}}),$t=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:g,branches:m=[],onEvent:x,isEOV:w=()=>!1,isDisabled:R=()=>!1})=>{const v=st(u,w()),O={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},N=R(),A=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:N?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:g,...v.args}});if(N){A();return}switch(v.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const k=m.find($=>$.id===v.args.branchId);if(!k)return;x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?L({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...O,action:L.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...O,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case I.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?M({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...O,action:M.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:u,container:{id:h,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:x=!1})=>{const w=st(u,m),R={timestamp:!w.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:h,actionType:w.type},v=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"container",type:T.actionChoice,actionType:w.type,payload:w.args});switch(w.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const O=g.find(N=>N.id===w.args.branchId);if(!O)return;v(),e.add({...R,action:L.bind(null,{subjectId:h,subjectName:"container",action:w,payload:{chapterId:O.chapterId,autoSelect:x}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{v(),e.add({...R,action:C.bind(null,{subjectId:h,subjectName:"container",action:w})});return}case I.openURI.trim().toLowerCase():{v(),e.add({...R,action:M.bind(null,{subjectId:h,subjectName:"container",action:w,payload:{URI:u.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:u,branches:h,isEOV:d=!1}){const g=Lt(u.events);if(g){const m=st(g.action,d);i.emit(y.interactives,{subjectId:u.id,subjectName:"container",type:T.actionChoice,actionType:m.type,payload:m.args}),e.add({timestamp:d?1/0:u.endTime,priority:"container",initiator:u.id,actionType:I.expect,action:p.bind(null,{subjectId:u.id,subjectName:"container"})}),r.isExpect=!0}else for(const m of u.events)a({action:m.action,container:u,branches:h,isEOV:d})}const l=({chapterId:u,action:h,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:u,subjectName:"chapter",type:T.actionChoice,actionType:h.type,payload:h.args});switch(h.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const m=d.find(x=>x.id===h.args.branchId);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{const m=Ti(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{const m=xi(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{const m=Si(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{const m=Ii(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case I.openURI.trim().toLowerCase():return g(),M.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function f(u){const h=Lt(u.events);if(h){if(et(u))return;i.emit(y.interactives,{subjectId:u.id,subjectName:"chapter",type:T.actionChoice,actionType:h.action.type,payload:h.action.args}),e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:I.expect,action:p.bind(null,{subjectId:u.id,subjectName:"chapter"})})}else u.events.forEach(d=>{const g=l({chapterId:u.id,action:d.action,branches:u.branches});g&&e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:d.action.type,action:g})})}const p=({subjectId:u,subjectName:h,action:d})=>{t.pause(),i.emit(y.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:d?.type??I.expect})},b=({subjectId:u,subjectName:h})=>{t.info.isEnded$.getValue()?e.execEndOfVideo():t.play(),i.emit(y.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:u,subjectName:h,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:g.type})},L=({subjectId:u,subjectName:h,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:g.type,payload:m})},M=({subjectId:u,subjectName:h,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const x=window.open(m.URI,"_blank","noopener,noreferrer");x&&(x.opener=null),i.emit(y.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:p,expectEventHandler:b,setManifestChapterEvents:f,setManifestContainerEvents:c,stopExpect:s,state:r}},Pt=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const r=t.chapters.find(o=>o.id===n);if(!r)return null;const s=t.media.videos.find(o=>r.videoId===o.id);if(!s)return null;e[n]=re(s)}return e[n]}).filter(Boolean)},Ri=i=>{for(const t of i.variants)if(Ai(t)&&"payload"in t)return t.payload.id},Ai=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",re=i=>{const t=Ri(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},Li=(i,t)=>{for(const e of i.media.videos)if(t===re(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},Oi=(i,t)=>i.reduce((e,n)=>{const r=Li(t,n);return r?[...e,r]:e},[]),ji=100;class Ni{state={history$:new j([]),hasPrevChapter$:new j(!1),prevChapter$:new j(null),isInitialChapter$:new j(!1),isGoBackLimited$:new j(!1)};#r=null;#s;#h=!1;#i=null;#u=null;#n=null;#a=null;#o=null;#t=new tt;#d=!1;#p=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:r,historyParams:s}){this.#n=e,this.#o=t,this.#a=n,this.#r=r,this.#s={maxLength:s?.maxLength||ji},this.state?.history$&&this.#t&&this.#t?.add(this.state?.history$.subscribe(o=>{this.state?.prevChapter$.next(o.at(-2)||null),this.state?.hasPrevChapter$.next(o.length>1),this.state?.isInitialChapter$.next(this.getInitialChapterId()===this.#i?.metadata?.initChapterId),this.state?.isGoBackLimited$.next(this.#p===this.#s.maxLength-1)}))}async setManifest(t){!this.#a||!this.#o||(this.#i=t,await this.getProjectHistory(),await this.#a.setChapter({chapterId:this.getInitialChapterId(),pushToHistory:!1}),this.#h||(this.#h=!0,this.#o.emit(y.historyInited,{initChapterId:this.getInitialChapterId()})))}get inited(){return this.#h}async updateHistory(t,e=!0){if(!this.#i)return;this.#d?(this.#d=!1,this.#p++):this.#p=0;const n=this.#i,r=t.length-this.#s.maxLength,s=r>0?t.slice(r):t,o=Pt(s,n);if(this.#u=o,this?.state?.history$.next(s),!(!e||!this.#r||!this.#n))try{await this.#r.save(this.#n,o)}catch{this.#o?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#a)return this.#o?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Cannot go back because HistoryController has not been initialized"));this.#d=!0;const t=this.state.history$.getValue().slice(0,-1),e=t.pop();this.state.history$.next(t),await this.#a.setChapter({chapterId:e})}async getProjectHistory(){if(!this.#i||!this.#n)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#r)try{const r=await this.#r.get(this.#n);r.length&&(e=r)}catch{this.#o?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Error while trying to fetch data"))}const n=Oi(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#i?.metadata.initChapterId}getInitialVideoId(){if(this.#i){const t=this.getInitialChapterId();return Pt([t],this.#i).pop()}return null}destroy(){this.state=null,this.#n=null,this.#r=null,this.#a=null,this.#t?.unsubscribe(),this.#t=null,this.#h=!1,this.#o?.emit(y.historyDestroyed),this.#o=null}}class H{constructor(t,e,n,r){this.target=t,this.type=e,this.listener=n,this.options=H.#r(t,r),this.target.addEventListener(e,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#r(t,e){if(e===void 0)return!1;if(typeof e=="boolean")return e;{const n=new Set(["passive","capture"]),r=Object.keys(e).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),H.#h(t)?e:e.capture||!1}}static#s=void 0;static#h(t){let e=H.#s;if(e===void 0){e=!1;try{const n={},r={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};t.addEventListener("test",s,n),t.removeEventListener("test",s,n)}catch{e=!1}H.#s=e}return e||!1}}class Vi{constructor(){this.bindingMap=new Ei}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,r){if(!this.bindingMap)return;const s=new H(t,e,n,r);this.bindingMap.push(e,s)}listenOnce(t,e,n,r){const s=o=>{this.unlisten(t,e,s),n(o)};this.listen(t,e,s,r)}unlisten(t,e,n){if(!this.bindingMap)return;const r=this.bindingMap.get(e)||[];for(const s of r)s.target===t&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(e,s))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class _i{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 t=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!t)return!1;const e=t.data,n=e.length;for(let r=3;r<n;r+=40)if(e[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(t){this.canvasImgSrc=t}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(t,e=!1){const n=t.width+t.height;if(this._prevSizeId===n)return;let r;e&&(r=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&r&&this.restore(r),this._prevSizeId=n}async save(){const t=this.rootElement.toDataURL("image/jpeg",1),e=new Image;return e.crossOrigin="anonymous",e.src=t,await e.decode(),e}restore(t){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(t,0,0,this.rootElement.width,this.rootElement.height)}}class $i{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:t,endOffsetMs:e=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
6
|
+
import{loadVKLangPack as oe,ValueSubject as j,Subscription as tt,Observable as yt,getCurrentBrowser as ce,CurrentClientBrowser as le,once as he}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as de}from"uuid";import{Player as ue}from"@vkontakte/videoplayer-core/esnext.esm.js";const pe="1.0.10-dev.45d43b13.0";function Mt(i,t=1){let e="0",n="0",r="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+r},${t})`}const V="SDK_NAME",fe="SDK_NAME-controls-container",kt=()=>document.querySelector(`.${fe}`),me=.4,_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},gt={top:"flex-start",bottom:"flex-end",center:"center"},vt={start:"flex-start",end:"flex-end",center:"center"},bt={start:"left",end:"right",center:"center"},Bt=({target:i,props:t})=>{i.style.alignItems=gt[t?.text?.gravityVertical]??gt.center,i.style.justifyContent=vt[t?.text?.gravityHorizontal]??vt.center,i.style.textAlign=bt[t?.text?.alignment]??bt.start},Ft=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.color=t?.text?.color??e.textColor,i.style.fontSize=`calc(${n.height} * ${t?.text?.size??e.textSize})`,i.textContent=t?.text?.value??e.textContent},Dt=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Mt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ht=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Mt(t?.shape?.border?.color??e.borderColor,t?.shape?.border?.alpha??e.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${t?.shape?.roundCorners??e.roundCorners})`},ot=({target:i,layoutParams:t,fallback:e})=>{i.style.transform=`rotate(${-t.angle}rad)`},it="int",ct={AREA:`${it}_area`,TEXT:`${it}_text`,BUTTON:`${it}_bttn`};class lt{constructor(t){this.control=t}createView(t){const e=document.createElement("div");e.classList.add(`${V}-control-container-${this.control.id}`),t(e,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??_.innerSizesDependOn)==="self"?{height:e.style.height,width:e.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:e,dependsOn:n}}setEvents(t,e){t&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":t.addEventListener("click",s=>{s.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${V}-control-container-${this.control.id}`)}}const Gt=i=>{if(i.type.trim().toLowerCase()==="area")return new ye(i)};class ye extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");return s.classList.add(`${V}-${this.control.id}`),s.setAttribute("data-testid",ct.AREA),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",Dt({target:s,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Ht({target:s,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),ot({target:s,layoutParams:this.control.layoutParams,fallback:_}),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${V}-${this.control.id}`)}}const Ut=i=>{if(i.type.trim().toLowerCase()==="button")return new ge(i)};class ge extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");s.type="button",s.classList.add(`${V}-${this.control.id}`),s.setAttribute("data-testid",ct.BUTTON),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.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",ot({target:s,layoutParams:this.control.layoutParams,fallback:_}),Dt({target:s,props:this.control.props,fallback:_}),Ht({target:s,props:this.control.props,fallback:_,dependsOn:n}),Bt({target:s,props:this.control.props}),Ft({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${V}-${this.control.id}`)}}const ve=i=>{if(i.type.trim().toLowerCase()==="text")return new be(i)};class be extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("div");s.classList.add(`${V}-${this.control.id}`),s.setAttribute("data-testid",ct.TEXT),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:s,layoutParams:this.control.layoutParams,fallback:_}),Bt({target:s,props:this.control.props}),Ft({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){}enable(){}getElement(){return document.querySelector(`.${V}-${this.control.id}`)}}class Ce{constructor(t){this.layout=t}}const Ee=i=>{if(i.type.trim().toLowerCase()==="relative")return new Wt(i)};class Wt extends Ce{constructor(t){super(t)}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,e){t.style.position="absolute",t.style.width=`calc(var(--interactive-content-width) * ${e.width})`,t.style.height=`calc(var(--interactive-content-height) * ${e.height})`,t.style.left=`calc(var(--interactive-content-width) * ${e.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,t.style.top=`calc(var(--interactive-content-height) * ${e.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class zt{constructor(t){this.container=t,this.factories=new Map,this.#s()}addControlFactory(t,e){this.factories.set(t.trim().toLowerCase(),e),this.#s()}removeControlFactory(t){this.factories.delete(t.trim().toLowerCase()),this.#s()}#s(){this.controls=this.#n()}#n(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...t,r(e)]:[...t]},[])}}const qt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new we(i,t)};class we extends zt{constructor(t,e){super(t),this.rootElement=e??kt(),this.layout=new Wt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Ut),this.addControlFactory("text",ve),this.addControlFactory("area",Gt)}createView(t){const e=document.createElement("div");return e.classList.add(`${V}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const r=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(r,t)}),this.rootElement.append(e),this.isRemoved=!1,e}hide(){const t=this.getElement();t&&(t.style.visibility="hidden")}show(){const t=this.getElement();t&&(t.style.visibility="visible")}enable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.enable()),t.style.opacity=1,this.isDisabled=!1)}disable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.disable()),t.style.opacity=me,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${V}-${this.container.id}`)}}function Qt(i,t){let e;return(...n)=>{clearTimeout(e),e=setTimeout(()=>i(...n),t)}}const z={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},G=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,ht=i=>G(i,z.Object),rt=i=>G(i,z.String),dt=i=>G(i,z.Array),Xt=i=>G(i,z.Number),Ie=i=>G(i,z.Function),Ct=i=>Xt(i)&&!isNaN(i),U=i=>ht(i)&&Object.keys(i).length===0,Yt=i=>dt(i)&&!i.length,Q=(i,t)=>rt(i)&&(t?i.trim():i).length,Kt=window.navigator.userAgent.toLowerCase(),Se=/mobi/i.test(Kt);Kt.indexOf("android")>-1;const Te="video_interactive",xe="videoint",Re=250;class Ae{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=e,this.onError=n,this.lang=r??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Le(t),this.resizeObserver=new ResizeObserver(Qt(this.onResize,Re)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=t=>{this.isReady&&(!t[0].contentRect.width||!t[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:t[0].contentRect.width,height:t[0].contentRect.height}))};getNextPoint(t=this.ngEditorSize){return[(this.lastZoomInfo.x-t.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-t.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=t=>{if(this.isReady){if(this.isHidden||this.hide(),!t?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(t.id),this.ngEditor.selectChapter(t.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=t.id,this.lastZoomInfo=void 0}};handleManifestChange=async(t,e=[])=>{if(!Xt(t.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 oe(this.lang,Te,xe)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:r}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new r(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:s,chapterId:o})=>{s==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",s=>{this.lastZoomInfo={...s}})}this.visitedChapterIds=new Set(e),t.metadata.id!==this.currentManifestId?(this.ngEditor.update(t),this.currentManifestId=t.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(t){this.visitedChapterIds=new Set([...this.visitedChapterIds,...t]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(t){this.ngEditor.updateVideosInfo(t)}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 Le(i){const t=document.createElement("div");return t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.height="100%",t.style.width="100%",t.style.display="none",i.append(t),t}const Oe=3e3,je=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Oe)=>{if(!i.length||t===null)return null;let a=-1,c=!1;const l=Math.round(t.info.position$.getValue()*1e3);for(const f of i){const p=f.startTime-o;if(p<=l&&(l<=f.endTime||f.endTime===null)){c=!0;break}l<p&&(a=a===-1?p:Math.min(a,p))}return!c&&a!==-1?a:null}}},Z=(i="",t="")=>{i=i.split("."),t=t.split(".");let e=0;for(let n=0;n<Math.max(i.length,t.length)&&!e;n++)i[n]>t[n]?e=1:i[n]<t[n]?e=-1:e=0;return e},Ne="3.1",Et={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Ve={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},_e=i=>{const t=[];for(const e of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let f=[Ve];switch(a){case"await":l?f=[]:s=[];break;case"default":{const p={type:"onSuspense",action:{type:Et.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[p]:s=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:Et[a],args:{}}};l?f=[p]:s=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:de(),events:f})}t.push({...e,containers:o,events:s,branches:r})}return i.metadata.version=Ne,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},$e="3.2",Pe=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:$e},media:t}}return i},Me="3.3",ke=(i=[])=>({edit:{chapters:i},view:{}}),wt={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Be=i=>{const t=[],e=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:f,type:p,...b})=>({...b,type:f??p})),events:l.events?.length?l.events:[wt]}));t.push({id:r,...a,containers:c,events:a.events?.length?a.events:[wt]}),e.push({id:r,x:s,y:o})}return{...i,chapters:t,graph:ke(e),metadata:{...i.metadata,version:Me}}},Fe=[{version:"3.0",migrate:_e},{version:"3.1",migrate:Pe},{version:"3.2",migrate:Be}],De=i=>Fe.reduce((t,e)=>Z(t.metadata.version,e.version)?t:e.migrate(t),i),He=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(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"})(F||(F={}));const It={metadata:"Object",chapters:"Array"},Ge="3.0.0",Ue="3.3.0",Zt=i=>{const t=Z(i,Ge);return t===-1?!1:t===0?!0:Z(i,Ue)!==1},We=i=>{if(!ht(i))return!1;for(const t in It)if(!i[t]||!G(i[t],It[t]))return!1;return Zt(i.metadata.version)},Jt=i=>i.type===He.Text;class E{constructor(t,e,...n){this.severity=t,this.category=e,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 te{listeners={};addListener(t,e){return this.listeners[t]=this.listeners[t]||[],this.listeners[t].push(e),this}on(t,e){return this.addListener(t,e)}once(t,e){this.listeners[t]=this.listeners[t]||[];const n=()=>{e(),this.off(t,n)};return this.listeners[t].push(n),this}off(t,e){return this.removeListener(t,e)}reset(){this.listeners={}}removeListener(t,e){const n=this.listeners[t];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===e){n.splice(r,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(r=>{r(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class ze{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{Ie(t)&&(this.fns.push(t),e&&this.updateFn())};removeFn=(t,e=!1)=>{this.fns=this.fns.filter(n=>n!==t),e&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(t=>t()),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 qe{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return Qe(...this.loaders[t])(e)}}function Qe(...i){return async function(e){const n=[...i];for(;n.length>0;)e=await n.shift()(e);return e}}function J(i,t,e){return i?{...i,[t]:i[t]?[e,...i[t]]:[e]}:{[t]:[e]}}function at({actions:i,errors:t,chapterId:e,...n}){if(e){const r=i.getManifest(),s=i.getChapter(r.chapters,e);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:t,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(t,at.name,"Could not find media"),actions:i}}}return{...n,errors:J(t,at.name,"Could not find chapter"),actions:i}}class St{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(t,e,n){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:n})}removeEventListener(t,e){if(!(t in this.listeners))return;const n=this.listeners[t];for(let r=0,s=n.length;r<s;r++)if(n[r].callback===e){n.splice(r,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const n=this.listeners[t.type].slice();for(let r=0,s=n.length;r<s;r++){const o=n[r];try{o.callback.call(this,t)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(t.type,o.callback)}return!t.defaultPrevented}}class ee extends St{constructor(){super(),this.listeners||St.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class Xe{constructor(){Object.defineProperty(this,"signal",{value:new ee,writable:!0,configurable:!0})}abort(t){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}let n=t;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(e)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Xe.prototype[Symbol.toStringTag]="AbortController",ee.prototype[Symbol.toStringTag]="AbortSignal");function ie(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Ye(i){typeof i=="function"&&(i={fetch:i});const{fetch:t,Request:e=t.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!ie({fetch:t,Request:e,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:t,Request:s};let s=e;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,f){let p;f&&f.signal&&(p=f.signal,delete f.signal);const b=new e(l,f);return p&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),b},s.prototype=e.prototype);const o=t;return{fetch:(c,l)=>{const f=s&&s.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(f){let p;try{p=new DOMException("Aborted","AbortError")}catch{p=new Error("Aborted"),p.name="AbortError"}if(f.aborted)return Promise.reject(p);const b=new Promise((C,L)=>{f.addEventListener("abort",()=>L(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:s}}const ut=ie({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ne=ut?Ye({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Tt=ut?ne.fetch:window.fetch;ut?ne.Request:window.Request;const Ke=async i=>{try{let t,e;if(ht(i))t=i;else if(rt(i)){e=new URL(i).href;const r=await Tt(e);if(!r.ok)return{};t=await r.json()}else return{};if(!We(t))return{};const n=t.metadata.media;if(rt(n)&&!t.media)try{let r;e?r=new URL(n,e).href:(r=new URL(n).href,e=r);const s=await Tt(r);if(!s.ok)throw new Error;t.metadata.media=await s.json()}catch{return ei(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function Ze(i){const{manifest:t,manifestURL:e}=await Ke(i),n=De(t);return n.media=Je(n.media,e),delete n.metadata.media,n}function nt(i,t){return i.find(e=>e.id===t)}function xt(i,t){return i.edit?.chapters?i.edit.chapters.find(e=>e.id===t):i.view?.chapters?i.view.chapters.find(e=>e.id===t):void 0}function Rt(i,t){return i.videos.find(e=>e.id===t)}function Je(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const r=ti(n.url,t);return{...n,url:r||n.url}})}))}}function ti(i,t){try{return new URL(i,t).href}catch{return""}}function ei(i){return Z(i,"3.2.0")>=0}const S=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pt=i=>dt(i)&&!Yt(i),et=i=>i.order==="end",ii=i=>dt(i.containers)&&!Yt(i.containers)&&et(i),ni=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e<(t.startTime??0)},At=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)},W=i=>i.some(t=>t.action.type==="expect"),Lt=i=>i.find(t=>t.action.type==="expect"),si=i=>i?.length===1,se=i=>si(i)&&Jt(i[0]),ri=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),ai=(i=[])=>i.reduce((t,e,n)=>{const r=(e?.controls??[]).filter(s=>!Jt(s));if(pt(r)){const s=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,f=[];const p=[];for(let b=0;b<t.length;b++){const C=t[b];if(p.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=s[0]&&C.range[1]>=s[1])return t[b].subjects.push(o),t;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[1]=C.range[1])}if(p.push(o),s[0]<=l&&s[1]>=c)return[{subjects:p,range:s}];a.length&&a.reverse().forEach(b=>{t.splice(b,1)}),t.push({subjects:f.concat([o]),range:s})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),oi=(i,t)=>W(i.events)?!1:t.some(({container:e})=>e.container.id!==i.id&&W(e.container.events)&&e.container.endTime===i.endTime&&!e.isRemoved);class ci extends qe{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new j(null),this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(t){this.release();const e=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:t});e.errors&&this.errorHandler(e.errors);const n=await Ze(e.result??t);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(t=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const e=await this.exec("chapterLoaders",at({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:xt,getChapter:nt,getMedia:Rt,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:t}));return e.errors&&this.errorHandler(e.errors),this.chapter=e.result.chapter,this.media=e.result.media,this.graph=e.result.graph,this}errorHandler(t){this.onError(t),console.error("Something went wrong with loaders",{errors:t})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(t=this.manifest.metadata.initChapterId){const e=nt(this.manifest.chapters,t);if(e){const n=Rt(this.manifest.media,e.videoId),r=xt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:r}}return null}getBranches(t=this.chapter.id){if(t===this.chapter.id)return this.getByBranches(this.chapter.branches);{const e=nt(this.manifest.chapters,t);return this.getByBranches(e?.branches)}}getByBranches(t=[]){return t.reduce((e,n)=>{const r=this.getByChapterId(n.chapterId);return r&&e.push(r),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter.id===this.manifest.metadata.initChapterId}isEndChapter(){return et(this.chapter)}}const li=i=>{const t=i.variants.find(e=>e.payload?.type==="vk");if(t&&"payload"in t){const[e,n]=t.payload.id.split("_");return[e,n]}return[]},y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},Ot={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function hi(){const i=new Map;function t({listId:r=Math.random().toString(),itemId:s=Math.random().toString(),...o}){const a=i.get(r),c={...o};return a?a[s]=c:i.set(r,{[s]:c}),{listId:r,itemId:s,...o}}function e(r,s){const o=i.get(r);if(o){if(s)return o[s]?.player.destroy(),o[s]?.container.remove(),o[s]?.subscription.unsubscribe(),delete o[s],Object.keys(o).length||i.delete(r),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(r),!0}else throw Error("Can't remove. Not find.")}function n(){for(const r of i)e(r[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function jt(i,t=[]){let e={},n;const r=!t.length;for(const s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:s.url}});break;case"dash":(r||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:e,thumbUrl:n,title:i.title??""}}const X=(i,t)=>{const e=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();e!==t&&n.includes(t)&&(i.setQuality(t),i.setAutoQuality(!1))},K={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},di=2;function ui(i){const t=hi();let e,n;const r=new te;let s={},o=!1,a=null,c=!1,l;i&&f(i);function f(d){a=d}function p(d,g,m){if(!a)throw Error("need to set interactive controller");const w=(t.map.get(d)??{})[g];if(w){s={chapterId:m,listId:d,itemId:g,...w};const R=s.player;n=R.info.currentQuality$.subscribe(v=>{if(!(!v||!R.info.position$.getValue())){e=v;for(const O of t.map)Object.values(O[1]).forEach(({player:N})=>{R.info.isAutoQualityEnabled$.getValue()||X(N,v)})}}),w.container.remove(),o=!1,a.setPlayer(w.player),c||(a.init(),c=!0),r.emit(K.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(m>=0&&!o){const w=a.getChapterBranches();o=!0;const R=new Set;for(const v of w)R.has(v.media.id)||(await L({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),R.add(v.media.id))}}async function C({chapter:{id:d},media:g}){if(U(s))return;n?.unsubscribe();const m=s.player.info.muted$.getValue(),x=s.player.info.currentQuality$.getValue(),w=s.player.info.isAutoQualityEnabled$.getValue(),R=s.player.info.volume$.getValue(),v=s.player.info.currentPlaybackRate$.getValue(),O=!w;let N=!1;for(const A of t.map)if(A[0]===g.id){const k=Object.keys(A[1]);for(const $ of k)$===s.itemId?(k.length<di||(N=!0),t.removePlayer(A[0],$)):(N=!0,p(A[0],$,d),O?X(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(m),s.player.setPlaybackRate(v))}else t.removePlayer(A[0]);N||(await L({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),O?X(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(m))}async function L({media:d,chapterId:g,prefetch:m=!0,setAsActive:x=!0,autoplay:w=!1,preferredExt:R,title:v,playbackRate:O}){const N=Math.random().toString(),A=document.createElement("div");l.append(A);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let $;if(a?.options?.vkVideoLoader){const q=li(d);q.length&&($=await a.options.vkVideoLoader(...q))}const ft={container:A,...$?.videos?.[0]||{sources:jt(d,R).sources},title:v},B=new ue;B.initVideo(ft);const ae=A.lastChild,mt=new tt;mt.add(B.info.position$.subscribe(function(q){b(N,B.info.duration$.getValue(),q)})).add(B.events.canplay$.subscribe(function(){k||X(B,e),O&&B.setPlaybackRate(O)})),ae&&(A.style.display="none",A.classList.add(g));const D=t.createPlayer({listId:d.id,itemId:N,player:B,container:A,sources:jt(d,R).sources,config:ft,subscription:mt});return x&&p(d.id,D.itemId,g),w&&D.player.play(),m&&!w&&D.player.prepare(),r.emit(K.playerCreated,D.player),{player:D.player,config:D.config}}function M(){u(),a=null}function u(){a?.off(y.chapterChanged,C),t.removeAll(),s={},c=!1,o=!1}async function h({container:d}){if(!a)throw Error("need to set interactive controller");u(),l=d;const{media:g,chapter:m}=a.getCurrentChapter();if(g){a.on(y.chapterChanged,C);const{player:x,config:w}=await L({media:g,chapterId:m.id,title:m.label});return r.emit(K.initiated,{container:d,media:g,chapterId:m.id}),{player:x,config:w}}else console.error("not found")}return{...t,on:r.on.bind(r),off:r.off.bind(r),init:h,setInteractiveController:f,createPlayer:L,removeAll:M,getActivePlayer:function(){return s}}}class pi{constructor({player:t,container:e,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:f}){this.container=e,this.branches=n,this.selectBranches=r,this.subscription=new tt,this.player=t,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&se(e.container.controls),this.disabledControls$=l,this.onRemove=f,this.globalEventEmitter=o,this.gameState=S.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)).add(this.disabledControls$.subscribe(t=>{t?this.container.disable?.():this.container.enable?.()}))}hide=()=>{setTimeout(()=>{this.gameState!==S.end&&(W(this.container.container.events)&&this.gameState===S.afterInteractive||this.selectBranches.state.isExpect||(this.gameState!==S.interactive&&this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===S.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const e=ri({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===S.end||this.gameState===S.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1}))},isEOV:()=>this.gameState===S.end});this.container.createView(e),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0}),this.disabledControls$.getValue()&&this.container.disable?.()}};selectContainerEvent(t=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:t?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:t}),!t&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const t=W(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!t)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=S.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[S.destroyed,S.removed].includes(this.gameState)&&!this.isPermanentText)return;const e=this.player.getExactTime();if(ni(e,this.container.container))this.gameState!==S.beforeInteractive&&(this.gameState=S.beforeInteractive,this.onBeforeStartTime());else if(At(e,this.container.container))this.gameState!==S.interactive&&(this.gameState=S.interactive,this.onStartTime());else if(this.gameState!==S.afterInteractive){const s=this.gameState;this.gameState=S.afterInteractive,s===S.interactive&&this.onEndTime()}else this.gameState!==S.destroyed&&!this.isPermanentText&&this.removeView();const n=At(e,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=S.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=S.removed,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=S.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}}function fi(){const i={};function t(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function e(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 r({timestamp:a,priority:c,initiator:l}){if(Ct(a)){const f=i[a]??null;if(f&&Q(c,!0)){let p={};const b=f[c];return b&&(p={...p,...b}),p=U(p)?null:p,p&&Q(l,!0)?p[l]??null:p}return f}return null}function s({timestamp:a,priority:c,initiator:l}){if(Ct(a))if(i[a]){if(Q(c,!0))if(i[a][c]){if(Q(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!U(i[a][c]))return!0}else return!1;if(delete i[a][c],!U(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...f}){i[a]?.[c]?.[l]?i[a][c][l].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...f}]}}:i[a]={[c]:{[l]:[{...f}]}}}return{map:i,remove:s,add:o,removeAll:t,get:r,getLte:e,getGte:n}}const mi=[I.expect,I.setNextBranch],yi=1/0;function Nt(i){let t=i,e;const n=gi(),r=new fi;let s;const o=()=>{b(),u()},a=h=>{r.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),mi.includes(d.actionType))break},l=(h=1/0)=>{const d=Y(r.get({timestamp:h,priority:"control"})??{}),g=Y(r.get({timestamp:h,priority:"container"})??{}),m=Y(r.get({timestamp:h,priority:"chapter"})??{});return[...d,...g,...m]},f=h=>{n.isReady(h)&&c(l(h))},p=()=>{c([...Y(r.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{e&&(s?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{f(1/0)}),s=t.events.ended$.subscribe(e))},L=h=>{b(),t=h},M=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},u=()=>{n.release(),r.removeAll()};return{setPlayer:L,add:a,remove:M,exec:f,execEndOfVideo:p,listen:C,unlisten:b,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function gi(){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??yi,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(t=>t.actionType===I.expect?-1:1)}const vi=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=t.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=r/s;let c,l;return a>o?(l=s,c=s*o):a<o?(l=r/o,c=r):(l=s,c=r),{videoContentWidth:l,videoContentHeight:c}},bi=250;function Ci(i){let t=()=>{};const e=new ResizeObserver(a=>{s(a),t=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:p}=vi(c,l);c.style.setProperty("--interactive-content-width",`${f}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 r(){const{parentElement:a}=i();a.removeAttribute("style")}const s=Qt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},bi);function o(){t=void 0,e.disconnect(),r()}return{resizeObserver:e,calc:()=>{t()},release:o}}class Ei{constructor(){this.map={}}push(t,e){t in this.map?this.map[t].push(e):this.map[t]=[e]}get(t){const e=this.map[t];return e?e.slice():null}getAll(){const t=[];for(const e in this.map)t.push(...this.map[e]);return t}remove(t,e){t in this.map&&(this.map[t]=this.map[t].filter(n=>n!==e),this.map[t].length===0&&delete this.map[t])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const wi=i=>Math.floor(Math.random()*i),Ii=i=>{let t=i.length,e=1/0,n=null;for(;t--;)i[t].weight<e&&(e=i[t].weight,n=i[t]);return n},Si=i=>{let t=i.length,e=-1/0,n=null;for(;t--;)i[t].weight>e&&(e=i[t].weight,n=i[t]);return n},Ti=i=>{const t=i.length,e=wi(t);return i[e]},Vt=1,xi=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??Vt;const e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??Vt,t>=e)return i[n];return i[i.length-1]},_t=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),st=(i,t=!1)=>({...i,args:t?{...i.args,..._t}:{..._t,...i.args}}),$t=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:g,branches:m=[],onEvent:x,isEOV:w=()=>!1,isDisabled:R=()=>!1})=>{const v=st(u,w()),O={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},N=R(),A=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:N?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:g,...v.args}});if(N){A();return}switch(v.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const k=m.find($=>$.id===v.args.branchId);if(!k)return;x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?L({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...O,action:L.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...O,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case I.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?M({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...O,action:M.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:u,container:{id:h,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:x=!1})=>{const w=st(u,m),R={timestamp:!w.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:h,actionType:w.type},v=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"container",type:T.actionChoice,actionType:w.type,payload:w.args});switch(w.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const O=g.find(N=>N.id===w.args.branchId);if(!O)return;v(),e.add({...R,action:L.bind(null,{subjectId:h,subjectName:"container",action:w,payload:{chapterId:O.chapterId,autoSelect:x}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{v(),e.add({...R,action:C.bind(null,{subjectId:h,subjectName:"container",action:w})});return}case I.openURI.trim().toLowerCase():{v(),e.add({...R,action:M.bind(null,{subjectId:h,subjectName:"container",action:w,payload:{URI:u.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:u,branches:h,isEOV:d=!1}){const g=Lt(u.events);if(g){const m=st(g.action,d);i.emit(y.interactives,{subjectId:u.id,subjectName:"container",type:T.actionChoice,actionType:m.type,payload:m.args}),e.add({timestamp:d?1/0:u.endTime,priority:"container",initiator:u.id,actionType:I.expect,action:p.bind(null,{subjectId:u.id,subjectName:"container"})}),r.isExpect=!0}else for(const m of u.events)a({action:m.action,container:u,branches:h,isEOV:d})}const l=({chapterId:u,action:h,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:u,subjectName:"chapter",type:T.actionChoice,actionType:h.type,payload:h.args});switch(h.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const m=d.find(x=>x.id===h.args.branchId);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{const m=Ti(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{const m=xi(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{const m=Si(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{const m=Ii(d);return m?.chapterId?(g(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case I.openURI.trim().toLowerCase():return g(),M.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function f(u){const h=Lt(u.events);if(h){if(et(u))return;i.emit(y.interactives,{subjectId:u.id,subjectName:"chapter",type:T.actionChoice,actionType:h.action.type,payload:h.action.args}),e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:I.expect,action:p.bind(null,{subjectId:u.id,subjectName:"chapter"})})}else u.events.forEach(d=>{const g=l({chapterId:u.id,action:d.action,branches:u.branches});g&&e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:d.action.type,action:g})})}const p=({subjectId:u,subjectName:h,action:d})=>{t.pause(),i.emit(y.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:d?.type??I.expect})},b=({subjectId:u,subjectName:h})=>{t.info.isEnded$.getValue()?e.execEndOfVideo():t.play(),i.emit(y.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:u,subjectName:h,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:g.type})},L=({subjectId:u,subjectName:h,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:g.type,payload:m})},M=({subjectId:u,subjectName:h,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const x=window.open(m.URI,"_blank","noopener,noreferrer");x&&(x.opener=null),i.emit(y.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:p,expectEventHandler:b,setManifestChapterEvents:f,setManifestContainerEvents:c,stopExpect:s,state:r}},Pt=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const r=t.chapters.find(o=>o.id===n);if(!r)return null;const s=t.media.videos.find(o=>r.videoId===o.id);if(!s)return null;e[n]=re(s)}return e[n]}).filter(Boolean)},Ri=i=>{for(const t of i.variants)if(Ai(t)&&"payload"in t)return t.payload.id},Ai=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",re=i=>{const t=Ri(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},Li=(i,t)=>{for(const e of i.media.videos)if(t===re(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},Oi=(i,t)=>i.reduce((e,n)=>{const r=Li(t,n);return r?[...e,r]:e},[]),ji=100;class Ni{state={history$:new j([]),hasPrevChapter$:new j(!1),prevChapter$:new j(null),isInitialChapter$:new j(!1),isGoBackLimited$:new j(!1)};#s=null;#n;#h=!1;#i=null;#u=null;#o=null;#r=null;#l=null;#t=null;#d=new tt;#p=!1;#a=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:r,historyParams:s,initChapterId:o}){this.#r=e,this.#t=t,this.#l=n,this.#s=r,this.#o=o,this.#n={maxLength:s?.maxLength||ji},this.state?.history$&&this.#d&&this.#d?.add(this.state?.history$.subscribe(a=>{this.state?.prevChapter$.next(a.at(-2)||null),this.state?.hasPrevChapter$.next(a.length>1),this.state?.isInitialChapter$.next(this.getInitialChapterId()===this.#i?.metadata?.initChapterId),this.state?.isGoBackLimited$.next(this.#a===this.#n.maxLength-1)}))}async setManifest(t){!this.#l||!this.#t||(this.#i=t,await this.getProjectHistory(),await this.#l.setChapter({chapterId:this.getInitialChapterId(),pushToHistory:!1}),this.#h||(this.#h=!0,this.#t.emit(y.historyInited,{initChapterId:this.getInitialChapterId()})))}get inited(){return this.#h}async updateHistory(t,e=!0){if(!this.#i)return;this.#p?(this.#p=!1,this.#a++):this.#a=0;const n=this.#i,r=t.length-this.#n.maxLength,s=r>0?t.slice(r):t,o=Pt(s,n);if(this.#u=o,this?.state?.history$.next(s),!(!e||!this.#s||!this.#r))try{await this.#s.save(this.#r,o)}catch{this.#t?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#l)return this.#t?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Cannot go back because HistoryController has not been initialized"));this.#p=!0;const t=this.state.history$.getValue().slice(0,-1),e=t.pop();this.state.history$.next(t),await this.#l.setChapter({chapterId:e})}async getProjectHistory(){if(!this.#i||!this.#r)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#s)try{const r=await this.#s.get(this.#r);r.length&&(e=r)}catch{this.#t?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Error while trying to fetch data"))}const n=Oi(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#o||this.#i?.metadata.initChapterId}getInitialVideoId(){if(this.#i){const t=this.getInitialChapterId();return Pt([t],this.#i).pop()}return null}destroy(){this.state=null,this.#r=null,this.#s=null,this.#l=null,this.#d?.unsubscribe(),this.#d=null,this.#h=!1,this.#t?.emit(y.historyDestroyed),this.#t=null}}class H{constructor(t,e,n,r){this.target=t,this.type=e,this.listener=n,this.options=H.#s(t,r),this.target.addEventListener(e,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#s(t,e){if(e===void 0)return!1;if(typeof e=="boolean")return e;{const n=new Set(["passive","capture"]),r=Object.keys(e).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),H.#h(t)?e:e.capture||!1}}static#n=void 0;static#h(t){let e=H.#n;if(e===void 0){e=!1;try{const n={},r={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};t.addEventListener("test",s,n),t.removeEventListener("test",s,n)}catch{e=!1}H.#n=e}return e||!1}}class Vi{constructor(){this.bindingMap=new Ei}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,r){if(!this.bindingMap)return;const s=new H(t,e,n,r);this.bindingMap.push(e,s)}listenOnce(t,e,n,r){const s=o=>{this.unlisten(t,e,s),n(o)};this.listen(t,e,s,r)}unlisten(t,e,n){if(!this.bindingMap)return;const r=this.bindingMap.get(e)||[];for(const s of r)s.target===t&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(e,s))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class _i{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 t=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!t)return!1;const e=t.data,n=e.length;for(let r=3;r<n;r+=40)if(e[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(t){this.canvasImgSrc=t}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(t,e=!1){const n=t.width+t.height;if(this._prevSizeId===n)return;let r;e&&(r=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&r&&this.restore(r),this._prevSizeId=n}async save(){const t=this.rootElement.toDataURL("image/jpeg",1),e=new Image;return e.crossOrigin="anonymous",e.src=t,await e.decode(),e}restore(t){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(t,0,0,this.rootElement.width,this.rootElement.height)}}class $i{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:t,endOffsetMs:e=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
7
7
|
position: absolute;
|
|
8
8
|
top: 0;
|
|
9
9
|
left: 0;
|
|
@@ -20,4 +20,4 @@ import{loadVKLangPack as oe,ValueSubject as j,Subscription as tt,Observable as y
|
|
|
20
20
|
position: absolute;
|
|
21
21
|
top: 0;
|
|
22
22
|
left: 0;
|
|
23
|
-
`,i}class Hi{#r=null;#s=null;#h=null;#i=null;#u=null;#n=null;#a=null;#o=null;#t=null;#d=new j(!1);#p=new Set;#l=null;#g=null;#c=null;#e=null;#f=je();state={prevChapter$:new j(null),isInitialChapter$:new j(!1),isEndChapter$:new j(!1),isInteractiveExpectation$:new j(!1),calledByInteractive$:new j(!1),lastChapterChangeWasInitiatedByInteractive$:new j(!1),disabledControls$:new j(!1)};constructor(t){this.options={...Mi,...t},this.#s=[],this.factories=new Map([["choice",qt]]),this.rootElement=ki(),this.options.parentElement.append(this.rootElement),this.#e=new te,this.#u=new tt,this.#h=new Vi,this.#i=new Ni({interactiveController:this,globalEventEmitter:this.#e,videoId:this.options.projectInfo?.videoId,historyApi:this.options.historyApi,historyParams:this.options.historyParams}),this.options.lastFrame&&(this.#c=new $i({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:e=>this.#e.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.SEAMLESS,e))})),this.#h.listen(this.rootElement,"mousedown",e=>e.stopPropagation()),this.#h.listen(this.rootElement,"mouseup",e=>e.stopPropagation()),this.#t=new ci(this.options.loaders,e=>this.#e.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.MANIFEST,e))),this.#n=Nt(this.options.player),this.#a=new ze,this.#o=$t({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#e,removeControllers:this.#m}),this.#r=Ci(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#c.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#l=new Ae({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:e=>{this.setChapter({chapterId:e}),this.#e.emit(y.graph,{type:Ot.watchAgainClicked,chapterId:e})},onError:e=>this.#e.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.LOADERS,{message:e}))})),this.#E(this.options.initSeamless),this.isFirstChapterFetched=!1,this.appState=P.created}emitPlayerChanged=t=>{setTimeout(()=>{this.#e.emit(y.playerChanged,t)})};#E(t=!1){this.#e.on(y.historyInited,async({initChapterId:e,videosInfo:n=[]})=>{t&&await this.#w({initialChapter:e,videosInfo:n})}),this.#e.on(y.interactives,async e=>{if(e.type===T.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){const{chapterId:r}=e.payload;this.setChapter({chapterId:r})}if(e.payload?.behaviour==="change-manifest"){const{manifestURL:r}=e.payload;this.setManifest(r)}const n=e.type==="action-execution";n&&e.actionType==="expect"?this.state.isInteractiveExpectation$.next(!0):n&&e.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!1)}}),this.#e.on(y.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})}async#w({source:t,videosInfo:e=[]}){this.#g=ui(this);const n=document.createElement("div");this.#g.on(K.activePlayerChanged,this.emitPlayerChanged);const{player:r,config:s}=await this.#g.init({source:t,initialChapter:this.#i.getInitialChapterId(),container:n});return this.updateGraphVideosInfo(e),{player:r,config:s}}getStatEvents(){return{click$:new yt(t=>{this.#e.on(y.graph,({type:e,visibility:n})=>{e==="visibility"&&t.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),e==="watchAgainClicked"&&t.next(F.WATCH_AGAIN)}),this.#e.on(y.interactives,({type:e,subjectName:n,subjectType:r})=>{e!=="action-choice"||n!=="control"||(r==="Button"&&t.next(F.GO_NEXT_BUTTON),r==="Area"&&t.next(F.GO_NEXT_AREA))})}),nextMovie$:new yt(t=>{this.#e.on(y.playerChanged,({config:e})=>{e?.unitedVideoId&&t.next(e.unitedVideoId)})})}}setPlayer(t){this.#v(),this.options.player=t,this.#f.setPlayer(this.options.player),this.#n?this.#n.setPlayer(this.options.player):this.#n=Nt(this.options.player),this.#o=$t({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#e,removeControllers:()=>this.#m(!1)}),this.appState===P.initiated&&(this.#b(),this.#y(this.#t.chapter))}async setManifest(t){this.#v(),this.isFirstChapterFetched=!1;const e=await this.#t.setManifest(t);return this.#l&&await this.#l.handleManifestChange(e.manifest),await this.#i.setManifest(e.manifest),this.#e.emit(y.manifestChanged,{manifest:e.manifest}),this.#y(this.#t.chapter),e.manifest}setVisitedChapters(t){Array.isArray(t)&&this.#l?.setVisitedChapters(t)}updateGraphVideosInfo(t){Array.isArray(t)&&this.#l?.updateVideosInfo(t)}async setChapter({chapterId:t,pushToHistory:e=!0}={}){this.#v(),this.#c&&this.isFirstChapterFetched&&(this.#c.draw(),this.#c.show()),ce().browser===le.Safari&&await Pi(35);const r=await(t?this.#t.setNext(t):this.#t.setInitial()),{chapter:s,media:o,graph:a}=r;return e&&this.#R(s.id),this.state.isInitialChapter$.next(this.#t.isInitialChapter()),this.state.isEndChapter$.next(this.#t.isEndChapter()),this.#l&&this.#l.handleChapterChange(a),this.#c?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(y.chapterChanged,{chapter:s,media:o,graph:a}),this.#y(this.#t.chapter),this.#p=new Set,this.isFirstChapterFetched=!0,{chapter:s,media:o,graph:a}}toggleGraphView(t=!0){this.#l&&(t?(this.#l.show(),this.#d.next(!1)):(this.#l.hide(),this.#C()),this.#e.emit(y.graph,{type:Ot.visibility,visibility:t}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===P.created&&(this.#r.resizeObserver.observe(this.options.fullscreenTargetElement),this.#b(),this.appState=P.initiated,this.#y(this.#t.chapter))}#v(){this.appState===P.ready&&(this.#m(),this.#s=[],this.#a.release(),this.#n?.release(),this.appState=P.initiated,this.#d.next(!1))}#A=()=>{this.#a.fns.forEach(n=>n());const t=this.options.player.info.position$.getValue()*1e3,e=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(t));for(const n of e){this.#n.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#n.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#s.find(r=>r.container.container.id===n.id).reset()}};#I=()=>{this.#r.calc(),this.#a.requestAnimation()};#S(t){(!this.#l||this.#l.isHidden)&&this.#C();const e=t*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>e>=s[1]);if(r){const s=r.range.join("-");this.#p.has(s)||(this.#p.add(s),this.#e.emit(y.interactives,{type:T.rangeEnded,payload:r,visibility:!0}))}}deadEndCheck(){return!(this.#n?.getPreparedToExecActions()??[]).some(n=>n.actionType===I.setNextBranch)}allControlsAreRemoved(){return!this.#s.some(e=>!e.container.isRemoved)}isEndedExpectation(){if(!this.options?.player||!this.#s)return!1;const t=this.options.player.info.position$.getValue(),e=this.options.player.info.duration$.getValue();return t===e&&this.#s.some(n=>{const r=n.container.container;return!r.isRemoved&&r.endTime===null&&W(r.events)})}#b(){this.#u.unsubscribe(),this.#u.add(this.options.player.events.started$.pipe(he()).subscribe(this.#I)).add(this.options.player.events.playing$.subscribe(this.#a.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#a.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#S.bind(this))).add(this.#t.prevChapter$.subscribe(t=>this.state.prevChapter$.next(t))),this.options.lastFrame&&this.#u.add(this.options.player.info.duration$.subscribe(t=>{this.#c.setVideoDuration(t*1e3)})).add(this.options.player.experimental.element$.subscribe(t=>{t&&this.#c.setVideoElement(t)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#c.reset(),setTimeout(()=>{this.#c.hide(),this.#c.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#c.onSeek))}#m=(t=!0)=>{this.#s.forEach(e=>{!t&&e.isPermanentText||(this.#a.removeFn(e.whilePlaying),e.destroy())})};#y(t){this.#t.chapter&&this.appState===P.initiated&&(this.#o.setManifestChapterEvents(t),this.#s=this.#T(t),this.#n.containersEventsCallState.setData(t.containers),this.#f.setContainers(this.#s.map(e=>e.container.container).filter(e=>!se(e.controls))),this.options.lastFrame&&this.#a.addFn(()=>{this.#c.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.appState=P.ready)}#T(t){return t?.containers?.reduce((e,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new pi({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#o,interactiveEvents:this.#n,globalEventEmitter:this.#e,ignoreContainerEvent:()=>oi(n,this.#s),permanentTextControls:this.options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.#f.deleteContainer(n.id)}});return this.#a.addFn(o.whilePlaying,!0),[...e,o]}return[...e]},[])??[]}#C(){if(this.state.isInteractiveExpectation$.getValue()){this.#d.next(!1);return}const e=this.#d.getValue(),n=!!this.#f.getNextInteractiveTime();(n&&!e||!n&&e)&&this.#d.next(!e)}#x(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}#R(t){if(this.#x(),!this.#i.inited)return;const e=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&et(n)&&ii(n))??!1,s=this.#t.manifest.metadata.initChapterId===t,o=this.#i.state.history$.getValue();if(s||r&&e){this.#i.updateHistory([t]);return}o.at(-1)!==t&&this.#i.updateHistory([...o,t])}playPrevChapter(){this.#i?.goBack()}setDisabledControls(t){this.state.disabledControls$.next(t)}isSupport(t=this.#t.manifest){return Zt(t.metadata.version)}getInitialVideoInfo(){return{videoId:this.#i.getInitialVideoId(),chapterId:this.#i.getInitialChapterId()}}getHistoryState(){return this.#i.state}getIsSeekable(){return this.#d}getInteractiveRanges(){return ai(this.#t.chapter?.containers)}getNextInteractiveStartTime(t){return this.#f.getNextInteractiveTime(t)}getChapterBranches(t){return this.#t.getBranches(t)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(t,e){this.factories.set(t.trim().toLowerCase(),e)}removeFactory(t){this.factories.delete(t.trim().toLowerCase())}on(...t){return this.#e.on(...t),this}off(...t){return this.#e.off(...t),this}once(...t){return this.#e.once(...t),this}destroy(){this.#m(),this.#s=void 0,this.state=void 0,this.#l?.destroy(),this.#l=void 0,this.#r.release(),this.#r=void 0,this.#o=void 0,this.#a.release(),this.#a=void 0,this.#n.release(),this.#n=void 0,this.#t.release(),this.#o=void 0,this.#h.release(),this.#h=void 0,this.#u.unsubscribe(),this.#u=void 0,this.#e.reset(),this.#e=void 0,this.#c?.destroy(),this.#c=void 0,this.rootElement.remove(),this.rootElement=void 0,this.#i.destroy(),this.#i=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=P.destroyed}}const Gi={Container:zt,createChoiceContainer:qt,createAreaControl:Gt,createButtonControl:Ut,createRelativeLayout:Ee,getRootEl:kt,classnamesPrefix:V},Ui={version:pe};export{E as CustomError,y as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Hi as Interactives,ci as ManifestController,Ui as SDKInfo,Pt as chapterIdsToVKVideoIds,Z as compareVersions,Li as getChapterIdByVkVideoId,re as getVKVideoIdByMedia,Ri as getVideoRawIdByMedia,Ot as graphEventTypes,ii as hasEndTemplate,T as interactivesEventTypes,et as isLastChapter,Zt as isSupportedManifest,Ai as isVKVariantItem,Gi as utils,Oi as vkVideoIdsToChapterIds};
|
|
23
|
+
`,i}class Hi{#s=null;#n=null;#h=null;#i=null;#u=null;#o=null;#r=null;#l=null;#t=null;#d=new j(!1);#p=new Set;#a=null;#g=null;#c=null;#e=null;#f=je();state={prevChapter$:new j(null),isInitialChapter$:new j(!1),isEndChapter$:new j(!1),isInteractiveExpectation$:new j(!1),calledByInteractive$:new j(!1),lastChapterChangeWasInitiatedByInteractive$:new j(!1),disabledControls$:new j(!1)};constructor(t){this.options={...Mi,...t},this.#n=[],this.factories=new Map([["choice",qt]]),this.rootElement=ki(),this.options.parentElement.append(this.rootElement),this.#e=new te,this.#u=new tt,this.#h=new Vi,this.#i=new Ni({interactiveController:this,globalEventEmitter:this.#e,videoId:this.options.projectInfo?.videoId,historyApi:this.options.historyApi,historyParams:this.options.historyParams,initChapterId:this.options.initChapterId}),this.options.lastFrame&&(this.#c=new $i({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:e=>this.#e.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.SEAMLESS,e))})),this.#h.listen(this.rootElement,"mousedown",e=>e.stopPropagation()),this.#h.listen(this.rootElement,"mouseup",e=>e.stopPropagation()),this.#t=new ci(this.options.loaders,e=>this.#e.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.MANIFEST,e))),this.#o=Nt(this.options.player),this.#r=new ze,this.#l=$t({player:this.options.player,interactiveEvents:this.#o,globalEventEmitter:this.#e,removeControllers:this.#m}),this.#s=Ci(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#c.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#a=new Ae({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:e=>{this.setChapter({chapterId:e}),this.#e.emit(y.graph,{type:Ot.watchAgainClicked,chapterId:e})},onError:e=>this.#e.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.LOADERS,{message:e}))})),this.#E(this.options.initSeamless),this.isFirstChapterFetched=!1,this.appState=P.created}emitPlayerChanged=t=>{setTimeout(()=>{this.#e.emit(y.playerChanged,t)})};#E(t=!1){this.#e.on(y.historyInited,async({initChapterId:e,videosInfo:n=[]})=>{t&&await this.#w({initialChapter:e,videosInfo:n})}),this.#e.on(y.interactives,async e=>{if(e.type===T.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){const{chapterId:r}=e.payload;this.setChapter({chapterId:r})}if(e.payload?.behaviour==="change-manifest"){const{manifestURL:r}=e.payload;this.setManifest(r)}const n=e.type==="action-execution";n&&e.actionType==="expect"?this.state.isInteractiveExpectation$.next(!0):n&&e.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!1)}}),this.#e.on(y.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})}async#w({source:t,videosInfo:e=[]}){this.#g=ui(this);const n=document.createElement("div");this.#g.on(K.activePlayerChanged,this.emitPlayerChanged);const{player:r,config:s}=await this.#g.init({source:t,initialChapter:this.#i.getInitialChapterId(),container:n});return this.updateGraphVideosInfo(e),{player:r,config:s}}getStatEvents(){return{click$:new yt(t=>{this.#e.on(y.graph,({type:e,visibility:n})=>{e==="visibility"&&t.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),e==="watchAgainClicked"&&t.next(F.WATCH_AGAIN)}),this.#e.on(y.interactives,({type:e,subjectName:n,subjectType:r})=>{e!=="action-choice"||n!=="control"||(r==="Button"&&t.next(F.GO_NEXT_BUTTON),r==="Area"&&t.next(F.GO_NEXT_AREA))})}),nextMovie$:new yt(t=>{this.#e.on(y.playerChanged,({config:e})=>{e?.unitedVideoId&&t.next(e.unitedVideoId)})})}}setPlayer(t){this.#v(),this.options.player=t,this.#f.setPlayer(this.options.player),this.#o?this.#o.setPlayer(this.options.player):this.#o=Nt(this.options.player),this.#l=$t({player:this.options.player,interactiveEvents:this.#o,globalEventEmitter:this.#e,removeControllers:()=>this.#m(!1)}),this.appState===P.initiated&&(this.#b(),this.#y(this.#t.chapter))}async setManifest(t){this.#v(),this.isFirstChapterFetched=!1;const e=await this.#t.setManifest(t);return this.#a&&await this.#a.handleManifestChange(e.manifest),await this.#i.setManifest(e.manifest),this.#e.emit(y.manifestChanged,{manifest:e.manifest}),this.#y(this.#t.chapter),e.manifest}setVisitedChapters(t){Array.isArray(t)&&this.#a?.setVisitedChapters(t)}updateGraphVideosInfo(t){Array.isArray(t)&&this.#a?.updateVideosInfo(t)}async setChapter({chapterId:t,pushToHistory:e=!0}={}){this.#v(),this.#c&&this.isFirstChapterFetched&&(this.#c.draw(),this.#c.show()),ce().browser===le.Safari&&await Pi(35);const r=await(t?this.#t.setNext(t):this.#t.setInitial()),{chapter:s,media:o,graph:a}=r;return e&&this.#R(s.id),this.state.isInitialChapter$.next(this.#t.isInitialChapter()),this.state.isEndChapter$.next(this.#t.isEndChapter()),this.#a&&this.#a.handleChapterChange(a),this.#c?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(y.chapterChanged,{chapter:s,media:o,graph:a}),this.#y(this.#t.chapter),this.#p=new Set,this.isFirstChapterFetched=!0,{chapter:s,media:o,graph:a}}toggleGraphView(t=!0){this.#a&&(t?(this.#a.show(),this.#d.next(!1)):(this.#a.hide(),this.#C()),this.#e.emit(y.graph,{type:Ot.visibility,visibility:t}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===P.created&&(this.#s.resizeObserver.observe(this.options.fullscreenTargetElement),this.#b(),this.appState=P.initiated,this.#y(this.#t.chapter))}#v(){this.appState===P.ready&&(this.#m(),this.#n=[],this.#r.release(),this.#o?.release(),this.appState=P.initiated,this.#d.next(!1))}#A=()=>{this.#r.fns.forEach(n=>n());const t=this.options.player.info.position$.getValue()*1e3,e=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(t));for(const n of e){this.#o.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#o.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#n.find(r=>r.container.container.id===n.id).reset()}};#I=()=>{this.#s.calc(),this.#r.requestAnimation()};#S(t){(!this.#a||this.#a.isHidden)&&this.#C();const e=t*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>e>=s[1]);if(r){const s=r.range.join("-");this.#p.has(s)||(this.#p.add(s),this.#e.emit(y.interactives,{type:T.rangeEnded,payload:r,visibility:!0}))}}deadEndCheck(){return!(this.#o?.getPreparedToExecActions()??[]).some(n=>n.actionType===I.setNextBranch)}allControlsAreRemoved(){return!this.#n.some(e=>!e.container.isRemoved)}isEndedExpectation(){if(!this.options?.player||!this.#n)return!1;const t=this.options.player.info.position$.getValue(),e=this.options.player.info.duration$.getValue();return t===e&&this.#n.some(n=>{const r=n.container.container;return!r.isRemoved&&r.endTime===null&&W(r.events)})}#b(){this.#u.unsubscribe(),this.#u.add(this.options.player.events.started$.pipe(he()).subscribe(this.#I)).add(this.options.player.events.playing$.subscribe(this.#r.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#r.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#S.bind(this))).add(this.#t.prevChapter$.subscribe(t=>this.state.prevChapter$.next(t))),this.options.lastFrame&&this.#u.add(this.options.player.info.duration$.subscribe(t=>{this.#c.setVideoDuration(t*1e3)})).add(this.options.player.experimental.element$.subscribe(t=>{t&&this.#c.setVideoElement(t)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#c.reset(),setTimeout(()=>{this.#c.hide(),this.#c.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#c.onSeek))}#m=(t=!0)=>{this.#n.forEach(e=>{!t&&e.isPermanentText||(this.#r.removeFn(e.whilePlaying),e.destroy())})};#y(t){this.#t.chapter&&this.appState===P.initiated&&(this.#l.setManifestChapterEvents(t),this.#n=this.#T(t),this.#o.containersEventsCallState.setData(t.containers),this.#f.setContainers(this.#n.map(e=>e.container.container).filter(e=>!se(e.controls))),this.options.lastFrame&&this.#r.addFn(()=>{this.#c.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.appState=P.ready)}#T(t){return t?.containers?.reduce((e,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new pi({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#l,interactiveEvents:this.#o,globalEventEmitter:this.#e,ignoreContainerEvent:()=>oi(n,this.#n),permanentTextControls:this.options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.#f.deleteContainer(n.id)}});return this.#r.addFn(o.whilePlaying,!0),[...e,o]}return[...e]},[])??[]}#C(){if(this.state.isInteractiveExpectation$.getValue()){this.#d.next(!1);return}const e=this.#d.getValue(),n=!!this.#f.getNextInteractiveTime();(n&&!e||!n&&e)&&this.#d.next(!e)}#x(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}#R(t){if(this.#x(),!this.#i.inited)return;const e=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&et(n)&&ii(n))??!1,s=this.#t.manifest.metadata.initChapterId===t,o=this.#i.state.history$.getValue();if(s||r&&e){this.#i.updateHistory([t]);return}o.at(-1)!==t&&this.#i.updateHistory([...o,t])}playPrevChapter(){this.#i?.goBack()}setDisabledControls(t){this.state.disabledControls$.next(t)}isSupport(t=this.#t.manifest){return Zt(t.metadata.version)}getInitialVideoInfo(){return{videoId:this.#i.getInitialVideoId(),chapterId:this.#i.getInitialChapterId()}}getHistoryState(){return this.#i.state}getIsSeekable(){return this.#d}getInteractiveRanges(){return ai(this.#t.chapter?.containers)}getNextInteractiveStartTime(t){return this.#f.getNextInteractiveTime(t)}getChapterBranches(t){return this.#t.getBranches(t)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(t,e){this.factories.set(t.trim().toLowerCase(),e)}removeFactory(t){this.factories.delete(t.trim().toLowerCase())}on(...t){return this.#e.on(...t),this}off(...t){return this.#e.off(...t),this}once(...t){return this.#e.once(...t),this}destroy(){this.#m(),this.#n=void 0,this.state=void 0,this.#a?.destroy(),this.#a=void 0,this.#s.release(),this.#s=void 0,this.#l=void 0,this.#r.release(),this.#r=void 0,this.#o.release(),this.#o=void 0,this.#t.release(),this.#l=void 0,this.#h.release(),this.#h=void 0,this.#u.unsubscribe(),this.#u=void 0,this.#e.reset(),this.#e=void 0,this.#c?.destroy(),this.#c=void 0,this.rootElement.remove(),this.rootElement=void 0,this.#i.destroy(),this.#i=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=P.destroyed}}const Gi={Container:zt,createChoiceContainer:qt,createAreaControl:Gt,createButtonControl:Ut,createRelativeLayout:Ee,getRootEl:kt,classnamesPrefix:V},Ui={version:pe};export{E as CustomError,y as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Hi as Interactives,ci as ManifestController,Ui as SDKInfo,Pt as chapterIdsToVKVideoIds,Z as compareVersions,Li as getChapterIdByVkVideoId,re as getVKVideoIdByMedia,Ri as getVideoRawIdByMedia,Ot as graphEventTypes,ii as hasEndTemplate,T as interactivesEventTypes,et as isLastChapter,Zt as isSupportedManifest,Ai as isVKVariantItem,Gi as utils,Oi as vkVideoIdsToChapterIds};
|