@vkontakte/videoplayer-interactive 1.0.11-dev.b4747814.0 → 1.0.11-dev.b72fcea2.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/esnext.cjs.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.11-dev.b4747814.0
3
- * Thu, 30 May 2024 12:04:59 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.11-dev.b72fcea2.0
3
+ * Fri, 31 May 2024 10:56:17 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-11/doc/
5
5
  */
6
- "use strict";var pe=Object.create;var bt=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var ve=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ge.call(i,s)&&s!==e&&bt(i,s,{get:()=>t[s],enumerable:!(n=fe(t,s))||n.enumerable});return i};var be=(i,t,e)=>(e=i!=null?pe(ye(i)):{},ve(t||!i||!i.__esModule?bt(e,"default",{value:i,enumerable:!0}):e,i));var E=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),Ce=require("uuid"),Ee=require("@vkontakte/videoplayer-core/esnext.cjs.js");const Ie="1.0.11-dev.b4747814.0";function Bt(i,t=1){let e="0",n="0",s="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+s},${t})`}const N="SDK_NAME",we="SDK_NAME-controls-container",Ft=()=>document.querySelector(`.${we}`),Se=.4,_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},Ct={top:"flex-start",bottom:"flex-end",center:"center"},Et={start:"flex-start",end:"flex-end",center:"center"},It={start:"left",end:"right",center:"center"},Dt=({target:i,props:t})=>{i.style.alignItems=Ct[t?.text?.gravityVertical]??Ct.center,i.style.justifyContent=Et[t?.text?.gravityHorizontal]??Et.center,i.style.textAlign=It[t?.text?.alignment]??It.start},Gt=({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},Ht=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Bt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ut=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Bt(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)`},tt="int",ct={AREA:`${tt}_area`,TEXT:`${tt}_text`,BUTTON:`${tt}_bttn`};class lt{constructor(t){this.control=t}createView(t){const e=document.createElement("div");e.classList.add(`${N}-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",r=>{r.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Wt=i=>{if(i.type.trim().toLowerCase()==="area")return new Te(i)};class Te extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");return r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.AREA),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ht({target:r,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Ut({target:r,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),ot({target:r,layoutParams:this.control.layoutParams,fallback:_}),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const zt=i=>{if(i.type.trim().toLowerCase()==="button")return new Re(i)};class Re extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");r.type="button",r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.BUTTON),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",ot({target:r,layoutParams:this.control.layoutParams,fallback:_}),Ht({target:r,props:this.control.props,fallback:_}),Ut({target:r,props:this.control.props,fallback:_,dependsOn:n}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:_,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const xe=i=>{if(i.type.trim().toLowerCase()==="text")return new Ae(i)};class Ae extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("div");r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.TEXT),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:r,layoutParams:this.control.layoutParams,fallback:_}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:_,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){}enable(){}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class Ve{constructor(t){this.layout=t}}const Le=i=>{if(i.type.trim().toLowerCase()==="relative")return new qt(i)};class qt extends Ve{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 Kt{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.#n()}#n(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...t,s(e)]:[...t]},[])}}const Qt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new je(i,t)};class je extends Kt{constructor(t,e){super(t),this.rootElement=e??Ft(),this.layout=new qt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",zt),this.addControlFactory("text",xe),this.addControlFactory("area",Wt)}createView(t){const e=document.createElement("div");return e.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const s=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(s,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=Se,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Xt(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),nt=i=>G(i,z.String),dt=i=>G(i,z.Array),Yt=i=>G(i,z.Number),Oe=i=>G(i,z.Function),wt=i=>Yt(i)&&!isNaN(i),H=i=>ht(i)&&Object.keys(i).length===0,Zt=i=>dt(i)&&!i.length,Q=(i,t)=>nt(i)&&(t?i.trim():i).length,Jt=window.navigator.userAgent.toLowerCase(),Ne=/mobi/i.test(Jt);Jt.indexOf("android")>-1;const _e="video_interactive",$e="videoint",Me=250;class Pe{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=e,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=ke(t),this.resizeObserver=new ResizeObserver(Xt(this.onResize,Me)),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(!Yt(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 E.loadVKLangPack(this.lang,_e,$e)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(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 ke(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 Be=3e3,Fe=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Be)=>{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}}},U=(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},De="3.1",St={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Ge={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},He=i=>{const t=[];for(const e of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let f=[Ge];switch(a){case"await":l?f=[]:r=[];break;case"default":{const p={type:"onSuspense",action:{type:St.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[p]:r=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:St[a],args:{}}};l?f=[p]:r=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:Ce.v4(),events:f})}t.push({...e,containers:o,events:r,branches:s})}return i.metadata.version=De,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},Ue="3.2",We=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:Ue},media:t}}return i},ze="3.3",qe=(i=[])=>({edit:{chapters:i},view:{}}),Tt={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ke=i=>{const t=[],e=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:f,type:p,...b})=>({...b,type:f??p})),events:l.events?.length?l.events:[Tt]}));t.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Tt]}),e.push({id:s,x:r,y:o})}return{...i,chapters:t,graph:qe(e),metadata:{...i.metadata,version:ze}}},Qe=[{version:"3.0",migrate:He},{version:"3.1",migrate:We},{version:"3.2",migrate:Ke}],Xe=i=>Qe.reduce((t,e)=>U(t.metadata.version,e.version)?t:e.migrate(t),i),Ye=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});exports.INTERACTIVE_CLICK_ACTIONS=void 0;(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"})(exports.INTERACTIVE_CLICK_ACTIONS||(exports.INTERACTIVE_CLICK_ACTIONS={}));const Rt={metadata:"Object",chapters:"Array"},Ze="3.0.0",Je="3.3.0",ut=i=>{const t=U(i,Ze);return t===-1?!1:t===0?!0:U(i,Je)!==1},ti=i=>{if(!ht(i))return!1;for(const t in Rt)if(!i[t]||!G(i[t],Rt[t]))return!1;return ut(i.metadata.version)},te=i=>i.type===Ye.Text;class I{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 ee{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 s=n.length;s>0;s--)if(n[s]===e){n.splice(s,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(s=>{s(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class ei{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{Oe(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 ii{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return ni(...this.loaders[t])(e)}}function ni(...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 st({actions:i,errors:t,chapterId:e,...n}){if(e){const s=i.getManifest(),r=i.getChapter(s.chapters,e);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:t,result:{chapter:r,media:o,graph:a}}:{...n,errors:J(t,st.name,"Could not find media"),actions:i}}}return{...n,errors:J(t,st.name,"Could not find chapter"),actions:i}}class xt{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 s=0,r=n.length;s<r;s++)if(n[s].callback===e){n.splice(s,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const n=this.listeners[t.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];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 ie extends xt{constructor(){super(),this.listeners||xt.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 si{constructor(){Object.defineProperty(this,"signal",{value:new ie,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&&(si.prototype[Symbol.toStringTag]="AbortController",ie.prototype[Symbol.toStringTag]="AbortSignal");function ne(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 ri(i){typeof i=="function"&&(i={fetch:i});const{fetch:t,Request:e=t.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!ne({fetch:t,Request:e,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:t,Request:r};let r=e;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=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},r.prototype=e.prototype);const o=t;return{fetch:(c,l)=>{const f=r&&r.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,V)=>{f.addEventListener("abort",()=>V(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const pt=ne({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),se=pt?ri({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,At=pt?se.fetch:window.fetch;pt?se.Request:window.Request;const ai=async i=>{try{let t,e;if(ht(i))t=i;else if(nt(i)){e=new URL(i).href;const s=await At(e);if(!s.ok)return{};t=await s.json()}else return{};if(!ti(t))return{};const n=t.metadata.media;if(nt(n)&&!t.media)try{let s;e?s=new URL(n,e).href:(s=new URL(n).href,e=s);const r=await At(s);if(!r.ok)throw new Error;t.metadata.media=await r.json()}catch{return hi(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function oi(i){const{manifest:t,manifestURL:e}=await ai(i),n=Xe(t);return n.media=ci(n.media,e),delete n.metadata.media,n}function et(i,t){return i.find(e=>e.id===t)}function Vt(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 Lt(i,t){return i.videos.find(e=>e.id===t)}function ci(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const s=li(n.url,t);return{...n,url:s||n.url}})}))}}function li(i,t){try{return new URL(i,t).href}catch{return""}}function hi(i){return U(i,"3.2.0")>=0}const R=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),ft=i=>dt(i)&&!Zt(i),q=i=>i.order==="end",re=i=>dt(i.containers)&&!Zt(i.containers)&&q(i),di=(i,t)=>{const e=i*1e3;return ft(t.controls)&&e<(t.startTime??0)},jt=(i,t)=>{const e=i*1e3;return ft(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)},W=i=>i.some(t=>t.action.type==="expect"),Ot=i=>i.find(t=>t.action.type==="expect"),ui=i=>i?.length===1,ae=i=>ui(i)&&te(i[0]),pi=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),fi=(i=[])=>i.reduce((t,e,n)=>{const s=(e?.controls??[]).filter(r=>!te(r));if(ft(s)){const r=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:r});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]<=r[0]&&C.range[1]>=r[1])return t[b].subjects.push(o),t;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[1]=C.range[1])}if(p.push(o),r[0]<=l&&r[1]>=c)return[{subjects:p,range:r}];a.length&&a.reverse().forEach(b=>{t.splice(b,1)}),t.push({subjects:f.concat([o]),range:r})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),mi=(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 oe extends ii{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new E.ValueSubject(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 oi(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",st({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Vt,getChapter:et,getMedia:Lt,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=et(this.manifest.chapters,t);if(e){const n=Lt(this.manifest.media,e.videoId),s=Vt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:s}}return null}getBranches(t=this.chapter.id){if(t===this.chapter.id)return this.getByBranches(this.chapter.branches);{const e=et(this.manifest.chapters,t);return this.getByBranches(e?.branches)}}getByBranches(t=[]){return t.reduce((e,n)=>{const s=this.getByChapterId(n.chapterId);return s&&e.push(s),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter.id===this.manifest.metadata.initChapterId}isEndChapter(){return q(this.chapter)}}const yi=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"},rt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function gi(){const i=new Map;function t({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function e(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)e(s[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function Nt(i,t=[]){let e={},n;const s=!t.length;for(const r of i.variants)if(!n&&"cover"in r&&(n=r.cover),"url"in r)switch(r.type.toLowerCase()){case"mp4":(s||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"mpeg":(s||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"hls":(s||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:r.url}});break;case"dash":(s||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:r.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))},Z={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},vi=2;function bi(i){const t=gi();let e,n;const s=new ee;let r={},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");if(!a.options)return;const w=(t.map.get(d)??{})[g];if(w){r={chapterId:m,listId:d,itemId:g,...w};const A=r.player;n=A.info.currentQuality$.subscribe(v=>{if(!(!v||!A.info.position$.getValue())){e=v;for(const j of t.map)Object.values(j[1]).forEach(({player:O})=>{A.info.isAutoQualityEnabled$.getValue()||X(O,v)})}}),w.container.remove(),o=!1,a.setPlayer(w.player),c||(a.init(),c=!0),s.emit(Z.activePlayerChanged,{player:r.player,config:r.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(H(r)||d!==r.itemId)return;if(m>=0&&!o){const w=a.getChapterBranches();o=!0;const A=new Set;for(const v of w)A.has(v.media.id)||(await V({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),A.add(v.media.id))}}async function C({chapter:{id:d},media:g}){if(H(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),x=r.player.info.currentQuality$.getValue(),w=r.player.info.isAutoQualityEnabled$.getValue(),A=r.player.info.volume$.getValue(),v=r.player.info.currentPlaybackRate$.getValue(),j=!w;let O=!1;for(const L of t.map)if(L[0]===g.id){const k=Object.keys(L[1]);for(const $ of k)$===r.itemId?(k.length<vi||(O=!0),t.removePlayer(L[0],$)):(O=!0,p(L[0],$,d),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(A),r.player.setMuted(m),r.player.setPlaybackRate(v))}else t.removePlayer(L[0]);O||(await V({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(A),r.player.setMuted(m))}async function V({media:d,chapterId:g,prefetch:m=!0,setAsActive:x=!0,autoplay:w=!1,preferredExt:A,title:v,playbackRate:j}){const O=Math.random().toString(),L=document.createElement("div");l.append(L);const k=r?.player?.info.isAutoQualityEnabled$.getValue();let $;if(a?.options?.vkVideoLoader){const K=yi(d);K.length&&($=await a.options.vkVideoLoader(...K))}const yt=a?.options?.coreConfig||{},ue={...yt,configName:[...yt.configName??[],"interactive"]},gt={container:L,...$?.videos?.[0]||{sources:Nt(d,A).sources},title:v},B=new Ee.Player(ue);B.initVideo(gt);const vt=new E.Subscription;vt.add(B.info.position$.subscribe(function(K){b(O,B.info.duration$.getValue(),K)})).add(B.events.canplay$.subscribe(function(){k||X(B,e),j&&B.setPlaybackRate(j)}));const F=t.createPlayer({listId:d.id,itemId:O,player:B,container:L,sources:Nt(d,A).sources,config:gt,subscription:vt});return x&&p(d.id,F.itemId,g),w&&F.player.play(),m&&!w&&F.player.prepare(),s.emit(Z.playerCreated,F.player),{player:F.player,config:F.config}}function P(){u(),a=null}function u(){a?.off(y.chapterChanged,C),t.removeAll(),r={},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 V({media:g,chapterId:m.id,title:m.label});return s.emit(Z.initiated,{container:d,media:g,chapterId:m.id}),{player:x,config:w}}else console.error("not found")}return{...t,on:s.on.bind(s),off:s.off.bind(s),init:h,setInteractiveController:f,createPlayer:V,removeAll:P,getActivePlayer:function(){return r}}}class Ci{constructor({player:t,container:e,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:f}){this.container=e,this.branches=n,this.selectBranches=s,this.subscription=new E.Subscription,this.player=t,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.isPermanentText=c&&ae(e.container.controls),this.disabledControls$=l,this.onRemove=f,this.globalEventEmitter=o,this.gameState=R.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!==R.end&&(W(this.container.container.events)&&this.gameState===R.afterInteractive||this.selectBranches.state.isExpect||(this.gameState!==R.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===R.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=pi({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,s)=>{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===R.end||this.gameState===R.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1}))},isEOV:()=>this.gameState===R.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=R.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[R.destroyed,R.removed].includes(this.gameState)&&!this.isPermanentText)return;const e=this.player.getExactTime();if(di(e,this.container.container))this.gameState!==R.beforeInteractive&&(this.gameState=R.beforeInteractive,this.onBeforeStartTime());else if(jt(e,this.container.container))this.gameState!==R.interactive&&(this.gameState=R.interactive,this.onStartTime());else if(this.gameState!==R.afterInteractive){const r=this.gameState;this.gameState=R.afterInteractive,r===R.interactive&&this.onEndTime()}else this.gameState!==R.destroyed&&!this.isPermanentText&&this.removeView();const n=jt(e,this.container.container),s=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:s,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=R.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=R.removed,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=R.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}}function Ei(){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 s({timestamp:a,priority:c,initiator:l}){if(wt(a)){const f=i[a]??null;if(f&&Q(c,!0)){let p={};const b=f[c];return b&&(p={...p,...b}),p=H(p)?null:p,p&&Q(l,!0)?p[l]??null:p}return f}return null}function r({timestamp:a,priority:c,initiator:l}){if(wt(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],!H(i[a][c]))return!0}else return!1;if(delete i[a][c],!H(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:r,add:o,removeAll:t,get:s,getLte:e,getGte:n}}const Ii=[S.expect,S.setNextBranch],wi=1/0;function _t(i){let t=i,e;const n=Si(),s=new Ei;let r;const o=()=>{b(),u()},a=h=>{s.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),Ii.includes(d.actionType))break},l=(h=1/0)=>{const d=Y(s.get({timestamp:h,priority:"control"})??{}),g=Y(s.get({timestamp:h,priority:"container"})??{}),m=Y(s.get({timestamp:h,priority:"chapter"})??{});return[...d,...g,...m]},f=h=>{n.isReady(h)&&c(l(h))},p=()=>{c([...Y(s.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{e&&(r?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{f(1/0)}),r=t.events.ended$.subscribe(e))},V=h=>{b(),t=h},P=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},u=()=>{n.release(),s.removeAll()};return{setPlayer:V,add:a,remove:P,exec:f,execEndOfVideo:p,listen:C,unlisten:b,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function Si(){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??wi,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===S.expect?-1:1)}const Ti=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=t.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},Ri=250;function xi(i){let t=()=>{};const e=new ResizeObserver(a=>{r(a),t=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:p}=Ti(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 s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Xt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},Ri);function o(){t=void 0,e.disconnect(),s()}return{resizeObserver:e,calc:()=>{t()},release:o}}class Ai{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 Vi=i=>Math.floor(Math.random()*i),Li=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},ji=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},Oi=i=>{const t=i.length,e=Vi(t);return i[e]},$t=1,Ni=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??$t;const e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??$t,t>=e)return i[n];return i[i.length-1]},Mt=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),it=(i,t=!1)=>({...i,args:t?{...i.args,...Mt}:{...Mt,...i.args}}),Pt=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:g,branches:m=[],onEvent:x,isEOV:w=()=>!1,isDisabled:A=()=>!1})=>{const v=it(u,w()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},O=A(),L=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:O?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:g,...v.args}});if(O){L();return}switch(v.type.trim().toLowerCase()){case S.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"})),L(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...j,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case S.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?P({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...j,action:P.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 I(I.Severity.RECOVERABLE,I.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=it(u,m),A={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 S.setNextBranch.trim().toLowerCase():{const j=g.find(O=>O.id===w.args.branchId);if(!j)return;v(),e.add({...A,action:V.bind(null,{subjectId:h,subjectName:"container",action:w,payload:{chapterId:j.chapterId,autoSelect:x}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{v(),e.add({...A,action:C.bind(null,{subjectId:h,subjectName:"container",action:w})});return}case S.openURI.trim().toLowerCase():{v(),e.add({...A,action:P.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 I(I.Severity.RECOVERABLE,I.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:u,branches:h,isEOV:d=!1}){const g=Ot(u.events);if(g){const m=it(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:S.expect,action:p.bind(null,{subjectId:u.id,subjectName:"container"})}),s.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 S.setNextBranch.trim().toLowerCase():{const m=d.find(x=>x.id===h.args.branchId);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const m=Ni(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const m=ji(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const m=Li(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case S.openURI.trim().toLowerCase():return g(),P.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new I(I.Severity.RECOVERABLE,I.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function f(u){const h=Ot(u.events);if(h){if(q(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:S.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??S.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})},V=({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})},P=({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:r,state:s}},at=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const s=t.chapters.find(o=>o.id===n);if(!s)return null;const r=t.media.videos.find(o=>s.videoId===o.id);if(!r)return null;e[n]=mt(r)}return e[n]}).filter(Boolean)},ce=i=>{for(const t of i.variants)if(le(t)&&"payload"in t)return t.payload.id},le=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",mt=i=>{const t=ce(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},he=(i,t)=>{for(const e of i.media.videos)if(t===mt(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},de=(i,t)=>i.reduce((e,n)=>{const s=he(t,n);return s?[...e,s]:e},[]);class _i{state={history$:new E.ValueSubject([]),hasPrevChapter$:new E.ValueSubject(!1),prevChapter$:new E.ValueSubject(null),isInitialChapter$:new E.ValueSubject(!1),isGoBackLimited$:new E.ValueSubject(!1)};#r=null;#n;#h=!1;#i=null;#u=null;#s=null;#a=null;#o=null;#t=new E.Subscription;#d=!1;#p=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:s,settings:r}){this.#s=e,this.#o=t,this.#a=n,this.#r=s,this.#n=r,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.#n.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,s=t.length-this.#n.maxLength,r=s>0?t.slice(s):t,o=at(r,n);if(this.#u=o,this?.state?.history$.next(r),!(!e||!this.#r||!this.#s))try{await this.#r.save(this.#s,o)}catch{this.#o?.emit(y.errors,new I(I.Severity.RECOVERABLE,I.Category.HISTORY,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#a)return this.#o?.emit(y.errors,new I(I.Severity.RECOVERABLE,I.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.#s)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#r)try{const s=await this.#r.get(this.#s);s.length&&(e=s)}catch{this.#o?.emit(y.errors,new I(I.Severity.RECOVERABLE,I.Category.HISTORY,"Error while trying to fetch data"))}const n=de(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#n.initChapterId||this.#i?.metadata.initChapterId}getInitialVideoId(){if(this.#i){const t=this.getInitialChapterId();return at([t],this.#i).pop()}return null}destroy(){this.state=null,this.#s=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 D{constructor(t,e,n,s){this.target=t,this.type=e,this.listener=n,this.options=D.#r(t,s),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"]),s=Object.keys(e).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),D.#h(t)?e:e.capture||!1}}static#n=void 0;static#h(t){let e=D.#n;if(e===void 0){e=!1;try{const n={},s={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};t.addEventListener("test",r,n),t.removeEventListener("test",r,n)}catch{e=!1}D.#n=e}return e||!1}}class $i{constructor(){this.bindingMap=new Ai}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,s){if(!this.bindingMap)return;const r=new D(t,e,n,s);this.bindingMap.push(e,r)}listenOnce(t,e,n,s){const r=o=>{this.unlisten(t,e,r),n(o)};this.listen(t,e,r,s)}unlisten(t,e,n){if(!this.bindingMap)return;const s=this.bindingMap.get(e)||[];for(const r of s)r.target===t&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(e,r))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class Mi{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 s=3;s<n;s+=40)if(e[s]!==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 s;e&&(s=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&s&&this.restore(s),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 Pi{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
+ "use strict";var pe=Object.create;var bt=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var ve=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ge.call(i,s)&&s!==e&&bt(i,s,{get:()=>t[s],enumerable:!(n=fe(t,s))||n.enumerable});return i};var be=(i,t,e)=>(e=i!=null?pe(ye(i)):{},ve(t||!i||!i.__esModule?bt(e,"default",{value:i,enumerable:!0}):e,i));var E=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),Ce=require("uuid"),Ee=require("@vkontakte/videoplayer-core/esnext.cjs.js");const Ie="1.0.11-dev.b72fcea2.0";function Bt(i,t=1){let e="0",n="0",s="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+s},${t})`}const N="SDK_NAME",we="SDK_NAME-controls-container",Ft=()=>document.querySelector(`.${we}`),Se=.4,_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},Ct={top:"flex-start",bottom:"flex-end",center:"center"},Et={start:"flex-start",end:"flex-end",center:"center"},It={start:"left",end:"right",center:"center"},Dt=({target:i,props:t})=>{i.style.alignItems=Ct[t?.text?.gravityVertical]??Ct.center,i.style.justifyContent=Et[t?.text?.gravityHorizontal]??Et.center,i.style.textAlign=It[t?.text?.alignment]??It.start},Gt=({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},Ht=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Bt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ut=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Bt(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)`},tt="int",ct={AREA:`${tt}_area`,TEXT:`${tt}_text`,BUTTON:`${tt}_bttn`};class lt{constructor(t){this.control=t}createView(t){const e=document.createElement("div");e.classList.add(`${N}-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",r=>{r.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Wt=i=>{if(i.type.trim().toLowerCase()==="area")return new Te(i)};class Te extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");return r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.AREA),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ht({target:r,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Ut({target:r,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),ot({target:r,layoutParams:this.control.layoutParams,fallback:_}),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const zt=i=>{if(i.type.trim().toLowerCase()==="button")return new Re(i)};class Re extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");r.type="button",r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.BUTTON),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",ot({target:r,layoutParams:this.control.layoutParams,fallback:_}),Ht({target:r,props:this.control.props,fallback:_}),Ut({target:r,props:this.control.props,fallback:_,dependsOn:n}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:_,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const xe=i=>{if(i.type.trim().toLowerCase()==="text")return new Ae(i)};class Ae extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("div");r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.TEXT),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:r,layoutParams:this.control.layoutParams,fallback:_}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:_,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){}enable(){}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class Ve{constructor(t){this.layout=t}}const Le=i=>{if(i.type.trim().toLowerCase()==="relative")return new qt(i)};class qt extends Ve{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 Kt{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.#n()}#n(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...t,s(e)]:[...t]},[])}}const Qt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new je(i,t)};class je extends Kt{constructor(t,e){super(t),this.rootElement=e??Ft(),this.layout=new qt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",zt),this.addControlFactory("text",xe),this.addControlFactory("area",Wt)}createView(t){const e=document.createElement("div");return e.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const s=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(s,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=Se,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Xt(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),nt=i=>G(i,z.String),dt=i=>G(i,z.Array),Yt=i=>G(i,z.Number),Oe=i=>G(i,z.Function),wt=i=>Yt(i)&&!isNaN(i),H=i=>ht(i)&&Object.keys(i).length===0,Zt=i=>dt(i)&&!i.length,Q=(i,t)=>nt(i)&&(t?i.trim():i).length,Jt=window.navigator.userAgent.toLowerCase(),Ne=/mobi/i.test(Jt);Jt.indexOf("android")>-1;const _e="video_interactive",$e="videoint",Me=250;class Pe{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=e,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=ke(t),this.resizeObserver=new ResizeObserver(Xt(this.onResize,Me)),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(!Yt(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 E.loadVKLangPack(this.lang,_e,$e)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(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 ke(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 Be=3e3,Fe=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Be)=>{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}}},U=(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},De="3.1",St={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Ge={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},He=i=>{const t=[];for(const e of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let f=[Ge];switch(a){case"await":l?f=[]:r=[];break;case"default":{const p={type:"onSuspense",action:{type:St.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[p]:r=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:St[a],args:{}}};l?f=[p]:r=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:Ce.v4(),events:f})}t.push({...e,containers:o,events:r,branches:s})}return i.metadata.version=De,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},Ue="3.2",We=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:Ue},media:t}}return i},ze="3.3",qe=(i=[])=>({edit:{chapters:i},view:{}}),Tt={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ke=i=>{const t=[],e=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:f,type:p,...b})=>({...b,type:f??p})),events:l.events?.length?l.events:[Tt]}));t.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Tt]}),e.push({id:s,x:r,y:o})}return{...i,chapters:t,graph:qe(e),metadata:{...i.metadata,version:ze}}},Qe=[{version:"3.0",migrate:He},{version:"3.1",migrate:We},{version:"3.2",migrate:Ke}],Xe=i=>Qe.reduce((t,e)=>U(t.metadata.version,e.version)?t:e.migrate(t),i),Ye=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});exports.INTERACTIVE_CLICK_ACTIONS=void 0;(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"})(exports.INTERACTIVE_CLICK_ACTIONS||(exports.INTERACTIVE_CLICK_ACTIONS={}));const Rt={metadata:"Object",chapters:"Array"},Ze="3.0.0",Je="3.3.0",ut=i=>{const t=U(i,Ze);return t===-1?!1:t===0?!0:U(i,Je)!==1},ti=i=>{if(!ht(i))return!1;for(const t in Rt)if(!i[t]||!G(i[t],Rt[t]))return!1;return ut(i.metadata.version)},te=i=>i.type===Ye.Text;class I{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 ee{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 s=n.length;s>0;s--)if(n[s]===e){n.splice(s,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(s=>{s(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class ei{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{Oe(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 ii{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return ni(...this.loaders[t])(e)}}function ni(...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 st({actions:i,errors:t,chapterId:e,...n}){if(e){const s=i.getManifest(),r=i.getChapter(s.chapters,e);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:t,result:{chapter:r,media:o,graph:a}}:{...n,errors:J(t,st.name,"Could not find media"),actions:i}}}return{...n,errors:J(t,st.name,"Could not find chapter"),actions:i}}class xt{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 s=0,r=n.length;s<r;s++)if(n[s].callback===e){n.splice(s,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const n=this.listeners[t.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];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 ie extends xt{constructor(){super(),this.listeners||xt.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 si{constructor(){Object.defineProperty(this,"signal",{value:new ie,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&&(si.prototype[Symbol.toStringTag]="AbortController",ie.prototype[Symbol.toStringTag]="AbortSignal");function ne(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 ri(i){typeof i=="function"&&(i={fetch:i});const{fetch:t,Request:e=t.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!ne({fetch:t,Request:e,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:t,Request:r};let r=e;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=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},r.prototype=e.prototype);const o=t;return{fetch:(c,l)=>{const f=r&&r.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,V)=>{f.addEventListener("abort",()=>V(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const pt=ne({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),se=pt?ri({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,At=pt?se.fetch:window.fetch;pt?se.Request:window.Request;const ai=async i=>{try{let t,e;if(ht(i))t=i;else if(nt(i)){e=new URL(i).href;const s=await At(e);if(!s.ok)return{};t=await s.json()}else return{};if(!ti(t))return{};const n=t.metadata.media;if(nt(n)&&!t.media)try{let s;e?s=new URL(n,e).href:(s=new URL(n).href,e=s);const r=await At(s);if(!r.ok)throw new Error;t.metadata.media=await r.json()}catch{return hi(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function oi(i){const{manifest:t,manifestURL:e}=await ai(i),n=Xe(t);return n.media=ci(n.media,e),delete n.metadata.media,n}function et(i,t){return i.find(e=>e.id===t)}function Vt(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 Lt(i,t){return i.videos.find(e=>e.id===t)}function ci(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const s=li(n.url,t);return{...n,url:s||n.url}})}))}}function li(i,t){try{return new URL(i,t).href}catch{return""}}function hi(i){return U(i,"3.2.0")>=0}const R=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),ft=i=>dt(i)&&!Zt(i),q=i=>i.order==="end",re=i=>dt(i.containers)&&!Zt(i.containers)&&q(i),di=(i,t)=>{const e=i*1e3;return ft(t.controls)&&e<(t.startTime??0)},jt=(i,t)=>{const e=i*1e3;return ft(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)},W=i=>i.some(t=>t.action.type==="expect"),Ot=i=>i.find(t=>t.action.type==="expect"),ui=i=>i?.length===1,ae=i=>ui(i)&&te(i[0]),pi=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),fi=(i=[])=>i.reduce((t,e,n)=>{const s=(e?.controls??[]).filter(r=>!te(r));if(ft(s)){const r=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:r});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]<=r[0]&&C.range[1]>=r[1])return t[b].subjects.push(o),t;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[1]=C.range[1])}if(p.push(o),r[0]<=l&&r[1]>=c)return[{subjects:p,range:r}];a.length&&a.reverse().forEach(b=>{t.splice(b,1)}),t.push({subjects:f.concat([o]),range:r})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),mi=(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 oe extends ii{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new E.ValueSubject(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 oi(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",st({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Vt,getChapter:et,getMedia:Lt,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=et(this.manifest.chapters,t);if(e){const n=Lt(this.manifest.media,e.videoId),s=Vt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:s}}return null}getBranches(t=this.chapter.id){if(t===this.chapter.id)return this.getByBranches(this.chapter.branches);{const e=et(this.manifest.chapters,t);return this.getByBranches(e?.branches)}}getByBranches(t=[]){return t.reduce((e,n)=>{const s=this.getByChapterId(n.chapterId);return s&&e.push(s),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter.id===this.manifest.metadata.initChapterId}isEndChapter(){return q(this.chapter)}}const yi=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"},rt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function gi(){const i=new Map;function t({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function e(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)e(s[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function Nt(i,t=[]){let e={},n;const s=!t.length;for(const r of i.variants)if(!n&&"cover"in r&&(n=r.cover),"url"in r)switch(r.type.toLowerCase()){case"mp4":(s||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"mpeg":(s||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"hls":(s||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:r.url}});break;case"dash":(s||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:r.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))},Z={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},vi=2;function bi(i){const t=gi();let e,n;const s=new ee;let r={},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");if(!a.options)return;const w=(t.map.get(d)??{})[g];if(w){r={chapterId:m,listId:d,itemId:g,...w};const A=r.player;n=A.info.currentQuality$.subscribe(v=>{if(!(!v||!A.info.position$.getValue())){e=v;for(const j of t.map)Object.values(j[1]).forEach(({player:O})=>{A.info.isAutoQualityEnabled$.getValue()||X(O,v)})}}),w.container.remove(),o=!1,a.setPlayer(w.player),c||(a.init(),c=!0),s.emit(Z.activePlayerChanged,{player:r.player,config:r.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(H(r)||d!==r.itemId)return;if(m>=0&&!o){const w=a.getChapterBranches();o=!0;const A=new Set;for(const v of w)A.has(v.media.id)||(await V({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),A.add(v.media.id))}}async function C({chapter:{id:d},media:g}){if(H(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),x=r.player.info.currentQuality$.getValue(),w=r.player.info.isAutoQualityEnabled$.getValue(),A=r.player.info.volume$.getValue(),v=r.player.info.currentPlaybackRate$.getValue(),j=!w;let O=!1;for(const L of t.map)if(L[0]===g.id){const k=Object.keys(L[1]);for(const $ of k)$===r.itemId?(k.length<vi||(O=!0),t.removePlayer(L[0],$)):(O=!0,p(L[0],$,d),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(A),r.player.setMuted(m),r.player.setPlaybackRate(v))}else t.removePlayer(L[0]);O||(await V({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(A),r.player.setMuted(m))}async function V({media:d,chapterId:g,prefetch:m=!0,setAsActive:x=!0,autoplay:w=!1,preferredExt:A,title:v,playbackRate:j}){const O=Math.random().toString(),L=document.createElement("div");l.append(L);const k=r?.player?.info.isAutoQualityEnabled$.getValue();let $;if(a?.options?.vkVideoLoader){const K=yi(d);K.length&&($=await a.options.vkVideoLoader(...K))}const yt=a?.options?.coreConfig||{},ue={...yt,configName:[...yt.configName??[],"interactive"]},gt={container:L,...$?.videos?.[0]||{sources:Nt(d,A).sources},title:v},B=new Ee.Player(ue);B.initVideo(gt);const vt=new E.Subscription;vt.add(B.info.position$.subscribe(function(K){b(O,B.info.duration$.getValue(),K)})).add(B.events.canplay$.subscribe(function(){k||X(B,e),j&&B.setPlaybackRate(j)}));const F=t.createPlayer({listId:d.id,itemId:O,player:B,container:L,sources:Nt(d,A).sources,config:gt,subscription:vt});return x&&p(d.id,F.itemId,g),w&&F.player.play(),m&&!w&&F.player.prepare(),s.emit(Z.playerCreated,F.player),{player:F.player,config:F.config}}function P(){u(),a=null}function u(){a?.off(y.chapterChanged,C),t.removeAll(),r={},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 V({media:g,chapterId:m.id,title:m.label});return s.emit(Z.initiated,{container:d,media:g,chapterId:m.id}),{player:x,config:w}}else console.error("not found")}return{...t,on:s.on.bind(s),off:s.off.bind(s),init:h,setInteractiveController:f,createPlayer:V,removeAll:P,getActivePlayer:function(){return r}}}class Ci{constructor({player:t,container:e,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:f}){this.container=e,this.branches=n,this.selectBranches=s,this.subscription=new E.Subscription,this.player=t,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.isPermanentText=c&&ae(e.container.controls),this.disabledControls$=l,this.onRemove=f,this.globalEventEmitter=o,this.gameState=R.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!==R.end&&(W(this.container.container.events)&&this.gameState===R.afterInteractive||this.selectBranches.state.isExpect||(this.gameState!==R.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===R.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=pi({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,s)=>{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===R.end||this.gameState===R.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1}))},isEOV:()=>this.gameState===R.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=R.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[R.destroyed,R.removed].includes(this.gameState)&&!this.isPermanentText)return;const e=this.player.getExactTime();if(di(e,this.container.container))this.gameState!==R.beforeInteractive&&(this.gameState=R.beforeInteractive,this.onBeforeStartTime());else if(jt(e,this.container.container))this.gameState!==R.interactive&&(this.gameState=R.interactive,this.onStartTime());else if(this.gameState!==R.afterInteractive){const r=this.gameState;this.gameState=R.afterInteractive,r===R.interactive&&this.onEndTime()}else this.gameState!==R.destroyed&&!this.isPermanentText&&this.removeView();const n=jt(e,this.container.container),s=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:s,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=R.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=R.removed,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=R.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}}function Ei(){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 s({timestamp:a,priority:c,initiator:l}){if(wt(a)){const f=i[a]??null;if(f&&Q(c,!0)){let p={};const b=f[c];return b&&(p={...p,...b}),p=H(p)?null:p,p&&Q(l,!0)?p[l]??null:p}return f}return null}function r({timestamp:a,priority:c,initiator:l}){if(wt(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],!H(i[a][c]))return!0}else return!1;if(delete i[a][c],!H(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:r,add:o,removeAll:t,get:s,getLte:e,getGte:n}}const Ii=[S.expect,S.setNextBranch],wi=1/0;function _t(i){let t=i,e;const n=Si(),s=new Ei;let r;const o=()=>{b(),u()},a=h=>{s.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),Ii.includes(d.actionType))break},l=(h=1/0)=>{const d=Y(s.get({timestamp:h,priority:"control"})??{}),g=Y(s.get({timestamp:h,priority:"container"})??{}),m=Y(s.get({timestamp:h,priority:"chapter"})??{});return[...d,...g,...m]},f=h=>{n.isReady(h)&&c(l(h))},p=()=>{c([...Y(s.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{e&&(r?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{f(1/0)}),r=t.events.ended$.subscribe(e))},V=h=>{b(),t=h},P=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},u=()=>{n.release(),s.removeAll()};return{setPlayer:V,add:a,remove:P,exec:f,execEndOfVideo:p,listen:C,unlisten:b,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function Si(){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??wi,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===S.expect?-1:1)}const Ti=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=t.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},Ri=250;function xi(i){let t=()=>{};const e=new ResizeObserver(a=>{r(a),t=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:p}=Ti(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 s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Xt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},Ri);function o(){t=void 0,e.disconnect(),s()}return{resizeObserver:e,calc:()=>{t()},release:o}}class Ai{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 Vi=i=>Math.floor(Math.random()*i),Li=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},ji=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},Oi=i=>{const t=i.length,e=Vi(t);return i[e]},$t=1,Ni=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??$t;const e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??$t,t>=e)return i[n];return i[i.length-1]},Mt=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),it=(i,t=!1)=>({...i,args:t?{...i.args,...Mt}:{...Mt,...i.args}}),Pt=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:g,branches:m=[],onEvent:x,isEOV:w=()=>!1,isDisabled:A=()=>!1})=>{const v=it(u,w()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},O=A(),L=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:O?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:g,...v.args}});if(O){L();return}switch(v.type.trim().toLowerCase()){case S.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"})),L(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...j,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case S.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?P({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...j,action:P.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 I(I.Severity.RECOVERABLE,I.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=it(u,m),A={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 S.setNextBranch.trim().toLowerCase():{const j=g.find(O=>O.id===w.args.branchId);if(!j)return;v(),e.add({...A,action:V.bind(null,{subjectId:h,subjectName:"container",action:w,payload:{chapterId:j.chapterId,autoSelect:x}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{v(),e.add({...A,action:C.bind(null,{subjectId:h,subjectName:"container",action:w})});return}case S.openURI.trim().toLowerCase():{v(),e.add({...A,action:P.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 I(I.Severity.RECOVERABLE,I.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:u,branches:h,isEOV:d=!1}){const g=Ot(u.events);if(g){const m=it(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:S.expect,action:p.bind(null,{subjectId:u.id,subjectName:"container"})}),s.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 S.setNextBranch.trim().toLowerCase():{const m=d.find(x=>x.id===h.args.branchId);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const m=Ni(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const m=ji(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const m=Li(d);return m?.chapterId?(g(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case S.openURI.trim().toLowerCase():return g(),P.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new I(I.Severity.RECOVERABLE,I.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function f(u){const h=Ot(u.events);if(h){if(q(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:S.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??S.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})},V=({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})},P=({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:r,state:s}},at=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const s=t.chapters.find(o=>o.id===n);if(!s)return null;const r=t.media.videos.find(o=>s.videoId===o.id);if(!r)return null;e[n]=mt(r)}return e[n]}).filter(Boolean)},ce=i=>{for(const t of i.variants)if(le(t)&&"payload"in t)return t.payload.id},le=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",mt=i=>{const t=ce(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},he=(i,t)=>{for(const e of i.media.videos)if(t===mt(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},de=(i,t)=>i.reduce((e,n)=>{const s=he(t,n);return s?[...e,s]:e},[]);class _i{state={history$:new E.ValueSubject([]),hasPrevChapter$:new E.ValueSubject(!1),prevChapter$:new E.ValueSubject(null),isInitialChapter$:new E.ValueSubject(!1),isGoBackLimited$:new E.ValueSubject(!1)};#r=null;#n;#h=!1;#i=null;#u=null;#s=null;#a=null;#o=null;#t=new E.Subscription;#d=!1;#p=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:s,settings:r}){this.#s=e,this.#o=t,this.#a=n,this.#r=s,this.#n=r,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.#n.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,s=t.length-this.#n.maxLength,r=s>0?t.slice(s):t,o=at(r,n);if(this.#u=o,this?.state?.history$.next(r),!(!e||!this.#r||!this.#s))try{await this.#r.save(this.#s,o)}catch{this.#o?.emit(y.errors,new I(I.Severity.RECOVERABLE,I.Category.HISTORY,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#a)return this.#o?.emit(y.errors,new I(I.Severity.RECOVERABLE,I.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.#s)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#r)try{const s=await this.#r.get(this.#s);s.length&&(e=s)}catch{this.#o?.emit(y.errors,new I(I.Severity.RECOVERABLE,I.Category.HISTORY,"Error while trying to fetch data"))}const n=de(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#n.initChapterId||this.#i?.metadata.initChapterId}getInitialVideoId(){if(this.#i){const t=this.getInitialChapterId();return at([t],this.#i).pop()}return null}destroy(){this.state=null,this.#s=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 D{constructor(t,e,n,s){this.target=t,this.type=e,this.listener=n,this.options=D.#r(t,s),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"]),s=Object.keys(e).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),D.#h(t)?e:e.capture||!1}}static#n=void 0;static#h(t){let e=D.#n;if(e===void 0){e=!1;try{const n={},s={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};t.addEventListener("test",r,n),t.removeEventListener("test",r,n)}catch{e=!1}D.#n=e}return e||!1}}class $i{constructor(){this.bindingMap=new Ai}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,s){if(!this.bindingMap)return;const r=new D(t,e,n,s);this.bindingMap.push(e,r)}listenOnce(t,e,n,s){const r=o=>{this.unlisten(t,e,r),n(o)};this.listen(t,e,r,s)}unlisten(t,e,n){if(!this.bindingMap)return;const s=this.bindingMap.get(e)||[];for(const r of s)r.target===t&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(e,r))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class Mi{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 s=3;s<n;s+=40)if(e[s]!==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 s;e&&(s=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&s&&this.restore(s),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 Pi{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;
package/esnext.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.11-dev.b4747814.0
3
- * Thu, 30 May 2024 12:04:59 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.11-dev.b72fcea2.0
3
+ * Fri, 31 May 2024 10:56:17 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-11/doc/
5
5
  */
6
- import{loadVKLangPack as le,ValueSubject as L,Subscription as tt,Subject as he,Observable as gt,getCurrentBrowser as de,CurrentClientBrowser as ue,once as pe,combine as fe}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as me}from"uuid";import{Player as ye}from"@vkontakte/videoplayer-core/esnext.esm.js";const ge="1.0.11-dev.b4747814.0";function Bt(i,t=1){let e="0",n="0",s="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+s},${t})`}const N="SDK_NAME",ve="SDK_NAME-controls-container",Ft=()=>document.querySelector(`.${ve}`),be=.4,V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},vt={top:"flex-start",bottom:"flex-end",center:"center"},bt={start:"flex-start",end:"flex-end",center:"center"},Ct={start:"left",end:"right",center:"center"},Dt=({target:i,props:t})=>{i.style.alignItems=vt[t?.text?.gravityVertical]??vt.center,i.style.justifyContent=bt[t?.text?.gravityHorizontal]??bt.center,i.style.textAlign=Ct[t?.text?.alignment]??Ct.start},Gt=({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},Ht=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Bt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ut=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Bt(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(`${N}-control-container-${this.control.id}`),t(e,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.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",r=>{r.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Wt=i=>{if(i.type.trim().toLowerCase()==="area")return new Ce(i)};class Ce extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");return r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.AREA),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ht({target:r,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),Ut({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),ot({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const zt=i=>{if(i.type.trim().toLowerCase()==="button")return new Ee(i)};class Ee extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");r.type="button",r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.BUTTON),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",ot({target:r,layoutParams:this.control.layoutParams,fallback:V}),Ht({target:r,props:this.control.props,fallback:V}),Ut({target:r,props:this.control.props,fallback:V,dependsOn:n}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const Ie=i=>{if(i.type.trim().toLowerCase()==="text")return new we(i)};class we extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("div");r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.TEXT),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:r,layoutParams:this.control.layoutParams,fallback:V}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){}enable(){}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class Se{constructor(t){this.layout=t}}const Te=i=>{if(i.type.trim().toLowerCase()==="relative")return new qt(i)};class qt extends Se{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 Qt{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.#n()}#n(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...t,s(e)]:[...t]},[])}}const Xt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new xe(i,t)};class xe extends Qt{constructor(t,e){super(t),this.rootElement=e??Ft(),this.layout=new qt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",zt),this.addControlFactory("text",Ie),this.addControlFactory("area",Wt)}createView(t){const e=document.createElement("div");return e.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const s=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(s,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=be,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Kt(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"},H=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,ht=i=>H(i,z.Object),rt=i=>H(i,z.String),dt=i=>H(i,z.Array),Yt=i=>H(i,z.Number),Re=i=>H(i,z.Function),Et=i=>Yt(i)&&!isNaN(i),U=i=>ht(i)&&Object.keys(i).length===0,Zt=i=>dt(i)&&!i.length,Q=(i,t)=>rt(i)&&(t?i.trim():i).length,Jt=window.navigator.userAgent.toLowerCase(),Ae=/mobi/i.test(Jt);Jt.indexOf("android")>-1;const Le="video_interactive",Oe="videoint",je=250;class $e{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=e,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Ne(t),this.resizeObserver=new ResizeObserver(Kt(this.onResize,je)),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(!Yt(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 le(this.lang,Le,Oe)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(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 Ne(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 Ve=3e3,_e=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Ve)=>{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},Me="3.1",It={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Pe={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},ke=i=>{const t=[];for(const e of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let f=[Pe];switch(a){case"await":l?f=[]:r=[];break;case"default":{const p={type:"onSuspense",action:{type:It.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[p]:r=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:It[a],args:{}}};l?f=[p]:r=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:me(),events:f})}t.push({...e,containers:o,events:r,branches:s})}return i.metadata.version=Me,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},Be="3.2",Fe=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:Be},media:t}}return i},De="3.3",Ge=(i=[])=>({edit:{chapters:i},view:{}}),wt={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},He=i=>{const t=[],e=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:f,type:p,...b})=>({...b,type:f??p})),events:l.events?.length?l.events:[wt]}));t.push({id:s,...a,containers:c,events:a.events?.length?a.events:[wt]}),e.push({id:s,x:r,y:o})}return{...i,chapters:t,graph:Ge(e),metadata:{...i.metadata,version:De}}},Ue=[{version:"3.0",migrate:ke},{version:"3.1",migrate:Fe},{version:"3.2",migrate:He}],We=i=>Ue.reduce((t,e)=>Z(t.metadata.version,e.version)?t:e.migrate(t),i),ze=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),w=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 St={metadata:"Object",chapters:"Array"},qe="3.0.0",Qe="3.3.0",te=i=>{const t=Z(i,qe);return t===-1?!1:t===0?!0:Z(i,Qe)!==1},Xe=i=>{if(!ht(i))return!1;for(const t in St)if(!i[t]||!H(i[t],St[t]))return!1;return te(i.metadata.version)},ee=i=>i.type===ze.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 ie{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 s=n.length;s>0;s--)if(n[s]===e){n.splice(s,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(s=>{s(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class Ke{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{Re(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 Ye{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return Ze(...this.loaders[t])(e)}}function Ze(...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 s=i.getManifest(),r=i.getChapter(s.chapters,e);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:t,result:{chapter:r,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 Tt{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 s=0,r=n.length;s<r;s++)if(n[s].callback===e){n.splice(s,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const n=this.listeners[t.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];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 ne extends Tt{constructor(){super(),this.listeners||Tt.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 Je{constructor(){Object.defineProperty(this,"signal",{value:new ne,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&&(Je.prototype[Symbol.toStringTag]="AbortController",ne.prototype[Symbol.toStringTag]="AbortSignal");function se(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 ti(i){typeof i=="function"&&(i={fetch:i});const{fetch:t,Request:e=t.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!se({fetch:t,Request:e,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:t,Request:r};let r=e;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=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},r.prototype=e.prototype);const o=t;return{fetch:(c,l)=>{const f=r&&r.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,A)=>{f.addEventListener("abort",()=>A(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const ut=se({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),re=ut?ti({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=ut?re.fetch:window.fetch;ut?re.Request:window.Request;const ei=async i=>{try{let t,e;if(ht(i))t=i;else if(rt(i)){e=new URL(i).href;const s=await xt(e);if(!s.ok)return{};t=await s.json()}else return{};if(!Xe(t))return{};const n=t.metadata.media;if(rt(n)&&!t.media)try{let s;e?s=new URL(n,e).href:(s=new URL(n).href,e=s);const r=await xt(s);if(!r.ok)throw new Error;t.metadata.media=await r.json()}catch{return ri(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function ii(i){const{manifest:t,manifestURL:e}=await ei(i),n=We(t);return n.media=ni(n.media,e),delete n.metadata.media,n}function nt(i,t){return i.find(e=>e.id===t)}function Rt(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 At(i,t){return i.videos.find(e=>e.id===t)}function ni(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const s=si(n.url,t);return{...n,url:s||n.url}})}))}}function si(i,t){try{return new URL(i,t).href}catch{return""}}function ri(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)&&!Zt(i),et=i=>i.order==="end",ai=i=>dt(i.containers)&&!Zt(i.containers)&&et(i),oi=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e<(t.startTime??0)},Lt=(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"),Ot=i=>i.find(t=>t.action.type==="expect"),ci=i=>i?.length===1,ae=i=>ci(i)&&ee(i[0]),li=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),hi=(i=[])=>i.reduce((t,e,n)=>{const s=(e?.controls??[]).filter(r=>!ee(r));if(pt(s)){const r=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:r});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]<=r[0]&&C.range[1]>=r[1])return t[b].subjects.push(o),t;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[1]=C.range[1])}if(p.push(o),r[0]<=l&&r[1]>=c)return[{subjects:p,range:r}];a.length&&a.reverse().forEach(b=>{t.splice(b,1)}),t.push({subjects:f.concat([o]),range:r})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),di=(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 ui extends Ye{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new L(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 ii(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:Rt,getChapter:nt,getMedia:At,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=At(this.manifest.media,e.videoId),s=Rt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:s}}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 s=this.getByChapterId(n.chapterId);return s&&e.push(s),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 pi=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"},jt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function fi(){const i=new Map;function t({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function e(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)e(s[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function $t(i,t=[]){let e={},n;const s=!t.length;for(const r of i.variants)if(!n&&"cover"in r&&(n=r.cover),"url"in r)switch(r.type.toLowerCase()){case"mp4":(s||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"mpeg":(s||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"hls":(s||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:r.url}});break;case"dash":(s||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:r.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))},Y={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},mi=2;function yi(i){const t=fi();let e,n;const s=new ie;let r={},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");if(!a.options)return;const I=(t.map.get(d)??{})[g];if(I){r={chapterId:m,listId:d,itemId:g,...I};const R=r.player;n=R.info.currentQuality$.subscribe(v=>{if(!(!v||!R.info.position$.getValue())){e=v;for(const j of t.map)Object.values(j[1]).forEach(({player:$})=>{R.info.isAutoQualityEnabled$.getValue()||X($,v)})}}),I.container.remove(),o=!1,a.setPlayer(I.player),c||(a.init(),c=!0),s.emit(Y.activePlayerChanged,{player:r.player,config:r.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(r)||d!==r.itemId)return;if(m>=0&&!o){const I=a.getChapterBranches();o=!0;const R=new Set;for(const v of I)R.has(v.media.id)||(await A({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(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),x=r.player.info.currentQuality$.getValue(),I=r.player.info.isAutoQualityEnabled$.getValue(),R=r.player.info.volume$.getValue(),v=r.player.info.currentPlaybackRate$.getValue(),j=!I;let $=!1;for(const O of t.map)if(O[0]===g.id){const k=Object.keys(O[1]);for(const _ of k)_===r.itemId?(k.length<mi||($=!0),t.removePlayer(O[0],_)):($=!0,p(O[0],_,d),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(R),r.player.setMuted(m),r.player.setPlaybackRate(v))}else t.removePlayer(O[0]);$||(await A({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(R),r.player.setMuted(m))}async function A({media:d,chapterId:g,prefetch:m=!0,setAsActive:x=!0,autoplay:I=!1,preferredExt:R,title:v,playbackRate:j}){const $=Math.random().toString(),O=document.createElement("div");l.append(O);const k=r?.player?.info.isAutoQualityEnabled$.getValue();let _;if(a?.options?.vkVideoLoader){const q=pi(d);q.length&&(_=await a.options.vkVideoLoader(...q))}const ft=a?.options?.coreConfig||{},ce={...ft,configName:[...ft.configName??[],"interactive"]},mt={container:O,..._?.videos?.[0]||{sources:$t(d,R).sources},title:v},B=new ye(ce);B.initVideo(mt);const yt=new tt;yt.add(B.info.position$.subscribe(function(q){b($,B.info.duration$.getValue(),q)})).add(B.events.canplay$.subscribe(function(){k||X(B,e),j&&B.setPlaybackRate(j)}));const D=t.createPlayer({listId:d.id,itemId:$,player:B,container:O,sources:$t(d,R).sources,config:mt,subscription:yt});return x&&p(d.id,D.itemId,g),I&&D.player.play(),m&&!I&&D.player.prepare(),s.emit(Y.playerCreated,D.player),{player:D.player,config:D.config}}function P(){u(),a=null}function u(){a?.off(y.chapterChanged,C),t.removeAll(),r={},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:I}=await A({media:g,chapterId:m.id,title:m.label});return s.emit(Y.initiated,{container:d,media:g,chapterId:m.id}),{player:x,config:I}}else console.error("not found")}return{...t,on:s.on.bind(s),off:s.off.bind(s),init:h,setInteractiveController:f,createPlayer:A,removeAll:P,getActivePlayer:function(){return r}}}class gi{constructor({player:t,container:e,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:f}){this.container=e,this.branches=n,this.selectBranches=s,this.subscription=new tt,this.player=t,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.isPermanentText=c&&ae(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=li({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,s)=>{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(),s(),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(oi(e,this.container.container))this.gameState!==S.beforeInteractive&&(this.gameState=S.beforeInteractive,this.onBeforeStartTime());else if(Lt(e,this.container.container))this.gameState!==S.interactive&&(this.gameState=S.interactive,this.onStartTime());else if(this.gameState!==S.afterInteractive){const r=this.gameState;this.gameState=S.afterInteractive,r===S.interactive&&this.onEndTime()}else this.gameState!==S.destroyed&&!this.isPermanentText&&this.removeView();const n=Lt(e,this.container.container),s=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:s,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 vi(){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 s({timestamp:a,priority:c,initiator:l}){if(Et(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 r({timestamp:a,priority:c,initiator:l}){if(Et(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:r,add:o,removeAll:t,get:s,getLte:e,getGte:n}}const bi=[w.expect,w.setNextBranch],Ci=1/0;function Nt(i){let t=i,e;const n=Ei(),s=new vi;let r;const o=()=>{b(),u()},a=h=>{s.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),bi.includes(d.actionType))break},l=(h=1/0)=>{const d=K(s.get({timestamp:h,priority:"control"})??{}),g=K(s.get({timestamp:h,priority:"container"})??{}),m=K(s.get({timestamp:h,priority:"chapter"})??{});return[...d,...g,...m]},f=h=>{n.isReady(h)&&c(l(h))},p=()=>{c([...K(s.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{e&&(r?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{f(1/0)}),r=t.events.ended$.subscribe(e))},A=h=>{b(),t=h},P=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},u=()=>{n.release(),s.removeAll()};return{setPlayer:A,add:a,remove:P,exec:f,execEndOfVideo:p,listen:C,unlisten:b,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function Ei(){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??Ci,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 K(i){return Object.values(i).flat().sort(t=>t.actionType===w.expect?-1:1)}const Ii=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=t.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},wi=250;function Si(i){let t=()=>{};const e=new ResizeObserver(a=>{r(a),t=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:p}=Ii(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 s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Kt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},wi);function o(){t=void 0,e.disconnect(),s()}return{resizeObserver:e,calc:()=>{t()},release:o}}class Ti{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 xi=i=>Math.floor(Math.random()*i),Ri=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},Ai=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},Li=i=>{const t=i.length,e=xi(t);return i[e]},Vt=1,Oi=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}}),Mt=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:g,branches:m=[],onEvent:x,isEOV:I=()=>!1,isDisabled:R=()=>!1})=>{const v=st(u,I()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},$=R(),O=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:$?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:g,...v.args}});if($){O();return}switch(v.type.trim().toLowerCase()){case w.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"})),O(),v.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...j,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),O(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case w.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),O(),v.args.shouldOpenNow?P({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...j,action:P.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 I=st(u,m),R={timestamp:!I.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:h,actionType:I.type},v=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"container",type:T.actionChoice,actionType:I.type,payload:I.args});switch(I.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const j=g.find($=>$.id===I.args.branchId);if(!j)return;v(),e.add({...R,action:A.bind(null,{subjectId:h,subjectName:"container",action:I,payload:{chapterId:j.chapterId,autoSelect:x}})}),n?.();return}case w.setMaxWeightBranch.trim().toLowerCase():return;case w.setMinWeightBranch.trim().toLowerCase():return;case w.setRandomBranch.trim().toLowerCase():return;case w.setWeightlessRandomBranch.trim().toLowerCase():return;case w.continuePlayback.trim().toLowerCase():{v(),e.add({...R,action:C.bind(null,{subjectId:h,subjectName:"container",action:I})});return}case w.openURI.trim().toLowerCase():{v(),e.add({...R,action:P.bind(null,{subjectId:h,subjectName:"container",action:I,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=Ot(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:w.expect,action:p.bind(null,{subjectId:u.id,subjectName:"container"})}),s.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 w.setNextBranch.trim().toLowerCase():{const m=d.find(x=>x.id===h.args.branchId);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const m=Li(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const m=Ai(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const m=Ri(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case w.openURI.trim().toLowerCase():return g(),P.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=Ot(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:w.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??w.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})},A=({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})},P=({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:r,state:s}},Pt=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const s=t.chapters.find(o=>o.id===n);if(!s)return null;const r=t.media.videos.find(o=>s.videoId===o.id);if(!r)return null;e[n]=oe(r)}return e[n]}).filter(Boolean)},ji=i=>{for(const t of i.variants)if($i(t)&&"payload"in t)return t.payload.id},$i=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",oe=i=>{const t=ji(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},Ni=(i,t)=>{for(const e of i.media.videos)if(t===oe(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},Vi=(i,t)=>i.reduce((e,n)=>{const s=Ni(t,n);return s?[...e,s]:e},[]);class _i{state={history$:new L([]),hasPrevChapter$:new L(!1),prevChapter$:new L(null),isInitialChapter$:new L(!1),isGoBackLimited$:new L(!1)};#r=null;#n;#h=!1;#i=null;#u=null;#s=null;#a=null;#o=null;#t=new tt;#d=!1;#p=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:s,settings:r}){this.#s=e,this.#o=t,this.#a=n,this.#r=s,this.#n=r,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.#n.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,s=t.length-this.#n.maxLength,r=s>0?t.slice(s):t,o=Pt(r,n);if(this.#u=o,this?.state?.history$.next(r),!(!e||!this.#r||!this.#s))try{await this.#r.save(this.#s,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.#s)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#r)try{const s=await this.#r.get(this.#s);s.length&&(e=s)}catch{this.#o?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Error while trying to fetch data"))}const n=Vi(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#n.initChapterId||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.#s=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 G{constructor(t,e,n,s){this.target=t,this.type=e,this.listener=n,this.options=G.#r(t,s),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"]),s=Object.keys(e).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),G.#h(t)?e:e.capture||!1}}static#n=void 0;static#h(t){let e=G.#n;if(e===void 0){e=!1;try{const n={},s={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};t.addEventListener("test",r,n),t.removeEventListener("test",r,n)}catch{e=!1}G.#n=e}return e||!1}}class Mi{constructor(){this.bindingMap=new Ti}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,s){if(!this.bindingMap)return;const r=new G(t,e,n,s);this.bindingMap.push(e,r)}listenOnce(t,e,n,s){const r=o=>{this.unlisten(t,e,r),n(o)};this.listen(t,e,r,s)}unlisten(t,e,n){if(!this.bindingMap)return;const s=this.bindingMap.get(e)||[];for(const r of s)r.target===t&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(e,r))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class Pi{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 s=3;s<n;s+=40)if(e[s]!==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 s;e&&(s=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&s&&this.restore(s),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 ki{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 le,ValueSubject as L,Subscription as tt,Subject as he,Observable as gt,getCurrentBrowser as de,CurrentClientBrowser as ue,once as pe,combine as fe}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as me}from"uuid";import{Player as ye}from"@vkontakte/videoplayer-core/esnext.esm.js";const ge="1.0.11-dev.b72fcea2.0";function Bt(i,t=1){let e="0",n="0",s="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+s},${t})`}const N="SDK_NAME",ve="SDK_NAME-controls-container",Ft=()=>document.querySelector(`.${ve}`),be=.4,V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},vt={top:"flex-start",bottom:"flex-end",center:"center"},bt={start:"flex-start",end:"flex-end",center:"center"},Ct={start:"left",end:"right",center:"center"},Dt=({target:i,props:t})=>{i.style.alignItems=vt[t?.text?.gravityVertical]??vt.center,i.style.justifyContent=bt[t?.text?.gravityHorizontal]??bt.center,i.style.textAlign=Ct[t?.text?.alignment]??Ct.start},Gt=({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},Ht=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Bt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ut=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Bt(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(`${N}-control-container-${this.control.id}`),t(e,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.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",r=>{r.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Wt=i=>{if(i.type.trim().toLowerCase()==="area")return new Ce(i)};class Ce extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");return r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.AREA),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ht({target:r,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),Ut({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),ot({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const zt=i=>{if(i.type.trim().toLowerCase()==="button")return new Ee(i)};class Ee extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("button");r.type="button",r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.BUTTON),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",ot({target:r,layoutParams:this.control.layoutParams,fallback:V}),Ht({target:r,props:this.control.props,fallback:V}),Ut({target:r,props:this.control.props,fallback:V,dependsOn:n}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const Ie=i=>{if(i.type.trim().toLowerCase()==="text")return new we(i)};class we extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:s}=super.createView(e),r=document.createElement("div");r.classList.add(`${N}-${this.control.id}`),r.setAttribute("data-testid",ct.TEXT),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:r,layoutParams:this.control.layoutParams,fallback:V}),Dt({target:r,props:this.control.props}),Gt({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),t.append(s),this.controlEl=r,s}disable(){}enable(){}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class Se{constructor(t){this.layout=t}}const Te=i=>{if(i.type.trim().toLowerCase()==="relative")return new qt(i)};class qt extends Se{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 Qt{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.#n()}#n(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...t,s(e)]:[...t]},[])}}const Xt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new xe(i,t)};class xe extends Qt{constructor(t,e){super(t),this.rootElement=e??Ft(),this.layout=new qt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",zt),this.addControlFactory("text",Ie),this.addControlFactory("area",Wt)}createView(t){const e=document.createElement("div");return e.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const s=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(s,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=be,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Kt(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"},H=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,ht=i=>H(i,z.Object),rt=i=>H(i,z.String),dt=i=>H(i,z.Array),Yt=i=>H(i,z.Number),Re=i=>H(i,z.Function),Et=i=>Yt(i)&&!isNaN(i),U=i=>ht(i)&&Object.keys(i).length===0,Zt=i=>dt(i)&&!i.length,Q=(i,t)=>rt(i)&&(t?i.trim():i).length,Jt=window.navigator.userAgent.toLowerCase(),Ae=/mobi/i.test(Jt);Jt.indexOf("android")>-1;const Le="video_interactive",Oe="videoint",je=250;class $e{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=e,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Ne(t),this.resizeObserver=new ResizeObserver(Kt(this.onResize,je)),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(!Yt(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 le(this.lang,Le,Oe)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(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 Ne(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 Ve=3e3,_e=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Ve)=>{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},Me="3.1",It={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Pe={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},ke=i=>{const t=[];for(const e of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let f=[Pe];switch(a){case"await":l?f=[]:r=[];break;case"default":{const p={type:"onSuspense",action:{type:It.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[p]:r=[p];break}case"random":case"weightlessRandom":case"max":case"min":{const p={type:"onSuspense",action:{type:It[a],args:{}}};l?f=[p]:r=[p];break}}for(const p of c.controls)o.push({...c,controls:[{...p}],id:me(),events:f})}t.push({...e,containers:o,events:r,branches:s})}return i.metadata.version=Me,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},Be="3.2",Fe=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:Be},media:t}}return i},De="3.3",Ge=(i=[])=>({edit:{chapters:i},view:{}}),wt={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},He=i=>{const t=[],e=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:f,type:p,...b})=>({...b,type:f??p})),events:l.events?.length?l.events:[wt]}));t.push({id:s,...a,containers:c,events:a.events?.length?a.events:[wt]}),e.push({id:s,x:r,y:o})}return{...i,chapters:t,graph:Ge(e),metadata:{...i.metadata,version:De}}},Ue=[{version:"3.0",migrate:ke},{version:"3.1",migrate:Fe},{version:"3.2",migrate:He}],We=i=>Ue.reduce((t,e)=>Z(t.metadata.version,e.version)?t:e.migrate(t),i),ze=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),w=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 St={metadata:"Object",chapters:"Array"},qe="3.0.0",Qe="3.3.0",te=i=>{const t=Z(i,qe);return t===-1?!1:t===0?!0:Z(i,Qe)!==1},Xe=i=>{if(!ht(i))return!1;for(const t in St)if(!i[t]||!H(i[t],St[t]))return!1;return te(i.metadata.version)},ee=i=>i.type===ze.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 ie{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 s=n.length;s>0;s--)if(n[s]===e){n.splice(s,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(s=>{s(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class Ke{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{Re(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 Ye{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return Ze(...this.loaders[t])(e)}}function Ze(...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 s=i.getManifest(),r=i.getChapter(s.chapters,e);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:t,result:{chapter:r,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 Tt{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 s=0,r=n.length;s<r;s++)if(n[s].callback===e){n.splice(s,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const n=this.listeners[t.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];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 ne extends Tt{constructor(){super(),this.listeners||Tt.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 Je{constructor(){Object.defineProperty(this,"signal",{value:new ne,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&&(Je.prototype[Symbol.toStringTag]="AbortController",ne.prototype[Symbol.toStringTag]="AbortSignal");function se(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 ti(i){typeof i=="function"&&(i={fetch:i});const{fetch:t,Request:e=t.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!se({fetch:t,Request:e,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:t,Request:r};let r=e;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=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},r.prototype=e.prototype);const o=t;return{fetch:(c,l)=>{const f=r&&r.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,A)=>{f.addEventListener("abort",()=>A(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const ut=se({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),re=ut?ti({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=ut?re.fetch:window.fetch;ut?re.Request:window.Request;const ei=async i=>{try{let t,e;if(ht(i))t=i;else if(rt(i)){e=new URL(i).href;const s=await xt(e);if(!s.ok)return{};t=await s.json()}else return{};if(!Xe(t))return{};const n=t.metadata.media;if(rt(n)&&!t.media)try{let s;e?s=new URL(n,e).href:(s=new URL(n).href,e=s);const r=await xt(s);if(!r.ok)throw new Error;t.metadata.media=await r.json()}catch{return ri(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function ii(i){const{manifest:t,manifestURL:e}=await ei(i),n=We(t);return n.media=ni(n.media,e),delete n.metadata.media,n}function nt(i,t){return i.find(e=>e.id===t)}function Rt(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 At(i,t){return i.videos.find(e=>e.id===t)}function ni(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const s=si(n.url,t);return{...n,url:s||n.url}})}))}}function si(i,t){try{return new URL(i,t).href}catch{return""}}function ri(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)&&!Zt(i),et=i=>i.order==="end",ai=i=>dt(i.containers)&&!Zt(i.containers)&&et(i),oi=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e<(t.startTime??0)},Lt=(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"),Ot=i=>i.find(t=>t.action.type==="expect"),ci=i=>i?.length===1,ae=i=>ci(i)&&ee(i[0]),li=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),hi=(i=[])=>i.reduce((t,e,n)=>{const s=(e?.controls??[]).filter(r=>!ee(r));if(pt(s)){const r=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:r});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]<=r[0]&&C.range[1]>=r[1])return t[b].subjects.push(o),t;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),r[1]=C.range[1])}if(p.push(o),r[0]<=l&&r[1]>=c)return[{subjects:p,range:r}];a.length&&a.reverse().forEach(b=>{t.splice(b,1)}),t.push({subjects:f.concat([o]),range:r})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),di=(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 ui extends Ye{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new L(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 ii(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:Rt,getChapter:nt,getMedia:At,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=At(this.manifest.media,e.videoId),s=Rt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:s}}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 s=this.getByChapterId(n.chapterId);return s&&e.push(s),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 pi=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"},jt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function fi(){const i=new Map;function t({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function e(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)e(s[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function $t(i,t=[]){let e={},n;const s=!t.length;for(const r of i.variants)if(!n&&"cover"in r&&(n=r.cover),"url"in r)switch(r.type.toLowerCase()){case"mp4":(s||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"mpeg":(s||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"hls":(s||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:r.url}});break;case"dash":(s||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:r.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))},Y={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},mi=2;function yi(i){const t=fi();let e,n;const s=new ie;let r={},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");if(!a.options)return;const I=(t.map.get(d)??{})[g];if(I){r={chapterId:m,listId:d,itemId:g,...I};const R=r.player;n=R.info.currentQuality$.subscribe(v=>{if(!(!v||!R.info.position$.getValue())){e=v;for(const j of t.map)Object.values(j[1]).forEach(({player:$})=>{R.info.isAutoQualityEnabled$.getValue()||X($,v)})}}),I.container.remove(),o=!1,a.setPlayer(I.player),c||(a.init(),c=!0),s.emit(Y.activePlayerChanged,{player:r.player,config:r.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(r)||d!==r.itemId)return;if(m>=0&&!o){const I=a.getChapterBranches();o=!0;const R=new Set;for(const v of I)R.has(v.media.id)||(await A({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(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),x=r.player.info.currentQuality$.getValue(),I=r.player.info.isAutoQualityEnabled$.getValue(),R=r.player.info.volume$.getValue(),v=r.player.info.currentPlaybackRate$.getValue(),j=!I;let $=!1;for(const O of t.map)if(O[0]===g.id){const k=Object.keys(O[1]);for(const _ of k)_===r.itemId?(k.length<mi||($=!0),t.removePlayer(O[0],_)):($=!0,p(O[0],_,d),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(R),r.player.setMuted(m),r.player.setPlaybackRate(v))}else t.removePlayer(O[0]);$||(await A({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),j?X(r.player,x):r.player.setAutoQuality(!0),r.player.setVolume(R),r.player.setMuted(m))}async function A({media:d,chapterId:g,prefetch:m=!0,setAsActive:x=!0,autoplay:I=!1,preferredExt:R,title:v,playbackRate:j}){const $=Math.random().toString(),O=document.createElement("div");l.append(O);const k=r?.player?.info.isAutoQualityEnabled$.getValue();let _;if(a?.options?.vkVideoLoader){const q=pi(d);q.length&&(_=await a.options.vkVideoLoader(...q))}const ft=a?.options?.coreConfig||{},ce={...ft,configName:[...ft.configName??[],"interactive"]},mt={container:O,..._?.videos?.[0]||{sources:$t(d,R).sources},title:v},B=new ye(ce);B.initVideo(mt);const yt=new tt;yt.add(B.info.position$.subscribe(function(q){b($,B.info.duration$.getValue(),q)})).add(B.events.canplay$.subscribe(function(){k||X(B,e),j&&B.setPlaybackRate(j)}));const D=t.createPlayer({listId:d.id,itemId:$,player:B,container:O,sources:$t(d,R).sources,config:mt,subscription:yt});return x&&p(d.id,D.itemId,g),I&&D.player.play(),m&&!I&&D.player.prepare(),s.emit(Y.playerCreated,D.player),{player:D.player,config:D.config}}function P(){u(),a=null}function u(){a?.off(y.chapterChanged,C),t.removeAll(),r={},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:I}=await A({media:g,chapterId:m.id,title:m.label});return s.emit(Y.initiated,{container:d,media:g,chapterId:m.id}),{player:x,config:I}}else console.error("not found")}return{...t,on:s.on.bind(s),off:s.off.bind(s),init:h,setInteractiveController:f,createPlayer:A,removeAll:P,getActivePlayer:function(){return r}}}class gi{constructor({player:t,container:e,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:f}){this.container=e,this.branches=n,this.selectBranches=s,this.subscription=new tt,this.player=t,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.isPermanentText=c&&ae(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=li({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,s)=>{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(),s(),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(oi(e,this.container.container))this.gameState!==S.beforeInteractive&&(this.gameState=S.beforeInteractive,this.onBeforeStartTime());else if(Lt(e,this.container.container))this.gameState!==S.interactive&&(this.gameState=S.interactive,this.onStartTime());else if(this.gameState!==S.afterInteractive){const r=this.gameState;this.gameState=S.afterInteractive,r===S.interactive&&this.onEndTime()}else this.gameState!==S.destroyed&&!this.isPermanentText&&this.removeView();const n=Lt(e,this.container.container),s=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:s,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 vi(){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 s({timestamp:a,priority:c,initiator:l}){if(Et(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 r({timestamp:a,priority:c,initiator:l}){if(Et(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:r,add:o,removeAll:t,get:s,getLte:e,getGte:n}}const bi=[w.expect,w.setNextBranch],Ci=1/0;function Nt(i){let t=i,e;const n=Ei(),s=new vi;let r;const o=()=>{b(),u()},a=h=>{s.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),bi.includes(d.actionType))break},l=(h=1/0)=>{const d=K(s.get({timestamp:h,priority:"control"})??{}),g=K(s.get({timestamp:h,priority:"container"})??{}),m=K(s.get({timestamp:h,priority:"chapter"})??{});return[...d,...g,...m]},f=h=>{n.isReady(h)&&c(l(h))},p=()=>{c([...K(s.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{e&&(r?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{f(1/0)}),r=t.events.ended$.subscribe(e))},A=h=>{b(),t=h},P=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},u=()=>{n.release(),s.removeAll()};return{setPlayer:A,add:a,remove:P,exec:f,execEndOfVideo:p,listen:C,unlisten:b,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function Ei(){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??Ci,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 K(i){return Object.values(i).flat().sort(t=>t.actionType===w.expect?-1:1)}const Ii=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=t.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},wi=250;function Si(i){let t=()=>{};const e=new ResizeObserver(a=>{r(a),t=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:p}=Ii(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 s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Kt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},wi);function o(){t=void 0,e.disconnect(),s()}return{resizeObserver:e,calc:()=>{t()},release:o}}class Ti{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 xi=i=>Math.floor(Math.random()*i),Ri=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},Ai=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},Li=i=>{const t=i.length,e=xi(t);return i[e]},Vt=1,Oi=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}}),Mt=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:g,branches:m=[],onEvent:x,isEOV:I=()=>!1,isDisabled:R=()=>!1})=>{const v=st(u,I()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},$=R(),O=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:$?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:g,...v.args}});if($){O();return}switch(v.type.trim().toLowerCase()){case w.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"})),O(),v.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...j,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),O(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case w.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),O(),v.args.shouldOpenNow?P({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...j,action:P.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 I=st(u,m),R={timestamp:!I.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:h,actionType:I.type},v=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"container",type:T.actionChoice,actionType:I.type,payload:I.args});switch(I.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const j=g.find($=>$.id===I.args.branchId);if(!j)return;v(),e.add({...R,action:A.bind(null,{subjectId:h,subjectName:"container",action:I,payload:{chapterId:j.chapterId,autoSelect:x}})}),n?.();return}case w.setMaxWeightBranch.trim().toLowerCase():return;case w.setMinWeightBranch.trim().toLowerCase():return;case w.setRandomBranch.trim().toLowerCase():return;case w.setWeightlessRandomBranch.trim().toLowerCase():return;case w.continuePlayback.trim().toLowerCase():{v(),e.add({...R,action:C.bind(null,{subjectId:h,subjectName:"container",action:I})});return}case w.openURI.trim().toLowerCase():{v(),e.add({...R,action:P.bind(null,{subjectId:h,subjectName:"container",action:I,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=Ot(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:w.expect,action:p.bind(null,{subjectId:u.id,subjectName:"container"})}),s.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 w.setNextBranch.trim().toLowerCase():{const m=d.find(x=>x.id===h.args.branchId);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const m=Li(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const m=Ai(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const m=Ri(d);return m?.chapterId?(g(),A.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case w.openURI.trim().toLowerCase():return g(),P.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=Ot(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:w.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??w.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})},A=({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})},P=({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:r,state:s}},Pt=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const s=t.chapters.find(o=>o.id===n);if(!s)return null;const r=t.media.videos.find(o=>s.videoId===o.id);if(!r)return null;e[n]=oe(r)}return e[n]}).filter(Boolean)},ji=i=>{for(const t of i.variants)if($i(t)&&"payload"in t)return t.payload.id},$i=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",oe=i=>{const t=ji(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},Ni=(i,t)=>{for(const e of i.media.videos)if(t===oe(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},Vi=(i,t)=>i.reduce((e,n)=>{const s=Ni(t,n);return s?[...e,s]:e},[]);class _i{state={history$:new L([]),hasPrevChapter$:new L(!1),prevChapter$:new L(null),isInitialChapter$:new L(!1),isGoBackLimited$:new L(!1)};#r=null;#n;#h=!1;#i=null;#u=null;#s=null;#a=null;#o=null;#t=new tt;#d=!1;#p=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:s,settings:r}){this.#s=e,this.#o=t,this.#a=n,this.#r=s,this.#n=r,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.#n.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,s=t.length-this.#n.maxLength,r=s>0?t.slice(s):t,o=Pt(r,n);if(this.#u=o,this?.state?.history$.next(r),!(!e||!this.#r||!this.#s))try{await this.#r.save(this.#s,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.#s)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#r)try{const s=await this.#r.get(this.#s);s.length&&(e=s)}catch{this.#o?.emit(y.errors,new E(E.Severity.RECOVERABLE,E.Category.HISTORY,"Error while trying to fetch data"))}const n=Vi(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#n.initChapterId||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.#s=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 G{constructor(t,e,n,s){this.target=t,this.type=e,this.listener=n,this.options=G.#r(t,s),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"]),s=Object.keys(e).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),G.#h(t)?e:e.capture||!1}}static#n=void 0;static#h(t){let e=G.#n;if(e===void 0){e=!1;try{const n={},s={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};t.addEventListener("test",r,n),t.removeEventListener("test",r,n)}catch{e=!1}G.#n=e}return e||!1}}class Mi{constructor(){this.bindingMap=new Ti}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,s){if(!this.bindingMap)return;const r=new G(t,e,n,s);this.bindingMap.push(e,r)}listenOnce(t,e,n,s){const r=o=>{this.unlisten(t,e,r),n(o)};this.listen(t,e,r,s)}unlisten(t,e,n){if(!this.bindingMap)return;const s=this.bindingMap.get(e)||[];for(const r of s)r.target===t&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(e,r))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class Pi{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 s=3;s<n;s+=40)if(e[s]!==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 s;e&&(s=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&s&&this.restore(s),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 ki{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;