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